import { createRequire as __bannerCrReq } from 'node:module';
import __bannerPath from 'node:path';
import __bannerUrl from 'node:url';

globalThis.require = __bannerCrReq(import.meta.url);
globalThis.__filename = __bannerUrl.fileURLToPath(import.meta.url);
globalThis.__dirname = __bannerPath.dirname(globalThis.__filename);
    
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
  if (typeof require !== "undefined") return require.apply(this, arguments);
  throw Error('Dynamic require of "' + x + '" is not supported');
});
var __esm = (fn, res) => function __init() {
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb, mod) => function __require2() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except2, desc2) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except2)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc(from, key)) || desc2.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));

// ../../node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err-helpers.js
var require_err_helpers = __commonJS({
  "../../node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err-helpers.js"(exports, module) {
    "use strict";
    var isErrorLike = (err) => {
      return err && typeof err.message === "string";
    };
    var getErrorCause = (err) => {
      if (!err) return;
      const cause = err.cause;
      if (typeof cause === "function") {
        const causeResult = err.cause();
        return isErrorLike(causeResult) ? causeResult : void 0;
      } else {
        return isErrorLike(cause) ? cause : void 0;
      }
    };
    var _stackWithCauses = (err, seen) => {
      if (!isErrorLike(err)) return "";
      const stack = err.stack || "";
      if (seen.has(err)) {
        return stack + "\ncauses have become circular...";
      }
      const cause = getErrorCause(err);
      if (cause) {
        seen.add(err);
        return stack + "\ncaused by: " + _stackWithCauses(cause, seen);
      } else {
        return stack;
      }
    };
    var stackWithCauses = (err) => _stackWithCauses(err, /* @__PURE__ */ new Set());
    var _messageWithCauses = (err, seen, skip) => {
      if (!isErrorLike(err)) return "";
      const message = skip ? "" : err.message || "";
      if (seen.has(err)) {
        return message + ": ...";
      }
      const cause = getErrorCause(err);
      if (cause) {
        seen.add(err);
        const skipIfVErrorStyleCause = typeof err.cause === "function";
        return message + (skipIfVErrorStyleCause ? "" : ": ") + _messageWithCauses(cause, seen, skipIfVErrorStyleCause);
      } else {
        return message;
      }
    };
    var messageWithCauses = (err) => _messageWithCauses(err, /* @__PURE__ */ new Set());
    module.exports = {
      isErrorLike,
      getErrorCause,
      stackWithCauses,
      messageWithCauses
    };
  }
});

// ../../node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err-proto.js
var require_err_proto = __commonJS({
  "../../node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err-proto.js"(exports, module) {
    "use strict";
    var seen = /* @__PURE__ */ Symbol("circular-ref-tag");
    var rawSymbol = /* @__PURE__ */ Symbol("pino-raw-err-ref");
    var pinoErrProto = Object.create({}, {
      type: {
        enumerable: true,
        writable: true,
        value: void 0
      },
      message: {
        enumerable: true,
        writable: true,
        value: void 0
      },
      stack: {
        enumerable: true,
        writable: true,
        value: void 0
      },
      aggregateErrors: {
        enumerable: true,
        writable: true,
        value: void 0
      },
      raw: {
        enumerable: false,
        get: function() {
          return this[rawSymbol];
        },
        set: function(val) {
          this[rawSymbol] = val;
        }
      }
    });
    Object.defineProperty(pinoErrProto, rawSymbol, {
      writable: true,
      value: {}
    });
    module.exports = {
      pinoErrProto,
      pinoErrorSymbols: {
        seen,
        rawSymbol
      }
    };
  }
});

// ../../node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err.js
var require_err = __commonJS({
  "../../node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err.js"(exports, module) {
    "use strict";
    module.exports = errSerializer;
    var { messageWithCauses, stackWithCauses, isErrorLike } = require_err_helpers();
    var { pinoErrProto, pinoErrorSymbols } = require_err_proto();
    var { seen } = pinoErrorSymbols;
    var { toString } = Object.prototype;
    function errSerializer(err) {
      if (!isErrorLike(err)) {
        return err;
      }
      err[seen] = void 0;
      const _err = Object.create(pinoErrProto);
      _err.type = toString.call(err.constructor) === "[object Function]" ? err.constructor.name : err.name;
      _err.message = messageWithCauses(err);
      _err.stack = stackWithCauses(err);
      if (Array.isArray(err.errors)) {
        _err.aggregateErrors = err.errors.map((err2) => errSerializer(err2));
      }
      for (const key in err) {
        if (_err[key] === void 0) {
          const val = err[key];
          if (isErrorLike(val)) {
            if (key !== "cause" && !Object.prototype.hasOwnProperty.call(val, seen)) {
              _err[key] = errSerializer(val);
            }
          } else {
            _err[key] = val;
          }
        }
      }
      delete err[seen];
      _err.raw = err;
      return _err;
    }
  }
});

// ../../node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err-with-cause.js
var require_err_with_cause = __commonJS({
  "../../node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err-with-cause.js"(exports, module) {
    "use strict";
    module.exports = errWithCauseSerializer;
    var { isErrorLike } = require_err_helpers();
    var { pinoErrProto, pinoErrorSymbols } = require_err_proto();
    var { seen } = pinoErrorSymbols;
    var { toString } = Object.prototype;
    function errWithCauseSerializer(err) {
      if (!isErrorLike(err)) {
        return err;
      }
      err[seen] = void 0;
      const _err = Object.create(pinoErrProto);
      _err.type = toString.call(err.constructor) === "[object Function]" ? err.constructor.name : err.name;
      _err.message = err.message;
      _err.stack = err.stack;
      if (Array.isArray(err.errors)) {
        _err.aggregateErrors = err.errors.map((err2) => errWithCauseSerializer(err2));
      }
      if (isErrorLike(err.cause) && !Object.prototype.hasOwnProperty.call(err.cause, seen)) {
        _err.cause = errWithCauseSerializer(err.cause);
      }
      for (const key in err) {
        if (_err[key] === void 0) {
          const val = err[key];
          if (isErrorLike(val)) {
            if (!Object.prototype.hasOwnProperty.call(val, seen)) {
              _err[key] = errWithCauseSerializer(val);
            }
          } else {
            _err[key] = val;
          }
        }
      }
      delete err[seen];
      _err.raw = err;
      return _err;
    }
  }
});

// ../../node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/req.js
var require_req = __commonJS({
  "../../node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/req.js"(exports, module) {
    "use strict";
    module.exports = {
      mapHttpRequest,
      reqSerializer
    };
    var rawSymbol = /* @__PURE__ */ Symbol("pino-raw-req-ref");
    var pinoReqProto = Object.create({}, {
      id: {
        enumerable: true,
        writable: true,
        value: ""
      },
      method: {
        enumerable: true,
        writable: true,
        value: ""
      },
      url: {
        enumerable: true,
        writable: true,
        value: ""
      },
      query: {
        enumerable: true,
        writable: true,
        value: ""
      },
      params: {
        enumerable: true,
        writable: true,
        value: ""
      },
      headers: {
        enumerable: true,
        writable: true,
        value: {}
      },
      remoteAddress: {
        enumerable: true,
        writable: true,
        value: ""
      },
      remotePort: {
        enumerable: true,
        writable: true,
        value: ""
      },
      raw: {
        enumerable: false,
        get: function() {
          return this[rawSymbol];
        },
        set: function(val) {
          this[rawSymbol] = val;
        }
      }
    });
    Object.defineProperty(pinoReqProto, rawSymbol, {
      writable: true,
      value: {}
    });
    function reqSerializer(req) {
      const connection = req.info || req.socket;
      const _req = Object.create(pinoReqProto);
      _req.id = typeof req.id === "function" ? req.id() : req.id || (req.info ? req.info.id : void 0);
      _req.method = req.method;
      if (req.originalUrl) {
        _req.url = req.originalUrl;
      } else {
        const path4 = req.path;
        _req.url = typeof path4 === "string" ? path4 : req.url ? req.url.path || req.url : void 0;
      }
      if (req.query) {
        _req.query = req.query;
      }
      if (req.params) {
        _req.params = req.params;
      }
      _req.headers = req.headers;
      _req.remoteAddress = connection && connection.remoteAddress;
      _req.remotePort = connection && connection.remotePort;
      _req.raw = req.raw || req;
      return _req;
    }
    function mapHttpRequest(req) {
      return {
        req: reqSerializer(req)
      };
    }
  }
});

// ../../node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/res.js
var require_res = __commonJS({
  "../../node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/res.js"(exports, module) {
    "use strict";
    module.exports = {
      mapHttpResponse,
      resSerializer
    };
    var rawSymbol = /* @__PURE__ */ Symbol("pino-raw-res-ref");
    var pinoResProto = Object.create({}, {
      statusCode: {
        enumerable: true,
        writable: true,
        value: 0
      },
      headers: {
        enumerable: true,
        writable: true,
        value: ""
      },
      raw: {
        enumerable: false,
        get: function() {
          return this[rawSymbol];
        },
        set: function(val) {
          this[rawSymbol] = val;
        }
      }
    });
    Object.defineProperty(pinoResProto, rawSymbol, {
      writable: true,
      value: {}
    });
    function resSerializer(res) {
      const _res = Object.create(pinoResProto);
      _res.statusCode = res.headersSent ? res.statusCode : null;
      _res.headers = res.getHeaders ? res.getHeaders() : res._headers;
      _res.raw = res;
      return _res;
    }
    function mapHttpResponse(res) {
      return {
        res: resSerializer(res)
      };
    }
  }
});

// ../../node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/index.js
var require_pino_std_serializers = __commonJS({
  "../../node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/index.js"(exports, module) {
    "use strict";
    var errSerializer = require_err();
    var errWithCauseSerializer = require_err_with_cause();
    var reqSerializers = require_req();
    var resSerializers = require_res();
    module.exports = {
      err: errSerializer,
      errWithCause: errWithCauseSerializer,
      mapHttpRequest: reqSerializers.mapHttpRequest,
      mapHttpResponse: resSerializers.mapHttpResponse,
      req: reqSerializers.reqSerializer,
      res: resSerializers.resSerializer,
      wrapErrorSerializer: function wrapErrorSerializer(customSerializer) {
        if (customSerializer === errSerializer) return customSerializer;
        return function wrapErrSerializer(err) {
          return customSerializer(errSerializer(err));
        };
      },
      wrapRequestSerializer: function wrapRequestSerializer(customSerializer) {
        if (customSerializer === reqSerializers.reqSerializer) return customSerializer;
        return function wrappedReqSerializer(req) {
          return customSerializer(reqSerializers.reqSerializer(req));
        };
      },
      wrapResponseSerializer: function wrapResponseSerializer(customSerializer) {
        if (customSerializer === resSerializers.resSerializer) return customSerializer;
        return function wrappedResSerializer(res) {
          return customSerializer(resSerializers.resSerializer(res));
        };
      }
    };
  }
});

// ../../node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/caller.js
var require_caller = __commonJS({
  "../../node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/caller.js"(exports, module) {
    "use strict";
    function noOpPrepareStackTrace(_, stack) {
      return stack;
    }
    module.exports = function getCallers() {
      const originalPrepare = Error.prepareStackTrace;
      Error.prepareStackTrace = noOpPrepareStackTrace;
      const stack = new Error().stack;
      Error.prepareStackTrace = originalPrepare;
      if (!Array.isArray(stack)) {
        return void 0;
      }
      const entries = stack.slice(2);
      const fileNames = [];
      for (const entry of entries) {
        if (!entry) {
          continue;
        }
        fileNames.push(entry.getFileName());
      }
      return fileNames;
    };
  }
});

// ../../node_modules/.pnpm/@pinojs+redact@0.4.0/node_modules/@pinojs/redact/index.js
var require_redact = __commonJS({
  "../../node_modules/.pnpm/@pinojs+redact@0.4.0/node_modules/@pinojs/redact/index.js"(exports, module) {
    "use strict";
    function deepClone(obj) {
      if (obj === null || typeof obj !== "object") {
        return obj;
      }
      if (obj instanceof Date) {
        return new Date(obj.getTime());
      }
      if (obj instanceof Array) {
        const cloned = [];
        for (let i = 0; i < obj.length; i++) {
          cloned[i] = deepClone(obj[i]);
        }
        return cloned;
      }
      if (typeof obj === "object") {
        const cloned = Object.create(Object.getPrototypeOf(obj));
        for (const key in obj) {
          if (Object.prototype.hasOwnProperty.call(obj, key)) {
            cloned[key] = deepClone(obj[key]);
          }
        }
        return cloned;
      }
      return obj;
    }
    function parsePath(path4) {
      const parts = [];
      let current = "";
      let inBrackets = false;
      let inQuotes = false;
      let quoteChar = "";
      for (let i = 0; i < path4.length; i++) {
        const char2 = path4[i];
        if (!inBrackets && char2 === ".") {
          if (current) {
            parts.push(current);
            current = "";
          }
        } else if (char2 === "[") {
          if (current) {
            parts.push(current);
            current = "";
          }
          inBrackets = true;
        } else if (char2 === "]" && inBrackets) {
          parts.push(current);
          current = "";
          inBrackets = false;
          inQuotes = false;
        } else if ((char2 === '"' || char2 === "'") && inBrackets) {
          if (!inQuotes) {
            inQuotes = true;
            quoteChar = char2;
          } else if (char2 === quoteChar) {
            inQuotes = false;
            quoteChar = "";
          } else {
            current += char2;
          }
        } else {
          current += char2;
        }
      }
      if (current) {
        parts.push(current);
      }
      return parts;
    }
    function setValue(obj, parts, value) {
      let current = obj;
      for (let i = 0; i < parts.length - 1; i++) {
        const key = parts[i];
        if (typeof current !== "object" || current === null || !(key in current)) {
          return false;
        }
        if (typeof current[key] !== "object" || current[key] === null) {
          return false;
        }
        current = current[key];
      }
      const lastKey = parts[parts.length - 1];
      if (lastKey === "*") {
        if (Array.isArray(current)) {
          for (let i = 0; i < current.length; i++) {
            current[i] = value;
          }
        } else if (typeof current === "object" && current !== null) {
          for (const key in current) {
            if (Object.prototype.hasOwnProperty.call(current, key)) {
              current[key] = value;
            }
          }
        }
      } else {
        if (typeof current === "object" && current !== null && lastKey in current && Object.prototype.hasOwnProperty.call(current, lastKey)) {
          current[lastKey] = value;
        }
      }
      return true;
    }
    function removeKey(obj, parts) {
      let current = obj;
      for (let i = 0; i < parts.length - 1; i++) {
        const key = parts[i];
        if (typeof current !== "object" || current === null || !(key in current)) {
          return false;
        }
        if (typeof current[key] !== "object" || current[key] === null) {
          return false;
        }
        current = current[key];
      }
      const lastKey = parts[parts.length - 1];
      if (lastKey === "*") {
        if (Array.isArray(current)) {
          for (let i = 0; i < current.length; i++) {
            current[i] = void 0;
          }
        } else if (typeof current === "object" && current !== null) {
          for (const key in current) {
            if (Object.prototype.hasOwnProperty.call(current, key)) {
              delete current[key];
            }
          }
        }
      } else {
        if (typeof current === "object" && current !== null && lastKey in current && Object.prototype.hasOwnProperty.call(current, lastKey)) {
          delete current[lastKey];
        }
      }
      return true;
    }
    var PATH_NOT_FOUND = /* @__PURE__ */ Symbol("PATH_NOT_FOUND");
    function getValueIfExists(obj, parts) {
      let current = obj;
      for (const part of parts) {
        if (current === null || current === void 0) {
          return PATH_NOT_FOUND;
        }
        if (typeof current !== "object" || current === null) {
          return PATH_NOT_FOUND;
        }
        if (!(part in current)) {
          return PATH_NOT_FOUND;
        }
        current = current[part];
      }
      return current;
    }
    function getValue(obj, parts) {
      let current = obj;
      for (const part of parts) {
        if (current === null || current === void 0) {
          return void 0;
        }
        if (typeof current !== "object" || current === null) {
          return void 0;
        }
        current = current[part];
      }
      return current;
    }
    function redactPaths(obj, paths, censor, remove = false) {
      for (const path4 of paths) {
        const parts = parsePath(path4);
        if (parts.includes("*")) {
          redactWildcardPath(obj, parts, censor, path4, remove);
        } else {
          if (remove) {
            removeKey(obj, parts);
          } else {
            const value = getValueIfExists(obj, parts);
            if (value === PATH_NOT_FOUND) {
              continue;
            }
            const actualCensor = typeof censor === "function" ? censor(value, parts) : censor;
            setValue(obj, parts, actualCensor);
          }
        }
      }
    }
    function redactWildcardPath(obj, parts, censor, originalPath, remove = false) {
      const wildcardIndex = parts.indexOf("*");
      if (wildcardIndex === parts.length - 1) {
        const parentParts = parts.slice(0, -1);
        let current = obj;
        for (const part of parentParts) {
          if (current === null || current === void 0) return;
          if (typeof current !== "object" || current === null) return;
          current = current[part];
        }
        if (Array.isArray(current)) {
          if (remove) {
            for (let i = 0; i < current.length; i++) {
              current[i] = void 0;
            }
          } else {
            for (let i = 0; i < current.length; i++) {
              const indexPath = [...parentParts, i.toString()];
              const actualCensor = typeof censor === "function" ? censor(current[i], indexPath) : censor;
              current[i] = actualCensor;
            }
          }
        } else if (typeof current === "object" && current !== null) {
          if (remove) {
            const keysToDelete = [];
            for (const key in current) {
              if (Object.prototype.hasOwnProperty.call(current, key)) {
                keysToDelete.push(key);
              }
            }
            for (const key of keysToDelete) {
              delete current[key];
            }
          } else {
            for (const key in current) {
              const keyPath = [...parentParts, key];
              const actualCensor = typeof censor === "function" ? censor(current[key], keyPath) : censor;
              current[key] = actualCensor;
            }
          }
        }
      } else {
        redactIntermediateWildcard(obj, parts, censor, wildcardIndex, originalPath, remove);
      }
    }
    function redactIntermediateWildcard(obj, parts, censor, wildcardIndex, originalPath, remove = false) {
      const beforeWildcard = parts.slice(0, wildcardIndex);
      const afterWildcard = parts.slice(wildcardIndex + 1);
      const pathArray = [];
      function traverse(current, pathLength) {
        if (pathLength === beforeWildcard.length) {
          if (Array.isArray(current)) {
            for (let i = 0; i < current.length; i++) {
              pathArray[pathLength] = i.toString();
              traverse(current[i], pathLength + 1);
            }
          } else if (typeof current === "object" && current !== null) {
            for (const key in current) {
              pathArray[pathLength] = key;
              traverse(current[key], pathLength + 1);
            }
          }
        } else if (pathLength < beforeWildcard.length) {
          const nextKey = beforeWildcard[pathLength];
          if (current && typeof current === "object" && current !== null && nextKey in current) {
            pathArray[pathLength] = nextKey;
            traverse(current[nextKey], pathLength + 1);
          }
        } else {
          if (afterWildcard.includes("*")) {
            const wrappedCensor = typeof censor === "function" ? (value, path4) => {
              const fullPath = [...pathArray.slice(0, pathLength), ...path4];
              return censor(value, fullPath);
            } : censor;
            redactWildcardPath(current, afterWildcard, wrappedCensor, originalPath, remove);
          } else {
            if (remove) {
              removeKey(current, afterWildcard);
            } else {
              const actualCensor = typeof censor === "function" ? censor(getValue(current, afterWildcard), [...pathArray.slice(0, pathLength), ...afterWildcard]) : censor;
              setValue(current, afterWildcard, actualCensor);
            }
          }
        }
      }
      if (beforeWildcard.length === 0) {
        traverse(obj, 0);
      } else {
        let current = obj;
        for (let i = 0; i < beforeWildcard.length; i++) {
          const part = beforeWildcard[i];
          if (current === null || current === void 0) return;
          if (typeof current !== "object" || current === null) return;
          current = current[part];
          pathArray[i] = part;
        }
        if (current !== null && current !== void 0) {
          traverse(current, beforeWildcard.length);
        }
      }
    }
    function buildPathStructure(pathsToClone) {
      if (pathsToClone.length === 0) {
        return null;
      }
      const pathStructure = /* @__PURE__ */ new Map();
      for (const path4 of pathsToClone) {
        const parts = parsePath(path4);
        let current = pathStructure;
        for (let i = 0; i < parts.length; i++) {
          const part = parts[i];
          if (!current.has(part)) {
            current.set(part, /* @__PURE__ */ new Map());
          }
          current = current.get(part);
        }
      }
      return pathStructure;
    }
    function selectiveClone(obj, pathStructure) {
      if (!pathStructure) {
        return obj;
      }
      function cloneSelectively(source, pathMap, depth = 0) {
        if (!pathMap || pathMap.size === 0) {
          return source;
        }
        if (source === null || typeof source !== "object") {
          return source;
        }
        if (source instanceof Date) {
          return new Date(source.getTime());
        }
        if (Array.isArray(source)) {
          const cloned2 = [];
          for (let i = 0; i < source.length; i++) {
            const indexStr = i.toString();
            if (pathMap.has(indexStr) || pathMap.has("*")) {
              cloned2[i] = cloneSelectively(source[i], pathMap.get(indexStr) || pathMap.get("*"));
            } else {
              cloned2[i] = source[i];
            }
          }
          return cloned2;
        }
        const cloned = Object.create(Object.getPrototypeOf(source));
        for (const key in source) {
          if (Object.prototype.hasOwnProperty.call(source, key)) {
            if (pathMap.has(key) || pathMap.has("*")) {
              cloned[key] = cloneSelectively(source[key], pathMap.get(key) || pathMap.get("*"));
            } else {
              cloned[key] = source[key];
            }
          }
        }
        return cloned;
      }
      return cloneSelectively(obj, pathStructure);
    }
    function validatePath(path4) {
      if (typeof path4 !== "string") {
        throw new Error("Paths must be (non-empty) strings");
      }
      if (path4 === "") {
        throw new Error("Invalid redaction path ()");
      }
      if (path4.includes("..")) {
        throw new Error(`Invalid redaction path (${path4})`);
      }
      if (path4.includes(",")) {
        throw new Error(`Invalid redaction path (${path4})`);
      }
      let bracketCount = 0;
      let inQuotes = false;
      let quoteChar = "";
      for (let i = 0; i < path4.length; i++) {
        const char2 = path4[i];
        if ((char2 === '"' || char2 === "'") && bracketCount > 0) {
          if (!inQuotes) {
            inQuotes = true;
            quoteChar = char2;
          } else if (char2 === quoteChar) {
            inQuotes = false;
            quoteChar = "";
          }
        } else if (char2 === "[" && !inQuotes) {
          bracketCount++;
        } else if (char2 === "]" && !inQuotes) {
          bracketCount--;
          if (bracketCount < 0) {
            throw new Error(`Invalid redaction path (${path4})`);
          }
        }
      }
      if (bracketCount !== 0) {
        throw new Error(`Invalid redaction path (${path4})`);
      }
    }
    function validatePaths(paths) {
      if (!Array.isArray(paths)) {
        throw new TypeError("paths must be an array");
      }
      for (const path4 of paths) {
        validatePath(path4);
      }
    }
    function slowRedact(options = {}) {
      const {
        paths = [],
        censor = "[REDACTED]",
        serialize = JSON.stringify,
        strict = true,
        remove = false
      } = options;
      validatePaths(paths);
      const pathStructure = buildPathStructure(paths);
      return function redact(obj) {
        if (strict && (obj === null || typeof obj !== "object")) {
          if (obj === null || obj === void 0) {
            return serialize ? serialize(obj) : obj;
          }
          if (typeof obj !== "object") {
            return serialize ? serialize(obj) : obj;
          }
        }
        const cloned = selectiveClone(obj, pathStructure);
        const original = obj;
        let actualCensor = censor;
        if (typeof censor === "function") {
          actualCensor = censor;
        }
        redactPaths(cloned, paths, actualCensor, remove);
        if (serialize === false) {
          cloned.restore = function() {
            return deepClone(original);
          };
          return cloned;
        }
        if (typeof serialize === "function") {
          return serialize(cloned);
        }
        return JSON.stringify(cloned);
      };
    }
    module.exports = slowRedact;
  }
});

// ../../node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/symbols.js
var require_symbols = __commonJS({
  "../../node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/symbols.js"(exports, module) {
    "use strict";
    var setLevelSym = /* @__PURE__ */ Symbol("pino.setLevel");
    var getLevelSym = /* @__PURE__ */ Symbol("pino.getLevel");
    var levelValSym = /* @__PURE__ */ Symbol("pino.levelVal");
    var levelCompSym = /* @__PURE__ */ Symbol("pino.levelComp");
    var useLevelLabelsSym = /* @__PURE__ */ Symbol("pino.useLevelLabels");
    var useOnlyCustomLevelsSym = /* @__PURE__ */ Symbol("pino.useOnlyCustomLevels");
    var mixinSym = /* @__PURE__ */ Symbol("pino.mixin");
    var lsCacheSym = /* @__PURE__ */ Symbol("pino.lsCache");
    var chindingsSym = /* @__PURE__ */ Symbol("pino.chindings");
    var asJsonSym = /* @__PURE__ */ Symbol("pino.asJson");
    var writeSym = /* @__PURE__ */ Symbol("pino.write");
    var redactFmtSym = /* @__PURE__ */ Symbol("pino.redactFmt");
    var timeSym = /* @__PURE__ */ Symbol("pino.time");
    var timeSliceIndexSym = /* @__PURE__ */ Symbol("pino.timeSliceIndex");
    var streamSym = /* @__PURE__ */ Symbol("pino.stream");
    var stringifySym = /* @__PURE__ */ Symbol("pino.stringify");
    var stringifySafeSym = /* @__PURE__ */ Symbol("pino.stringifySafe");
    var stringifiersSym = /* @__PURE__ */ Symbol("pino.stringifiers");
    var endSym = /* @__PURE__ */ Symbol("pino.end");
    var formatOptsSym = /* @__PURE__ */ Symbol("pino.formatOpts");
    var messageKeySym = /* @__PURE__ */ Symbol("pino.messageKey");
    var errorKeySym = /* @__PURE__ */ Symbol("pino.errorKey");
    var nestedKeySym = /* @__PURE__ */ Symbol("pino.nestedKey");
    var nestedKeyStrSym = /* @__PURE__ */ Symbol("pino.nestedKeyStr");
    var mixinMergeStrategySym = /* @__PURE__ */ Symbol("pino.mixinMergeStrategy");
    var msgPrefixSym = /* @__PURE__ */ Symbol("pino.msgPrefix");
    var wildcardFirstSym = /* @__PURE__ */ Symbol("pino.wildcardFirst");
    var serializersSym = /* @__PURE__ */ Symbol.for("pino.serializers");
    var formattersSym = /* @__PURE__ */ Symbol.for("pino.formatters");
    var hooksSym = /* @__PURE__ */ Symbol.for("pino.hooks");
    var needsMetadataGsym = /* @__PURE__ */ Symbol.for("pino.metadata");
    module.exports = {
      setLevelSym,
      getLevelSym,
      levelValSym,
      levelCompSym,
      useLevelLabelsSym,
      mixinSym,
      lsCacheSym,
      chindingsSym,
      asJsonSym,
      writeSym,
      serializersSym,
      redactFmtSym,
      timeSym,
      timeSliceIndexSym,
      streamSym,
      stringifySym,
      stringifySafeSym,
      stringifiersSym,
      endSym,
      formatOptsSym,
      messageKeySym,
      errorKeySym,
      nestedKeySym,
      wildcardFirstSym,
      needsMetadataGsym,
      useOnlyCustomLevelsSym,
      formattersSym,
      hooksSym,
      nestedKeyStrSym,
      mixinMergeStrategySym,
      msgPrefixSym
    };
  }
});

// ../../node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/redaction.js
var require_redaction = __commonJS({
  "../../node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/redaction.js"(exports, module) {
    "use strict";
    var Redact = require_redact();
    var { redactFmtSym, wildcardFirstSym } = require_symbols();
    var rx = /[^.[\]]+|\[([^[\]]*?)\]/g;
    var CENSOR = "[Redacted]";
    var strict = false;
    function redaction(opts, serialize) {
      const { paths, censor, remove } = handle(opts);
      const shape = paths.reduce((o, str) => {
        rx.lastIndex = 0;
        const first = rx.exec(str);
        const next = rx.exec(str);
        let ns = first[1] !== void 0 ? first[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/, "$1") : first[0];
        if (ns === "*") {
          ns = wildcardFirstSym;
        }
        if (next === null) {
          o[ns] = null;
          return o;
        }
        if (o[ns] === null) {
          return o;
        }
        const { index: index2 } = next;
        const nextPath = `${str.substr(index2, str.length - 1)}`;
        o[ns] = o[ns] || [];
        if (ns !== wildcardFirstSym && o[ns].length === 0) {
          o[ns].push(...o[wildcardFirstSym] || []);
        }
        if (ns === wildcardFirstSym) {
          Object.keys(o).forEach(function(k) {
            if (o[k]) {
              o[k].push(nextPath);
            }
          });
        }
        o[ns].push(nextPath);
        return o;
      }, {});
      const result = {
        [redactFmtSym]: Redact({ paths, censor, serialize, strict, remove })
      };
      const topCensor = (...args) => {
        return typeof censor === "function" ? serialize(censor(...args)) : serialize(censor);
      };
      return [...Object.keys(shape), ...Object.getOwnPropertySymbols(shape)].reduce((o, k) => {
        if (shape[k] === null) {
          o[k] = (value) => topCensor(value, [k]);
        } else {
          const wrappedCensor = typeof censor === "function" ? (value, path4) => {
            return censor(value, [k, ...path4]);
          } : censor;
          o[k] = Redact({
            paths: shape[k],
            censor: wrappedCensor,
            serialize,
            strict,
            remove
          });
        }
        return o;
      }, result);
    }
    function handle(opts) {
      if (Array.isArray(opts)) {
        opts = { paths: opts, censor: CENSOR };
        return opts;
      }
      let { paths, censor = CENSOR, remove } = opts;
      if (Array.isArray(paths) === false) {
        throw Error("pino \u2013 redact must contain an array of strings");
      }
      if (remove === true) censor = void 0;
      return { paths, censor, remove };
    }
    module.exports = redaction;
  }
});

// ../../node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/time.js
var require_time = __commonJS({
  "../../node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/time.js"(exports, module) {
    "use strict";
    var nullTime = () => "";
    var epochTime = () => `,"time":${Date.now()}`;
    var unixTime = () => `,"time":${Math.round(Date.now() / 1e3)}`;
    var isoTime = () => `,"time":"${new Date(Date.now()).toISOString()}"`;
    var NS_PER_MS = 1000000n;
    var NS_PER_SEC = 1000000000n;
    var startWallTimeNs = BigInt(Date.now()) * NS_PER_MS;
    var startHrTime = process.hrtime.bigint();
    var isoTimeNano = () => {
      const elapsedNs = process.hrtime.bigint() - startHrTime;
      const currentTimeNs = startWallTimeNs + elapsedNs;
      const secondsSinceEpoch = currentTimeNs / NS_PER_SEC;
      const nanosWithinSecond = currentTimeNs % NS_PER_SEC;
      const msSinceEpoch = Number(secondsSinceEpoch * 1000n + nanosWithinSecond / 1000000n);
      const date6 = new Date(msSinceEpoch);
      const year = date6.getUTCFullYear();
      const month = (date6.getUTCMonth() + 1).toString().padStart(2, "0");
      const day = date6.getUTCDate().toString().padStart(2, "0");
      const hours = date6.getUTCHours().toString().padStart(2, "0");
      const minutes = date6.getUTCMinutes().toString().padStart(2, "0");
      const seconds = date6.getUTCSeconds().toString().padStart(2, "0");
      return `,"time":"${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${nanosWithinSecond.toString().padStart(9, "0")}Z"`;
    };
    module.exports = { nullTime, epochTime, unixTime, isoTime, isoTimeNano };
  }
});

// ../../node_modules/.pnpm/quick-format-unescaped@4.0.4/node_modules/quick-format-unescaped/index.js
var require_quick_format_unescaped = __commonJS({
  "../../node_modules/.pnpm/quick-format-unescaped@4.0.4/node_modules/quick-format-unescaped/index.js"(exports, module) {
    "use strict";
    function tryStringify(o) {
      try {
        return JSON.stringify(o);
      } catch (e) {
        return '"[Circular]"';
      }
    }
    module.exports = format;
    function format(f, args, opts) {
      var ss = opts && opts.stringify || tryStringify;
      var offset = 1;
      if (typeof f === "object" && f !== null) {
        var len = args.length + offset;
        if (len === 1) return f;
        var objects = new Array(len);
        objects[0] = ss(f);
        for (var index2 = 1; index2 < len; index2++) {
          objects[index2] = ss(args[index2]);
        }
        return objects.join(" ");
      }
      if (typeof f !== "string") {
        return f;
      }
      var argLen = args.length;
      if (argLen === 0) return f;
      var str = "";
      var a = 1 - offset;
      var lastPos = -1;
      var flen = f && f.length || 0;
      for (var i = 0; i < flen; ) {
        if (f.charCodeAt(i) === 37 && i + 1 < flen) {
          lastPos = lastPos > -1 ? lastPos : 0;
          switch (f.charCodeAt(i + 1)) {
            case 100:
            // 'd'
            case 102:
              if (a >= argLen)
                break;
              if (args[a] == null) break;
              if (lastPos < i)
                str += f.slice(lastPos, i);
              str += Number(args[a]);
              lastPos = i + 2;
              i++;
              break;
            case 105:
              if (a >= argLen)
                break;
              if (args[a] == null) break;
              if (lastPos < i)
                str += f.slice(lastPos, i);
              str += Math.floor(Number(args[a]));
              lastPos = i + 2;
              i++;
              break;
            case 79:
            // 'O'
            case 111:
            // 'o'
            case 106:
              if (a >= argLen)
                break;
              if (args[a] === void 0) break;
              if (lastPos < i)
                str += f.slice(lastPos, i);
              var type = typeof args[a];
              if (type === "string") {
                str += "'" + args[a] + "'";
                lastPos = i + 2;
                i++;
                break;
              }
              if (type === "function") {
                str += args[a].name || "<anonymous>";
                lastPos = i + 2;
                i++;
                break;
              }
              str += ss(args[a]);
              lastPos = i + 2;
              i++;
              break;
            case 115:
              if (a >= argLen)
                break;
              if (lastPos < i)
                str += f.slice(lastPos, i);
              str += String(args[a]);
              lastPos = i + 2;
              i++;
              break;
            case 37:
              if (lastPos < i)
                str += f.slice(lastPos, i);
              str += "%";
              lastPos = i + 2;
              i++;
              a--;
              break;
          }
          ++a;
        }
        ++i;
      }
      if (lastPos === -1)
        return f;
      else if (lastPos < flen) {
        str += f.slice(lastPos);
      }
      return str;
    }
  }
});

// ../../node_modules/.pnpm/atomic-sleep@1.0.0/node_modules/atomic-sleep/index.js
var require_atomic_sleep = __commonJS({
  "../../node_modules/.pnpm/atomic-sleep@1.0.0/node_modules/atomic-sleep/index.js"(exports, module) {
    "use strict";
    if (typeof SharedArrayBuffer !== "undefined" && typeof Atomics !== "undefined") {
      let sleep = function(ms) {
        const valid = ms > 0 && ms < Infinity;
        if (valid === false) {
          if (typeof ms !== "number" && typeof ms !== "bigint") {
            throw TypeError("sleep: ms must be a number");
          }
          throw RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");
        }
        Atomics.wait(nil, 0, 0, Number(ms));
      };
      const nil = new Int32Array(new SharedArrayBuffer(4));
      module.exports = sleep;
    } else {
      let sleep = function(ms) {
        const valid = ms > 0 && ms < Infinity;
        if (valid === false) {
          if (typeof ms !== "number" && typeof ms !== "bigint") {
            throw TypeError("sleep: ms must be a number");
          }
          throw RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");
        }
        const target = Date.now() + Number(ms);
        while (target > Date.now()) {
        }
      };
      module.exports = sleep;
    }
  }
});

// ../../node_modules/.pnpm/sonic-boom@4.2.1/node_modules/sonic-boom/index.js
var require_sonic_boom = __commonJS({
  "../../node_modules/.pnpm/sonic-boom@4.2.1/node_modules/sonic-boom/index.js"(exports, module) {
    "use strict";
    var fs2 = __require("fs");
    var EventEmitter2 = __require("events");
    var inherits = __require("util").inherits;
    var path4 = __require("path");
    var sleep = require_atomic_sleep();
    var assert2 = __require("assert");
    var BUSY_WRITE_TIMEOUT = 100;
    var kEmptyBuffer = Buffer.allocUnsafe(0);
    var MAX_WRITE = 16 * 1024;
    var kContentModeBuffer = "buffer";
    var kContentModeUtf8 = "utf8";
    var [major, minor] = (process.versions.node || "0.0").split(".").map(Number);
    var kCopyBuffer = major >= 22 && minor >= 7;
    function openFile(file2, sonic) {
      sonic._opening = true;
      sonic._writing = true;
      sonic._asyncDrainScheduled = false;
      function fileOpened(err, fd) {
        if (err) {
          sonic._reopening = false;
          sonic._writing = false;
          sonic._opening = false;
          if (sonic.sync) {
            process.nextTick(() => {
              if (sonic.listenerCount("error") > 0) {
                sonic.emit("error", err);
              }
            });
          } else {
            sonic.emit("error", err);
          }
          return;
        }
        const reopening = sonic._reopening;
        sonic.fd = fd;
        sonic.file = file2;
        sonic._reopening = false;
        sonic._opening = false;
        sonic._writing = false;
        if (sonic.sync) {
          process.nextTick(() => sonic.emit("ready"));
        } else {
          sonic.emit("ready");
        }
        if (sonic.destroyed) {
          return;
        }
        if (!sonic._writing && sonic._len > sonic.minLength || sonic._flushPending) {
          sonic._actualWrite();
        } else if (reopening) {
          process.nextTick(() => sonic.emit("drain"));
        }
      }
      const flags = sonic.append ? "a" : "w";
      const mode = sonic.mode;
      if (sonic.sync) {
        try {
          if (sonic.mkdir) fs2.mkdirSync(path4.dirname(file2), { recursive: true });
          const fd = fs2.openSync(file2, flags, mode);
          fileOpened(null, fd);
        } catch (err) {
          fileOpened(err);
          throw err;
        }
      } else if (sonic.mkdir) {
        fs2.mkdir(path4.dirname(file2), { recursive: true }, (err) => {
          if (err) return fileOpened(err);
          fs2.open(file2, flags, mode, fileOpened);
        });
      } else {
        fs2.open(file2, flags, mode, fileOpened);
      }
    }
    function SonicBoom(opts) {
      if (!(this instanceof SonicBoom)) {
        return new SonicBoom(opts);
      }
      let { fd, dest, minLength, maxLength, maxWrite, periodicFlush, sync, append = true, mkdir, retryEAGAIN, fsync, contentMode, mode } = opts || {};
      fd = fd || dest;
      this._len = 0;
      this.fd = -1;
      this._bufs = [];
      this._lens = [];
      this._writing = false;
      this._ending = false;
      this._reopening = false;
      this._asyncDrainScheduled = false;
      this._flushPending = false;
      this._hwm = Math.max(minLength || 0, 16387);
      this.file = null;
      this.destroyed = false;
      this.minLength = minLength || 0;
      this.maxLength = maxLength || 0;
      this.maxWrite = maxWrite || MAX_WRITE;
      this._periodicFlush = periodicFlush || 0;
      this._periodicFlushTimer = void 0;
      this.sync = sync || false;
      this.writable = true;
      this._fsync = fsync || false;
      this.append = append || false;
      this.mode = mode;
      this.retryEAGAIN = retryEAGAIN || (() => true);
      this.mkdir = mkdir || false;
      let fsWriteSync;
      let fsWrite;
      if (contentMode === kContentModeBuffer) {
        this._writingBuf = kEmptyBuffer;
        this.write = writeBuffer;
        this.flush = flushBuffer;
        this.flushSync = flushBufferSync;
        this._actualWrite = actualWriteBuffer;
        fsWriteSync = () => fs2.writeSync(this.fd, this._writingBuf);
        fsWrite = () => fs2.write(this.fd, this._writingBuf, this.release);
      } else if (contentMode === void 0 || contentMode === kContentModeUtf8) {
        this._writingBuf = "";
        this.write = write;
        this.flush = flush;
        this.flushSync = flushSync;
        this._actualWrite = actualWrite;
        fsWriteSync = () => {
          if (Buffer.isBuffer(this._writingBuf)) {
            return fs2.writeSync(this.fd, this._writingBuf);
          }
          return fs2.writeSync(this.fd, this._writingBuf, "utf8");
        };
        fsWrite = () => {
          if (Buffer.isBuffer(this._writingBuf)) {
            return fs2.write(this.fd, this._writingBuf, this.release);
          }
          return fs2.write(this.fd, this._writingBuf, "utf8", this.release);
        };
      } else {
        throw new Error(`SonicBoom supports "${kContentModeUtf8}" and "${kContentModeBuffer}", but passed ${contentMode}`);
      }
      if (typeof fd === "number") {
        this.fd = fd;
        process.nextTick(() => this.emit("ready"));
      } else if (typeof fd === "string") {
        openFile(fd, this);
      } else {
        throw new Error("SonicBoom supports only file descriptors and files");
      }
      if (this.minLength >= this.maxWrite) {
        throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);
      }
      this.release = (err, n) => {
        if (err) {
          if ((err.code === "EAGAIN" || err.code === "EBUSY") && this.retryEAGAIN(err, this._writingBuf.length, this._len - this._writingBuf.length)) {
            if (this.sync) {
              try {
                sleep(BUSY_WRITE_TIMEOUT);
                this.release(void 0, 0);
              } catch (err2) {
                this.release(err2);
              }
            } else {
              setTimeout(fsWrite, BUSY_WRITE_TIMEOUT);
            }
          } else {
            this._writing = false;
            this.emit("error", err);
          }
          return;
        }
        this.emit("write", n);
        const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n);
        this._len = releasedBufObj.len;
        this._writingBuf = releasedBufObj.writingBuf;
        if (this._writingBuf.length) {
          if (!this.sync) {
            fsWrite();
            return;
          }
          try {
            do {
              const n2 = fsWriteSync();
              const releasedBufObj2 = releaseWritingBuf(this._writingBuf, this._len, n2);
              this._len = releasedBufObj2.len;
              this._writingBuf = releasedBufObj2.writingBuf;
            } while (this._writingBuf.length);
          } catch (err2) {
            this.release(err2);
            return;
          }
        }
        if (this._fsync) {
          fs2.fsyncSync(this.fd);
        }
        const len = this._len;
        if (this._reopening) {
          this._writing = false;
          this._reopening = false;
          this.reopen();
        } else if (len > this.minLength) {
          this._actualWrite();
        } else if (this._ending) {
          if (len > 0) {
            this._actualWrite();
          } else {
            this._writing = false;
            actualClose(this);
          }
        } else {
          this._writing = false;
          if (this.sync) {
            if (!this._asyncDrainScheduled) {
              this._asyncDrainScheduled = true;
              process.nextTick(emitDrain, this);
            }
          } else {
            this.emit("drain");
          }
        }
      };
      this.on("newListener", function(name) {
        if (name === "drain") {
          this._asyncDrainScheduled = false;
        }
      });
      if (this._periodicFlush !== 0) {
        this._periodicFlushTimer = setInterval(() => this.flush(null), this._periodicFlush);
        this._periodicFlushTimer.unref();
      }
    }
    function releaseWritingBuf(writingBuf, len, n) {
      if (typeof writingBuf === "string") {
        writingBuf = Buffer.from(writingBuf);
      }
      len = Math.max(len - n, 0);
      writingBuf = writingBuf.subarray(n);
      return { writingBuf, len };
    }
    function emitDrain(sonic) {
      const hasListeners = sonic.listenerCount("drain") > 0;
      if (!hasListeners) return;
      sonic._asyncDrainScheduled = false;
      sonic.emit("drain");
    }
    inherits(SonicBoom, EventEmitter2);
    function mergeBuf(bufs, len) {
      if (bufs.length === 0) {
        return kEmptyBuffer;
      }
      if (bufs.length === 1) {
        return bufs[0];
      }
      return Buffer.concat(bufs, len);
    }
    function write(data) {
      if (this.destroyed) {
        throw new Error("SonicBoom destroyed");
      }
      data = "" + data;
      const dataLen = Buffer.byteLength(data);
      const len = this._len + dataLen;
      const bufs = this._bufs;
      if (this.maxLength && len > this.maxLength) {
        this.emit("drop", data);
        return this._len < this._hwm;
      }
      if (bufs.length === 0 || Buffer.byteLength(bufs[bufs.length - 1]) + dataLen > this.maxWrite) {
        bufs.push(data);
      } else {
        bufs[bufs.length - 1] += data;
      }
      this._len = len;
      if (!this._writing && this._len >= this.minLength) {
        this._actualWrite();
      }
      return this._len < this._hwm;
    }
    function writeBuffer(data) {
      if (this.destroyed) {
        throw new Error("SonicBoom destroyed");
      }
      const len = this._len + data.length;
      const bufs = this._bufs;
      const lens = this._lens;
      if (this.maxLength && len > this.maxLength) {
        this.emit("drop", data);
        return this._len < this._hwm;
      }
      if (bufs.length === 0 || lens[lens.length - 1] + data.length > this.maxWrite) {
        bufs.push([data]);
        lens.push(data.length);
      } else {
        bufs[bufs.length - 1].push(data);
        lens[lens.length - 1] += data.length;
      }
      this._len = len;
      if (!this._writing && this._len >= this.minLength) {
        this._actualWrite();
      }
      return this._len < this._hwm;
    }
    function callFlushCallbackOnDrain(cb) {
      this._flushPending = true;
      const onDrain = () => {
        if (!this._fsync) {
          try {
            fs2.fsync(this.fd, (err) => {
              this._flushPending = false;
              cb(err);
            });
          } catch (err) {
            cb(err);
          }
        } else {
          this._flushPending = false;
          cb();
        }
        this.off("error", onError);
      };
      const onError = (err) => {
        this._flushPending = false;
        cb(err);
        this.off("drain", onDrain);
      };
      this.once("drain", onDrain);
      this.once("error", onError);
    }
    function flush(cb) {
      if (cb != null && typeof cb !== "function") {
        throw new Error("flush cb must be a function");
      }
      if (this.destroyed) {
        const error40 = new Error("SonicBoom destroyed");
        if (cb) {
          cb(error40);
          return;
        }
        throw error40;
      }
      if (this.minLength <= 0) {
        cb?.();
        return;
      }
      if (cb) {
        callFlushCallbackOnDrain.call(this, cb);
      }
      if (this._writing) {
        return;
      }
      if (this._bufs.length === 0) {
        this._bufs.push("");
      }
      this._actualWrite();
    }
    function flushBuffer(cb) {
      if (cb != null && typeof cb !== "function") {
        throw new Error("flush cb must be a function");
      }
      if (this.destroyed) {
        const error40 = new Error("SonicBoom destroyed");
        if (cb) {
          cb(error40);
          return;
        }
        throw error40;
      }
      if (this.minLength <= 0) {
        cb?.();
        return;
      }
      if (cb) {
        callFlushCallbackOnDrain.call(this, cb);
      }
      if (this._writing) {
        return;
      }
      if (this._bufs.length === 0) {
        this._bufs.push([]);
        this._lens.push(0);
      }
      this._actualWrite();
    }
    SonicBoom.prototype.reopen = function(file2) {
      if (this.destroyed) {
        throw new Error("SonicBoom destroyed");
      }
      if (this._opening) {
        this.once("ready", () => {
          this.reopen(file2);
        });
        return;
      }
      if (this._ending) {
        return;
      }
      if (!this.file) {
        throw new Error("Unable to reopen a file descriptor, you must pass a file to SonicBoom");
      }
      if (file2) {
        this.file = file2;
      }
      this._reopening = true;
      if (this._writing) {
        return;
      }
      const fd = this.fd;
      this.once("ready", () => {
        if (fd !== this.fd) {
          fs2.close(fd, (err) => {
            if (err) {
              return this.emit("error", err);
            }
          });
        }
      });
      openFile(this.file, this);
    };
    SonicBoom.prototype.end = function() {
      if (this.destroyed) {
        throw new Error("SonicBoom destroyed");
      }
      if (this._opening) {
        this.once("ready", () => {
          this.end();
        });
        return;
      }
      if (this._ending) {
        return;
      }
      this._ending = true;
      if (this._writing) {
        return;
      }
      if (this._len > 0 && this.fd >= 0) {
        this._actualWrite();
      } else {
        actualClose(this);
      }
    };
    function flushSync() {
      if (this.destroyed) {
        throw new Error("SonicBoom destroyed");
      }
      if (this.fd < 0) {
        throw new Error("sonic boom is not ready yet");
      }
      if (!this._writing && this._writingBuf.length > 0) {
        this._bufs.unshift(this._writingBuf);
        this._writingBuf = "";
      }
      let buf = "";
      while (this._bufs.length || buf.length) {
        if (buf.length <= 0) {
          buf = this._bufs[0];
        }
        try {
          const n = Buffer.isBuffer(buf) ? fs2.writeSync(this.fd, buf) : fs2.writeSync(this.fd, buf, "utf8");
          const releasedBufObj = releaseWritingBuf(buf, this._len, n);
          buf = releasedBufObj.writingBuf;
          this._len = releasedBufObj.len;
          if (buf.length <= 0) {
            this._bufs.shift();
          }
        } catch (err) {
          const shouldRetry = err.code === "EAGAIN" || err.code === "EBUSY";
          if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {
            throw err;
          }
          sleep(BUSY_WRITE_TIMEOUT);
        }
      }
      try {
        fs2.fsyncSync(this.fd);
      } catch {
      }
    }
    function flushBufferSync() {
      if (this.destroyed) {
        throw new Error("SonicBoom destroyed");
      }
      if (this.fd < 0) {
        throw new Error("sonic boom is not ready yet");
      }
      if (!this._writing && this._writingBuf.length > 0) {
        this._bufs.unshift([this._writingBuf]);
        this._writingBuf = kEmptyBuffer;
      }
      let buf = kEmptyBuffer;
      while (this._bufs.length || buf.length) {
        if (buf.length <= 0) {
          buf = mergeBuf(this._bufs[0], this._lens[0]);
        }
        try {
          const n = fs2.writeSync(this.fd, buf);
          buf = buf.subarray(n);
          this._len = Math.max(this._len - n, 0);
          if (buf.length <= 0) {
            this._bufs.shift();
            this._lens.shift();
          }
        } catch (err) {
          const shouldRetry = err.code === "EAGAIN" || err.code === "EBUSY";
          if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {
            throw err;
          }
          sleep(BUSY_WRITE_TIMEOUT);
        }
      }
    }
    SonicBoom.prototype.destroy = function() {
      if (this.destroyed) {
        return;
      }
      actualClose(this);
    };
    function actualWrite() {
      const release = this.release;
      this._writing = true;
      this._writingBuf = this._writingBuf.length ? this._writingBuf : this._bufs.shift() || "";
      if (this.sync) {
        try {
          const written = Buffer.isBuffer(this._writingBuf) ? fs2.writeSync(this.fd, this._writingBuf) : fs2.writeSync(this.fd, this._writingBuf, "utf8");
          release(null, written);
        } catch (err) {
          release(err);
        }
      } else {
        fs2.write(this.fd, this._writingBuf, release);
      }
    }
    function actualWriteBuffer() {
      const release = this.release;
      this._writing = true;
      this._writingBuf = this._writingBuf.length ? this._writingBuf : mergeBuf(this._bufs.shift(), this._lens.shift());
      if (this.sync) {
        try {
          const written = fs2.writeSync(this.fd, this._writingBuf);
          release(null, written);
        } catch (err) {
          release(err);
        }
      } else {
        if (kCopyBuffer) {
          this._writingBuf = Buffer.from(this._writingBuf);
        }
        fs2.write(this.fd, this._writingBuf, release);
      }
    }
    function actualClose(sonic) {
      if (sonic.fd === -1) {
        sonic.once("ready", actualClose.bind(null, sonic));
        return;
      }
      if (sonic._periodicFlushTimer !== void 0) {
        clearInterval(sonic._periodicFlushTimer);
      }
      sonic.destroyed = true;
      sonic._bufs = [];
      sonic._lens = [];
      assert2(typeof sonic.fd === "number", `sonic.fd must be a number, got ${typeof sonic.fd}`);
      try {
        fs2.fsync(sonic.fd, closeWrapped);
      } catch {
      }
      function closeWrapped() {
        if (sonic.fd !== 1 && sonic.fd !== 2) {
          fs2.close(sonic.fd, done);
        } else {
          done();
        }
      }
      function done(err) {
        if (err) {
          sonic.emit("error", err);
          return;
        }
        if (sonic._ending && !sonic._writing) {
          sonic.emit("finish");
        }
        sonic.emit("close");
      }
    }
    SonicBoom.SonicBoom = SonicBoom;
    SonicBoom.default = SonicBoom;
    module.exports = SonicBoom;
  }
});

// ../../node_modules/.pnpm/on-exit-leak-free@2.1.2/node_modules/on-exit-leak-free/index.js
var require_on_exit_leak_free = __commonJS({
  "../../node_modules/.pnpm/on-exit-leak-free@2.1.2/node_modules/on-exit-leak-free/index.js"(exports, module) {
    "use strict";
    var refs = {
      exit: [],
      beforeExit: []
    };
    var functions = {
      exit: onExit,
      beforeExit: onBeforeExit
    };
    var registry2;
    function ensureRegistry() {
      if (registry2 === void 0) {
        registry2 = new FinalizationRegistry(clear);
      }
    }
    function install(event) {
      if (refs[event].length > 0) {
        return;
      }
      process.on(event, functions[event]);
    }
    function uninstall(event) {
      if (refs[event].length > 0) {
        return;
      }
      process.removeListener(event, functions[event]);
      if (refs.exit.length === 0 && refs.beforeExit.length === 0) {
        registry2 = void 0;
      }
    }
    function onExit() {
      callRefs("exit");
    }
    function onBeforeExit() {
      callRefs("beforeExit");
    }
    function callRefs(event) {
      for (const ref of refs[event]) {
        const obj = ref.deref();
        const fn = ref.fn;
        if (obj !== void 0) {
          fn(obj, event);
        }
      }
      refs[event] = [];
    }
    function clear(ref) {
      for (const event of ["exit", "beforeExit"]) {
        const index2 = refs[event].indexOf(ref);
        refs[event].splice(index2, index2 + 1);
        uninstall(event);
      }
    }
    function _register(event, obj, fn) {
      if (obj === void 0) {
        throw new Error("the object can't be undefined");
      }
      install(event);
      const ref = new WeakRef(obj);
      ref.fn = fn;
      ensureRegistry();
      registry2.register(obj, ref);
      refs[event].push(ref);
    }
    function register(obj, fn) {
      _register("exit", obj, fn);
    }
    function registerBeforeExit(obj, fn) {
      _register("beforeExit", obj, fn);
    }
    function unregister(obj) {
      if (registry2 === void 0) {
        return;
      }
      registry2.unregister(obj);
      for (const event of ["exit", "beforeExit"]) {
        refs[event] = refs[event].filter((ref) => {
          const _obj = ref.deref();
          return _obj && _obj !== obj;
        });
        uninstall(event);
      }
    }
    module.exports = {
      register,
      registerBeforeExit,
      unregister
    };
  }
});

// ../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/package.json
var require_package = __commonJS({
  "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/package.json"(exports, module) {
    module.exports = {
      name: "thread-stream",
      version: "3.1.0",
      description: "A streaming way to send data to a Node.js Worker Thread",
      main: "index.js",
      types: "index.d.ts",
      dependencies: {
        "real-require": "^0.2.0"
      },
      devDependencies: {
        "@types/node": "^20.1.0",
        "@types/tap": "^15.0.0",
        "@yao-pkg/pkg": "^5.11.5",
        desm: "^1.3.0",
        fastbench: "^1.0.1",
        husky: "^9.0.6",
        "pino-elasticsearch": "^8.0.0",
        "sonic-boom": "^4.0.1",
        standard: "^17.0.0",
        tap: "^16.2.0",
        "ts-node": "^10.8.0",
        typescript: "^5.3.2",
        "why-is-node-running": "^2.2.2"
      },
      scripts: {
        build: "tsc --noEmit",
        test: 'standard && npm run build && npm run transpile && tap "test/**/*.test.*js" && tap --ts test/*.test.*ts',
        "test:ci": "standard && npm run transpile && npm run test:ci:js && npm run test:ci:ts",
        "test:ci:js": 'tap --no-check-coverage --timeout=120 --coverage-report=lcovonly "test/**/*.test.*js"',
        "test:ci:ts": 'tap --ts --no-check-coverage --coverage-report=lcovonly "test/**/*.test.*ts"',
        "test:yarn": 'npm run transpile && tap "test/**/*.test.js" --no-check-coverage',
        transpile: "sh ./test/ts/transpile.sh",
        prepare: "husky install"
      },
      standard: {
        ignore: [
          "test/ts/**/*",
          "test/syntax-error.mjs"
        ]
      },
      repository: {
        type: "git",
        url: "git+https://github.com/mcollina/thread-stream.git"
      },
      keywords: [
        "worker",
        "thread",
        "threads",
        "stream"
      ],
      author: "Matteo Collina <hello@matteocollina.com>",
      license: "MIT",
      bugs: {
        url: "https://github.com/mcollina/thread-stream/issues"
      },
      homepage: "https://github.com/mcollina/thread-stream#readme"
    };
  }
});

// ../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/wait.js
var require_wait = __commonJS({
  "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/wait.js"(exports, module) {
    "use strict";
    var MAX_TIMEOUT = 1e3;
    function wait(state, index2, expected, timeout, done) {
      const max = Date.now() + timeout;
      let current = Atomics.load(state, index2);
      if (current === expected) {
        done(null, "ok");
        return;
      }
      let prior = current;
      const check2 = (backoff) => {
        if (Date.now() > max) {
          done(null, "timed-out");
        } else {
          setTimeout(() => {
            prior = current;
            current = Atomics.load(state, index2);
            if (current === prior) {
              check2(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff * 2);
            } else {
              if (current === expected) done(null, "ok");
              else done(null, "not-equal");
            }
          }, backoff);
        }
      };
      check2(1);
    }
    function waitDiff(state, index2, expected, timeout, done) {
      const max = Date.now() + timeout;
      let current = Atomics.load(state, index2);
      if (current !== expected) {
        done(null, "ok");
        return;
      }
      const check2 = (backoff) => {
        if (Date.now() > max) {
          done(null, "timed-out");
        } else {
          setTimeout(() => {
            current = Atomics.load(state, index2);
            if (current !== expected) {
              done(null, "ok");
            } else {
              check2(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff * 2);
            }
          }, backoff);
        }
      };
      check2(1);
    }
    module.exports = { wait, waitDiff };
  }
});

// ../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/indexes.js
var require_indexes = __commonJS({
  "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/indexes.js"(exports, module) {
    "use strict";
    var WRITE_INDEX = 4;
    var READ_INDEX = 8;
    module.exports = {
      WRITE_INDEX,
      READ_INDEX
    };
  }
});

// ../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/index.js
var require_thread_stream = __commonJS({
  "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/index.js"(exports, module) {
    "use strict";
    var { version: version3 } = require_package();
    var { EventEmitter: EventEmitter2 } = __require("events");
    var { Worker } = __require("worker_threads");
    var { join } = __require("path");
    var { pathToFileURL } = __require("url");
    var { wait } = require_wait();
    var {
      WRITE_INDEX,
      READ_INDEX
    } = require_indexes();
    var buffer = __require("buffer");
    var assert2 = __require("assert");
    var kImpl = /* @__PURE__ */ Symbol("kImpl");
    var MAX_STRING = buffer.constants.MAX_STRING_LENGTH;
    var FakeWeakRef = class {
      constructor(value) {
        this._value = value;
      }
      deref() {
        return this._value;
      }
    };
    var FakeFinalizationRegistry = class {
      register() {
      }
      unregister() {
      }
    };
    var FinalizationRegistry2 = process.env.NODE_V8_COVERAGE ? FakeFinalizationRegistry : global.FinalizationRegistry || FakeFinalizationRegistry;
    var WeakRef2 = process.env.NODE_V8_COVERAGE ? FakeWeakRef : global.WeakRef || FakeWeakRef;
    var registry2 = new FinalizationRegistry2((worker) => {
      if (worker.exited) {
        return;
      }
      worker.terminate();
    });
    function createWorker(stream, opts) {
      const { filename, workerData } = opts;
      const bundlerOverrides = "__bundlerPathsOverrides" in globalThis ? globalThis.__bundlerPathsOverrides : {};
      const toExecute = bundlerOverrides["thread-stream-worker"] || join(__dirname, "lib", "worker.js");
      const worker = new Worker(toExecute, {
        ...opts.workerOpts,
        trackUnmanagedFds: false,
        workerData: {
          filename: filename.indexOf("file://") === 0 ? filename : pathToFileURL(filename).href,
          dataBuf: stream[kImpl].dataBuf,
          stateBuf: stream[kImpl].stateBuf,
          workerData: {
            $context: {
              threadStreamVersion: version3
            },
            ...workerData
          }
        }
      });
      worker.stream = new FakeWeakRef(stream);
      worker.on("message", onWorkerMessage);
      worker.on("exit", onWorkerExit);
      registry2.register(stream, worker);
      return worker;
    }
    function drain(stream) {
      assert2(!stream[kImpl].sync);
      if (stream[kImpl].needDrain) {
        stream[kImpl].needDrain = false;
        stream.emit("drain");
      }
    }
    function nextFlush(stream) {
      const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX);
      let leftover = stream[kImpl].data.length - writeIndex;
      if (leftover > 0) {
        if (stream[kImpl].buf.length === 0) {
          stream[kImpl].flushing = false;
          if (stream[kImpl].ending) {
            end(stream);
          } else if (stream[kImpl].needDrain) {
            process.nextTick(drain, stream);
          }
          return;
        }
        let toWrite = stream[kImpl].buf.slice(0, leftover);
        let toWriteBytes = Buffer.byteLength(toWrite);
        if (toWriteBytes <= leftover) {
          stream[kImpl].buf = stream[kImpl].buf.slice(leftover);
          write(stream, toWrite, nextFlush.bind(null, stream));
        } else {
          stream.flush(() => {
            if (stream.destroyed) {
              return;
            }
            Atomics.store(stream[kImpl].state, READ_INDEX, 0);
            Atomics.store(stream[kImpl].state, WRITE_INDEX, 0);
            while (toWriteBytes > stream[kImpl].data.length) {
              leftover = leftover / 2;
              toWrite = stream[kImpl].buf.slice(0, leftover);
              toWriteBytes = Buffer.byteLength(toWrite);
            }
            stream[kImpl].buf = stream[kImpl].buf.slice(leftover);
            write(stream, toWrite, nextFlush.bind(null, stream));
          });
        }
      } else if (leftover === 0) {
        if (writeIndex === 0 && stream[kImpl].buf.length === 0) {
          return;
        }
        stream.flush(() => {
          Atomics.store(stream[kImpl].state, READ_INDEX, 0);
          Atomics.store(stream[kImpl].state, WRITE_INDEX, 0);
          nextFlush(stream);
        });
      } else {
        destroy(stream, new Error("overwritten"));
      }
    }
    function onWorkerMessage(msg) {
      const stream = this.stream.deref();
      if (stream === void 0) {
        this.exited = true;
        this.terminate();
        return;
      }
      switch (msg.code) {
        case "READY":
          this.stream = new WeakRef2(stream);
          stream.flush(() => {
            stream[kImpl].ready = true;
            stream.emit("ready");
          });
          break;
        case "ERROR":
          destroy(stream, msg.err);
          break;
        case "EVENT":
          if (Array.isArray(msg.args)) {
            stream.emit(msg.name, ...msg.args);
          } else {
            stream.emit(msg.name, msg.args);
          }
          break;
        case "WARNING":
          process.emitWarning(msg.err);
          break;
        default:
          destroy(stream, new Error("this should not happen: " + msg.code));
      }
    }
    function onWorkerExit(code) {
      const stream = this.stream.deref();
      if (stream === void 0) {
        return;
      }
      registry2.unregister(stream);
      stream.worker.exited = true;
      stream.worker.off("exit", onWorkerExit);
      destroy(stream, code !== 0 ? new Error("the worker thread exited") : null);
    }
    var ThreadStream = class extends EventEmitter2 {
      constructor(opts = {}) {
        super();
        if (opts.bufferSize < 4) {
          throw new Error("bufferSize must at least fit a 4-byte utf-8 char");
        }
        this[kImpl] = {};
        this[kImpl].stateBuf = new SharedArrayBuffer(128);
        this[kImpl].state = new Int32Array(this[kImpl].stateBuf);
        this[kImpl].dataBuf = new SharedArrayBuffer(opts.bufferSize || 4 * 1024 * 1024);
        this[kImpl].data = Buffer.from(this[kImpl].dataBuf);
        this[kImpl].sync = opts.sync || false;
        this[kImpl].ending = false;
        this[kImpl].ended = false;
        this[kImpl].needDrain = false;
        this[kImpl].destroyed = false;
        this[kImpl].flushing = false;
        this[kImpl].ready = false;
        this[kImpl].finished = false;
        this[kImpl].errored = null;
        this[kImpl].closed = false;
        this[kImpl].buf = "";
        this.worker = createWorker(this, opts);
        this.on("message", (message, transferList) => {
          this.worker.postMessage(message, transferList);
        });
      }
      write(data) {
        if (this[kImpl].destroyed) {
          error40(this, new Error("the worker has exited"));
          return false;
        }
        if (this[kImpl].ending) {
          error40(this, new Error("the worker is ending"));
          return false;
        }
        if (this[kImpl].flushing && this[kImpl].buf.length + data.length >= MAX_STRING) {
          try {
            writeSync(this);
            this[kImpl].flushing = true;
          } catch (err) {
            destroy(this, err);
            return false;
          }
        }
        this[kImpl].buf += data;
        if (this[kImpl].sync) {
          try {
            writeSync(this);
            return true;
          } catch (err) {
            destroy(this, err);
            return false;
          }
        }
        if (!this[kImpl].flushing) {
          this[kImpl].flushing = true;
          setImmediate(nextFlush, this);
        }
        this[kImpl].needDrain = this[kImpl].data.length - this[kImpl].buf.length - Atomics.load(this[kImpl].state, WRITE_INDEX) <= 0;
        return !this[kImpl].needDrain;
      }
      end() {
        if (this[kImpl].destroyed) {
          return;
        }
        this[kImpl].ending = true;
        end(this);
      }
      flush(cb) {
        if (this[kImpl].destroyed) {
          if (typeof cb === "function") {
            process.nextTick(cb, new Error("the worker has exited"));
          }
          return;
        }
        const writeIndex = Atomics.load(this[kImpl].state, WRITE_INDEX);
        wait(this[kImpl].state, READ_INDEX, writeIndex, Infinity, (err, res) => {
          if (err) {
            destroy(this, err);
            process.nextTick(cb, err);
            return;
          }
          if (res === "not-equal") {
            this.flush(cb);
            return;
          }
          process.nextTick(cb);
        });
      }
      flushSync() {
        if (this[kImpl].destroyed) {
          return;
        }
        writeSync(this);
        flushSync(this);
      }
      unref() {
        this.worker.unref();
      }
      ref() {
        this.worker.ref();
      }
      get ready() {
        return this[kImpl].ready;
      }
      get destroyed() {
        return this[kImpl].destroyed;
      }
      get closed() {
        return this[kImpl].closed;
      }
      get writable() {
        return !this[kImpl].destroyed && !this[kImpl].ending;
      }
      get writableEnded() {
        return this[kImpl].ending;
      }
      get writableFinished() {
        return this[kImpl].finished;
      }
      get writableNeedDrain() {
        return this[kImpl].needDrain;
      }
      get writableObjectMode() {
        return false;
      }
      get writableErrored() {
        return this[kImpl].errored;
      }
    };
    function error40(stream, err) {
      setImmediate(() => {
        stream.emit("error", err);
      });
    }
    function destroy(stream, err) {
      if (stream[kImpl].destroyed) {
        return;
      }
      stream[kImpl].destroyed = true;
      if (err) {
        stream[kImpl].errored = err;
        error40(stream, err);
      }
      if (!stream.worker.exited) {
        stream.worker.terminate().catch(() => {
        }).then(() => {
          stream[kImpl].closed = true;
          stream.emit("close");
        });
      } else {
        setImmediate(() => {
          stream[kImpl].closed = true;
          stream.emit("close");
        });
      }
    }
    function write(stream, data, cb) {
      const current = Atomics.load(stream[kImpl].state, WRITE_INDEX);
      const length = Buffer.byteLength(data);
      stream[kImpl].data.write(data, current);
      Atomics.store(stream[kImpl].state, WRITE_INDEX, current + length);
      Atomics.notify(stream[kImpl].state, WRITE_INDEX);
      cb();
      return true;
    }
    function end(stream) {
      if (stream[kImpl].ended || !stream[kImpl].ending || stream[kImpl].flushing) {
        return;
      }
      stream[kImpl].ended = true;
      try {
        stream.flushSync();
        let readIndex = Atomics.load(stream[kImpl].state, READ_INDEX);
        Atomics.store(stream[kImpl].state, WRITE_INDEX, -1);
        Atomics.notify(stream[kImpl].state, WRITE_INDEX);
        let spins = 0;
        while (readIndex !== -1) {
          Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1e3);
          readIndex = Atomics.load(stream[kImpl].state, READ_INDEX);
          if (readIndex === -2) {
            destroy(stream, new Error("end() failed"));
            return;
          }
          if (++spins === 10) {
            destroy(stream, new Error("end() took too long (10s)"));
            return;
          }
        }
        process.nextTick(() => {
          stream[kImpl].finished = true;
          stream.emit("finish");
        });
      } catch (err) {
        destroy(stream, err);
      }
    }
    function writeSync(stream) {
      const cb = () => {
        if (stream[kImpl].ending) {
          end(stream);
        } else if (stream[kImpl].needDrain) {
          process.nextTick(drain, stream);
        }
      };
      stream[kImpl].flushing = false;
      while (stream[kImpl].buf.length !== 0) {
        const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX);
        let leftover = stream[kImpl].data.length - writeIndex;
        if (leftover === 0) {
          flushSync(stream);
          Atomics.store(stream[kImpl].state, READ_INDEX, 0);
          Atomics.store(stream[kImpl].state, WRITE_INDEX, 0);
          continue;
        } else if (leftover < 0) {
          throw new Error("overwritten");
        }
        let toWrite = stream[kImpl].buf.slice(0, leftover);
        let toWriteBytes = Buffer.byteLength(toWrite);
        if (toWriteBytes <= leftover) {
          stream[kImpl].buf = stream[kImpl].buf.slice(leftover);
          write(stream, toWrite, cb);
        } else {
          flushSync(stream);
          Atomics.store(stream[kImpl].state, READ_INDEX, 0);
          Atomics.store(stream[kImpl].state, WRITE_INDEX, 0);
          while (toWriteBytes > stream[kImpl].buf.length) {
            leftover = leftover / 2;
            toWrite = stream[kImpl].buf.slice(0, leftover);
            toWriteBytes = Buffer.byteLength(toWrite);
          }
          stream[kImpl].buf = stream[kImpl].buf.slice(leftover);
          write(stream, toWrite, cb);
        }
      }
    }
    function flushSync(stream) {
      if (stream[kImpl].flushing) {
        throw new Error("unable to flush while flushing");
      }
      const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX);
      let spins = 0;
      while (true) {
        const readIndex = Atomics.load(stream[kImpl].state, READ_INDEX);
        if (readIndex === -2) {
          throw Error("_flushSync failed");
        }
        if (readIndex !== writeIndex) {
          Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1e3);
        } else {
          break;
        }
        if (++spins === 10) {
          throw new Error("_flushSync took too long (10s)");
        }
      }
    }
    module.exports = ThreadStream;
  }
});

// ../../node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/transport.js
var require_transport = __commonJS({
  "../../node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/transport.js"(exports, module) {
    "use strict";
    var { createRequire } = __require("module");
    var getCallers = require_caller();
    var { join, isAbsolute, sep } = __require("node:path");
    var sleep = require_atomic_sleep();
    var onExit = require_on_exit_leak_free();
    var ThreadStream = require_thread_stream();
    function setupOnExit(stream) {
      onExit.register(stream, autoEnd);
      onExit.registerBeforeExit(stream, flush);
      stream.on("close", function() {
        onExit.unregister(stream);
      });
    }
    function buildStream(filename, workerData, workerOpts, sync) {
      const stream = new ThreadStream({
        filename,
        workerData,
        workerOpts,
        sync
      });
      stream.on("ready", onReady);
      stream.on("close", function() {
        process.removeListener("exit", onExit2);
      });
      process.on("exit", onExit2);
      function onReady() {
        process.removeListener("exit", onExit2);
        stream.unref();
        if (workerOpts.autoEnd !== false) {
          setupOnExit(stream);
        }
      }
      function onExit2() {
        if (stream.closed) {
          return;
        }
        stream.flushSync();
        sleep(100);
        stream.end();
      }
      return stream;
    }
    function autoEnd(stream) {
      stream.ref();
      stream.flushSync();
      stream.end();
      stream.once("close", function() {
        stream.unref();
      });
    }
    function flush(stream) {
      stream.flushSync();
    }
    function transport(fullOptions) {
      const { pipeline, targets, levels, dedupe, worker = {}, caller = getCallers(), sync = false } = fullOptions;
      const options = {
        ...fullOptions.options
      };
      const callers = typeof caller === "string" ? [caller] : caller;
      const bundlerOverrides = "__bundlerPathsOverrides" in globalThis ? globalThis.__bundlerPathsOverrides : {};
      let target = fullOptions.target;
      if (target && targets) {
        throw new Error("only one of target or targets can be specified");
      }
      if (targets) {
        target = bundlerOverrides["pino-worker"] || join(__dirname, "worker.js");
        options.targets = targets.filter((dest) => dest.target).map((dest) => {
          return {
            ...dest,
            target: fixTarget(dest.target)
          };
        });
        options.pipelines = targets.filter((dest) => dest.pipeline).map((dest) => {
          return dest.pipeline.map((t) => {
            return {
              ...t,
              level: dest.level,
              // duplicate the pipeline `level` property defined in the upper level
              target: fixTarget(t.target)
            };
          });
        });
      } else if (pipeline) {
        target = bundlerOverrides["pino-worker"] || join(__dirname, "worker.js");
        options.pipelines = [pipeline.map((dest) => {
          return {
            ...dest,
            target: fixTarget(dest.target)
          };
        })];
      }
      if (levels) {
        options.levels = levels;
      }
      if (dedupe) {
        options.dedupe = dedupe;
      }
      options.pinoWillSendConfig = true;
      return buildStream(fixTarget(target), options, worker, sync);
      function fixTarget(origin) {
        origin = bundlerOverrides[origin] || origin;
        if (isAbsolute(origin) || origin.indexOf("file://") === 0) {
          return origin;
        }
        if (origin === "pino/file") {
          return join(__dirname, "..", "file.js");
        }
        let fixTarget2;
        for (const filePath of callers) {
          try {
            const context = filePath === "node:repl" ? process.cwd() + sep : filePath;
            fixTarget2 = createRequire(context).resolve(origin);
            break;
          } catch (err) {
            continue;
          }
        }
        if (!fixTarget2) {
          throw new Error(`unable to determine transport target for "${origin}"`);
        }
        return fixTarget2;
      }
    }
    module.exports = transport;
  }
});

// ../../node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/tools.js
var require_tools = __commonJS({
  "../../node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/tools.js"(exports, module) {
    "use strict";
    var diagChan = __require("node:diagnostics_channel");
    var format = require_quick_format_unescaped();
    var { mapHttpRequest, mapHttpResponse } = require_pino_std_serializers();
    var SonicBoom = require_sonic_boom();
    var onExit = require_on_exit_leak_free();
    var {
      lsCacheSym,
      chindingsSym,
      writeSym,
      serializersSym,
      formatOptsSym,
      endSym,
      stringifiersSym,
      stringifySym,
      stringifySafeSym,
      wildcardFirstSym,
      nestedKeySym,
      formattersSym,
      messageKeySym,
      errorKeySym,
      nestedKeyStrSym,
      msgPrefixSym
    } = require_symbols();
    var { isMainThread } = __require("worker_threads");
    var transport = require_transport();
    var asJsonChan;
    if (typeof diagChan.tracingChannel === "function") {
      asJsonChan = diagChan.tracingChannel("pino_asJson");
    } else {
      asJsonChan = {
        hasSubscribers: false,
        traceSync(fn, store, thisArg, ...args) {
          return fn.call(thisArg, ...args);
        }
      };
    }
    function noop() {
    }
    function genLog(level, hook) {
      if (!hook) return LOG;
      return function hookWrappedLog(...args) {
        hook.call(this, args, LOG, level);
      };
      function LOG(o, ...n) {
        if (typeof o === "object") {
          let msg = o;
          if (o !== null) {
            if (o.method && o.headers && o.socket) {
              o = mapHttpRequest(o);
            } else if (typeof o.setHeader === "function") {
              o = mapHttpResponse(o);
            }
          }
          let formatParams;
          if (msg === null && n.length === 0) {
            formatParams = [null];
          } else {
            msg = n.shift();
            formatParams = n;
          }
          if (typeof this[msgPrefixSym] === "string" && msg !== void 0 && msg !== null) {
            msg = this[msgPrefixSym] + msg;
          }
          this[writeSym](o, format(msg, formatParams, this[formatOptsSym]), level);
        } else {
          let msg = o === void 0 ? n.shift() : o;
          if (typeof this[msgPrefixSym] === "string" && msg !== void 0 && msg !== null) {
            msg = this[msgPrefixSym] + msg;
          }
          this[writeSym](null, format(msg, n, this[formatOptsSym]), level);
        }
      }
    }
    function asString(str) {
      let result = "";
      let last = 0;
      let found = false;
      let point2 = 255;
      const l = str.length;
      if (l > 100) {
        return JSON.stringify(str);
      }
      for (var i = 0; i < l && point2 >= 32; i++) {
        point2 = str.charCodeAt(i);
        if (point2 === 34 || point2 === 92) {
          result += str.slice(last, i) + "\\";
          last = i;
          found = true;
        }
      }
      if (!found) {
        result = str;
      } else {
        result += str.slice(last);
      }
      return point2 < 32 ? JSON.stringify(str) : '"' + result + '"';
    }
    function asJson(obj, msg, num, time4) {
      if (asJsonChan.hasSubscribers === false) {
        return _asJson.call(this, obj, msg, num, time4);
      }
      const store = { instance: this, arguments };
      return asJsonChan.traceSync(_asJson, store, this, obj, msg, num, time4);
    }
    function _asJson(obj, msg, num, time4) {
      const stringify2 = this[stringifySym];
      const stringifySafe = this[stringifySafeSym];
      const stringifiers = this[stringifiersSym];
      const end = this[endSym];
      const chindings = this[chindingsSym];
      const serializers = this[serializersSym];
      const formatters = this[formattersSym];
      const messageKey = this[messageKeySym];
      const errorKey = this[errorKeySym];
      let data = this[lsCacheSym][num] + time4;
      data = data + chindings;
      let value;
      if (formatters.log) {
        obj = formatters.log(obj);
      }
      const wildcardStringifier = stringifiers[wildcardFirstSym];
      let propStr = "";
      for (const key in obj) {
        value = obj[key];
        if (Object.prototype.hasOwnProperty.call(obj, key) && value !== void 0) {
          if (serializers[key]) {
            value = serializers[key](value);
          } else if (key === errorKey && serializers.err) {
            value = serializers.err(value);
          }
          const stringifier = stringifiers[key] || wildcardStringifier;
          switch (typeof value) {
            case "undefined":
            case "function":
              continue;
            case "number":
              if (Number.isFinite(value) === false) {
                value = null;
              }
            // this case explicitly falls through to the next one
            case "boolean":
              if (stringifier) value = stringifier(value);
              break;
            case "string":
              value = (stringifier || asString)(value);
              break;
            default:
              value = (stringifier || stringify2)(value, stringifySafe);
          }
          if (value === void 0) continue;
          const strKey = asString(key);
          propStr += "," + strKey + ":" + value;
        }
      }
      let msgStr = "";
      if (msg !== void 0) {
        value = serializers[messageKey] ? serializers[messageKey](msg) : msg;
        const stringifier = stringifiers[messageKey] || wildcardStringifier;
        switch (typeof value) {
          case "function":
            break;
          case "number":
            if (Number.isFinite(value) === false) {
              value = null;
            }
          // this case explicitly falls through to the next one
          case "boolean":
            if (stringifier) value = stringifier(value);
            msgStr = ',"' + messageKey + '":' + value;
            break;
          case "string":
            value = (stringifier || asString)(value);
            msgStr = ',"' + messageKey + '":' + value;
            break;
          default:
            value = (stringifier || stringify2)(value, stringifySafe);
            msgStr = ',"' + messageKey + '":' + value;
        }
      }
      if (this[nestedKeySym] && propStr) {
        return data + this[nestedKeyStrSym] + propStr.slice(1) + "}" + msgStr + end;
      } else {
        return data + propStr + msgStr + end;
      }
    }
    function asChindings(instance, bindings) {
      let value;
      let data = instance[chindingsSym];
      const stringify2 = instance[stringifySym];
      const stringifySafe = instance[stringifySafeSym];
      const stringifiers = instance[stringifiersSym];
      const wildcardStringifier = stringifiers[wildcardFirstSym];
      const serializers = instance[serializersSym];
      const formatter = instance[formattersSym].bindings;
      bindings = formatter(bindings);
      for (const key in bindings) {
        value = bindings[key];
        const valid = (key.length < 5 || key !== "level" && key !== "serializers" && key !== "formatters" && key !== "customLevels") && bindings.hasOwnProperty(key) && value !== void 0;
        if (valid === true) {
          value = serializers[key] ? serializers[key](value) : value;
          value = (stringifiers[key] || wildcardStringifier || stringify2)(value, stringifySafe);
          if (value === void 0) continue;
          data += ',"' + key + '":' + value;
        }
      }
      return data;
    }
    function hasBeenTampered(stream) {
      return stream.write !== stream.constructor.prototype.write;
    }
    function buildSafeSonicBoom(opts) {
      const stream = new SonicBoom(opts);
      stream.on("error", filterBrokenPipe);
      if (!opts.sync && isMainThread) {
        onExit.register(stream, autoEnd);
        stream.on("close", function() {
          onExit.unregister(stream);
        });
      }
      return stream;
      function filterBrokenPipe(err) {
        if (err.code === "EPIPE") {
          stream.write = noop;
          stream.end = noop;
          stream.flushSync = noop;
          stream.destroy = noop;
          return;
        }
        stream.removeListener("error", filterBrokenPipe);
        stream.emit("error", err);
      }
    }
    function autoEnd(stream, eventName) {
      if (stream.destroyed) {
        return;
      }
      if (eventName === "beforeExit") {
        stream.flush();
        stream.on("drain", function() {
          stream.end();
        });
      } else {
        stream.flushSync();
      }
    }
    function createArgsNormalizer(defaultOptions) {
      return function normalizeArgs(instance, caller, opts = {}, stream) {
        if (typeof opts === "string") {
          stream = buildSafeSonicBoom({ dest: opts });
          opts = {};
        } else if (typeof stream === "string") {
          if (opts && opts.transport) {
            throw Error("only one of option.transport or stream can be specified");
          }
          stream = buildSafeSonicBoom({ dest: stream });
        } else if (opts instanceof SonicBoom || opts.writable || opts._writableState) {
          stream = opts;
          opts = {};
        } else if (opts.transport) {
          if (opts.transport instanceof SonicBoom || opts.transport.writable || opts.transport._writableState) {
            throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)");
          }
          if (opts.transport.targets && opts.transport.targets.length && opts.formatters && typeof opts.formatters.level === "function") {
            throw Error("option.transport.targets do not allow custom level formatters");
          }
          let customLevels;
          if (opts.customLevels) {
            customLevels = opts.useOnlyCustomLevels ? opts.customLevels : Object.assign({}, opts.levels, opts.customLevels);
          }
          stream = transport({ caller, ...opts.transport, levels: customLevels });
        }
        opts = Object.assign({}, defaultOptions, opts);
        opts.serializers = Object.assign({}, defaultOptions.serializers, opts.serializers);
        opts.formatters = Object.assign({}, defaultOptions.formatters, opts.formatters);
        if (opts.prettyPrint) {
          throw new Error("prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)");
        }
        const { enabled: enabled2, onChild } = opts;
        if (enabled2 === false) opts.level = "silent";
        if (!onChild) opts.onChild = noop;
        if (!stream) {
          if (!hasBeenTampered(process.stdout)) {
            stream = buildSafeSonicBoom({ fd: process.stdout.fd || 1 });
          } else {
            stream = process.stdout;
          }
        }
        return { opts, stream };
      };
    }
    function stringify(obj, stringifySafeFn) {
      try {
        return JSON.stringify(obj);
      } catch (_) {
        try {
          const stringify2 = stringifySafeFn || this[stringifySafeSym];
          return stringify2(obj);
        } catch (_2) {
          return '"[unable to serialize, circular reference is too complex to analyze]"';
        }
      }
    }
    function buildFormatters(level, bindings, log) {
      return {
        level,
        bindings,
        log
      };
    }
    function normalizeDestFileDescriptor(destination) {
      const fd = Number(destination);
      if (typeof destination === "string" && Number.isFinite(fd)) {
        return fd;
      }
      if (destination === void 0) {
        return 1;
      }
      return destination;
    }
    module.exports = {
      noop,
      buildSafeSonicBoom,
      asChindings,
      asJson,
      genLog,
      createArgsNormalizer,
      stringify,
      buildFormatters,
      normalizeDestFileDescriptor
    };
  }
});

// ../../node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/constants.js
var require_constants = __commonJS({
  "../../node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/constants.js"(exports, module) {
    var DEFAULT_LEVELS = {
      trace: 10,
      debug: 20,
      info: 30,
      warn: 40,
      error: 50,
      fatal: 60
    };
    var SORTING_ORDER = {
      ASC: "ASC",
      DESC: "DESC"
    };
    module.exports = {
      DEFAULT_LEVELS,
      SORTING_ORDER
    };
  }
});

// ../../node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/levels.js
var require_levels = __commonJS({
  "../../node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/levels.js"(exports, module) {
    "use strict";
    var {
      lsCacheSym,
      levelValSym,
      useOnlyCustomLevelsSym,
      streamSym,
      formattersSym,
      hooksSym,
      levelCompSym
    } = require_symbols();
    var { noop, genLog } = require_tools();
    var { DEFAULT_LEVELS, SORTING_ORDER } = require_constants();
    var levelMethods = {
      fatal: (hook) => {
        const logFatal = genLog(DEFAULT_LEVELS.fatal, hook);
        return function(...args) {
          const stream = this[streamSym];
          logFatal.call(this, ...args);
          if (typeof stream.flushSync === "function") {
            try {
              stream.flushSync();
            } catch (e) {
            }
          }
        };
      },
      error: (hook) => genLog(DEFAULT_LEVELS.error, hook),
      warn: (hook) => genLog(DEFAULT_LEVELS.warn, hook),
      info: (hook) => genLog(DEFAULT_LEVELS.info, hook),
      debug: (hook) => genLog(DEFAULT_LEVELS.debug, hook),
      trace: (hook) => genLog(DEFAULT_LEVELS.trace, hook)
    };
    var nums = Object.keys(DEFAULT_LEVELS).reduce((o, k) => {
      o[DEFAULT_LEVELS[k]] = k;
      return o;
    }, {});
    var initialLsCache = Object.keys(nums).reduce((o, k) => {
      o[k] = '{"level":' + Number(k);
      return o;
    }, {});
    function genLsCache(instance) {
      const formatter = instance[formattersSym].level;
      const { labels } = instance.levels;
      const cache = {};
      for (const label in labels) {
        const level = formatter(labels[label], Number(label));
        cache[label] = JSON.stringify(level).slice(0, -1);
      }
      instance[lsCacheSym] = cache;
      return instance;
    }
    function isStandardLevel(level, useOnlyCustomLevels) {
      if (useOnlyCustomLevels) {
        return false;
      }
      switch (level) {
        case "fatal":
        case "error":
        case "warn":
        case "info":
        case "debug":
        case "trace":
          return true;
        default:
          return false;
      }
    }
    function setLevel(level) {
      const { labels, values } = this.levels;
      if (typeof level === "number") {
        if (labels[level] === void 0) throw Error("unknown level value" + level);
        level = labels[level];
      }
      if (values[level] === void 0) throw Error("unknown level " + level);
      const preLevelVal = this[levelValSym];
      const levelVal = this[levelValSym] = values[level];
      const useOnlyCustomLevelsVal = this[useOnlyCustomLevelsSym];
      const levelComparison = this[levelCompSym];
      const hook = this[hooksSym].logMethod;
      for (const key in values) {
        if (levelComparison(values[key], levelVal) === false) {
          this[key] = noop;
          continue;
        }
        this[key] = isStandardLevel(key, useOnlyCustomLevelsVal) ? levelMethods[key](hook) : genLog(values[key], hook);
      }
      this.emit(
        "level-change",
        level,
        levelVal,
        labels[preLevelVal],
        preLevelVal,
        this
      );
    }
    function getLevel(level) {
      const { levels, levelVal } = this;
      return levels && levels.labels ? levels.labels[levelVal] : "";
    }
    function isLevelEnabled(logLevel) {
      const { values } = this.levels;
      const logLevelVal = values[logLevel];
      return logLevelVal !== void 0 && this[levelCompSym](logLevelVal, this[levelValSym]);
    }
    function compareLevel(direction, current, expected) {
      if (direction === SORTING_ORDER.DESC) {
        return current <= expected;
      }
      return current >= expected;
    }
    function genLevelComparison(levelComparison) {
      if (typeof levelComparison === "string") {
        return compareLevel.bind(null, levelComparison);
      }
      return levelComparison;
    }
    function mappings(customLevels = null, useOnlyCustomLevels = false) {
      const customNums = customLevels ? Object.keys(customLevels).reduce((o, k) => {
        o[customLevels[k]] = k;
        return o;
      }, {}) : null;
      const labels = Object.assign(
        Object.create(Object.prototype, { Infinity: { value: "silent" } }),
        useOnlyCustomLevels ? null : nums,
        customNums
      );
      const values = Object.assign(
        Object.create(Object.prototype, { silent: { value: Infinity } }),
        useOnlyCustomLevels ? null : DEFAULT_LEVELS,
        customLevels
      );
      return { labels, values };
    }
    function assertDefaultLevelFound(defaultLevel, customLevels, useOnlyCustomLevels) {
      if (typeof defaultLevel === "number") {
        const values = [].concat(
          Object.keys(customLevels || {}).map((key) => customLevels[key]),
          useOnlyCustomLevels ? [] : Object.keys(nums).map((level) => +level),
          Infinity
        );
        if (!values.includes(defaultLevel)) {
          throw Error(`default level:${defaultLevel} must be included in custom levels`);
        }
        return;
      }
      const labels = Object.assign(
        Object.create(Object.prototype, { silent: { value: Infinity } }),
        useOnlyCustomLevels ? null : DEFAULT_LEVELS,
        customLevels
      );
      if (!(defaultLevel in labels)) {
        throw Error(`default level:${defaultLevel} must be included in custom levels`);
      }
    }
    function assertNoLevelCollisions(levels, customLevels) {
      const { labels, values } = levels;
      for (const k in customLevels) {
        if (k in values) {
          throw Error("levels cannot be overridden");
        }
        if (customLevels[k] in labels) {
          throw Error("pre-existing level values cannot be used for new levels");
        }
      }
    }
    function assertLevelComparison(levelComparison) {
      if (typeof levelComparison === "function") {
        return;
      }
      if (typeof levelComparison === "string" && Object.values(SORTING_ORDER).includes(levelComparison)) {
        return;
      }
      throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type');
    }
    module.exports = {
      initialLsCache,
      genLsCache,
      levelMethods,
      getLevel,
      setLevel,
      isLevelEnabled,
      mappings,
      assertNoLevelCollisions,
      assertDefaultLevelFound,
      genLevelComparison,
      assertLevelComparison
    };
  }
});

// ../../node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/meta.js
var require_meta = __commonJS({
  "../../node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/meta.js"(exports, module) {
    "use strict";
    module.exports = { version: "9.14.0" };
  }
});

// ../../node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/proto.js
var require_proto = __commonJS({
  "../../node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/proto.js"(exports, module) {
    "use strict";
    var { EventEmitter: EventEmitter2 } = __require("node:events");
    var {
      lsCacheSym,
      levelValSym,
      setLevelSym,
      getLevelSym,
      chindingsSym,
      parsedChindingsSym,
      mixinSym,
      asJsonSym,
      writeSym,
      mixinMergeStrategySym,
      timeSym,
      timeSliceIndexSym,
      streamSym,
      serializersSym,
      formattersSym,
      errorKeySym,
      messageKeySym,
      useOnlyCustomLevelsSym,
      needsMetadataGsym,
      redactFmtSym,
      stringifySym,
      formatOptsSym,
      stringifiersSym,
      msgPrefixSym,
      hooksSym
    } = require_symbols();
    var {
      getLevel,
      setLevel,
      isLevelEnabled,
      mappings,
      initialLsCache,
      genLsCache,
      assertNoLevelCollisions
    } = require_levels();
    var {
      asChindings,
      asJson,
      buildFormatters,
      stringify,
      noop
    } = require_tools();
    var {
      version: version3
    } = require_meta();
    var redaction = require_redaction();
    var constructor = class Pino {
    };
    var prototype = {
      constructor,
      child,
      bindings,
      setBindings,
      flush,
      isLevelEnabled,
      version: version3,
      get level() {
        return this[getLevelSym]();
      },
      set level(lvl) {
        this[setLevelSym](lvl);
      },
      get levelVal() {
        return this[levelValSym];
      },
      set levelVal(n) {
        throw Error("levelVal is read-only");
      },
      get msgPrefix() {
        return this[msgPrefixSym];
      },
      get [Symbol.toStringTag]() {
        return "Pino";
      },
      [lsCacheSym]: initialLsCache,
      [writeSym]: write,
      [asJsonSym]: asJson,
      [getLevelSym]: getLevel,
      [setLevelSym]: setLevel
    };
    Object.setPrototypeOf(prototype, EventEmitter2.prototype);
    module.exports = function() {
      return Object.create(prototype);
    };
    var resetChildingsFormatter = (bindings2) => bindings2;
    function child(bindings2, options) {
      if (!bindings2) {
        throw Error("missing bindings for child Pino");
      }
      const serializers = this[serializersSym];
      const formatters = this[formattersSym];
      const instance = Object.create(this);
      if (options == null) {
        if (instance[formattersSym].bindings !== resetChildingsFormatter) {
          instance[formattersSym] = buildFormatters(
            formatters.level,
            resetChildingsFormatter,
            formatters.log
          );
        }
        instance[chindingsSym] = asChindings(instance, bindings2);
        instance[setLevelSym](this.level);
        if (this.onChild !== noop) {
          this.onChild(instance);
        }
        return instance;
      }
      if (options.hasOwnProperty("serializers") === true) {
        instance[serializersSym] = /* @__PURE__ */ Object.create(null);
        for (const k in serializers) {
          instance[serializersSym][k] = serializers[k];
        }
        const parentSymbols = Object.getOwnPropertySymbols(serializers);
        for (var i = 0; i < parentSymbols.length; i++) {
          const ks = parentSymbols[i];
          instance[serializersSym][ks] = serializers[ks];
        }
        for (const bk in options.serializers) {
          instance[serializersSym][bk] = options.serializers[bk];
        }
        const bindingsSymbols = Object.getOwnPropertySymbols(options.serializers);
        for (var bi = 0; bi < bindingsSymbols.length; bi++) {
          const bks = bindingsSymbols[bi];
          instance[serializersSym][bks] = options.serializers[bks];
        }
      } else instance[serializersSym] = serializers;
      if (options.hasOwnProperty("formatters")) {
        const { level, bindings: chindings, log } = options.formatters;
        instance[formattersSym] = buildFormatters(
          level || formatters.level,
          chindings || resetChildingsFormatter,
          log || formatters.log
        );
      } else {
        instance[formattersSym] = buildFormatters(
          formatters.level,
          resetChildingsFormatter,
          formatters.log
        );
      }
      if (options.hasOwnProperty("customLevels") === true) {
        assertNoLevelCollisions(this.levels, options.customLevels);
        instance.levels = mappings(options.customLevels, instance[useOnlyCustomLevelsSym]);
        genLsCache(instance);
      }
      if (typeof options.redact === "object" && options.redact !== null || Array.isArray(options.redact)) {
        instance.redact = options.redact;
        const stringifiers = redaction(instance.redact, stringify);
        const formatOpts = { stringify: stringifiers[redactFmtSym] };
        instance[stringifySym] = stringify;
        instance[stringifiersSym] = stringifiers;
        instance[formatOptsSym] = formatOpts;
      }
      if (typeof options.msgPrefix === "string") {
        instance[msgPrefixSym] = (this[msgPrefixSym] || "") + options.msgPrefix;
      }
      instance[chindingsSym] = asChindings(instance, bindings2);
      const childLevel = options.level || this.level;
      instance[setLevelSym](childLevel);
      this.onChild(instance);
      return instance;
    }
    function bindings() {
      const chindings = this[chindingsSym];
      const chindingsJson = `{${chindings.substr(1)}}`;
      const bindingsFromJson = JSON.parse(chindingsJson);
      delete bindingsFromJson.pid;
      delete bindingsFromJson.hostname;
      return bindingsFromJson;
    }
    function setBindings(newBindings) {
      const chindings = asChindings(this, newBindings);
      this[chindingsSym] = chindings;
      delete this[parsedChindingsSym];
    }
    function defaultMixinMergeStrategy(mergeObject, mixinObject) {
      return Object.assign(mixinObject, mergeObject);
    }
    function write(_obj, msg, num) {
      const t = this[timeSym]();
      const mixin = this[mixinSym];
      const errorKey = this[errorKeySym];
      const messageKey = this[messageKeySym];
      const mixinMergeStrategy = this[mixinMergeStrategySym] || defaultMixinMergeStrategy;
      let obj;
      const streamWriteHook = this[hooksSym].streamWrite;
      if (_obj === void 0 || _obj === null) {
        obj = {};
      } else if (_obj instanceof Error) {
        obj = { [errorKey]: _obj };
        if (msg === void 0) {
          msg = _obj.message;
        }
      } else {
        obj = _obj;
        if (msg === void 0 && _obj[messageKey] === void 0 && _obj[errorKey]) {
          msg = _obj[errorKey].message;
        }
      }
      if (mixin) {
        obj = mixinMergeStrategy(obj, mixin(obj, num, this));
      }
      const s = this[asJsonSym](obj, msg, num, t);
      const stream = this[streamSym];
      if (stream[needsMetadataGsym] === true) {
        stream.lastLevel = num;
        stream.lastObj = obj;
        stream.lastMsg = msg;
        stream.lastTime = t.slice(this[timeSliceIndexSym]);
        stream.lastLogger = this;
      }
      stream.write(streamWriteHook ? streamWriteHook(s) : s);
    }
    function flush(cb) {
      if (cb != null && typeof cb !== "function") {
        throw Error("callback must be a function");
      }
      const stream = this[streamSym];
      if (typeof stream.flush === "function") {
        stream.flush(cb || noop);
      } else if (cb) cb();
    }
  }
});

// ../../node_modules/.pnpm/safe-stable-stringify@2.5.0/node_modules/safe-stable-stringify/index.js
var require_safe_stable_stringify = __commonJS({
  "../../node_modules/.pnpm/safe-stable-stringify@2.5.0/node_modules/safe-stable-stringify/index.js"(exports, module) {
    "use strict";
    var { hasOwnProperty } = Object.prototype;
    var stringify = configure();
    stringify.configure = configure;
    stringify.stringify = stringify;
    stringify.default = stringify;
    exports.stringify = stringify;
    exports.configure = configure;
    module.exports = stringify;
    var strEscapeSequencesRegExp = /[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;
    function strEscape(str) {
      if (str.length < 5e3 && !strEscapeSequencesRegExp.test(str)) {
        return `"${str}"`;
      }
      return JSON.stringify(str);
    }
    function sort(array2, comparator) {
      if (array2.length > 200 || comparator) {
        return array2.sort(comparator);
      }
      for (let i = 1; i < array2.length; i++) {
        const currentValue = array2[i];
        let position = i;
        while (position !== 0 && array2[position - 1] > currentValue) {
          array2[position] = array2[position - 1];
          position--;
        }
        array2[position] = currentValue;
      }
      return array2;
    }
    var typedArrayPrototypeGetSymbolToStringTag = Object.getOwnPropertyDescriptor(
      Object.getPrototypeOf(
        Object.getPrototypeOf(
          new Int8Array()
        )
      ),
      Symbol.toStringTag
    ).get;
    function isTypedArrayWithEntries(value) {
      return typedArrayPrototypeGetSymbolToStringTag.call(value) !== void 0 && value.length !== 0;
    }
    function stringifyTypedArray(array2, separator, maximumBreadth) {
      if (array2.length < maximumBreadth) {
        maximumBreadth = array2.length;
      }
      const whitespace = separator === "," ? "" : " ";
      let res = `"0":${whitespace}${array2[0]}`;
      for (let i = 1; i < maximumBreadth; i++) {
        res += `${separator}"${i}":${whitespace}${array2[i]}`;
      }
      return res;
    }
    function getCircularValueOption(options) {
      if (hasOwnProperty.call(options, "circularValue")) {
        const circularValue = options.circularValue;
        if (typeof circularValue === "string") {
          return `"${circularValue}"`;
        }
        if (circularValue == null) {
          return circularValue;
        }
        if (circularValue === Error || circularValue === TypeError) {
          return {
            toString() {
              throw new TypeError("Converting circular structure to JSON");
            }
          };
        }
        throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined');
      }
      return '"[Circular]"';
    }
    function getDeterministicOption(options) {
      let value;
      if (hasOwnProperty.call(options, "deterministic")) {
        value = options.deterministic;
        if (typeof value !== "boolean" && typeof value !== "function") {
          throw new TypeError('The "deterministic" argument must be of type boolean or comparator function');
        }
      }
      return value === void 0 ? true : value;
    }
    function getBooleanOption(options, key) {
      let value;
      if (hasOwnProperty.call(options, key)) {
        value = options[key];
        if (typeof value !== "boolean") {
          throw new TypeError(`The "${key}" argument must be of type boolean`);
        }
      }
      return value === void 0 ? true : value;
    }
    function getPositiveIntegerOption(options, key) {
      let value;
      if (hasOwnProperty.call(options, key)) {
        value = options[key];
        if (typeof value !== "number") {
          throw new TypeError(`The "${key}" argument must be of type number`);
        }
        if (!Number.isInteger(value)) {
          throw new TypeError(`The "${key}" argument must be an integer`);
        }
        if (value < 1) {
          throw new RangeError(`The "${key}" argument must be >= 1`);
        }
      }
      return value === void 0 ? Infinity : value;
    }
    function getItemCount(number4) {
      if (number4 === 1) {
        return "1 item";
      }
      return `${number4} items`;
    }
    function getUniqueReplacerSet(replacerArray) {
      const replacerSet = /* @__PURE__ */ new Set();
      for (const value of replacerArray) {
        if (typeof value === "string" || typeof value === "number") {
          replacerSet.add(String(value));
        }
      }
      return replacerSet;
    }
    function getStrictOption(options) {
      if (hasOwnProperty.call(options, "strict")) {
        const value = options.strict;
        if (typeof value !== "boolean") {
          throw new TypeError('The "strict" argument must be of type boolean');
        }
        if (value) {
          return (value2) => {
            let message = `Object can not safely be stringified. Received type ${typeof value2}`;
            if (typeof value2 !== "function") message += ` (${value2.toString()})`;
            throw new Error(message);
          };
        }
      }
    }
    function configure(options) {
      options = { ...options };
      const fail = getStrictOption(options);
      if (fail) {
        if (options.bigint === void 0) {
          options.bigint = false;
        }
        if (!("circularValue" in options)) {
          options.circularValue = Error;
        }
      }
      const circularValue = getCircularValueOption(options);
      const bigint5 = getBooleanOption(options, "bigint");
      const deterministic = getDeterministicOption(options);
      const comparator = typeof deterministic === "function" ? deterministic : void 0;
      const maximumDepth = getPositiveIntegerOption(options, "maximumDepth");
      const maximumBreadth = getPositiveIntegerOption(options, "maximumBreadth");
      function stringifyFnReplacer(key, parent, stack, replacer, spacer, indentation) {
        let value = parent[key];
        if (typeof value === "object" && value !== null && typeof value.toJSON === "function") {
          value = value.toJSON(key);
        }
        value = replacer.call(parent, key, value);
        switch (typeof value) {
          case "string":
            return strEscape(value);
          case "object": {
            if (value === null) {
              return "null";
            }
            if (stack.indexOf(value) !== -1) {
              return circularValue;
            }
            let res = "";
            let join = ",";
            const originalIndentation = indentation;
            if (Array.isArray(value)) {
              if (value.length === 0) {
                return "[]";
              }
              if (maximumDepth < stack.length + 1) {
                return '"[Array]"';
              }
              stack.push(value);
              if (spacer !== "") {
                indentation += spacer;
                res += `
${indentation}`;
                join = `,
${indentation}`;
              }
              const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
              let i = 0;
              for (; i < maximumValuesToStringify - 1; i++) {
                const tmp2 = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation);
                res += tmp2 !== void 0 ? tmp2 : "null";
                res += join;
              }
              const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation);
              res += tmp !== void 0 ? tmp : "null";
              if (value.length - 1 > maximumBreadth) {
                const removedKeys = value.length - maximumBreadth - 1;
                res += `${join}"... ${getItemCount(removedKeys)} not stringified"`;
              }
              if (spacer !== "") {
                res += `
${originalIndentation}`;
              }
              stack.pop();
              return `[${res}]`;
            }
            let keys = Object.keys(value);
            const keyLength = keys.length;
            if (keyLength === 0) {
              return "{}";
            }
            if (maximumDepth < stack.length + 1) {
              return '"[Object]"';
            }
            let whitespace = "";
            let separator = "";
            if (spacer !== "") {
              indentation += spacer;
              join = `,
${indentation}`;
              whitespace = " ";
            }
            const maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth);
            if (deterministic && !isTypedArrayWithEntries(value)) {
              keys = sort(keys, comparator);
            }
            stack.push(value);
            for (let i = 0; i < maximumPropertiesToStringify; i++) {
              const key2 = keys[i];
              const tmp = stringifyFnReplacer(key2, value, stack, replacer, spacer, indentation);
              if (tmp !== void 0) {
                res += `${separator}${strEscape(key2)}:${whitespace}${tmp}`;
                separator = join;
              }
            }
            if (keyLength > maximumBreadth) {
              const removedKeys = keyLength - maximumBreadth;
              res += `${separator}"...":${whitespace}"${getItemCount(removedKeys)} not stringified"`;
              separator = join;
            }
            if (spacer !== "" && separator.length > 1) {
              res = `
${indentation}${res}
${originalIndentation}`;
            }
            stack.pop();
            return `{${res}}`;
          }
          case "number":
            return isFinite(value) ? String(value) : fail ? fail(value) : "null";
          case "boolean":
            return value === true ? "true" : "false";
          case "undefined":
            return void 0;
          case "bigint":
            if (bigint5) {
              return String(value);
            }
          // fallthrough
          default:
            return fail ? fail(value) : void 0;
        }
      }
      function stringifyArrayReplacer(key, value, stack, replacer, spacer, indentation) {
        if (typeof value === "object" && value !== null && typeof value.toJSON === "function") {
          value = value.toJSON(key);
        }
        switch (typeof value) {
          case "string":
            return strEscape(value);
          case "object": {
            if (value === null) {
              return "null";
            }
            if (stack.indexOf(value) !== -1) {
              return circularValue;
            }
            const originalIndentation = indentation;
            let res = "";
            let join = ",";
            if (Array.isArray(value)) {
              if (value.length === 0) {
                return "[]";
              }
              if (maximumDepth < stack.length + 1) {
                return '"[Array]"';
              }
              stack.push(value);
              if (spacer !== "") {
                indentation += spacer;
                res += `
${indentation}`;
                join = `,
${indentation}`;
              }
              const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
              let i = 0;
              for (; i < maximumValuesToStringify - 1; i++) {
                const tmp2 = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation);
                res += tmp2 !== void 0 ? tmp2 : "null";
                res += join;
              }
              const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation);
              res += tmp !== void 0 ? tmp : "null";
              if (value.length - 1 > maximumBreadth) {
                const removedKeys = value.length - maximumBreadth - 1;
                res += `${join}"... ${getItemCount(removedKeys)} not stringified"`;
              }
              if (spacer !== "") {
                res += `
${originalIndentation}`;
              }
              stack.pop();
              return `[${res}]`;
            }
            stack.push(value);
            let whitespace = "";
            if (spacer !== "") {
              indentation += spacer;
              join = `,
${indentation}`;
              whitespace = " ";
            }
            let separator = "";
            for (const key2 of replacer) {
              const tmp = stringifyArrayReplacer(key2, value[key2], stack, replacer, spacer, indentation);
              if (tmp !== void 0) {
                res += `${separator}${strEscape(key2)}:${whitespace}${tmp}`;
                separator = join;
              }
            }
            if (spacer !== "" && separator.length > 1) {
              res = `
${indentation}${res}
${originalIndentation}`;
            }
            stack.pop();
            return `{${res}}`;
          }
          case "number":
            return isFinite(value) ? String(value) : fail ? fail(value) : "null";
          case "boolean":
            return value === true ? "true" : "false";
          case "undefined":
            return void 0;
          case "bigint":
            if (bigint5) {
              return String(value);
            }
          // fallthrough
          default:
            return fail ? fail(value) : void 0;
        }
      }
      function stringifyIndent(key, value, stack, spacer, indentation) {
        switch (typeof value) {
          case "string":
            return strEscape(value);
          case "object": {
            if (value === null) {
              return "null";
            }
            if (typeof value.toJSON === "function") {
              value = value.toJSON(key);
              if (typeof value !== "object") {
                return stringifyIndent(key, value, stack, spacer, indentation);
              }
              if (value === null) {
                return "null";
              }
            }
            if (stack.indexOf(value) !== -1) {
              return circularValue;
            }
            const originalIndentation = indentation;
            if (Array.isArray(value)) {
              if (value.length === 0) {
                return "[]";
              }
              if (maximumDepth < stack.length + 1) {
                return '"[Array]"';
              }
              stack.push(value);
              indentation += spacer;
              let res2 = `
${indentation}`;
              const join2 = `,
${indentation}`;
              const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
              let i = 0;
              for (; i < maximumValuesToStringify - 1; i++) {
                const tmp2 = stringifyIndent(String(i), value[i], stack, spacer, indentation);
                res2 += tmp2 !== void 0 ? tmp2 : "null";
                res2 += join2;
              }
              const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation);
              res2 += tmp !== void 0 ? tmp : "null";
              if (value.length - 1 > maximumBreadth) {
                const removedKeys = value.length - maximumBreadth - 1;
                res2 += `${join2}"... ${getItemCount(removedKeys)} not stringified"`;
              }
              res2 += `
${originalIndentation}`;
              stack.pop();
              return `[${res2}]`;
            }
            let keys = Object.keys(value);
            const keyLength = keys.length;
            if (keyLength === 0) {
              return "{}";
            }
            if (maximumDepth < stack.length + 1) {
              return '"[Object]"';
            }
            indentation += spacer;
            const join = `,
${indentation}`;
            let res = "";
            let separator = "";
            let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth);
            if (isTypedArrayWithEntries(value)) {
              res += stringifyTypedArray(value, join, maximumBreadth);
              keys = keys.slice(value.length);
              maximumPropertiesToStringify -= value.length;
              separator = join;
            }
            if (deterministic) {
              keys = sort(keys, comparator);
            }
            stack.push(value);
            for (let i = 0; i < maximumPropertiesToStringify; i++) {
              const key2 = keys[i];
              const tmp = stringifyIndent(key2, value[key2], stack, spacer, indentation);
              if (tmp !== void 0) {
                res += `${separator}${strEscape(key2)}: ${tmp}`;
                separator = join;
              }
            }
            if (keyLength > maximumBreadth) {
              const removedKeys = keyLength - maximumBreadth;
              res += `${separator}"...": "${getItemCount(removedKeys)} not stringified"`;
              separator = join;
            }
            if (separator !== "") {
              res = `
${indentation}${res}
${originalIndentation}`;
            }
            stack.pop();
            return `{${res}}`;
          }
          case "number":
            return isFinite(value) ? String(value) : fail ? fail(value) : "null";
          case "boolean":
            return value === true ? "true" : "false";
          case "undefined":
            return void 0;
          case "bigint":
            if (bigint5) {
              return String(value);
            }
          // fallthrough
          default:
            return fail ? fail(value) : void 0;
        }
      }
      function stringifySimple(key, value, stack) {
        switch (typeof value) {
          case "string":
            return strEscape(value);
          case "object": {
            if (value === null) {
              return "null";
            }
            if (typeof value.toJSON === "function") {
              value = value.toJSON(key);
              if (typeof value !== "object") {
                return stringifySimple(key, value, stack);
              }
              if (value === null) {
                return "null";
              }
            }
            if (stack.indexOf(value) !== -1) {
              return circularValue;
            }
            let res = "";
            const hasLength = value.length !== void 0;
            if (hasLength && Array.isArray(value)) {
              if (value.length === 0) {
                return "[]";
              }
              if (maximumDepth < stack.length + 1) {
                return '"[Array]"';
              }
              stack.push(value);
              const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
              let i = 0;
              for (; i < maximumValuesToStringify - 1; i++) {
                const tmp2 = stringifySimple(String(i), value[i], stack);
                res += tmp2 !== void 0 ? tmp2 : "null";
                res += ",";
              }
              const tmp = stringifySimple(String(i), value[i], stack);
              res += tmp !== void 0 ? tmp : "null";
              if (value.length - 1 > maximumBreadth) {
                const removedKeys = value.length - maximumBreadth - 1;
                res += `,"... ${getItemCount(removedKeys)} not stringified"`;
              }
              stack.pop();
              return `[${res}]`;
            }
            let keys = Object.keys(value);
            const keyLength = keys.length;
            if (keyLength === 0) {
              return "{}";
            }
            if (maximumDepth < stack.length + 1) {
              return '"[Object]"';
            }
            let separator = "";
            let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth);
            if (hasLength && isTypedArrayWithEntries(value)) {
              res += stringifyTypedArray(value, ",", maximumBreadth);
              keys = keys.slice(value.length);
              maximumPropertiesToStringify -= value.length;
              separator = ",";
            }
            if (deterministic) {
              keys = sort(keys, comparator);
            }
            stack.push(value);
            for (let i = 0; i < maximumPropertiesToStringify; i++) {
              const key2 = keys[i];
              const tmp = stringifySimple(key2, value[key2], stack);
              if (tmp !== void 0) {
                res += `${separator}${strEscape(key2)}:${tmp}`;
                separator = ",";
              }
            }
            if (keyLength > maximumBreadth) {
              const removedKeys = keyLength - maximumBreadth;
              res += `${separator}"...":"${getItemCount(removedKeys)} not stringified"`;
            }
            stack.pop();
            return `{${res}}`;
          }
          case "number":
            return isFinite(value) ? String(value) : fail ? fail(value) : "null";
          case "boolean":
            return value === true ? "true" : "false";
          case "undefined":
            return void 0;
          case "bigint":
            if (bigint5) {
              return String(value);
            }
          // fallthrough
          default:
            return fail ? fail(value) : void 0;
        }
      }
      function stringify2(value, replacer, space) {
        if (arguments.length > 1) {
          let spacer = "";
          if (typeof space === "number") {
            spacer = " ".repeat(Math.min(space, 10));
          } else if (typeof space === "string") {
            spacer = space.slice(0, 10);
          }
          if (replacer != null) {
            if (typeof replacer === "function") {
              return stringifyFnReplacer("", { "": value }, [], replacer, spacer, "");
            }
            if (Array.isArray(replacer)) {
              return stringifyArrayReplacer("", value, [], getUniqueReplacerSet(replacer), spacer, "");
            }
          }
          if (spacer.length !== 0) {
            return stringifyIndent("", value, [], spacer, "");
          }
        }
        return stringifySimple("", value, []);
      }
      return stringify2;
    }
  }
});

// ../../node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/multistream.js
var require_multistream = __commonJS({
  "../../node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/multistream.js"(exports, module) {
    "use strict";
    var metadata = /* @__PURE__ */ Symbol.for("pino.metadata");
    var { DEFAULT_LEVELS } = require_constants();
    var DEFAULT_INFO_LEVEL = DEFAULT_LEVELS.info;
    function multistream(streamsArray, opts) {
      streamsArray = streamsArray || [];
      opts = opts || { dedupe: false };
      const streamLevels = Object.create(DEFAULT_LEVELS);
      streamLevels.silent = Infinity;
      if (opts.levels && typeof opts.levels === "object") {
        Object.keys(opts.levels).forEach((i) => {
          streamLevels[i] = opts.levels[i];
        });
      }
      const res = {
        write,
        add,
        remove,
        emit,
        flushSync,
        end,
        minLevel: 0,
        lastId: 0,
        streams: [],
        clone: clone2,
        [metadata]: true,
        streamLevels
      };
      if (Array.isArray(streamsArray)) {
        streamsArray.forEach(add, res);
      } else {
        add.call(res, streamsArray);
      }
      streamsArray = null;
      return res;
      function write(data) {
        let dest;
        const level = this.lastLevel;
        const { streams } = this;
        let recordedLevel = 0;
        let stream;
        for (let i = initLoopVar(streams.length, opts.dedupe); checkLoopVar(i, streams.length, opts.dedupe); i = adjustLoopVar(i, opts.dedupe)) {
          dest = streams[i];
          if (dest.level <= level) {
            if (recordedLevel !== 0 && recordedLevel !== dest.level) {
              break;
            }
            stream = dest.stream;
            if (stream[metadata]) {
              const { lastTime, lastMsg, lastObj, lastLogger } = this;
              stream.lastLevel = level;
              stream.lastTime = lastTime;
              stream.lastMsg = lastMsg;
              stream.lastObj = lastObj;
              stream.lastLogger = lastLogger;
            }
            stream.write(data);
            if (opts.dedupe) {
              recordedLevel = dest.level;
            }
          } else if (!opts.dedupe) {
            break;
          }
        }
      }
      function emit(...args) {
        for (const { stream } of this.streams) {
          if (typeof stream.emit === "function") {
            stream.emit(...args);
          }
        }
      }
      function flushSync() {
        for (const { stream } of this.streams) {
          if (typeof stream.flushSync === "function") {
            stream.flushSync();
          }
        }
      }
      function add(dest) {
        if (!dest) {
          return res;
        }
        const isStream = typeof dest.write === "function" || dest.stream;
        const stream_ = dest.write ? dest : dest.stream;
        if (!isStream) {
          throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");
        }
        const { streams, streamLevels: streamLevels2 } = this;
        let level;
        if (typeof dest.levelVal === "number") {
          level = dest.levelVal;
        } else if (typeof dest.level === "string") {
          level = streamLevels2[dest.level];
        } else if (typeof dest.level === "number") {
          level = dest.level;
        } else {
          level = DEFAULT_INFO_LEVEL;
        }
        const dest_ = {
          stream: stream_,
          level,
          levelVal: void 0,
          id: ++res.lastId
        };
        streams.unshift(dest_);
        streams.sort(compareByLevel);
        this.minLevel = streams[0].level;
        return res;
      }
      function remove(id) {
        const { streams } = this;
        const index2 = streams.findIndex((s) => s.id === id);
        if (index2 >= 0) {
          streams.splice(index2, 1);
          streams.sort(compareByLevel);
          this.minLevel = streams.length > 0 ? streams[0].level : -1;
        }
        return res;
      }
      function end() {
        for (const { stream } of this.streams) {
          if (typeof stream.flushSync === "function") {
            stream.flushSync();
          }
          stream.end();
        }
      }
      function clone2(level) {
        const streams = new Array(this.streams.length);
        for (let i = 0; i < streams.length; i++) {
          streams[i] = {
            level,
            stream: this.streams[i].stream
          };
        }
        return {
          write,
          add,
          remove,
          minLevel: level,
          streams,
          clone: clone2,
          emit,
          flushSync,
          [metadata]: true
        };
      }
    }
    function compareByLevel(a, b) {
      return a.level - b.level;
    }
    function initLoopVar(length, dedupe) {
      return dedupe ? length - 1 : 0;
    }
    function adjustLoopVar(i, dedupe) {
      return dedupe ? i - 1 : i + 1;
    }
    function checkLoopVar(i, length, dedupe) {
      return dedupe ? i >= 0 : i < length;
    }
    module.exports = multistream;
  }
});

// ../../node_modules/.pnpm/pino@9.14.0/node_modules/pino/pino.js
var require_pino = __commonJS({
  "../../node_modules/.pnpm/pino@9.14.0/node_modules/pino/pino.js"(exports, module) {
    function pinoBundlerAbsolutePath(p) {
      try {
        const path4 = __require("path");
        const outputDir = "C:\\Users\\HP G3\\Documents\\my-apps\\wwn-ca\\artifacts\\api-server\\dist";
        return path4.resolve(outputDir, p.replace(/^\.\//, ""));
      } catch (e) {
        const f = new Function("p", "return new URL(p, import.meta.url).pathname");
        return f(p);
      }
    }
    globalThis.__bundlerPathsOverrides = { ...globalThis.__bundlerPathsOverrides || {}, "thread-stream-worker": pinoBundlerAbsolutePath("./thread-stream-worker.mjs"), "pino-worker": pinoBundlerAbsolutePath("./pino-worker.mjs"), "pino/file": pinoBundlerAbsolutePath("./pino-file.mjs"), "pino-pretty": pinoBundlerAbsolutePath("./pino-pretty.mjs") };
    var os = __require("node:os");
    var stdSerializers = require_pino_std_serializers();
    var caller = require_caller();
    var redaction = require_redaction();
    var time4 = require_time();
    var proto = require_proto();
    var symbols = require_symbols();
    var { configure } = require_safe_stable_stringify();
    var { assertDefaultLevelFound, mappings, genLsCache, genLevelComparison, assertLevelComparison } = require_levels();
    var { DEFAULT_LEVELS, SORTING_ORDER } = require_constants();
    var {
      createArgsNormalizer,
      asChindings,
      buildSafeSonicBoom,
      buildFormatters,
      stringify,
      normalizeDestFileDescriptor,
      noop
    } = require_tools();
    var { version: version3 } = require_meta();
    var {
      chindingsSym,
      redactFmtSym,
      serializersSym,
      timeSym,
      timeSliceIndexSym,
      streamSym,
      stringifySym,
      stringifySafeSym,
      stringifiersSym,
      setLevelSym,
      endSym,
      formatOptsSym,
      messageKeySym,
      errorKeySym,
      nestedKeySym,
      mixinSym,
      levelCompSym,
      useOnlyCustomLevelsSym,
      formattersSym,
      hooksSym,
      nestedKeyStrSym,
      mixinMergeStrategySym,
      msgPrefixSym
    } = symbols;
    var { epochTime, nullTime } = time4;
    var { pid } = process;
    var hostname2 = os.hostname();
    var defaultErrorSerializer = stdSerializers.err;
    var defaultOptions = {
      level: "info",
      levelComparison: SORTING_ORDER.ASC,
      levels: DEFAULT_LEVELS,
      messageKey: "msg",
      errorKey: "err",
      nestedKey: null,
      enabled: true,
      base: { pid, hostname: hostname2 },
      serializers: Object.assign(/* @__PURE__ */ Object.create(null), {
        err: defaultErrorSerializer
      }),
      formatters: Object.assign(/* @__PURE__ */ Object.create(null), {
        bindings(bindings) {
          return bindings;
        },
        level(label, number4) {
          return { level: number4 };
        }
      }),
      hooks: {
        logMethod: void 0,
        streamWrite: void 0
      },
      timestamp: epochTime,
      name: void 0,
      redact: null,
      customLevels: null,
      useOnlyCustomLevels: false,
      depthLimit: 5,
      edgeLimit: 100
    };
    var normalize = createArgsNormalizer(defaultOptions);
    var serializers = Object.assign(/* @__PURE__ */ Object.create(null), stdSerializers);
    function pino2(...args) {
      const instance = {};
      const { opts, stream } = normalize(instance, caller(), ...args);
      if (opts.level && typeof opts.level === "string" && DEFAULT_LEVELS[opts.level.toLowerCase()] !== void 0) opts.level = opts.level.toLowerCase();
      const {
        redact,
        crlf,
        serializers: serializers2,
        timestamp: timestamp2,
        messageKey,
        errorKey,
        nestedKey,
        base,
        name,
        level,
        customLevels,
        levelComparison,
        mixin,
        mixinMergeStrategy,
        useOnlyCustomLevels,
        formatters,
        hooks,
        depthLimit,
        edgeLimit,
        onChild,
        msgPrefix
      } = opts;
      const stringifySafe = configure({
        maximumDepth: depthLimit,
        maximumBreadth: edgeLimit
      });
      const allFormatters = buildFormatters(
        formatters.level,
        formatters.bindings,
        formatters.log
      );
      const stringifyFn = stringify.bind({
        [stringifySafeSym]: stringifySafe
      });
      const stringifiers = redact ? redaction(redact, stringifyFn) : {};
      const formatOpts = redact ? { stringify: stringifiers[redactFmtSym] } : { stringify: stringifyFn };
      const end = "}" + (crlf ? "\r\n" : "\n");
      const coreChindings = asChindings.bind(null, {
        [chindingsSym]: "",
        [serializersSym]: serializers2,
        [stringifiersSym]: stringifiers,
        [stringifySym]: stringify,
        [stringifySafeSym]: stringifySafe,
        [formattersSym]: allFormatters
      });
      let chindings = "";
      if (base !== null) {
        if (name === void 0) {
          chindings = coreChindings(base);
        } else {
          chindings = coreChindings(Object.assign({}, base, { name }));
        }
      }
      const time5 = timestamp2 instanceof Function ? timestamp2 : timestamp2 ? epochTime : nullTime;
      const timeSliceIndex = time5().indexOf(":") + 1;
      if (useOnlyCustomLevels && !customLevels) throw Error("customLevels is required if useOnlyCustomLevels is set true");
      if (mixin && typeof mixin !== "function") throw Error(`Unknown mixin type "${typeof mixin}" - expected "function"`);
      if (msgPrefix && typeof msgPrefix !== "string") throw Error(`Unknown msgPrefix type "${typeof msgPrefix}" - expected "string"`);
      assertDefaultLevelFound(level, customLevels, useOnlyCustomLevels);
      const levels = mappings(customLevels, useOnlyCustomLevels);
      if (typeof stream.emit === "function") {
        stream.emit("message", { code: "PINO_CONFIG", config: { levels, messageKey, errorKey } });
      }
      assertLevelComparison(levelComparison);
      const levelCompFunc = genLevelComparison(levelComparison);
      Object.assign(instance, {
        levels,
        [levelCompSym]: levelCompFunc,
        [useOnlyCustomLevelsSym]: useOnlyCustomLevels,
        [streamSym]: stream,
        [timeSym]: time5,
        [timeSliceIndexSym]: timeSliceIndex,
        [stringifySym]: stringify,
        [stringifySafeSym]: stringifySafe,
        [stringifiersSym]: stringifiers,
        [endSym]: end,
        [formatOptsSym]: formatOpts,
        [messageKeySym]: messageKey,
        [errorKeySym]: errorKey,
        [nestedKeySym]: nestedKey,
        // protect against injection
        [nestedKeyStrSym]: nestedKey ? `,${JSON.stringify(nestedKey)}:{` : "",
        [serializersSym]: serializers2,
        [mixinSym]: mixin,
        [mixinMergeStrategySym]: mixinMergeStrategy,
        [chindingsSym]: chindings,
        [formattersSym]: allFormatters,
        [hooksSym]: hooks,
        silent: noop,
        onChild,
        [msgPrefixSym]: msgPrefix
      });
      Object.setPrototypeOf(instance, proto());
      genLsCache(instance);
      instance[setLevelSym](level);
      return instance;
    }
    module.exports = pino2;
    module.exports.destination = (dest = process.stdout.fd) => {
      if (typeof dest === "object") {
        dest.dest = normalizeDestFileDescriptor(dest.dest || process.stdout.fd);
        return buildSafeSonicBoom(dest);
      } else {
        return buildSafeSonicBoom({ dest: normalizeDestFileDescriptor(dest), minLength: 0 });
      }
    };
    module.exports.transport = require_transport();
    module.exports.multistream = require_multistream();
    module.exports.levels = mappings();
    module.exports.stdSerializers = serializers;
    module.exports.stdTimeFunctions = Object.assign({}, time4);
    module.exports.symbols = symbols;
    module.exports.version = version3;
    module.exports.default = pino2;
    module.exports.pino = pino2;
  }
});

// src/lib/logger.ts
var import_pino, isProduction, logger;
var init_logger = __esm({
  "src/lib/logger.ts"() {
    "use strict";
    import_pino = __toESM(require_pino(), 1);
    isProduction = process.env.NODE_ENV === "production";
    logger = (0, import_pino.default)({
      level: process.env.LOG_LEVEL ?? "info",
      redact: [
        "req.headers.authorization",
        "req.headers.cookie",
        "res.headers['set-cookie']"
      ],
      ...isProduction ? {} : {
        transport: {
          target: "pino-pretty",
          options: { colorize: true }
        }
      }
    });
  }
});

// ../../node_modules/.pnpm/depd@2.0.0/node_modules/depd/index.js
var require_depd = __commonJS({
  "../../node_modules/.pnpm/depd@2.0.0/node_modules/depd/index.js"(exports, module) {
    var relative = __require("path").relative;
    module.exports = depd;
    var basePath = process.cwd();
    function containsNamespace(str, namespace) {
      var vals = str.split(/[ ,]+/);
      var ns = String(namespace).toLowerCase();
      for (var i = 0; i < vals.length; i++) {
        var val = vals[i];
        if (val && (val === "*" || val.toLowerCase() === ns)) {
          return true;
        }
      }
      return false;
    }
    function convertDataDescriptorToAccessor(obj, prop, message) {
      var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
      var value = descriptor.value;
      descriptor.get = function getter() {
        return value;
      };
      if (descriptor.writable) {
        descriptor.set = function setter(val) {
          return value = val;
        };
      }
      delete descriptor.value;
      delete descriptor.writable;
      Object.defineProperty(obj, prop, descriptor);
      return descriptor;
    }
    function createArgumentsString(arity) {
      var str = "";
      for (var i = 0; i < arity; i++) {
        str += ", arg" + i;
      }
      return str.substr(2);
    }
    function createStackString(stack) {
      var str = this.name + ": " + this.namespace;
      if (this.message) {
        str += " deprecated " + this.message;
      }
      for (var i = 0; i < stack.length; i++) {
        str += "\n    at " + stack[i].toString();
      }
      return str;
    }
    function depd(namespace) {
      if (!namespace) {
        throw new TypeError("argument namespace is required");
      }
      var stack = getStack();
      var site = callSiteLocation(stack[1]);
      var file2 = site[0];
      function deprecate(message) {
        log.call(deprecate, message);
      }
      deprecate._file = file2;
      deprecate._ignored = isignored(namespace);
      deprecate._namespace = namespace;
      deprecate._traced = istraced(namespace);
      deprecate._warned = /* @__PURE__ */ Object.create(null);
      deprecate.function = wrapfunction;
      deprecate.property = wrapproperty;
      return deprecate;
    }
    function eehaslisteners(emitter, type) {
      var count3 = typeof emitter.listenerCount !== "function" ? emitter.listeners(type).length : emitter.listenerCount(type);
      return count3 > 0;
    }
    function isignored(namespace) {
      if (process.noDeprecation) {
        return true;
      }
      var str = process.env.NO_DEPRECATION || "";
      return containsNamespace(str, namespace);
    }
    function istraced(namespace) {
      if (process.traceDeprecation) {
        return true;
      }
      var str = process.env.TRACE_DEPRECATION || "";
      return containsNamespace(str, namespace);
    }
    function log(message, site) {
      var haslisteners = eehaslisteners(process, "deprecation");
      if (!haslisteners && this._ignored) {
        return;
      }
      var caller;
      var callFile;
      var callSite;
      var depSite;
      var i = 0;
      var seen = false;
      var stack = getStack();
      var file2 = this._file;
      if (site) {
        depSite = site;
        callSite = callSiteLocation(stack[1]);
        callSite.name = depSite.name;
        file2 = callSite[0];
      } else {
        i = 2;
        depSite = callSiteLocation(stack[i]);
        callSite = depSite;
      }
      for (; i < stack.length; i++) {
        caller = callSiteLocation(stack[i]);
        callFile = caller[0];
        if (callFile === file2) {
          seen = true;
        } else if (callFile === this._file) {
          file2 = this._file;
        } else if (seen) {
          break;
        }
      }
      var key = caller ? depSite.join(":") + "__" + caller.join(":") : void 0;
      if (key !== void 0 && key in this._warned) {
        return;
      }
      this._warned[key] = true;
      var msg = message;
      if (!msg) {
        msg = callSite === depSite || !callSite.name ? defaultMessage(depSite) : defaultMessage(callSite);
      }
      if (haslisteners) {
        var err = DeprecationError(this._namespace, msg, stack.slice(i));
        process.emit("deprecation", err);
        return;
      }
      var format = process.stderr.isTTY ? formatColor : formatPlain;
      var output = format.call(this, msg, caller, stack.slice(i));
      process.stderr.write(output + "\n", "utf8");
    }
    function callSiteLocation(callSite) {
      var file2 = callSite.getFileName() || "<anonymous>";
      var line2 = callSite.getLineNumber();
      var colm = callSite.getColumnNumber();
      if (callSite.isEval()) {
        file2 = callSite.getEvalOrigin() + ", " + file2;
      }
      var site = [file2, line2, colm];
      site.callSite = callSite;
      site.name = callSite.getFunctionName();
      return site;
    }
    function defaultMessage(site) {
      var callSite = site.callSite;
      var funcName = site.name;
      if (!funcName) {
        funcName = "<anonymous@" + formatLocation(site) + ">";
      }
      var context = callSite.getThis();
      var typeName = context && callSite.getTypeName();
      if (typeName === "Object") {
        typeName = void 0;
      }
      if (typeName === "Function") {
        typeName = context.name || typeName;
      }
      return typeName && callSite.getMethodName() ? typeName + "." + funcName : funcName;
    }
    function formatPlain(msg, caller, stack) {
      var timestamp2 = (/* @__PURE__ */ new Date()).toUTCString();
      var formatted = timestamp2 + " " + this._namespace + " deprecated " + msg;
      if (this._traced) {
        for (var i = 0; i < stack.length; i++) {
          formatted += "\n    at " + stack[i].toString();
        }
        return formatted;
      }
      if (caller) {
        formatted += " at " + formatLocation(caller);
      }
      return formatted;
    }
    function formatColor(msg, caller, stack) {
      var formatted = "\x1B[36;1m" + this._namespace + "\x1B[22;39m \x1B[33;1mdeprecated\x1B[22;39m \x1B[0m" + msg + "\x1B[39m";
      if (this._traced) {
        for (var i = 0; i < stack.length; i++) {
          formatted += "\n    \x1B[36mat " + stack[i].toString() + "\x1B[39m";
        }
        return formatted;
      }
      if (caller) {
        formatted += " \x1B[36m" + formatLocation(caller) + "\x1B[39m";
      }
      return formatted;
    }
    function formatLocation(callSite) {
      return relative(basePath, callSite[0]) + ":" + callSite[1] + ":" + callSite[2];
    }
    function getStack() {
      var limit = Error.stackTraceLimit;
      var obj = {};
      var prep = Error.prepareStackTrace;
      Error.prepareStackTrace = prepareObjectStackTrace;
      Error.stackTraceLimit = Math.max(10, limit);
      Error.captureStackTrace(obj);
      var stack = obj.stack.slice(1);
      Error.prepareStackTrace = prep;
      Error.stackTraceLimit = limit;
      return stack;
    }
    function prepareObjectStackTrace(obj, stack) {
      return stack;
    }
    function wrapfunction(fn, message) {
      if (typeof fn !== "function") {
        throw new TypeError("argument fn must be a function");
      }
      var args = createArgumentsString(fn.length);
      var stack = getStack();
      var site = callSiteLocation(stack[1]);
      site.name = fn.name;
      var deprecatedfn = new Function(
        "fn",
        "log",
        "deprecate",
        "message",
        "site",
        '"use strict"\nreturn function (' + args + ") {log.call(deprecate, message, site)\nreturn fn.apply(this, arguments)\n}"
      )(fn, log, this, message, site);
      return deprecatedfn;
    }
    function wrapproperty(obj, prop, message) {
      if (!obj || typeof obj !== "object" && typeof obj !== "function") {
        throw new TypeError("argument obj must be object");
      }
      var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
      if (!descriptor) {
        throw new TypeError("must call property on owner object");
      }
      if (!descriptor.configurable) {
        throw new TypeError("property must be configurable");
      }
      var deprecate = this;
      var stack = getStack();
      var site = callSiteLocation(stack[1]);
      site.name = prop;
      if ("value" in descriptor) {
        descriptor = convertDataDescriptorToAccessor(obj, prop, message);
      }
      var get = descriptor.get;
      var set2 = descriptor.set;
      if (typeof get === "function") {
        descriptor.get = function getter() {
          log.call(deprecate, message, site);
          return get.apply(this, arguments);
        };
      }
      if (typeof set2 === "function") {
        descriptor.set = function setter() {
          log.call(deprecate, message, site);
          return set2.apply(this, arguments);
        };
      }
      Object.defineProperty(obj, prop, descriptor);
    }
    function DeprecationError(namespace, message, stack) {
      var error40 = new Error();
      var stackString;
      Object.defineProperty(error40, "constructor", {
        value: DeprecationError
      });
      Object.defineProperty(error40, "message", {
        configurable: true,
        enumerable: false,
        value: message,
        writable: true
      });
      Object.defineProperty(error40, "name", {
        enumerable: false,
        configurable: true,
        value: "DeprecationError",
        writable: true
      });
      Object.defineProperty(error40, "namespace", {
        configurable: true,
        enumerable: false,
        value: namespace,
        writable: true
      });
      Object.defineProperty(error40, "stack", {
        configurable: true,
        enumerable: false,
        get: function() {
          if (stackString !== void 0) {
            return stackString;
          }
          return stackString = createStackString.call(this, stack);
        },
        set: function setter(val) {
          stackString = val;
        }
      });
      return error40;
    }
  }
});

// ../../node_modules/.pnpm/bytes@3.1.2/node_modules/bytes/index.js
var require_bytes = __commonJS({
  "../../node_modules/.pnpm/bytes@3.1.2/node_modules/bytes/index.js"(exports, module) {
    "use strict";
    module.exports = bytes;
    module.exports.format = format;
    module.exports.parse = parse3;
    var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g;
    var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/;
    var map2 = {
      b: 1,
      kb: 1 << 10,
      mb: 1 << 20,
      gb: 1 << 30,
      tb: Math.pow(1024, 4),
      pb: Math.pow(1024, 5)
    };
    var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i;
    function bytes(value, options) {
      if (typeof value === "string") {
        return parse3(value);
      }
      if (typeof value === "number") {
        return format(value, options);
      }
      return null;
    }
    function format(value, options) {
      if (!Number.isFinite(value)) {
        return null;
      }
      var mag = Math.abs(value);
      var thousandsSeparator = options && options.thousandsSeparator || "";
      var unitSeparator = options && options.unitSeparator || "";
      var decimalPlaces = options && options.decimalPlaces !== void 0 ? options.decimalPlaces : 2;
      var fixedDecimals = Boolean(options && options.fixedDecimals);
      var unit = options && options.unit || "";
      if (!unit || !map2[unit.toLowerCase()]) {
        if (mag >= map2.pb) {
          unit = "PB";
        } else if (mag >= map2.tb) {
          unit = "TB";
        } else if (mag >= map2.gb) {
          unit = "GB";
        } else if (mag >= map2.mb) {
          unit = "MB";
        } else if (mag >= map2.kb) {
          unit = "KB";
        } else {
          unit = "B";
        }
      }
      var val = value / map2[unit.toLowerCase()];
      var str = val.toFixed(decimalPlaces);
      if (!fixedDecimals) {
        str = str.replace(formatDecimalsRegExp, "$1");
      }
      if (thousandsSeparator) {
        str = str.split(".").map(function(s, i) {
          return i === 0 ? s.replace(formatThousandsRegExp, thousandsSeparator) : s;
        }).join(".");
      }
      return str + unitSeparator + unit;
    }
    function parse3(val) {
      if (typeof val === "number" && !isNaN(val)) {
        return val;
      }
      if (typeof val !== "string") {
        return null;
      }
      var results = parseRegExp.exec(val);
      var floatValue;
      var unit = "b";
      if (!results) {
        floatValue = parseInt(val, 10);
        unit = "b";
      } else {
        floatValue = parseFloat(results[1]);
        unit = results[4].toLowerCase();
      }
      if (isNaN(floatValue)) {
        return null;
      }
      return Math.floor(map2[unit] * floatValue);
    }
  }
});

// ../../node_modules/.pnpm/content-type@1.0.5/node_modules/content-type/index.js
var require_content_type = __commonJS({
  "../../node_modules/.pnpm/content-type@1.0.5/node_modules/content-type/index.js"(exports) {
    "use strict";
    var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g;
    var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/;
    var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
    var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g;
    var QUOTE_REGEXP = /([\\"])/g;
    var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
    exports.format = format;
    exports.parse = parse3;
    function format(obj) {
      if (!obj || typeof obj !== "object") {
        throw new TypeError("argument obj is required");
      }
      var parameters = obj.parameters;
      var type = obj.type;
      if (!type || !TYPE_REGEXP.test(type)) {
        throw new TypeError("invalid type");
      }
      var string4 = type;
      if (parameters && typeof parameters === "object") {
        var param;
        var params = Object.keys(parameters).sort();
        for (var i = 0; i < params.length; i++) {
          param = params[i];
          if (!TOKEN_REGEXP.test(param)) {
            throw new TypeError("invalid parameter name");
          }
          string4 += "; " + param + "=" + qstring(parameters[param]);
        }
      }
      return string4;
    }
    function parse3(string4) {
      if (!string4) {
        throw new TypeError("argument string is required");
      }
      var header = typeof string4 === "object" ? getcontenttype(string4) : string4;
      if (typeof header !== "string") {
        throw new TypeError("argument string is required to be a string");
      }
      var index2 = header.indexOf(";");
      var type = index2 !== -1 ? header.slice(0, index2).trim() : header.trim();
      if (!TYPE_REGEXP.test(type)) {
        throw new TypeError("invalid media type");
      }
      var obj = new ContentType(type.toLowerCase());
      if (index2 !== -1) {
        var key;
        var match;
        var value;
        PARAM_REGEXP.lastIndex = index2;
        while (match = PARAM_REGEXP.exec(header)) {
          if (match.index !== index2) {
            throw new TypeError("invalid parameter format");
          }
          index2 += match[0].length;
          key = match[1].toLowerCase();
          value = match[2];
          if (value.charCodeAt(0) === 34) {
            value = value.slice(1, -1);
            if (value.indexOf("\\") !== -1) {
              value = value.replace(QESC_REGEXP, "$1");
            }
          }
          obj.parameters[key] = value;
        }
        if (index2 !== header.length) {
          throw new TypeError("invalid parameter format");
        }
      }
      return obj;
    }
    function getcontenttype(obj) {
      var header;
      if (typeof obj.getHeader === "function") {
        header = obj.getHeader("content-type");
      } else if (typeof obj.headers === "object") {
        header = obj.headers && obj.headers["content-type"];
      }
      if (typeof header !== "string") {
        throw new TypeError("content-type header is missing from object");
      }
      return header;
    }
    function qstring(val) {
      var str = String(val);
      if (TOKEN_REGEXP.test(str)) {
        return str;
      }
      if (str.length > 0 && !TEXT_REGEXP.test(str)) {
        throw new TypeError("invalid parameter value");
      }
      return '"' + str.replace(QUOTE_REGEXP, "\\$1") + '"';
    }
    function ContentType(type) {
      this.parameters = /* @__PURE__ */ Object.create(null);
      this.type = type;
    }
  }
});

// ../../node_modules/.pnpm/setprototypeof@1.2.0/node_modules/setprototypeof/index.js
var require_setprototypeof = __commonJS({
  "../../node_modules/.pnpm/setprototypeof@1.2.0/node_modules/setprototypeof/index.js"(exports, module) {
    "use strict";
    module.exports = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array ? setProtoOf : mixinProperties);
    function setProtoOf(obj, proto) {
      obj.__proto__ = proto;
      return obj;
    }
    function mixinProperties(obj, proto) {
      for (var prop in proto) {
        if (!Object.prototype.hasOwnProperty.call(obj, prop)) {
          obj[prop] = proto[prop];
        }
      }
      return obj;
    }
  }
});

// ../../node_modules/.pnpm/statuses@2.0.1/node_modules/statuses/codes.json
var require_codes = __commonJS({
  "../../node_modules/.pnpm/statuses@2.0.1/node_modules/statuses/codes.json"(exports, module) {
    module.exports = {
      "100": "Continue",
      "101": "Switching Protocols",
      "102": "Processing",
      "103": "Early Hints",
      "200": "OK",
      "201": "Created",
      "202": "Accepted",
      "203": "Non-Authoritative Information",
      "204": "No Content",
      "205": "Reset Content",
      "206": "Partial Content",
      "207": "Multi-Status",
      "208": "Already Reported",
      "226": "IM Used",
      "300": "Multiple Choices",
      "301": "Moved Permanently",
      "302": "Found",
      "303": "See Other",
      "304": "Not Modified",
      "305": "Use Proxy",
      "307": "Temporary Redirect",
      "308": "Permanent Redirect",
      "400": "Bad Request",
      "401": "Unauthorized",
      "402": "Payment Required",
      "403": "Forbidden",
      "404": "Not Found",
      "405": "Method Not Allowed",
      "406": "Not Acceptable",
      "407": "Proxy Authentication Required",
      "408": "Request Timeout",
      "409": "Conflict",
      "410": "Gone",
      "411": "Length Required",
      "412": "Precondition Failed",
      "413": "Payload Too Large",
      "414": "URI Too Long",
      "415": "Unsupported Media Type",
      "416": "Range Not Satisfiable",
      "417": "Expectation Failed",
      "418": "I'm a Teapot",
      "421": "Misdirected Request",
      "422": "Unprocessable Entity",
      "423": "Locked",
      "424": "Failed Dependency",
      "425": "Too Early",
      "426": "Upgrade Required",
      "428": "Precondition Required",
      "429": "Too Many Requests",
      "431": "Request Header Fields Too Large",
      "451": "Unavailable For Legal Reasons",
      "500": "Internal Server Error",
      "501": "Not Implemented",
      "502": "Bad Gateway",
      "503": "Service Unavailable",
      "504": "Gateway Timeout",
      "505": "HTTP Version Not Supported",
      "506": "Variant Also Negotiates",
      "507": "Insufficient Storage",
      "508": "Loop Detected",
      "509": "Bandwidth Limit Exceeded",
      "510": "Not Extended",
      "511": "Network Authentication Required"
    };
  }
});

// ../../node_modules/.pnpm/statuses@2.0.1/node_modules/statuses/index.js
var require_statuses = __commonJS({
  "../../node_modules/.pnpm/statuses@2.0.1/node_modules/statuses/index.js"(exports, module) {
    "use strict";
    var codes = require_codes();
    module.exports = status;
    status.message = codes;
    status.code = createMessageToStatusCodeMap(codes);
    status.codes = createStatusCodeList(codes);
    status.redirect = {
      300: true,
      301: true,
      302: true,
      303: true,
      305: true,
      307: true,
      308: true
    };
    status.empty = {
      204: true,
      205: true,
      304: true
    };
    status.retry = {
      502: true,
      503: true,
      504: true
    };
    function createMessageToStatusCodeMap(codes2) {
      var map2 = {};
      Object.keys(codes2).forEach(function forEachCode(code) {
        var message = codes2[code];
        var status2 = Number(code);
        map2[message.toLowerCase()] = status2;
      });
      return map2;
    }
    function createStatusCodeList(codes2) {
      return Object.keys(codes2).map(function mapCode(code) {
        return Number(code);
      });
    }
    function getStatusCode(message) {
      var msg = message.toLowerCase();
      if (!Object.prototype.hasOwnProperty.call(status.code, msg)) {
        throw new Error('invalid status message: "' + message + '"');
      }
      return status.code[msg];
    }
    function getStatusMessage(code) {
      if (!Object.prototype.hasOwnProperty.call(status.message, code)) {
        throw new Error("invalid status code: " + code);
      }
      return status.message[code];
    }
    function status(code) {
      if (typeof code === "number") {
        return getStatusMessage(code);
      }
      if (typeof code !== "string") {
        throw new TypeError("code must be a number or string");
      }
      var n = parseInt(code, 10);
      if (!isNaN(n)) {
        return getStatusMessage(n);
      }
      return getStatusCode(code);
    }
  }
});

// ../../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits_browser.js
var require_inherits_browser = __commonJS({
  "../../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits_browser.js"(exports, module) {
    if (typeof Object.create === "function") {
      module.exports = function inherits(ctor, superCtor) {
        if (superCtor) {
          ctor.super_ = superCtor;
          ctor.prototype = Object.create(superCtor.prototype, {
            constructor: {
              value: ctor,
              enumerable: false,
              writable: true,
              configurable: true
            }
          });
        }
      };
    } else {
      module.exports = function inherits(ctor, superCtor) {
        if (superCtor) {
          ctor.super_ = superCtor;
          var TempCtor = function() {
          };
          TempCtor.prototype = superCtor.prototype;
          ctor.prototype = new TempCtor();
          ctor.prototype.constructor = ctor;
        }
      };
    }
  }
});

// ../../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits.js
var require_inherits = __commonJS({
  "../../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits.js"(exports, module) {
    try {
      util2 = __require("util");
      if (typeof util2.inherits !== "function") throw "";
      module.exports = util2.inherits;
    } catch (e) {
      module.exports = require_inherits_browser();
    }
    var util2;
  }
});

// ../../node_modules/.pnpm/toidentifier@1.0.1/node_modules/toidentifier/index.js
var require_toidentifier = __commonJS({
  "../../node_modules/.pnpm/toidentifier@1.0.1/node_modules/toidentifier/index.js"(exports, module) {
    "use strict";
    module.exports = toIdentifier;
    function toIdentifier(str) {
      return str.split(" ").map(function(token) {
        return token.slice(0, 1).toUpperCase() + token.slice(1);
      }).join("").replace(/[^ _0-9a-z]/gi, "");
    }
  }
});

// ../../node_modules/.pnpm/http-errors@2.0.0/node_modules/http-errors/index.js
var require_http_errors = __commonJS({
  "../../node_modules/.pnpm/http-errors@2.0.0/node_modules/http-errors/index.js"(exports, module) {
    "use strict";
    var deprecate = require_depd()("http-errors");
    var setPrototypeOf = require_setprototypeof();
    var statuses = require_statuses();
    var inherits = require_inherits();
    var toIdentifier = require_toidentifier();
    module.exports = createError;
    module.exports.HttpError = createHttpErrorConstructor();
    module.exports.isHttpError = createIsHttpErrorFunction(module.exports.HttpError);
    populateConstructorExports(module.exports, statuses.codes, module.exports.HttpError);
    function codeClass(status) {
      return Number(String(status).charAt(0) + "00");
    }
    function createError() {
      var err;
      var msg;
      var status = 500;
      var props = {};
      for (var i = 0; i < arguments.length; i++) {
        var arg = arguments[i];
        var type = typeof arg;
        if (type === "object" && arg instanceof Error) {
          err = arg;
          status = err.status || err.statusCode || status;
        } else if (type === "number" && i === 0) {
          status = arg;
        } else if (type === "string") {
          msg = arg;
        } else if (type === "object") {
          props = arg;
        } else {
          throw new TypeError("argument #" + (i + 1) + " unsupported type " + type);
        }
      }
      if (typeof status === "number" && (status < 400 || status >= 600)) {
        deprecate("non-error status code; use only 4xx or 5xx status codes");
      }
      if (typeof status !== "number" || !statuses.message[status] && (status < 400 || status >= 600)) {
        status = 500;
      }
      var HttpError = createError[status] || createError[codeClass(status)];
      if (!err) {
        err = HttpError ? new HttpError(msg) : new Error(msg || statuses.message[status]);
        Error.captureStackTrace(err, createError);
      }
      if (!HttpError || !(err instanceof HttpError) || err.status !== status) {
        err.expose = status < 500;
        err.status = err.statusCode = status;
      }
      for (var key in props) {
        if (key !== "status" && key !== "statusCode") {
          err[key] = props[key];
        }
      }
      return err;
    }
    function createHttpErrorConstructor() {
      function HttpError() {
        throw new TypeError("cannot construct abstract class");
      }
      inherits(HttpError, Error);
      return HttpError;
    }
    function createClientErrorConstructor(HttpError, name, code) {
      var className = toClassName(name);
      function ClientError(message) {
        var msg = message != null ? message : statuses.message[code];
        var err = new Error(msg);
        Error.captureStackTrace(err, ClientError);
        setPrototypeOf(err, ClientError.prototype);
        Object.defineProperty(err, "message", {
          enumerable: true,
          configurable: true,
          value: msg,
          writable: true
        });
        Object.defineProperty(err, "name", {
          enumerable: false,
          configurable: true,
          value: className,
          writable: true
        });
        return err;
      }
      inherits(ClientError, HttpError);
      nameFunc(ClientError, className);
      ClientError.prototype.status = code;
      ClientError.prototype.statusCode = code;
      ClientError.prototype.expose = true;
      return ClientError;
    }
    function createIsHttpErrorFunction(HttpError) {
      return function isHttpError(val) {
        if (!val || typeof val !== "object") {
          return false;
        }
        if (val instanceof HttpError) {
          return true;
        }
        return val instanceof Error && typeof val.expose === "boolean" && typeof val.statusCode === "number" && val.status === val.statusCode;
      };
    }
    function createServerErrorConstructor(HttpError, name, code) {
      var className = toClassName(name);
      function ServerError(message) {
        var msg = message != null ? message : statuses.message[code];
        var err = new Error(msg);
        Error.captureStackTrace(err, ServerError);
        setPrototypeOf(err, ServerError.prototype);
        Object.defineProperty(err, "message", {
          enumerable: true,
          configurable: true,
          value: msg,
          writable: true
        });
        Object.defineProperty(err, "name", {
          enumerable: false,
          configurable: true,
          value: className,
          writable: true
        });
        return err;
      }
      inherits(ServerError, HttpError);
      nameFunc(ServerError, className);
      ServerError.prototype.status = code;
      ServerError.prototype.statusCode = code;
      ServerError.prototype.expose = false;
      return ServerError;
    }
    function nameFunc(func, name) {
      var desc2 = Object.getOwnPropertyDescriptor(func, "name");
      if (desc2 && desc2.configurable) {
        desc2.value = name;
        Object.defineProperty(func, "name", desc2);
      }
    }
    function populateConstructorExports(exports2, codes, HttpError) {
      codes.forEach(function forEachCode(code) {
        var CodeError;
        var name = toIdentifier(statuses.message[code]);
        switch (codeClass(code)) {
          case 400:
            CodeError = createClientErrorConstructor(HttpError, name, code);
            break;
          case 500:
            CodeError = createServerErrorConstructor(HttpError, name, code);
            break;
        }
        if (CodeError) {
          exports2[code] = CodeError;
          exports2[name] = CodeError;
        }
      });
    }
    function toClassName(name) {
      return name.substr(-5) !== "Error" ? name + "Error" : name;
    }
  }
});

// ../../node_modules/.pnpm/ms@2.0.0/node_modules/ms/index.js
var require_ms = __commonJS({
  "../../node_modules/.pnpm/ms@2.0.0/node_modules/ms/index.js"(exports, module) {
    var s = 1e3;
    var m = s * 60;
    var h = m * 60;
    var d = h * 24;
    var y = d * 365.25;
    module.exports = function(val, options) {
      options = options || {};
      var type = typeof val;
      if (type === "string" && val.length > 0) {
        return parse3(val);
      } else if (type === "number" && isNaN(val) === false) {
        return options.long ? fmtLong(val) : fmtShort(val);
      }
      throw new Error(
        "val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
      );
    };
    function parse3(str) {
      str = String(str);
      if (str.length > 100) {
        return;
      }
      var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
        str
      );
      if (!match) {
        return;
      }
      var n = parseFloat(match[1]);
      var type = (match[2] || "ms").toLowerCase();
      switch (type) {
        case "years":
        case "year":
        case "yrs":
        case "yr":
        case "y":
          return n * y;
        case "days":
        case "day":
        case "d":
          return n * d;
        case "hours":
        case "hour":
        case "hrs":
        case "hr":
        case "h":
          return n * h;
        case "minutes":
        case "minute":
        case "mins":
        case "min":
        case "m":
          return n * m;
        case "seconds":
        case "second":
        case "secs":
        case "sec":
        case "s":
          return n * s;
        case "milliseconds":
        case "millisecond":
        case "msecs":
        case "msec":
        case "ms":
          return n;
        default:
          return void 0;
      }
    }
    function fmtShort(ms) {
      if (ms >= d) {
        return Math.round(ms / d) + "d";
      }
      if (ms >= h) {
        return Math.round(ms / h) + "h";
      }
      if (ms >= m) {
        return Math.round(ms / m) + "m";
      }
      if (ms >= s) {
        return Math.round(ms / s) + "s";
      }
      return ms + "ms";
    }
    function fmtLong(ms) {
      return plural(ms, d, "day") || plural(ms, h, "hour") || plural(ms, m, "minute") || plural(ms, s, "second") || ms + " ms";
    }
    function plural(ms, n, name) {
      if (ms < n) {
        return;
      }
      if (ms < n * 1.5) {
        return Math.floor(ms / n) + " " + name;
      }
      return Math.ceil(ms / n) + " " + name + "s";
    }
  }
});

// ../../node_modules/.pnpm/debug@2.6.9/node_modules/debug/src/debug.js
var require_debug = __commonJS({
  "../../node_modules/.pnpm/debug@2.6.9/node_modules/debug/src/debug.js"(exports, module) {
    exports = module.exports = createDebug.debug = createDebug["default"] = createDebug;
    exports.coerce = coerce2;
    exports.disable = disable;
    exports.enable = enable;
    exports.enabled = enabled2;
    exports.humanize = require_ms();
    exports.names = [];
    exports.skips = [];
    exports.formatters = {};
    var prevTime;
    function selectColor(namespace) {
      var hash2 = 0, i;
      for (i in namespace) {
        hash2 = (hash2 << 5) - hash2 + namespace.charCodeAt(i);
        hash2 |= 0;
      }
      return exports.colors[Math.abs(hash2) % exports.colors.length];
    }
    function createDebug(namespace) {
      function debug() {
        if (!debug.enabled) return;
        var self = debug;
        var curr = +/* @__PURE__ */ new Date();
        var ms = curr - (prevTime || curr);
        self.diff = ms;
        self.prev = prevTime;
        self.curr = curr;
        prevTime = curr;
        var args = new Array(arguments.length);
        for (var i = 0; i < args.length; i++) {
          args[i] = arguments[i];
        }
        args[0] = exports.coerce(args[0]);
        if ("string" !== typeof args[0]) {
          args.unshift("%O");
        }
        var index2 = 0;
        args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
          if (match === "%%") return match;
          index2++;
          var formatter = exports.formatters[format];
          if ("function" === typeof formatter) {
            var val = args[index2];
            match = formatter.call(self, val);
            args.splice(index2, 1);
            index2--;
          }
          return match;
        });
        exports.formatArgs.call(self, args);
        var logFn = debug.log || exports.log || console.log.bind(console);
        logFn.apply(self, args);
      }
      debug.namespace = namespace;
      debug.enabled = exports.enabled(namespace);
      debug.useColors = exports.useColors();
      debug.color = selectColor(namespace);
      if ("function" === typeof exports.init) {
        exports.init(debug);
      }
      return debug;
    }
    function enable(namespaces) {
      exports.save(namespaces);
      exports.names = [];
      exports.skips = [];
      var split = (typeof namespaces === "string" ? namespaces : "").split(/[\s,]+/);
      var len = split.length;
      for (var i = 0; i < len; i++) {
        if (!split[i]) continue;
        namespaces = split[i].replace(/\*/g, ".*?");
        if (namespaces[0] === "-") {
          exports.skips.push(new RegExp("^" + namespaces.substr(1) + "$"));
        } else {
          exports.names.push(new RegExp("^" + namespaces + "$"));
        }
      }
    }
    function disable() {
      exports.enable("");
    }
    function enabled2(name) {
      var i, len;
      for (i = 0, len = exports.skips.length; i < len; i++) {
        if (exports.skips[i].test(name)) {
          return false;
        }
      }
      for (i = 0, len = exports.names.length; i < len; i++) {
        if (exports.names[i].test(name)) {
          return true;
        }
      }
      return false;
    }
    function coerce2(val) {
      if (val instanceof Error) return val.stack || val.message;
      return val;
    }
  }
});

// ../../node_modules/.pnpm/debug@2.6.9/node_modules/debug/src/browser.js
var require_browser = __commonJS({
  "../../node_modules/.pnpm/debug@2.6.9/node_modules/debug/src/browser.js"(exports, module) {
    exports = module.exports = require_debug();
    exports.log = log;
    exports.formatArgs = formatArgs;
    exports.save = save;
    exports.load = load;
    exports.useColors = useColors;
    exports.storage = "undefined" != typeof chrome && "undefined" != typeof chrome.storage ? chrome.storage.local : localstorage();
    exports.colors = [
      "lightseagreen",
      "forestgreen",
      "goldenrod",
      "dodgerblue",
      "darkorchid",
      "crimson"
    ];
    function useColors() {
      if (typeof window !== "undefined" && window.process && window.process.type === "renderer") {
        return true;
      }
      return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // is firebug? http://stackoverflow.com/a/398120/376773
      typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // is firefox >= v31?
      // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
      typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // double check webkit in userAgent just in case we are in a worker
      typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
    }
    exports.formatters.j = function(v) {
      try {
        return JSON.stringify(v);
      } catch (err) {
        return "[UnexpectedJSONParseError]: " + err.message;
      }
    };
    function formatArgs(args) {
      var useColors2 = this.useColors;
      args[0] = (useColors2 ? "%c" : "") + this.namespace + (useColors2 ? " %c" : " ") + args[0] + (useColors2 ? "%c " : " ") + "+" + exports.humanize(this.diff);
      if (!useColors2) return;
      var c = "color: " + this.color;
      args.splice(1, 0, c, "color: inherit");
      var index2 = 0;
      var lastC = 0;
      args[0].replace(/%[a-zA-Z%]/g, function(match) {
        if ("%%" === match) return;
        index2++;
        if ("%c" === match) {
          lastC = index2;
        }
      });
      args.splice(lastC, 0, c);
    }
    function log() {
      return "object" === typeof console && console.log && Function.prototype.apply.call(console.log, console, arguments);
    }
    function save(namespaces) {
      try {
        if (null == namespaces) {
          exports.storage.removeItem("debug");
        } else {
          exports.storage.debug = namespaces;
        }
      } catch (e) {
      }
    }
    function load() {
      var r;
      try {
        r = exports.storage.debug;
      } catch (e) {
      }
      if (!r && typeof process !== "undefined" && "env" in process) {
        r = process.env.DEBUG;
      }
      return r;
    }
    exports.enable(load());
    function localstorage() {
      try {
        return window.localStorage;
      } catch (e) {
      }
    }
  }
});

// ../../node_modules/.pnpm/debug@2.6.9/node_modules/debug/src/node.js
var require_node = __commonJS({
  "../../node_modules/.pnpm/debug@2.6.9/node_modules/debug/src/node.js"(exports, module) {
    var tty = __require("tty");
    var util2 = __require("util");
    exports = module.exports = require_debug();
    exports.init = init;
    exports.log = log;
    exports.formatArgs = formatArgs;
    exports.save = save;
    exports.load = load;
    exports.useColors = useColors;
    exports.colors = [6, 2, 3, 4, 5, 1];
    exports.inspectOpts = Object.keys(process.env).filter(function(key) {
      return /^debug_/i.test(key);
    }).reduce(function(obj, key) {
      var prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, function(_, k) {
        return k.toUpperCase();
      });
      var val = process.env[key];
      if (/^(yes|on|true|enabled)$/i.test(val)) val = true;
      else if (/^(no|off|false|disabled)$/i.test(val)) val = false;
      else if (val === "null") val = null;
      else val = Number(val);
      obj[prop] = val;
      return obj;
    }, {});
    var fd = parseInt(process.env.DEBUG_FD, 10) || 2;
    if (1 !== fd && 2 !== fd) {
      util2.deprecate(function() {
      }, "except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)")();
    }
    var stream = 1 === fd ? process.stdout : 2 === fd ? process.stderr : createWritableStdioStream(fd);
    function useColors() {
      return "colors" in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(fd);
    }
    exports.formatters.o = function(v) {
      this.inspectOpts.colors = this.useColors;
      return util2.inspect(v, this.inspectOpts).split("\n").map(function(str) {
        return str.trim();
      }).join(" ");
    };
    exports.formatters.O = function(v) {
      this.inspectOpts.colors = this.useColors;
      return util2.inspect(v, this.inspectOpts);
    };
    function formatArgs(args) {
      var name = this.namespace;
      var useColors2 = this.useColors;
      if (useColors2) {
        var c = this.color;
        var prefix = "  \x1B[3" + c + ";1m" + name + " \x1B[0m";
        args[0] = prefix + args[0].split("\n").join("\n" + prefix);
        args.push("\x1B[3" + c + "m+" + exports.humanize(this.diff) + "\x1B[0m");
      } else {
        args[0] = (/* @__PURE__ */ new Date()).toUTCString() + " " + name + " " + args[0];
      }
    }
    function log() {
      return stream.write(util2.format.apply(util2, arguments) + "\n");
    }
    function save(namespaces) {
      if (null == namespaces) {
        delete process.env.DEBUG;
      } else {
        process.env.DEBUG = namespaces;
      }
    }
    function load() {
      return process.env.DEBUG;
    }
    function createWritableStdioStream(fd2) {
      var stream2;
      var tty_wrap = process.binding("tty_wrap");
      switch (tty_wrap.guessHandleType(fd2)) {
        case "TTY":
          stream2 = new tty.WriteStream(fd2);
          stream2._type = "tty";
          if (stream2._handle && stream2._handle.unref) {
            stream2._handle.unref();
          }
          break;
        case "FILE":
          var fs2 = __require("fs");
          stream2 = new fs2.SyncWriteStream(fd2, { autoClose: false });
          stream2._type = "fs";
          break;
        case "PIPE":
        case "TCP":
          var net = __require("net");
          stream2 = new net.Socket({
            fd: fd2,
            readable: false,
            writable: true
          });
          stream2.readable = false;
          stream2.read = null;
          stream2._type = "pipe";
          if (stream2._handle && stream2._handle.unref) {
            stream2._handle.unref();
          }
          break;
        default:
          throw new Error("Implement me. Unknown stream file type!");
      }
      stream2.fd = fd2;
      stream2._isStdio = true;
      return stream2;
    }
    function init(debug) {
      debug.inspectOpts = {};
      var keys = Object.keys(exports.inspectOpts);
      for (var i = 0; i < keys.length; i++) {
        debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
      }
    }
    exports.enable(load());
  }
});

// ../../node_modules/.pnpm/debug@2.6.9/node_modules/debug/src/index.js
var require_src = __commonJS({
  "../../node_modules/.pnpm/debug@2.6.9/node_modules/debug/src/index.js"(exports, module) {
    if (typeof process !== "undefined" && process.type === "renderer") {
      module.exports = require_browser();
    } else {
      module.exports = require_node();
    }
  }
});

// ../../node_modules/.pnpm/destroy@1.2.0/node_modules/destroy/index.js
var require_destroy = __commonJS({
  "../../node_modules/.pnpm/destroy@1.2.0/node_modules/destroy/index.js"(exports, module) {
    "use strict";
    var EventEmitter2 = __require("events").EventEmitter;
    var ReadStream = __require("fs").ReadStream;
    var Stream = __require("stream");
    var Zlib = __require("zlib");
    module.exports = destroy;
    function destroy(stream, suppress) {
      if (isFsReadStream(stream)) {
        destroyReadStream(stream);
      } else if (isZlibStream(stream)) {
        destroyZlibStream(stream);
      } else if (hasDestroy(stream)) {
        stream.destroy();
      }
      if (isEventEmitter(stream) && suppress) {
        stream.removeAllListeners("error");
        stream.addListener("error", noop);
      }
      return stream;
    }
    function destroyReadStream(stream) {
      stream.destroy();
      if (typeof stream.close === "function") {
        stream.on("open", onOpenClose);
      }
    }
    function closeZlibStream(stream) {
      if (stream._hadError === true) {
        var prop = stream._binding === null ? "_binding" : "_handle";
        stream[prop] = {
          close: function() {
            this[prop] = null;
          }
        };
      }
      stream.close();
    }
    function destroyZlibStream(stream) {
      if (typeof stream.destroy === "function") {
        if (stream._binding) {
          stream.destroy();
          if (stream._processing) {
            stream._needDrain = true;
            stream.once("drain", onDrainClearBinding);
          } else {
            stream._binding.clear();
          }
        } else if (stream._destroy && stream._destroy !== Stream.Transform.prototype._destroy) {
          stream.destroy();
        } else if (stream._destroy && typeof stream.close === "function") {
          stream.destroyed = true;
          stream.close();
        } else {
          stream.destroy();
        }
      } else if (typeof stream.close === "function") {
        closeZlibStream(stream);
      }
    }
    function hasDestroy(stream) {
      return stream instanceof Stream && typeof stream.destroy === "function";
    }
    function isEventEmitter(val) {
      return val instanceof EventEmitter2;
    }
    function isFsReadStream(stream) {
      return stream instanceof ReadStream;
    }
    function isZlibStream(stream) {
      return stream instanceof Zlib.Gzip || stream instanceof Zlib.Gunzip || stream instanceof Zlib.Deflate || stream instanceof Zlib.DeflateRaw || stream instanceof Zlib.Inflate || stream instanceof Zlib.InflateRaw || stream instanceof Zlib.Unzip;
    }
    function noop() {
    }
    function onDrainClearBinding() {
      this._binding.clear();
    }
    function onOpenClose() {
      if (typeof this.fd === "number") {
        this.close();
      }
    }
  }
});

// ../../node_modules/.pnpm/safer-buffer@2.1.2/node_modules/safer-buffer/safer.js
var require_safer = __commonJS({
  "../../node_modules/.pnpm/safer-buffer@2.1.2/node_modules/safer-buffer/safer.js"(exports, module) {
    "use strict";
    var buffer = __require("buffer");
    var Buffer3 = buffer.Buffer;
    var safer = {};
    var key;
    for (key in buffer) {
      if (!buffer.hasOwnProperty(key)) continue;
      if (key === "SlowBuffer" || key === "Buffer") continue;
      safer[key] = buffer[key];
    }
    var Safer = safer.Buffer = {};
    for (key in Buffer3) {
      if (!Buffer3.hasOwnProperty(key)) continue;
      if (key === "allocUnsafe" || key === "allocUnsafeSlow") continue;
      Safer[key] = Buffer3[key];
    }
    safer.Buffer.prototype = Buffer3.prototype;
    if (!Safer.from || Safer.from === Uint8Array.from) {
      Safer.from = function(value, encodingOrOffset, length) {
        if (typeof value === "number") {
          throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value);
        }
        if (value && typeof value.length === "undefined") {
          throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value);
        }
        return Buffer3(value, encodingOrOffset, length);
      };
    }
    if (!Safer.alloc) {
      Safer.alloc = function(size, fill, encoding) {
        if (typeof size !== "number") {
          throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size);
        }
        if (size < 0 || size >= 2 * (1 << 30)) {
          throw new RangeError('The value "' + size + '" is invalid for option "size"');
        }
        var buf = Buffer3(size);
        if (!fill || fill.length === 0) {
          buf.fill(0);
        } else if (typeof encoding === "string") {
          buf.fill(fill, encoding);
        } else {
          buf.fill(fill);
        }
        return buf;
      };
    }
    if (!safer.kStringMaxLength) {
      try {
        safer.kStringMaxLength = process.binding("buffer").kStringMaxLength;
      } catch (e) {
      }
    }
    if (!safer.constants) {
      safer.constants = {
        MAX_LENGTH: safer.kMaxLength
      };
      if (safer.kStringMaxLength) {
        safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength;
      }
    }
    module.exports = safer;
  }
});

// ../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/lib/bom-handling.js
var require_bom_handling = __commonJS({
  "../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/lib/bom-handling.js"(exports) {
    "use strict";
    var BOMChar = "\uFEFF";
    exports.PrependBOM = PrependBOMWrapper;
    function PrependBOMWrapper(encoder, options) {
      this.encoder = encoder;
      this.addBOM = true;
    }
    PrependBOMWrapper.prototype.write = function(str) {
      if (this.addBOM) {
        str = BOMChar + str;
        this.addBOM = false;
      }
      return this.encoder.write(str);
    };
    PrependBOMWrapper.prototype.end = function() {
      return this.encoder.end();
    };
    exports.StripBOM = StripBOMWrapper;
    function StripBOMWrapper(decoder, options) {
      this.decoder = decoder;
      this.pass = false;
      this.options = options || {};
    }
    StripBOMWrapper.prototype.write = function(buf) {
      var res = this.decoder.write(buf);
      if (this.pass || !res)
        return res;
      if (res[0] === BOMChar) {
        res = res.slice(1);
        if (typeof this.options.stripBOM === "function")
          this.options.stripBOM();
      }
      this.pass = true;
      return res;
    };
    StripBOMWrapper.prototype.end = function() {
      return this.decoder.end();
    };
  }
});

// ../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/internal.js
var require_internal = __commonJS({
  "../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/internal.js"(exports, module) {
    "use strict";
    var Buffer3 = require_safer().Buffer;
    module.exports = {
      // Encodings
      utf8: { type: "_internal", bomAware: true },
      cesu8: { type: "_internal", bomAware: true },
      unicode11utf8: "utf8",
      ucs2: { type: "_internal", bomAware: true },
      utf16le: "ucs2",
      binary: { type: "_internal" },
      base64: { type: "_internal" },
      hex: { type: "_internal" },
      // Codec.
      _internal: InternalCodec
    };
    function InternalCodec(codecOptions, iconv) {
      this.enc = codecOptions.encodingName;
      this.bomAware = codecOptions.bomAware;
      if (this.enc === "base64")
        this.encoder = InternalEncoderBase64;
      else if (this.enc === "cesu8") {
        this.enc = "utf8";
        this.encoder = InternalEncoderCesu8;
        if (Buffer3.from("eda0bdedb2a9", "hex").toString() !== "\u{1F4A9}") {
          this.decoder = InternalDecoderCesu8;
          this.defaultCharUnicode = iconv.defaultCharUnicode;
        }
      }
    }
    InternalCodec.prototype.encoder = InternalEncoder;
    InternalCodec.prototype.decoder = InternalDecoder;
    var StringDecoder = __require("string_decoder").StringDecoder;
    if (!StringDecoder.prototype.end)
      StringDecoder.prototype.end = function() {
      };
    function InternalDecoder(options, codec) {
      StringDecoder.call(this, codec.enc);
    }
    InternalDecoder.prototype = StringDecoder.prototype;
    function InternalEncoder(options, codec) {
      this.enc = codec.enc;
    }
    InternalEncoder.prototype.write = function(str) {
      return Buffer3.from(str, this.enc);
    };
    InternalEncoder.prototype.end = function() {
    };
    function InternalEncoderBase64(options, codec) {
      this.prevStr = "";
    }
    InternalEncoderBase64.prototype.write = function(str) {
      str = this.prevStr + str;
      var completeQuads = str.length - str.length % 4;
      this.prevStr = str.slice(completeQuads);
      str = str.slice(0, completeQuads);
      return Buffer3.from(str, "base64");
    };
    InternalEncoderBase64.prototype.end = function() {
      return Buffer3.from(this.prevStr, "base64");
    };
    function InternalEncoderCesu8(options, codec) {
    }
    InternalEncoderCesu8.prototype.write = function(str) {
      var buf = Buffer3.alloc(str.length * 3), bufIdx = 0;
      for (var i = 0; i < str.length; i++) {
        var charCode = str.charCodeAt(i);
        if (charCode < 128)
          buf[bufIdx++] = charCode;
        else if (charCode < 2048) {
          buf[bufIdx++] = 192 + (charCode >>> 6);
          buf[bufIdx++] = 128 + (charCode & 63);
        } else {
          buf[bufIdx++] = 224 + (charCode >>> 12);
          buf[bufIdx++] = 128 + (charCode >>> 6 & 63);
          buf[bufIdx++] = 128 + (charCode & 63);
        }
      }
      return buf.slice(0, bufIdx);
    };
    InternalEncoderCesu8.prototype.end = function() {
    };
    function InternalDecoderCesu8(options, codec) {
      this.acc = 0;
      this.contBytes = 0;
      this.accBytes = 0;
      this.defaultCharUnicode = codec.defaultCharUnicode;
    }
    InternalDecoderCesu8.prototype.write = function(buf) {
      var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, res = "";
      for (var i = 0; i < buf.length; i++) {
        var curByte = buf[i];
        if ((curByte & 192) !== 128) {
          if (contBytes > 0) {
            res += this.defaultCharUnicode;
            contBytes = 0;
          }
          if (curByte < 128) {
            res += String.fromCharCode(curByte);
          } else if (curByte < 224) {
            acc = curByte & 31;
            contBytes = 1;
            accBytes = 1;
          } else if (curByte < 240) {
            acc = curByte & 15;
            contBytes = 2;
            accBytes = 1;
          } else {
            res += this.defaultCharUnicode;
          }
        } else {
          if (contBytes > 0) {
            acc = acc << 6 | curByte & 63;
            contBytes--;
            accBytes++;
            if (contBytes === 0) {
              if (accBytes === 2 && acc < 128 && acc > 0)
                res += this.defaultCharUnicode;
              else if (accBytes === 3 && acc < 2048)
                res += this.defaultCharUnicode;
              else
                res += String.fromCharCode(acc);
            }
          } else {
            res += this.defaultCharUnicode;
          }
        }
      }
      this.acc = acc;
      this.contBytes = contBytes;
      this.accBytes = accBytes;
      return res;
    };
    InternalDecoderCesu8.prototype.end = function() {
      var res = 0;
      if (this.contBytes > 0)
        res += this.defaultCharUnicode;
      return res;
    };
  }
});

// ../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/utf16.js
var require_utf16 = __commonJS({
  "../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/utf16.js"(exports) {
    "use strict";
    var Buffer3 = require_safer().Buffer;
    exports.utf16be = Utf16BECodec;
    function Utf16BECodec() {
    }
    Utf16BECodec.prototype.encoder = Utf16BEEncoder;
    Utf16BECodec.prototype.decoder = Utf16BEDecoder;
    Utf16BECodec.prototype.bomAware = true;
    function Utf16BEEncoder() {
    }
    Utf16BEEncoder.prototype.write = function(str) {
      var buf = Buffer3.from(str, "ucs2");
      for (var i = 0; i < buf.length; i += 2) {
        var tmp = buf[i];
        buf[i] = buf[i + 1];
        buf[i + 1] = tmp;
      }
      return buf;
    };
    Utf16BEEncoder.prototype.end = function() {
    };
    function Utf16BEDecoder() {
      this.overflowByte = -1;
    }
    Utf16BEDecoder.prototype.write = function(buf) {
      if (buf.length == 0)
        return "";
      var buf2 = Buffer3.alloc(buf.length + 1), i = 0, j = 0;
      if (this.overflowByte !== -1) {
        buf2[0] = buf[0];
        buf2[1] = this.overflowByte;
        i = 1;
        j = 2;
      }
      for (; i < buf.length - 1; i += 2, j += 2) {
        buf2[j] = buf[i + 1];
        buf2[j + 1] = buf[i];
      }
      this.overflowByte = i == buf.length - 1 ? buf[buf.length - 1] : -1;
      return buf2.slice(0, j).toString("ucs2");
    };
    Utf16BEDecoder.prototype.end = function() {
    };
    exports.utf16 = Utf16Codec;
    function Utf16Codec(codecOptions, iconv) {
      this.iconv = iconv;
    }
    Utf16Codec.prototype.encoder = Utf16Encoder;
    Utf16Codec.prototype.decoder = Utf16Decoder;
    function Utf16Encoder(options, codec) {
      options = options || {};
      if (options.addBOM === void 0)
        options.addBOM = true;
      this.encoder = codec.iconv.getEncoder("utf-16le", options);
    }
    Utf16Encoder.prototype.write = function(str) {
      return this.encoder.write(str);
    };
    Utf16Encoder.prototype.end = function() {
      return this.encoder.end();
    };
    function Utf16Decoder(options, codec) {
      this.decoder = null;
      this.initialBytes = [];
      this.initialBytesLen = 0;
      this.options = options || {};
      this.iconv = codec.iconv;
    }
    Utf16Decoder.prototype.write = function(buf) {
      if (!this.decoder) {
        this.initialBytes.push(buf);
        this.initialBytesLen += buf.length;
        if (this.initialBytesLen < 16)
          return "";
        var buf = Buffer3.concat(this.initialBytes), encoding = detectEncoding(buf, this.options.defaultEncoding);
        this.decoder = this.iconv.getDecoder(encoding, this.options);
        this.initialBytes.length = this.initialBytesLen = 0;
      }
      return this.decoder.write(buf);
    };
    Utf16Decoder.prototype.end = function() {
      if (!this.decoder) {
        var buf = Buffer3.concat(this.initialBytes), encoding = detectEncoding(buf, this.options.defaultEncoding);
        this.decoder = this.iconv.getDecoder(encoding, this.options);
        var res = this.decoder.write(buf), trail = this.decoder.end();
        return trail ? res + trail : res;
      }
      return this.decoder.end();
    };
    function detectEncoding(buf, defaultEncoding) {
      var enc = defaultEncoding || "utf-16le";
      if (buf.length >= 2) {
        if (buf[0] == 254 && buf[1] == 255)
          enc = "utf-16be";
        else if (buf[0] == 255 && buf[1] == 254)
          enc = "utf-16le";
        else {
          var asciiCharsLE = 0, asciiCharsBE = 0, _len = Math.min(buf.length - buf.length % 2, 64);
          for (var i = 0; i < _len; i += 2) {
            if (buf[i] === 0 && buf[i + 1] !== 0) asciiCharsBE++;
            if (buf[i] !== 0 && buf[i + 1] === 0) asciiCharsLE++;
          }
          if (asciiCharsBE > asciiCharsLE)
            enc = "utf-16be";
          else if (asciiCharsBE < asciiCharsLE)
            enc = "utf-16le";
        }
      }
      return enc;
    }
  }
});

// ../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/utf7.js
var require_utf7 = __commonJS({
  "../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/utf7.js"(exports) {
    "use strict";
    var Buffer3 = require_safer().Buffer;
    exports.utf7 = Utf7Codec;
    exports.unicode11utf7 = "utf7";
    function Utf7Codec(codecOptions, iconv) {
      this.iconv = iconv;
    }
    Utf7Codec.prototype.encoder = Utf7Encoder;
    Utf7Codec.prototype.decoder = Utf7Decoder;
    Utf7Codec.prototype.bomAware = true;
    var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g;
    function Utf7Encoder(options, codec) {
      this.iconv = codec.iconv;
    }
    Utf7Encoder.prototype.write = function(str) {
      return Buffer3.from(str.replace(nonDirectChars, function(chunk2) {
        return "+" + (chunk2 === "+" ? "" : this.iconv.encode(chunk2, "utf16-be").toString("base64").replace(/=+$/, "")) + "-";
      }.bind(this)));
    };
    Utf7Encoder.prototype.end = function() {
    };
    function Utf7Decoder(options, codec) {
      this.iconv = codec.iconv;
      this.inBase64 = false;
      this.base64Accum = "";
    }
    var base64Regex2 = /[A-Za-z0-9\/+]/;
    var base64Chars = [];
    for (i = 0; i < 256; i++)
      base64Chars[i] = base64Regex2.test(String.fromCharCode(i));
    var i;
    var plusChar = "+".charCodeAt(0);
    var minusChar = "-".charCodeAt(0);
    var andChar = "&".charCodeAt(0);
    Utf7Decoder.prototype.write = function(buf) {
      var res = "", lastI = 0, inBase64 = this.inBase64, base64Accum = this.base64Accum;
      for (var i2 = 0; i2 < buf.length; i2++) {
        if (!inBase64) {
          if (buf[i2] == plusChar) {
            res += this.iconv.decode(buf.slice(lastI, i2), "ascii");
            lastI = i2 + 1;
            inBase64 = true;
          }
        } else {
          if (!base64Chars[buf[i2]]) {
            if (i2 == lastI && buf[i2] == minusChar) {
              res += "+";
            } else {
              var b64str = base64Accum + buf.slice(lastI, i2).toString();
              res += this.iconv.decode(Buffer3.from(b64str, "base64"), "utf16-be");
            }
            if (buf[i2] != minusChar)
              i2--;
            lastI = i2 + 1;
            inBase64 = false;
            base64Accum = "";
          }
        }
      }
      if (!inBase64) {
        res += this.iconv.decode(buf.slice(lastI), "ascii");
      } else {
        var b64str = base64Accum + buf.slice(lastI).toString();
        var canBeDecoded = b64str.length - b64str.length % 8;
        base64Accum = b64str.slice(canBeDecoded);
        b64str = b64str.slice(0, canBeDecoded);
        res += this.iconv.decode(Buffer3.from(b64str, "base64"), "utf16-be");
      }
      this.inBase64 = inBase64;
      this.base64Accum = base64Accum;
      return res;
    };
    Utf7Decoder.prototype.end = function() {
      var res = "";
      if (this.inBase64 && this.base64Accum.length > 0)
        res = this.iconv.decode(Buffer3.from(this.base64Accum, "base64"), "utf16-be");
      this.inBase64 = false;
      this.base64Accum = "";
      return res;
    };
    exports.utf7imap = Utf7IMAPCodec;
    function Utf7IMAPCodec(codecOptions, iconv) {
      this.iconv = iconv;
    }
    Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder;
    Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder;
    Utf7IMAPCodec.prototype.bomAware = true;
    function Utf7IMAPEncoder(options, codec) {
      this.iconv = codec.iconv;
      this.inBase64 = false;
      this.base64Accum = Buffer3.alloc(6);
      this.base64AccumIdx = 0;
    }
    Utf7IMAPEncoder.prototype.write = function(str) {
      var inBase64 = this.inBase64, base64Accum = this.base64Accum, base64AccumIdx = this.base64AccumIdx, buf = Buffer3.alloc(str.length * 5 + 10), bufIdx = 0;
      for (var i2 = 0; i2 < str.length; i2++) {
        var uChar = str.charCodeAt(i2);
        if (32 <= uChar && uChar <= 126) {
          if (inBase64) {
            if (base64AccumIdx > 0) {
              bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString("base64").replace(/\//g, ",").replace(/=+$/, ""), bufIdx);
              base64AccumIdx = 0;
            }
            buf[bufIdx++] = minusChar;
            inBase64 = false;
          }
          if (!inBase64) {
            buf[bufIdx++] = uChar;
            if (uChar === andChar)
              buf[bufIdx++] = minusChar;
          }
        } else {
          if (!inBase64) {
            buf[bufIdx++] = andChar;
            inBase64 = true;
          }
          if (inBase64) {
            base64Accum[base64AccumIdx++] = uChar >> 8;
            base64Accum[base64AccumIdx++] = uChar & 255;
            if (base64AccumIdx == base64Accum.length) {
              bufIdx += buf.write(base64Accum.toString("base64").replace(/\//g, ","), bufIdx);
              base64AccumIdx = 0;
            }
          }
        }
      }
      this.inBase64 = inBase64;
      this.base64AccumIdx = base64AccumIdx;
      return buf.slice(0, bufIdx);
    };
    Utf7IMAPEncoder.prototype.end = function() {
      var buf = Buffer3.alloc(10), bufIdx = 0;
      if (this.inBase64) {
        if (this.base64AccumIdx > 0) {
          bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString("base64").replace(/\//g, ",").replace(/=+$/, ""), bufIdx);
          this.base64AccumIdx = 0;
        }
        buf[bufIdx++] = minusChar;
        this.inBase64 = false;
      }
      return buf.slice(0, bufIdx);
    };
    function Utf7IMAPDecoder(options, codec) {
      this.iconv = codec.iconv;
      this.inBase64 = false;
      this.base64Accum = "";
    }
    var base64IMAPChars = base64Chars.slice();
    base64IMAPChars[",".charCodeAt(0)] = true;
    Utf7IMAPDecoder.prototype.write = function(buf) {
      var res = "", lastI = 0, inBase64 = this.inBase64, base64Accum = this.base64Accum;
      for (var i2 = 0; i2 < buf.length; i2++) {
        if (!inBase64) {
          if (buf[i2] == andChar) {
            res += this.iconv.decode(buf.slice(lastI, i2), "ascii");
            lastI = i2 + 1;
            inBase64 = true;
          }
        } else {
          if (!base64IMAPChars[buf[i2]]) {
            if (i2 == lastI && buf[i2] == minusChar) {
              res += "&";
            } else {
              var b64str = base64Accum + buf.slice(lastI, i2).toString().replace(/,/g, "/");
              res += this.iconv.decode(Buffer3.from(b64str, "base64"), "utf16-be");
            }
            if (buf[i2] != minusChar)
              i2--;
            lastI = i2 + 1;
            inBase64 = false;
            base64Accum = "";
          }
        }
      }
      if (!inBase64) {
        res += this.iconv.decode(buf.slice(lastI), "ascii");
      } else {
        var b64str = base64Accum + buf.slice(lastI).toString().replace(/,/g, "/");
        var canBeDecoded = b64str.length - b64str.length % 8;
        base64Accum = b64str.slice(canBeDecoded);
        b64str = b64str.slice(0, canBeDecoded);
        res += this.iconv.decode(Buffer3.from(b64str, "base64"), "utf16-be");
      }
      this.inBase64 = inBase64;
      this.base64Accum = base64Accum;
      return res;
    };
    Utf7IMAPDecoder.prototype.end = function() {
      var res = "";
      if (this.inBase64 && this.base64Accum.length > 0)
        res = this.iconv.decode(Buffer3.from(this.base64Accum, "base64"), "utf16-be");
      this.inBase64 = false;
      this.base64Accum = "";
      return res;
    };
  }
});

// ../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/sbcs-codec.js
var require_sbcs_codec = __commonJS({
  "../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/sbcs-codec.js"(exports) {
    "use strict";
    var Buffer3 = require_safer().Buffer;
    exports._sbcs = SBCSCodec;
    function SBCSCodec(codecOptions, iconv) {
      if (!codecOptions)
        throw new Error("SBCS codec is called without the data.");
      if (!codecOptions.chars || codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256)
        throw new Error("Encoding '" + codecOptions.type + "' has incorrect 'chars' (must be of len 128 or 256)");
      if (codecOptions.chars.length === 128) {
        var asciiString = "";
        for (var i = 0; i < 128; i++)
          asciiString += String.fromCharCode(i);
        codecOptions.chars = asciiString + codecOptions.chars;
      }
      this.decodeBuf = Buffer3.from(codecOptions.chars, "ucs2");
      var encodeBuf = Buffer3.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0));
      for (var i = 0; i < codecOptions.chars.length; i++)
        encodeBuf[codecOptions.chars.charCodeAt(i)] = i;
      this.encodeBuf = encodeBuf;
    }
    SBCSCodec.prototype.encoder = SBCSEncoder;
    SBCSCodec.prototype.decoder = SBCSDecoder;
    function SBCSEncoder(options, codec) {
      this.encodeBuf = codec.encodeBuf;
    }
    SBCSEncoder.prototype.write = function(str) {
      var buf = Buffer3.alloc(str.length);
      for (var i = 0; i < str.length; i++)
        buf[i] = this.encodeBuf[str.charCodeAt(i)];
      return buf;
    };
    SBCSEncoder.prototype.end = function() {
    };
    function SBCSDecoder(options, codec) {
      this.decodeBuf = codec.decodeBuf;
    }
    SBCSDecoder.prototype.write = function(buf) {
      var decodeBuf = this.decodeBuf;
      var newBuf = Buffer3.alloc(buf.length * 2);
      var idx1 = 0, idx2 = 0;
      for (var i = 0; i < buf.length; i++) {
        idx1 = buf[i] * 2;
        idx2 = i * 2;
        newBuf[idx2] = decodeBuf[idx1];
        newBuf[idx2 + 1] = decodeBuf[idx1 + 1];
      }
      return newBuf.toString("ucs2");
    };
    SBCSDecoder.prototype.end = function() {
    };
  }
});

// ../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/sbcs-data.js
var require_sbcs_data = __commonJS({
  "../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/sbcs-data.js"(exports, module) {
    "use strict";
    module.exports = {
      // Not supported by iconv, not sure why.
      "10029": "maccenteuro",
      "maccenteuro": {
        "type": "_sbcs",
        "chars": "\xC4\u0100\u0101\xC9\u0104\xD6\xDC\xE1\u0105\u010C\xE4\u010D\u0106\u0107\xE9\u0179\u017A\u010E\xED\u010F\u0112\u0113\u0116\xF3\u0117\xF4\xF6\xF5\xFA\u011A\u011B\xFC\u2020\xB0\u0118\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\u0119\xA8\u2260\u0123\u012E\u012F\u012A\u2264\u2265\u012B\u0136\u2202\u2211\u0142\u013B\u013C\u013D\u013E\u0139\u013A\u0145\u0146\u0143\xAC\u221A\u0144\u0147\u2206\xAB\xBB\u2026\xA0\u0148\u0150\xD5\u0151\u014C\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\u014D\u0154\u0155\u0158\u2039\u203A\u0159\u0156\u0157\u0160\u201A\u201E\u0161\u015A\u015B\xC1\u0164\u0165\xCD\u017D\u017E\u016A\xD3\xD4\u016B\u016E\xDA\u016F\u0170\u0171\u0172\u0173\xDD\xFD\u0137\u017B\u0141\u017C\u0122\u02C7"
      },
      "808": "cp808",
      "ibm808": "cp808",
      "cp808": {
        "type": "_sbcs",
        "chars": "\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u0401\u0451\u0404\u0454\u0407\u0457\u040E\u045E\xB0\u2219\xB7\u221A\u2116\u20AC\u25A0\xA0"
      },
      "mik": {
        "type": "_sbcs",
        "chars": "\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u2514\u2534\u252C\u251C\u2500\u253C\u2563\u2551\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2510\u2591\u2592\u2593\u2502\u2524\u2116\xA7\u2557\u255D\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0"
      },
      // Aliases of generated encodings.
      "ascii8bit": "ascii",
      "usascii": "ascii",
      "ansix34": "ascii",
      "ansix341968": "ascii",
      "ansix341986": "ascii",
      "csascii": "ascii",
      "cp367": "ascii",
      "ibm367": "ascii",
      "isoir6": "ascii",
      "iso646us": "ascii",
      "iso646irv": "ascii",
      "us": "ascii",
      "latin1": "iso88591",
      "latin2": "iso88592",
      "latin3": "iso88593",
      "latin4": "iso88594",
      "latin5": "iso88599",
      "latin6": "iso885910",
      "latin7": "iso885913",
      "latin8": "iso885914",
      "latin9": "iso885915",
      "latin10": "iso885916",
      "csisolatin1": "iso88591",
      "csisolatin2": "iso88592",
      "csisolatin3": "iso88593",
      "csisolatin4": "iso88594",
      "csisolatincyrillic": "iso88595",
      "csisolatinarabic": "iso88596",
      "csisolatingreek": "iso88597",
      "csisolatinhebrew": "iso88598",
      "csisolatin5": "iso88599",
      "csisolatin6": "iso885910",
      "l1": "iso88591",
      "l2": "iso88592",
      "l3": "iso88593",
      "l4": "iso88594",
      "l5": "iso88599",
      "l6": "iso885910",
      "l7": "iso885913",
      "l8": "iso885914",
      "l9": "iso885915",
      "l10": "iso885916",
      "isoir14": "iso646jp",
      "isoir57": "iso646cn",
      "isoir100": "iso88591",
      "isoir101": "iso88592",
      "isoir109": "iso88593",
      "isoir110": "iso88594",
      "isoir144": "iso88595",
      "isoir127": "iso88596",
      "isoir126": "iso88597",
      "isoir138": "iso88598",
      "isoir148": "iso88599",
      "isoir157": "iso885910",
      "isoir166": "tis620",
      "isoir179": "iso885913",
      "isoir199": "iso885914",
      "isoir203": "iso885915",
      "isoir226": "iso885916",
      "cp819": "iso88591",
      "ibm819": "iso88591",
      "cyrillic": "iso88595",
      "arabic": "iso88596",
      "arabic8": "iso88596",
      "ecma114": "iso88596",
      "asmo708": "iso88596",
      "greek": "iso88597",
      "greek8": "iso88597",
      "ecma118": "iso88597",
      "elot928": "iso88597",
      "hebrew": "iso88598",
      "hebrew8": "iso88598",
      "turkish": "iso88599",
      "turkish8": "iso88599",
      "thai": "iso885911",
      "thai8": "iso885911",
      "celtic": "iso885914",
      "celtic8": "iso885914",
      "isoceltic": "iso885914",
      "tis6200": "tis620",
      "tis62025291": "tis620",
      "tis62025330": "tis620",
      "10000": "macroman",
      "10006": "macgreek",
      "10007": "maccyrillic",
      "10079": "maciceland",
      "10081": "macturkish",
      "cspc8codepage437": "cp437",
      "cspc775baltic": "cp775",
      "cspc850multilingual": "cp850",
      "cspcp852": "cp852",
      "cspc862latinhebrew": "cp862",
      "cpgr": "cp869",
      "msee": "cp1250",
      "mscyrl": "cp1251",
      "msansi": "cp1252",
      "msgreek": "cp1253",
      "msturk": "cp1254",
      "mshebr": "cp1255",
      "msarab": "cp1256",
      "winbaltrim": "cp1257",
      "cp20866": "koi8r",
      "20866": "koi8r",
      "ibm878": "koi8r",
      "cskoi8r": "koi8r",
      "cp21866": "koi8u",
      "21866": "koi8u",
      "ibm1168": "koi8u",
      "strk10482002": "rk1048",
      "tcvn5712": "tcvn",
      "tcvn57121": "tcvn",
      "gb198880": "iso646cn",
      "cn": "iso646cn",
      "csiso14jisc6220ro": "iso646jp",
      "jisc62201969ro": "iso646jp",
      "jp": "iso646jp",
      "cshproman8": "hproman8",
      "r8": "hproman8",
      "roman8": "hproman8",
      "xroman8": "hproman8",
      "ibm1051": "hproman8",
      "mac": "macintosh",
      "csmacintosh": "macintosh"
    };
  }
});

// ../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/sbcs-data-generated.js
var require_sbcs_data_generated = __commonJS({
  "../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/sbcs-data-generated.js"(exports, module) {
    "use strict";
    module.exports = {
      "437": "cp437",
      "737": "cp737",
      "775": "cp775",
      "850": "cp850",
      "852": "cp852",
      "855": "cp855",
      "856": "cp856",
      "857": "cp857",
      "858": "cp858",
      "860": "cp860",
      "861": "cp861",
      "862": "cp862",
      "863": "cp863",
      "864": "cp864",
      "865": "cp865",
      "866": "cp866",
      "869": "cp869",
      "874": "windows874",
      "922": "cp922",
      "1046": "cp1046",
      "1124": "cp1124",
      "1125": "cp1125",
      "1129": "cp1129",
      "1133": "cp1133",
      "1161": "cp1161",
      "1162": "cp1162",
      "1163": "cp1163",
      "1250": "windows1250",
      "1251": "windows1251",
      "1252": "windows1252",
      "1253": "windows1253",
      "1254": "windows1254",
      "1255": "windows1255",
      "1256": "windows1256",
      "1257": "windows1257",
      "1258": "windows1258",
      "28591": "iso88591",
      "28592": "iso88592",
      "28593": "iso88593",
      "28594": "iso88594",
      "28595": "iso88595",
      "28596": "iso88596",
      "28597": "iso88597",
      "28598": "iso88598",
      "28599": "iso88599",
      "28600": "iso885910",
      "28601": "iso885911",
      "28603": "iso885913",
      "28604": "iso885914",
      "28605": "iso885915",
      "28606": "iso885916",
      "windows874": {
        "type": "_sbcs",
        "chars": "\u20AC\uFFFD\uFFFD\uFFFD\uFFFD\u2026\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\xA0\u0E01\u0E02\u0E03\u0E04\u0E05\u0E06\u0E07\u0E08\u0E09\u0E0A\u0E0B\u0E0C\u0E0D\u0E0E\u0E0F\u0E10\u0E11\u0E12\u0E13\u0E14\u0E15\u0E16\u0E17\u0E18\u0E19\u0E1A\u0E1B\u0E1C\u0E1D\u0E1E\u0E1F\u0E20\u0E21\u0E22\u0E23\u0E24\u0E25\u0E26\u0E27\u0E28\u0E29\u0E2A\u0E2B\u0E2C\u0E2D\u0E2E\u0E2F\u0E30\u0E31\u0E32\u0E33\u0E34\u0E35\u0E36\u0E37\u0E38\u0E39\u0E3A\uFFFD\uFFFD\uFFFD\uFFFD\u0E3F\u0E40\u0E41\u0E42\u0E43\u0E44\u0E45\u0E46\u0E47\u0E48\u0E49\u0E4A\u0E4B\u0E4C\u0E4D\u0E4E\u0E4F\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59\u0E5A\u0E5B\uFFFD\uFFFD\uFFFD\uFFFD"
      },
      "win874": "windows874",
      "cp874": "windows874",
      "windows1250": {
        "type": "_sbcs",
        "chars": "\u20AC\uFFFD\u201A\uFFFD\u201E\u2026\u2020\u2021\uFFFD\u2030\u0160\u2039\u015A\u0164\u017D\u0179\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\u2122\u0161\u203A\u015B\u0165\u017E\u017A\xA0\u02C7\u02D8\u0141\xA4\u0104\xA6\xA7\xA8\xA9\u015E\xAB\xAC\xAD\xAE\u017B\xB0\xB1\u02DB\u0142\xB4\xB5\xB6\xB7\xB8\u0105\u015F\xBB\u013D\u02DD\u013E\u017C\u0154\xC1\xC2\u0102\xC4\u0139\u0106\xC7\u010C\xC9\u0118\xCB\u011A\xCD\xCE\u010E\u0110\u0143\u0147\xD3\xD4\u0150\xD6\xD7\u0158\u016E\xDA\u0170\xDC\xDD\u0162\xDF\u0155\xE1\xE2\u0103\xE4\u013A\u0107\xE7\u010D\xE9\u0119\xEB\u011B\xED\xEE\u010F\u0111\u0144\u0148\xF3\xF4\u0151\xF6\xF7\u0159\u016F\xFA\u0171\xFC\xFD\u0163\u02D9"
      },
      "win1250": "windows1250",
      "cp1250": "windows1250",
      "windows1251": {
        "type": "_sbcs",
        "chars": "\u0402\u0403\u201A\u0453\u201E\u2026\u2020\u2021\u20AC\u2030\u0409\u2039\u040A\u040C\u040B\u040F\u0452\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\u2122\u0459\u203A\u045A\u045C\u045B\u045F\xA0\u040E\u045E\u0408\xA4\u0490\xA6\xA7\u0401\xA9\u0404\xAB\xAC\xAD\xAE\u0407\xB0\xB1\u0406\u0456\u0491\xB5\xB6\xB7\u0451\u2116\u0454\xBB\u0458\u0405\u0455\u0457\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F"
      },
      "win1251": "windows1251",
      "cp1251": "windows1251",
      "windows1252": {
        "type": "_sbcs",
        "chars": "\u20AC\uFFFD\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\u0160\u2039\u0152\uFFFD\u017D\uFFFD\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u02DC\u2122\u0161\u203A\u0153\uFFFD\u017E\u0178\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"
      },
      "win1252": "windows1252",
      "cp1252": "windows1252",
      "windows1253": {
        "type": "_sbcs",
        "chars": "\u20AC\uFFFD\u201A\u0192\u201E\u2026\u2020\u2021\uFFFD\u2030\uFFFD\u2039\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\u2122\uFFFD\u203A\uFFFD\uFFFD\uFFFD\uFFFD\xA0\u0385\u0386\xA3\xA4\xA5\xA6\xA7\xA8\xA9\uFFFD\xAB\xAC\xAD\xAE\u2015\xB0\xB1\xB2\xB3\u0384\xB5\xB6\xB7\u0388\u0389\u038A\xBB\u038C\xBD\u038E\u038F\u0390\u0391\u0392\u0393\u0394\u0395\u0396\u0397\u0398\u0399\u039A\u039B\u039C\u039D\u039E\u039F\u03A0\u03A1\uFFFD\u03A3\u03A4\u03A5\u03A6\u03A7\u03A8\u03A9\u03AA\u03AB\u03AC\u03AD\u03AE\u03AF\u03B0\u03B1\u03B2\u03B3\u03B4\u03B5\u03B6\u03B7\u03B8\u03B9\u03BA\u03BB\u03BC\u03BD\u03BE\u03BF\u03C0\u03C1\u03C2\u03C3\u03C4\u03C5\u03C6\u03C7\u03C8\u03C9\u03CA\u03CB\u03CC\u03CD\u03CE\uFFFD"
      },
      "win1253": "windows1253",
      "cp1253": "windows1253",
      "windows1254": {
        "type": "_sbcs",
        "chars": "\u20AC\uFFFD\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\u0160\u2039\u0152\uFFFD\uFFFD\uFFFD\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u02DC\u2122\u0161\u203A\u0153\uFFFD\uFFFD\u0178\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\u011E\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\u0130\u015E\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\u011F\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\u0131\u015F\xFF"
      },
      "win1254": "windows1254",
      "cp1254": "windows1254",
      "windows1255": {
        "type": "_sbcs",
        "chars": "\u20AC\uFFFD\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\uFFFD\u2039\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u02DC\u2122\uFFFD\u203A\uFFFD\uFFFD\uFFFD\uFFFD\xA0\xA1\xA2\xA3\u20AA\xA5\xA6\xA7\xA8\xA9\xD7\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xF7\xBB\xBC\xBD\xBE\xBF\u05B0\u05B1\u05B2\u05B3\u05B4\u05B5\u05B6\u05B7\u05B8\u05B9\u05BA\u05BB\u05BC\u05BD\u05BE\u05BF\u05C0\u05C1\u05C2\u05C3\u05F0\u05F1\u05F2\u05F3\u05F4\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u05D0\u05D1\u05D2\u05D3\u05D4\u05D5\u05D6\u05D7\u05D8\u05D9\u05DA\u05DB\u05DC\u05DD\u05DE\u05DF\u05E0\u05E1\u05E2\u05E3\u05E4\u05E5\u05E6\u05E7\u05E8\u05E9\u05EA\uFFFD\uFFFD\u200E\u200F\uFFFD"
      },
      "win1255": "windows1255",
      "cp1255": "windows1255",
      "windows1256": {
        "type": "_sbcs",
        "chars": "\u20AC\u067E\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\u0679\u2039\u0152\u0686\u0698\u0688\u06AF\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u06A9\u2122\u0691\u203A\u0153\u200C\u200D\u06BA\xA0\u060C\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\u06BE\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\u061B\xBB\xBC\xBD\xBE\u061F\u06C1\u0621\u0622\u0623\u0624\u0625\u0626\u0627\u0628\u0629\u062A\u062B\u062C\u062D\u062E\u062F\u0630\u0631\u0632\u0633\u0634\u0635\u0636\xD7\u0637\u0638\u0639\u063A\u0640\u0641\u0642\u0643\xE0\u0644\xE2\u0645\u0646\u0647\u0648\xE7\xE8\xE9\xEA\xEB\u0649\u064A\xEE\xEF\u064B\u064C\u064D\u064E\xF4\u064F\u0650\xF7\u0651\xF9\u0652\xFB\xFC\u200E\u200F\u06D2"
      },
      "win1256": "windows1256",
      "cp1256": "windows1256",
      "windows1257": {
        "type": "_sbcs",
        "chars": "\u20AC\uFFFD\u201A\uFFFD\u201E\u2026\u2020\u2021\uFFFD\u2030\uFFFD\u2039\uFFFD\xA8\u02C7\xB8\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\u2122\uFFFD\u203A\uFFFD\xAF\u02DB\uFFFD\xA0\uFFFD\xA2\xA3\xA4\uFFFD\xA6\xA7\xD8\xA9\u0156\xAB\xAC\xAD\xAE\xC6\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xF8\xB9\u0157\xBB\xBC\xBD\xBE\xE6\u0104\u012E\u0100\u0106\xC4\xC5\u0118\u0112\u010C\xC9\u0179\u0116\u0122\u0136\u012A\u013B\u0160\u0143\u0145\xD3\u014C\xD5\xD6\xD7\u0172\u0141\u015A\u016A\xDC\u017B\u017D\xDF\u0105\u012F\u0101\u0107\xE4\xE5\u0119\u0113\u010D\xE9\u017A\u0117\u0123\u0137\u012B\u013C\u0161\u0144\u0146\xF3\u014D\xF5\xF6\xF7\u0173\u0142\u015B\u016B\xFC\u017C\u017E\u02D9"
      },
      "win1257": "windows1257",
      "cp1257": "windows1257",
      "windows1258": {
        "type": "_sbcs",
        "chars": "\u20AC\uFFFD\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\uFFFD\u2039\u0152\uFFFD\uFFFD\uFFFD\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u02DC\u2122\uFFFD\u203A\u0153\uFFFD\uFFFD\u0178\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\u0102\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\u0300\xCD\xCE\xCF\u0110\xD1\u0309\xD3\xD4\u01A0\xD6\xD7\xD8\xD9\xDA\xDB\xDC\u01AF\u0303\xDF\xE0\xE1\xE2\u0103\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\u0301\xED\xEE\xEF\u0111\xF1\u0323\xF3\xF4\u01A1\xF6\xF7\xF8\xF9\xFA\xFB\xFC\u01B0\u20AB\xFF"
      },
      "win1258": "windows1258",
      "cp1258": "windows1258",
      "iso88591": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"
      },
      "cp28591": "iso88591",
      "iso88592": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0104\u02D8\u0141\xA4\u013D\u015A\xA7\xA8\u0160\u015E\u0164\u0179\xAD\u017D\u017B\xB0\u0105\u02DB\u0142\xB4\u013E\u015B\u02C7\xB8\u0161\u015F\u0165\u017A\u02DD\u017E\u017C\u0154\xC1\xC2\u0102\xC4\u0139\u0106\xC7\u010C\xC9\u0118\xCB\u011A\xCD\xCE\u010E\u0110\u0143\u0147\xD3\xD4\u0150\xD6\xD7\u0158\u016E\xDA\u0170\xDC\xDD\u0162\xDF\u0155\xE1\xE2\u0103\xE4\u013A\u0107\xE7\u010D\xE9\u0119\xEB\u011B\xED\xEE\u010F\u0111\u0144\u0148\xF3\xF4\u0151\xF6\xF7\u0159\u016F\xFA\u0171\xFC\xFD\u0163\u02D9"
      },
      "cp28592": "iso88592",
      "iso88593": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0126\u02D8\xA3\xA4\uFFFD\u0124\xA7\xA8\u0130\u015E\u011E\u0134\xAD\uFFFD\u017B\xB0\u0127\xB2\xB3\xB4\xB5\u0125\xB7\xB8\u0131\u015F\u011F\u0135\xBD\uFFFD\u017C\xC0\xC1\xC2\uFFFD\xC4\u010A\u0108\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\uFFFD\xD1\xD2\xD3\xD4\u0120\xD6\xD7\u011C\xD9\xDA\xDB\xDC\u016C\u015C\xDF\xE0\xE1\xE2\uFFFD\xE4\u010B\u0109\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\uFFFD\xF1\xF2\xF3\xF4\u0121\xF6\xF7\u011D\xF9\xFA\xFB\xFC\u016D\u015D\u02D9"
      },
      "cp28593": "iso88593",
      "iso88594": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0104\u0138\u0156\xA4\u0128\u013B\xA7\xA8\u0160\u0112\u0122\u0166\xAD\u017D\xAF\xB0\u0105\u02DB\u0157\xB4\u0129\u013C\u02C7\xB8\u0161\u0113\u0123\u0167\u014A\u017E\u014B\u0100\xC1\xC2\xC3\xC4\xC5\xC6\u012E\u010C\xC9\u0118\xCB\u0116\xCD\xCE\u012A\u0110\u0145\u014C\u0136\xD4\xD5\xD6\xD7\xD8\u0172\xDA\xDB\xDC\u0168\u016A\xDF\u0101\xE1\xE2\xE3\xE4\xE5\xE6\u012F\u010D\xE9\u0119\xEB\u0117\xED\xEE\u012B\u0111\u0146\u014D\u0137\xF4\xF5\xF6\xF7\xF8\u0173\xFA\xFB\xFC\u0169\u016B\u02D9"
      },
      "cp28594": "iso88594",
      "iso88595": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0401\u0402\u0403\u0404\u0405\u0406\u0407\u0408\u0409\u040A\u040B\u040C\xAD\u040E\u040F\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u2116\u0451\u0452\u0453\u0454\u0455\u0456\u0457\u0458\u0459\u045A\u045B\u045C\xA7\u045E\u045F"
      },
      "cp28595": "iso88595",
      "iso88596": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\uFFFD\uFFFD\uFFFD\xA4\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u060C\xAD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u061B\uFFFD\uFFFD\uFFFD\u061F\uFFFD\u0621\u0622\u0623\u0624\u0625\u0626\u0627\u0628\u0629\u062A\u062B\u062C\u062D\u062E\u062F\u0630\u0631\u0632\u0633\u0634\u0635\u0636\u0637\u0638\u0639\u063A\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0640\u0641\u0642\u0643\u0644\u0645\u0646\u0647\u0648\u0649\u064A\u064B\u064C\u064D\u064E\u064F\u0650\u0651\u0652\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"
      },
      "cp28596": "iso88596",
      "iso88597": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u2018\u2019\xA3\u20AC\u20AF\xA6\xA7\xA8\xA9\u037A\xAB\xAC\xAD\uFFFD\u2015\xB0\xB1\xB2\xB3\u0384\u0385\u0386\xB7\u0388\u0389\u038A\xBB\u038C\xBD\u038E\u038F\u0390\u0391\u0392\u0393\u0394\u0395\u0396\u0397\u0398\u0399\u039A\u039B\u039C\u039D\u039E\u039F\u03A0\u03A1\uFFFD\u03A3\u03A4\u03A5\u03A6\u03A7\u03A8\u03A9\u03AA\u03AB\u03AC\u03AD\u03AE\u03AF\u03B0\u03B1\u03B2\u03B3\u03B4\u03B5\u03B6\u03B7\u03B8\u03B9\u03BA\u03BB\u03BC\u03BD\u03BE\u03BF\u03C0\u03C1\u03C2\u03C3\u03C4\u03C5\u03C6\u03C7\u03C8\u03C9\u03CA\u03CB\u03CC\u03CD\u03CE\uFFFD"
      },
      "cp28597": "iso88597",
      "iso88598": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\uFFFD\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xD7\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xF7\xBB\xBC\xBD\xBE\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u2017\u05D0\u05D1\u05D2\u05D3\u05D4\u05D5\u05D6\u05D7\u05D8\u05D9\u05DA\u05DB\u05DC\u05DD\u05DE\u05DF\u05E0\u05E1\u05E2\u05E3\u05E4\u05E5\u05E6\u05E7\u05E8\u05E9\u05EA\uFFFD\uFFFD\u200E\u200F\uFFFD"
      },
      "cp28598": "iso88598",
      "iso88599": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\u011E\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\u0130\u015E\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\u011F\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\u0131\u015F\xFF"
      },
      "cp28599": "iso88599",
      "iso885910": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0104\u0112\u0122\u012A\u0128\u0136\xA7\u013B\u0110\u0160\u0166\u017D\xAD\u016A\u014A\xB0\u0105\u0113\u0123\u012B\u0129\u0137\xB7\u013C\u0111\u0161\u0167\u017E\u2015\u016B\u014B\u0100\xC1\xC2\xC3\xC4\xC5\xC6\u012E\u010C\xC9\u0118\xCB\u0116\xCD\xCE\xCF\xD0\u0145\u014C\xD3\xD4\xD5\xD6\u0168\xD8\u0172\xDA\xDB\xDC\xDD\xDE\xDF\u0101\xE1\xE2\xE3\xE4\xE5\xE6\u012F\u010D\xE9\u0119\xEB\u0117\xED\xEE\xEF\xF0\u0146\u014D\xF3\xF4\xF5\xF6\u0169\xF8\u0173\xFA\xFB\xFC\xFD\xFE\u0138"
      },
      "cp28600": "iso885910",
      "iso885911": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0E01\u0E02\u0E03\u0E04\u0E05\u0E06\u0E07\u0E08\u0E09\u0E0A\u0E0B\u0E0C\u0E0D\u0E0E\u0E0F\u0E10\u0E11\u0E12\u0E13\u0E14\u0E15\u0E16\u0E17\u0E18\u0E19\u0E1A\u0E1B\u0E1C\u0E1D\u0E1E\u0E1F\u0E20\u0E21\u0E22\u0E23\u0E24\u0E25\u0E26\u0E27\u0E28\u0E29\u0E2A\u0E2B\u0E2C\u0E2D\u0E2E\u0E2F\u0E30\u0E31\u0E32\u0E33\u0E34\u0E35\u0E36\u0E37\u0E38\u0E39\u0E3A\uFFFD\uFFFD\uFFFD\uFFFD\u0E3F\u0E40\u0E41\u0E42\u0E43\u0E44\u0E45\u0E46\u0E47\u0E48\u0E49\u0E4A\u0E4B\u0E4C\u0E4D\u0E4E\u0E4F\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59\u0E5A\u0E5B\uFFFD\uFFFD\uFFFD\uFFFD"
      },
      "cp28601": "iso885911",
      "iso885913": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u201D\xA2\xA3\xA4\u201E\xA6\xA7\xD8\xA9\u0156\xAB\xAC\xAD\xAE\xC6\xB0\xB1\xB2\xB3\u201C\xB5\xB6\xB7\xF8\xB9\u0157\xBB\xBC\xBD\xBE\xE6\u0104\u012E\u0100\u0106\xC4\xC5\u0118\u0112\u010C\xC9\u0179\u0116\u0122\u0136\u012A\u013B\u0160\u0143\u0145\xD3\u014C\xD5\xD6\xD7\u0172\u0141\u015A\u016A\xDC\u017B\u017D\xDF\u0105\u012F\u0101\u0107\xE4\xE5\u0119\u0113\u010D\xE9\u017A\u0117\u0123\u0137\u012B\u013C\u0161\u0144\u0146\xF3\u014D\xF5\xF6\xF7\u0173\u0142\u015B\u016B\xFC\u017C\u017E\u2019"
      },
      "cp28603": "iso885913",
      "iso885914": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u1E02\u1E03\xA3\u010A\u010B\u1E0A\xA7\u1E80\xA9\u1E82\u1E0B\u1EF2\xAD\xAE\u0178\u1E1E\u1E1F\u0120\u0121\u1E40\u1E41\xB6\u1E56\u1E81\u1E57\u1E83\u1E60\u1EF3\u1E84\u1E85\u1E61\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\u0174\xD1\xD2\xD3\xD4\xD5\xD6\u1E6A\xD8\xD9\xDA\xDB\xDC\xDD\u0176\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\u0175\xF1\xF2\xF3\xF4\xF5\xF6\u1E6B\xF8\xF9\xFA\xFB\xFC\xFD\u0177\xFF"
      },
      "cp28604": "iso885914",
      "iso885915": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\u20AC\xA5\u0160\xA7\u0161\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\u017D\xB5\xB6\xB7\u017E\xB9\xBA\xBB\u0152\u0153\u0178\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"
      },
      "cp28605": "iso885915",
      "iso885916": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0104\u0105\u0141\u20AC\u201E\u0160\xA7\u0161\xA9\u0218\xAB\u0179\xAD\u017A\u017B\xB0\xB1\u010C\u0142\u017D\u201D\xB6\xB7\u017E\u010D\u0219\xBB\u0152\u0153\u0178\u017C\xC0\xC1\xC2\u0102\xC4\u0106\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\u0110\u0143\xD2\xD3\xD4\u0150\xD6\u015A\u0170\xD9\xDA\xDB\xDC\u0118\u021A\xDF\xE0\xE1\xE2\u0103\xE4\u0107\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\u0111\u0144\xF2\xF3\xF4\u0151\xF6\u015B\u0171\xF9\xFA\xFB\xFC\u0119\u021B\xFF"
      },
      "cp28606": "iso885916",
      "cp437": {
        "type": "_sbcs",
        "chars": "\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0"
      },
      "ibm437": "cp437",
      "csibm437": "cp437",
      "cp737": {
        "type": "_sbcs",
        "chars": "\u0391\u0392\u0393\u0394\u0395\u0396\u0397\u0398\u0399\u039A\u039B\u039C\u039D\u039E\u039F\u03A0\u03A1\u03A3\u03A4\u03A5\u03A6\u03A7\u03A8\u03A9\u03B1\u03B2\u03B3\u03B4\u03B5\u03B6\u03B7\u03B8\u03B9\u03BA\u03BB\u03BC\u03BD\u03BE\u03BF\u03C0\u03C1\u03C3\u03C2\u03C4\u03C5\u03C6\u03C7\u03C8\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03C9\u03AC\u03AD\u03AE\u03CA\u03AF\u03CC\u03CD\u03CB\u03CE\u0386\u0388\u0389\u038A\u038C\u038E\u038F\xB1\u2265\u2264\u03AA\u03AB\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0"
      },
      "ibm737": "cp737",
      "csibm737": "cp737",
      "cp775": {
        "type": "_sbcs",
        "chars": "\u0106\xFC\xE9\u0101\xE4\u0123\xE5\u0107\u0142\u0113\u0156\u0157\u012B\u0179\xC4\xC5\xC9\xE6\xC6\u014D\xF6\u0122\xA2\u015A\u015B\xD6\xDC\xF8\xA3\xD8\xD7\xA4\u0100\u012A\xF3\u017B\u017C\u017A\u201D\xA6\xA9\xAE\xAC\xBD\xBC\u0141\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u0104\u010C\u0118\u0116\u2563\u2551\u2557\u255D\u012E\u0160\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u0172\u016A\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u017D\u0105\u010D\u0119\u0117\u012F\u0161\u0173\u016B\u017E\u2518\u250C\u2588\u2584\u258C\u2590\u2580\xD3\xDF\u014C\u0143\xF5\xD5\xB5\u0144\u0136\u0137\u013B\u013C\u0146\u0112\u0145\u2019\xAD\xB1\u201C\xBE\xB6\xA7\xF7\u201E\xB0\u2219\xB7\xB9\xB3\xB2\u25A0\xA0"
      },
      "ibm775": "cp775",
      "csibm775": "cp775",
      "cp850": {
        "type": "_sbcs",
        "chars": "\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xF8\xA3\xD8\xD7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\xAE\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\xC1\xC2\xC0\xA9\u2563\u2551\u2557\u255D\xA2\xA5\u2510\u2514\u2534\u252C\u251C\u2500\u253C\xE3\xC3\u255A\u2554\u2569\u2566\u2560\u2550\u256C\xA4\xF0\xD0\xCA\xCB\xC8\u0131\xCD\xCE\xCF\u2518\u250C\u2588\u2584\xA6\xCC\u2580\xD3\xDF\xD4\xD2\xF5\xD5\xB5\xFE\xDE\xDA\xDB\xD9\xFD\xDD\xAF\xB4\xAD\xB1\u2017\xBE\xB6\xA7\xF7\xB8\xB0\xA8\xB7\xB9\xB3\xB2\u25A0\xA0"
      },
      "ibm850": "cp850",
      "csibm850": "cp850",
      "cp852": {
        "type": "_sbcs",
        "chars": "\xC7\xFC\xE9\xE2\xE4\u016F\u0107\xE7\u0142\xEB\u0150\u0151\xEE\u0179\xC4\u0106\xC9\u0139\u013A\xF4\xF6\u013D\u013E\u015A\u015B\xD6\xDC\u0164\u0165\u0141\xD7\u010D\xE1\xED\xF3\xFA\u0104\u0105\u017D\u017E\u0118\u0119\xAC\u017A\u010C\u015F\xAB\xBB\u2591\u2592\u2593\u2502\u2524\xC1\xC2\u011A\u015E\u2563\u2551\u2557\u255D\u017B\u017C\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u0102\u0103\u255A\u2554\u2569\u2566\u2560\u2550\u256C\xA4\u0111\u0110\u010E\xCB\u010F\u0147\xCD\xCE\u011B\u2518\u250C\u2588\u2584\u0162\u016E\u2580\xD3\xDF\xD4\u0143\u0144\u0148\u0160\u0161\u0154\xDA\u0155\u0170\xFD\xDD\u0163\xB4\xAD\u02DD\u02DB\u02C7\u02D8\xA7\xF7\xB8\xB0\xA8\u02D9\u0171\u0158\u0159\u25A0\xA0"
      },
      "ibm852": "cp852",
      "csibm852": "cp852",
      "cp855": {
        "type": "_sbcs",
        "chars": "\u0452\u0402\u0453\u0403\u0451\u0401\u0454\u0404\u0455\u0405\u0456\u0406\u0457\u0407\u0458\u0408\u0459\u0409\u045A\u040A\u045B\u040B\u045C\u040C\u045E\u040E\u045F\u040F\u044E\u042E\u044A\u042A\u0430\u0410\u0431\u0411\u0446\u0426\u0434\u0414\u0435\u0415\u0444\u0424\u0433\u0413\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u0445\u0425\u0438\u0418\u2563\u2551\u2557\u255D\u0439\u0419\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u043A\u041A\u255A\u2554\u2569\u2566\u2560\u2550\u256C\xA4\u043B\u041B\u043C\u041C\u043D\u041D\u043E\u041E\u043F\u2518\u250C\u2588\u2584\u041F\u044F\u2580\u042F\u0440\u0420\u0441\u0421\u0442\u0422\u0443\u0423\u0436\u0416\u0432\u0412\u044C\u042C\u2116\xAD\u044B\u042B\u0437\u0417\u0448\u0428\u044D\u042D\u0449\u0429\u0447\u0427\xA7\u25A0\xA0"
      },
      "ibm855": "cp855",
      "csibm855": "cp855",
      "cp856": {
        "type": "_sbcs",
        "chars": "\u05D0\u05D1\u05D2\u05D3\u05D4\u05D5\u05D6\u05D7\u05D8\u05D9\u05DA\u05DB\u05DC\u05DD\u05DE\u05DF\u05E0\u05E1\u05E2\u05E3\u05E4\u05E5\u05E6\u05E7\u05E8\u05E9\u05EA\uFFFD\xA3\uFFFD\xD7\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\xAE\xAC\xBD\xBC\uFFFD\xAB\xBB\u2591\u2592\u2593\u2502\u2524\uFFFD\uFFFD\uFFFD\xA9\u2563\u2551\u2557\u255D\xA2\xA5\u2510\u2514\u2534\u252C\u251C\u2500\u253C\uFFFD\uFFFD\u255A\u2554\u2569\u2566\u2560\u2550\u256C\xA4\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u2518\u250C\u2588\u2584\xA6\uFFFD\u2580\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\xB5\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\xAF\xB4\xAD\xB1\u2017\xBE\xB6\xA7\xF7\xB8\xB0\xA8\xB7\xB9\xB3\xB2\u25A0\xA0"
      },
      "ibm856": "cp856",
      "csibm856": "cp856",
      "cp857": {
        "type": "_sbcs",
        "chars": "\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\u0131\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\u0130\xD6\xDC\xF8\xA3\xD8\u015E\u015F\xE1\xED\xF3\xFA\xF1\xD1\u011E\u011F\xBF\xAE\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\xC1\xC2\xC0\xA9\u2563\u2551\u2557\u255D\xA2\xA5\u2510\u2514\u2534\u252C\u251C\u2500\u253C\xE3\xC3\u255A\u2554\u2569\u2566\u2560\u2550\u256C\xA4\xBA\xAA\xCA\xCB\xC8\uFFFD\xCD\xCE\xCF\u2518\u250C\u2588\u2584\xA6\xCC\u2580\xD3\xDF\xD4\xD2\xF5\xD5\xB5\uFFFD\xD7\xDA\xDB\xD9\xEC\xFF\xAF\xB4\xAD\xB1\uFFFD\xBE\xB6\xA7\xF7\xB8\xB0\xA8\xB7\xB9\xB3\xB2\u25A0\xA0"
      },
      "ibm857": "cp857",
      "csibm857": "cp857",
      "cp858": {
        "type": "_sbcs",
        "chars": "\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xF8\xA3\xD8\xD7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\xAE\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\xC1\xC2\xC0\xA9\u2563\u2551\u2557\u255D\xA2\xA5\u2510\u2514\u2534\u252C\u251C\u2500\u253C\xE3\xC3\u255A\u2554\u2569\u2566\u2560\u2550\u256C\xA4\xF0\xD0\xCA\xCB\xC8\u20AC\xCD\xCE\xCF\u2518\u250C\u2588\u2584\xA6\xCC\u2580\xD3\xDF\xD4\xD2\xF5\xD5\xB5\xFE\xDE\xDA\xDB\xD9\xFD\xDD\xAF\xB4\xAD\xB1\u2017\xBE\xB6\xA7\xF7\xB8\xB0\xA8\xB7\xB9\xB3\xB2\u25A0\xA0"
      },
      "ibm858": "cp858",
      "csibm858": "cp858",
      "cp860": {
        "type": "_sbcs",
        "chars": "\xC7\xFC\xE9\xE2\xE3\xE0\xC1\xE7\xEA\xCA\xE8\xCD\xD4\xEC\xC3\xC2\xC9\xC0\xC8\xF4\xF5\xF2\xDA\xF9\xCC\xD5\xDC\xA2\xA3\xD9\u20A7\xD3\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\xD2\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0"
      },
      "ibm860": "cp860",
      "csibm860": "cp860",
      "cp861": {
        "type": "_sbcs",
        "chars": "\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xD0\xF0\xDE\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xFE\xFB\xDD\xFD\xD6\xDC\xF8\xA3\xD8\u20A7\u0192\xE1\xED\xF3\xFA\xC1\xCD\xD3\xDA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0"
      },
      "ibm861": "cp861",
      "csibm861": "cp861",
      "cp862": {
        "type": "_sbcs",
        "chars": "\u05D0\u05D1\u05D2\u05D3\u05D4\u05D5\u05D6\u05D7\u05D8\u05D9\u05DA\u05DB\u05DC\u05DD\u05DE\u05DF\u05E0\u05E1\u05E2\u05E3\u05E4\u05E5\u05E6\u05E7\u05E8\u05E9\u05EA\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0"
      },
      "ibm862": "cp862",
      "csibm862": "cp862",
      "cp863": {
        "type": "_sbcs",
        "chars": "\xC7\xFC\xE9\xE2\xC2\xE0\xB6\xE7\xEA\xEB\xE8\xEF\xEE\u2017\xC0\xA7\xC9\xC8\xCA\xF4\xCB\xCF\xFB\xF9\xA4\xD4\xDC\xA2\xA3\xD9\xDB\u0192\xA6\xB4\xF3\xFA\xA8\xB8\xB3\xAF\xCE\u2310\xAC\xBD\xBC\xBE\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0"
      },
      "ibm863": "cp863",
      "csibm863": "cp863",
      "cp864": {
        "type": "_sbcs",
        "chars": "\0\x07\b	\n\v\f\r\x1B !\"#$\u066A&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7F\xB0\xB7\u2219\u221A\u2592\u2500\u2502\u253C\u2524\u252C\u251C\u2534\u2510\u250C\u2514\u2518\u03B2\u221E\u03C6\xB1\xBD\xBC\u2248\xAB\xBB\uFEF7\uFEF8\uFFFD\uFFFD\uFEFB\uFEFC\uFFFD\xA0\xAD\uFE82\xA3\xA4\uFE84\uFFFD\uFFFD\uFE8E\uFE8F\uFE95\uFE99\u060C\uFE9D\uFEA1\uFEA5\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669\uFED1\u061B\uFEB1\uFEB5\uFEB9\u061F\xA2\uFE80\uFE81\uFE83\uFE85\uFECA\uFE8B\uFE8D\uFE91\uFE93\uFE97\uFE9B\uFE9F\uFEA3\uFEA7\uFEA9\uFEAB\uFEAD\uFEAF\uFEB3\uFEB7\uFEBB\uFEBF\uFEC1\uFEC5\uFECB\uFECF\xA6\xAC\xF7\xD7\uFEC9\u0640\uFED3\uFED7\uFEDB\uFEDF\uFEE3\uFEE7\uFEEB\uFEED\uFEEF\uFEF3\uFEBD\uFECC\uFECE\uFECD\uFEE1\uFE7D\u0651\uFEE5\uFEE9\uFEEC\uFEF0\uFEF2\uFED0\uFED5\uFEF5\uFEF6\uFEDD\uFED9\uFEF1\u25A0\uFFFD"
      },
      "ibm864": "cp864",
      "csibm864": "cp864",
      "cp865": {
        "type": "_sbcs",
        "chars": "\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xF8\xA3\xD8\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xA4\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0"
      },
      "ibm865": "cp865",
      "csibm865": "cp865",
      "cp866": {
        "type": "_sbcs",
        "chars": "\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u0401\u0451\u0404\u0454\u0407\u0457\u040E\u045E\xB0\u2219\xB7\u221A\u2116\xA4\u25A0\xA0"
      },
      "ibm866": "cp866",
      "csibm866": "cp866",
      "cp869": {
        "type": "_sbcs",
        "chars": "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0386\uFFFD\xB7\xAC\xA6\u2018\u2019\u0388\u2015\u0389\u038A\u03AA\u038C\uFFFD\uFFFD\u038E\u03AB\xA9\u038F\xB2\xB3\u03AC\xA3\u03AD\u03AE\u03AF\u03CA\u0390\u03CC\u03CD\u0391\u0392\u0393\u0394\u0395\u0396\u0397\xBD\u0398\u0399\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u039A\u039B\u039C\u039D\u2563\u2551\u2557\u255D\u039E\u039F\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u03A0\u03A1\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u03A3\u03A4\u03A5\u03A6\u03A7\u03A8\u03A9\u03B1\u03B2\u03B3\u2518\u250C\u2588\u2584\u03B4\u03B5\u2580\u03B6\u03B7\u03B8\u03B9\u03BA\u03BB\u03BC\u03BD\u03BE\u03BF\u03C0\u03C1\u03C3\u03C2\u03C4\u0384\xAD\xB1\u03C5\u03C6\u03C7\xA7\u03C8\u0385\xB0\xA8\u03C9\u03CB\u03B0\u03CE\u25A0\xA0"
      },
      "ibm869": "cp869",
      "csibm869": "cp869",
      "cp922": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\u203E\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\u0160\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\u017D\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\u0161\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\u017E\xFF"
      },
      "ibm922": "cp922",
      "csibm922": "cp922",
      "cp1046": {
        "type": "_sbcs",
        "chars": "\uFE88\xD7\xF7\uF8F6\uF8F5\uF8F4\uF8F7\uFE71\x88\u25A0\u2502\u2500\u2510\u250C\u2514\u2518\uFE79\uFE7B\uFE7D\uFE7F\uFE77\uFE8A\uFEF0\uFEF3\uFEF2\uFECE\uFECF\uFED0\uFEF6\uFEF8\uFEFA\uFEFC\xA0\uF8FA\uF8F9\uF8F8\xA4\uF8FB\uFE8B\uFE91\uFE97\uFE9B\uFE9F\uFEA3\u060C\xAD\uFEA7\uFEB3\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669\uFEB7\u061B\uFEBB\uFEBF\uFECA\u061F\uFECB\u0621\u0622\u0623\u0624\u0625\u0626\u0627\u0628\u0629\u062A\u062B\u062C\u062D\u062E\u062F\u0630\u0631\u0632\u0633\u0634\u0635\u0636\u0637\uFEC7\u0639\u063A\uFECC\uFE82\uFE84\uFE8E\uFED3\u0640\u0641\u0642\u0643\u0644\u0645\u0646\u0647\u0648\u0649\u064A\u064B\u064C\u064D\u064E\u064F\u0650\u0651\u0652\uFED7\uFEDB\uFEDF\uF8FC\uFEF5\uFEF7\uFEF9\uFEFB\uFEE3\uFEE7\uFEEC\uFEE9\uFFFD"
      },
      "ibm1046": "cp1046",
      "csibm1046": "cp1046",
      "cp1124": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0401\u0402\u0490\u0404\u0405\u0406\u0407\u0408\u0409\u040A\u040B\u040C\xAD\u040E\u040F\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u2116\u0451\u0452\u0491\u0454\u0455\u0456\u0457\u0458\u0459\u045A\u045B\u045C\xA7\u045E\u045F"
      },
      "ibm1124": "cp1124",
      "csibm1124": "cp1124",
      "cp1125": {
        "type": "_sbcs",
        "chars": "\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u0401\u0451\u0490\u0491\u0404\u0454\u0406\u0456\u0407\u0457\xB7\u221A\u2116\xA4\u25A0\xA0"
      },
      "ibm1125": "cp1125",
      "csibm1125": "cp1125",
      "cp1129": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\u0153\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\u0178\xB5\xB6\xB7\u0152\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\u0102\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\u0300\xCD\xCE\xCF\u0110\xD1\u0309\xD3\xD4\u01A0\xD6\xD7\xD8\xD9\xDA\xDB\xDC\u01AF\u0303\xDF\xE0\xE1\xE2\u0103\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\u0301\xED\xEE\xEF\u0111\xF1\u0323\xF3\xF4\u01A1\xF6\xF7\xF8\xF9\xFA\xFB\xFC\u01B0\u20AB\xFF"
      },
      "ibm1129": "cp1129",
      "csibm1129": "cp1129",
      "cp1133": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0E81\u0E82\u0E84\u0E87\u0E88\u0EAA\u0E8A\u0E8D\u0E94\u0E95\u0E96\u0E97\u0E99\u0E9A\u0E9B\u0E9C\u0E9D\u0E9E\u0E9F\u0EA1\u0EA2\u0EA3\u0EA5\u0EA7\u0EAB\u0EAD\u0EAE\uFFFD\uFFFD\uFFFD\u0EAF\u0EB0\u0EB2\u0EB3\u0EB4\u0EB5\u0EB6\u0EB7\u0EB8\u0EB9\u0EBC\u0EB1\u0EBB\u0EBD\uFFFD\uFFFD\uFFFD\u0EC0\u0EC1\u0EC2\u0EC3\u0EC4\u0EC8\u0EC9\u0ECA\u0ECB\u0ECC\u0ECD\u0EC6\uFFFD\u0EDC\u0EDD\u20AD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0ED0\u0ED1\u0ED2\u0ED3\u0ED4\u0ED5\u0ED6\u0ED7\u0ED8\u0ED9\uFFFD\uFFFD\xA2\xAC\xA6\uFFFD"
      },
      "ibm1133": "cp1133",
      "csibm1133": "cp1133",
      "cp1161": {
        "type": "_sbcs",
        "chars": "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0E48\u0E01\u0E02\u0E03\u0E04\u0E05\u0E06\u0E07\u0E08\u0E09\u0E0A\u0E0B\u0E0C\u0E0D\u0E0E\u0E0F\u0E10\u0E11\u0E12\u0E13\u0E14\u0E15\u0E16\u0E17\u0E18\u0E19\u0E1A\u0E1B\u0E1C\u0E1D\u0E1E\u0E1F\u0E20\u0E21\u0E22\u0E23\u0E24\u0E25\u0E26\u0E27\u0E28\u0E29\u0E2A\u0E2B\u0E2C\u0E2D\u0E2E\u0E2F\u0E30\u0E31\u0E32\u0E33\u0E34\u0E35\u0E36\u0E37\u0E38\u0E39\u0E3A\u0E49\u0E4A\u0E4B\u20AC\u0E3F\u0E40\u0E41\u0E42\u0E43\u0E44\u0E45\u0E46\u0E47\u0E48\u0E49\u0E4A\u0E4B\u0E4C\u0E4D\u0E4E\u0E4F\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59\u0E5A\u0E5B\xA2\xAC\xA6\xA0"
      },
      "ibm1161": "cp1161",
      "csibm1161": "cp1161",
      "cp1162": {
        "type": "_sbcs",
        "chars": "\u20AC\x81\x82\x83\x84\u2026\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\u2018\u2019\u201C\u201D\u2022\u2013\u2014\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0E01\u0E02\u0E03\u0E04\u0E05\u0E06\u0E07\u0E08\u0E09\u0E0A\u0E0B\u0E0C\u0E0D\u0E0E\u0E0F\u0E10\u0E11\u0E12\u0E13\u0E14\u0E15\u0E16\u0E17\u0E18\u0E19\u0E1A\u0E1B\u0E1C\u0E1D\u0E1E\u0E1F\u0E20\u0E21\u0E22\u0E23\u0E24\u0E25\u0E26\u0E27\u0E28\u0E29\u0E2A\u0E2B\u0E2C\u0E2D\u0E2E\u0E2F\u0E30\u0E31\u0E32\u0E33\u0E34\u0E35\u0E36\u0E37\u0E38\u0E39\u0E3A\uFFFD\uFFFD\uFFFD\uFFFD\u0E3F\u0E40\u0E41\u0E42\u0E43\u0E44\u0E45\u0E46\u0E47\u0E48\u0E49\u0E4A\u0E4B\u0E4C\u0E4D\u0E4E\u0E4F\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59\u0E5A\u0E5B\uFFFD\uFFFD\uFFFD\uFFFD"
      },
      "ibm1162": "cp1162",
      "csibm1162": "cp1162",
      "cp1163": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\u20AC\xA5\xA6\xA7\u0153\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\u0178\xB5\xB6\xB7\u0152\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\u0102\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\u0300\xCD\xCE\xCF\u0110\xD1\u0309\xD3\xD4\u01A0\xD6\xD7\xD8\xD9\xDA\xDB\xDC\u01AF\u0303\xDF\xE0\xE1\xE2\u0103\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\u0301\xED\xEE\xEF\u0111\xF1\u0323\xF3\xF4\u01A1\xF6\xF7\xF8\xF9\xFA\xFB\xFC\u01B0\u20AB\xFF"
      },
      "ibm1163": "cp1163",
      "csibm1163": "cp1163",
      "maccroatian": {
        "type": "_sbcs",
        "chars": "\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC\u2020\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\u0160\u2122\xB4\xA8\u2260\u017D\xD8\u221E\xB1\u2264\u2265\u2206\xB5\u2202\u2211\u220F\u0161\u222B\xAA\xBA\u2126\u017E\xF8\xBF\xA1\xAC\u221A\u0192\u2248\u0106\xAB\u010C\u2026\xA0\xC0\xC3\xD5\u0152\u0153\u0110\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\uFFFD\xA9\u2044\xA4\u2039\u203A\xC6\xBB\u2013\xB7\u201A\u201E\u2030\xC2\u0107\xC1\u010D\xC8\xCD\xCE\xCF\xCC\xD3\xD4\u0111\xD2\xDA\xDB\xD9\u0131\u02C6\u02DC\xAF\u03C0\xCB\u02DA\xB8\xCA\xE6\u02C7"
      },
      "maccyrillic": {
        "type": "_sbcs",
        "chars": "\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u2020\xB0\xA2\xA3\xA7\u2022\xB6\u0406\xAE\xA9\u2122\u0402\u0452\u2260\u0403\u0453\u221E\xB1\u2264\u2265\u0456\xB5\u2202\u0408\u0404\u0454\u0407\u0457\u0409\u0459\u040A\u045A\u0458\u0405\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\u040B\u045B\u040C\u045C\u0455\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u201E\u040E\u045E\u040F\u045F\u2116\u0401\u0451\u044F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\xA4"
      },
      "macgreek": {
        "type": "_sbcs",
        "chars": "\xC4\xB9\xB2\xC9\xB3\xD6\xDC\u0385\xE0\xE2\xE4\u0384\xA8\xE7\xE9\xE8\xEA\xEB\xA3\u2122\xEE\xEF\u2022\xBD\u2030\xF4\xF6\xA6\xAD\xF9\xFB\xFC\u2020\u0393\u0394\u0398\u039B\u039E\u03A0\xDF\xAE\xA9\u03A3\u03AA\xA7\u2260\xB0\u0387\u0391\xB1\u2264\u2265\xA5\u0392\u0395\u0396\u0397\u0399\u039A\u039C\u03A6\u03AB\u03A8\u03A9\u03AC\u039D\xAC\u039F\u03A1\u2248\u03A4\xAB\xBB\u2026\xA0\u03A5\u03A7\u0386\u0388\u0153\u2013\u2015\u201C\u201D\u2018\u2019\xF7\u0389\u038A\u038C\u038E\u03AD\u03AE\u03AF\u03CC\u038F\u03CD\u03B1\u03B2\u03C8\u03B4\u03B5\u03C6\u03B3\u03B7\u03B9\u03BE\u03BA\u03BB\u03BC\u03BD\u03BF\u03C0\u03CE\u03C1\u03C3\u03C4\u03B8\u03C9\u03C2\u03C7\u03C5\u03B6\u03CA\u03CB\u0390\u03B0\uFFFD"
      },
      "maciceland": {
        "type": "_sbcs",
        "chars": "\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC\xDD\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\xB4\xA8\u2260\xC6\xD8\u221E\xB1\u2264\u2265\xA5\xB5\u2202\u2211\u220F\u03C0\u222B\xAA\xBA\u2126\xE6\xF8\xBF\xA1\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\xC0\xC3\xD5\u0152\u0153\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\xFF\u0178\u2044\xA4\xD0\xF0\xDE\xFE\xFD\xB7\u201A\u201E\u2030\xC2\xCA\xC1\xCB\xC8\xCD\xCE\xCF\xCC\xD3\xD4\uFFFD\xD2\xDA\xDB\xD9\u0131\u02C6\u02DC\xAF\u02D8\u02D9\u02DA\xB8\u02DD\u02DB\u02C7"
      },
      "macroman": {
        "type": "_sbcs",
        "chars": "\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC\u2020\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\xB4\xA8\u2260\xC6\xD8\u221E\xB1\u2264\u2265\xA5\xB5\u2202\u2211\u220F\u03C0\u222B\xAA\xBA\u2126\xE6\xF8\xBF\xA1\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\xC0\xC3\xD5\u0152\u0153\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\xFF\u0178\u2044\xA4\u2039\u203A\uFB01\uFB02\u2021\xB7\u201A\u201E\u2030\xC2\xCA\xC1\xCB\xC8\xCD\xCE\xCF\xCC\xD3\xD4\uFFFD\xD2\xDA\xDB\xD9\u0131\u02C6\u02DC\xAF\u02D8\u02D9\u02DA\xB8\u02DD\u02DB\u02C7"
      },
      "macromania": {
        "type": "_sbcs",
        "chars": "\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC\u2020\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\xB4\xA8\u2260\u0102\u015E\u221E\xB1\u2264\u2265\xA5\xB5\u2202\u2211\u220F\u03C0\u222B\xAA\xBA\u2126\u0103\u015F\xBF\xA1\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\xC0\xC3\xD5\u0152\u0153\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\xFF\u0178\u2044\xA4\u2039\u203A\u0162\u0163\u2021\xB7\u201A\u201E\u2030\xC2\xCA\xC1\xCB\xC8\xCD\xCE\xCF\xCC\xD3\xD4\uFFFD\xD2\xDA\xDB\xD9\u0131\u02C6\u02DC\xAF\u02D8\u02D9\u02DA\xB8\u02DD\u02DB\u02C7"
      },
      "macthai": {
        "type": "_sbcs",
        "chars": "\xAB\xBB\u2026\uF88C\uF88F\uF892\uF895\uF898\uF88B\uF88E\uF891\uF894\uF897\u201C\u201D\uF899\uFFFD\u2022\uF884\uF889\uF885\uF886\uF887\uF888\uF88A\uF88D\uF890\uF893\uF896\u2018\u2019\uFFFD\xA0\u0E01\u0E02\u0E03\u0E04\u0E05\u0E06\u0E07\u0E08\u0E09\u0E0A\u0E0B\u0E0C\u0E0D\u0E0E\u0E0F\u0E10\u0E11\u0E12\u0E13\u0E14\u0E15\u0E16\u0E17\u0E18\u0E19\u0E1A\u0E1B\u0E1C\u0E1D\u0E1E\u0E1F\u0E20\u0E21\u0E22\u0E23\u0E24\u0E25\u0E26\u0E27\u0E28\u0E29\u0E2A\u0E2B\u0E2C\u0E2D\u0E2E\u0E2F\u0E30\u0E31\u0E32\u0E33\u0E34\u0E35\u0E36\u0E37\u0E38\u0E39\u0E3A\uFEFF\u200B\u2013\u2014\u0E3F\u0E40\u0E41\u0E42\u0E43\u0E44\u0E45\u0E46\u0E47\u0E48\u0E49\u0E4A\u0E4B\u0E4C\u0E4D\u2122\u0E4F\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59\xAE\xA9\uFFFD\uFFFD\uFFFD\uFFFD"
      },
      "macturkish": {
        "type": "_sbcs",
        "chars": "\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC\u2020\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\xB4\xA8\u2260\xC6\xD8\u221E\xB1\u2264\u2265\xA5\xB5\u2202\u2211\u220F\u03C0\u222B\xAA\xBA\u2126\xE6\xF8\xBF\xA1\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\xC0\xC3\xD5\u0152\u0153\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\xFF\u0178\u011E\u011F\u0130\u0131\u015E\u015F\u2021\xB7\u201A\u201E\u2030\xC2\xCA\xC1\xCB\xC8\xCD\xCE\xCF\xCC\xD3\xD4\uFFFD\xD2\xDA\xDB\xD9\uFFFD\u02C6\u02DC\xAF\u02D8\u02D9\u02DA\xB8\u02DD\u02DB\u02C7"
      },
      "macukraine": {
        "type": "_sbcs",
        "chars": "\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u2020\xB0\u0490\xA3\xA7\u2022\xB6\u0406\xAE\xA9\u2122\u0402\u0452\u2260\u0403\u0453\u221E\xB1\u2264\u2265\u0456\xB5\u0491\u0408\u0404\u0454\u0407\u0457\u0409\u0459\u040A\u045A\u0458\u0405\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\u040B\u045B\u040C\u045C\u0455\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u201E\u040E\u045E\u040F\u045F\u2116\u0401\u0451\u044F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\xA4"
      },
      "koi8r": {
        "type": "_sbcs",
        "chars": "\u2500\u2502\u250C\u2510\u2514\u2518\u251C\u2524\u252C\u2534\u253C\u2580\u2584\u2588\u258C\u2590\u2591\u2592\u2593\u2320\u25A0\u2219\u221A\u2248\u2264\u2265\xA0\u2321\xB0\xB2\xB7\xF7\u2550\u2551\u2552\u0451\u2553\u2554\u2555\u2556\u2557\u2558\u2559\u255A\u255B\u255C\u255D\u255E\u255F\u2560\u2561\u0401\u2562\u2563\u2564\u2565\u2566\u2567\u2568\u2569\u256A\u256B\u256C\xA9\u044E\u0430\u0431\u0446\u0434\u0435\u0444\u0433\u0445\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u044F\u0440\u0441\u0442\u0443\u0436\u0432\u044C\u044B\u0437\u0448\u044D\u0449\u0447\u044A\u042E\u0410\u0411\u0426\u0414\u0415\u0424\u0413\u0425\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u042F\u0420\u0421\u0422\u0423\u0416\u0412\u042C\u042B\u0417\u0428\u042D\u0429\u0427\u042A"
      },
      "koi8u": {
        "type": "_sbcs",
        "chars": "\u2500\u2502\u250C\u2510\u2514\u2518\u251C\u2524\u252C\u2534\u253C\u2580\u2584\u2588\u258C\u2590\u2591\u2592\u2593\u2320\u25A0\u2219\u221A\u2248\u2264\u2265\xA0\u2321\xB0\xB2\xB7\xF7\u2550\u2551\u2552\u0451\u0454\u2554\u0456\u0457\u2557\u2558\u2559\u255A\u255B\u0491\u255D\u255E\u255F\u2560\u2561\u0401\u0404\u2563\u0406\u0407\u2566\u2567\u2568\u2569\u256A\u0490\u256C\xA9\u044E\u0430\u0431\u0446\u0434\u0435\u0444\u0433\u0445\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u044F\u0440\u0441\u0442\u0443\u0436\u0432\u044C\u044B\u0437\u0448\u044D\u0449\u0447\u044A\u042E\u0410\u0411\u0426\u0414\u0415\u0424\u0413\u0425\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u042F\u0420\u0421\u0422\u0423\u0416\u0412\u042C\u042B\u0417\u0428\u042D\u0429\u0427\u042A"
      },
      "koi8ru": {
        "type": "_sbcs",
        "chars": "\u2500\u2502\u250C\u2510\u2514\u2518\u251C\u2524\u252C\u2534\u253C\u2580\u2584\u2588\u258C\u2590\u2591\u2592\u2593\u2320\u25A0\u2219\u221A\u2248\u2264\u2265\xA0\u2321\xB0\xB2\xB7\xF7\u2550\u2551\u2552\u0451\u0454\u2554\u0456\u0457\u2557\u2558\u2559\u255A\u255B\u0491\u045E\u255E\u255F\u2560\u2561\u0401\u0404\u2563\u0406\u0407\u2566\u2567\u2568\u2569\u256A\u0490\u040E\xA9\u044E\u0430\u0431\u0446\u0434\u0435\u0444\u0433\u0445\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u044F\u0440\u0441\u0442\u0443\u0436\u0432\u044C\u044B\u0437\u0448\u044D\u0449\u0447\u044A\u042E\u0410\u0411\u0426\u0414\u0415\u0424\u0413\u0425\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u042F\u0420\u0421\u0422\u0423\u0416\u0412\u042C\u042B\u0417\u0428\u042D\u0429\u0427\u042A"
      },
      "koi8t": {
        "type": "_sbcs",
        "chars": "\u049B\u0493\u201A\u0492\u201E\u2026\u2020\u2021\uFFFD\u2030\u04B3\u2039\u04B2\u04B7\u04B6\uFFFD\u049A\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\u2122\uFFFD\u203A\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u04EF\u04EE\u0451\xA4\u04E3\xA6\xA7\uFFFD\uFFFD\uFFFD\xAB\xAC\xAD\xAE\uFFFD\xB0\xB1\xB2\u0401\uFFFD\u04E2\xB6\xB7\uFFFD\u2116\uFFFD\xBB\uFFFD\uFFFD\uFFFD\xA9\u044E\u0430\u0431\u0446\u0434\u0435\u0444\u0433\u0445\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u044F\u0440\u0441\u0442\u0443\u0436\u0432\u044C\u044B\u0437\u0448\u044D\u0449\u0447\u044A\u042E\u0410\u0411\u0426\u0414\u0415\u0424\u0413\u0425\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u042F\u0420\u0421\u0422\u0423\u0416\u0412\u042C\u042B\u0417\u0428\u042D\u0429\u0427\u042A"
      },
      "armscii8": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\uFFFD\u0587\u0589)(\xBB\xAB\u2014.\u055D,-\u058A\u2026\u055C\u055B\u055E\u0531\u0561\u0532\u0562\u0533\u0563\u0534\u0564\u0535\u0565\u0536\u0566\u0537\u0567\u0538\u0568\u0539\u0569\u053A\u056A\u053B\u056B\u053C\u056C\u053D\u056D\u053E\u056E\u053F\u056F\u0540\u0570\u0541\u0571\u0542\u0572\u0543\u0573\u0544\u0574\u0545\u0575\u0546\u0576\u0547\u0577\u0548\u0578\u0549\u0579\u054A\u057A\u054B\u057B\u054C\u057C\u054D\u057D\u054E\u057E\u054F\u057F\u0550\u0580\u0551\u0581\u0552\u0582\u0553\u0583\u0554\u0584\u0555\u0585\u0556\u0586\u055A\uFFFD"
      },
      "rk1048": {
        "type": "_sbcs",
        "chars": "\u0402\u0403\u201A\u0453\u201E\u2026\u2020\u2021\u20AC\u2030\u0409\u2039\u040A\u049A\u04BA\u040F\u0452\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\u2122\u0459\u203A\u045A\u049B\u04BB\u045F\xA0\u04B0\u04B1\u04D8\xA4\u04E8\xA6\xA7\u0401\xA9\u0492\xAB\xAC\xAD\xAE\u04AE\xB0\xB1\u0406\u0456\u04E9\xB5\xB6\xB7\u0451\u2116\u0493\xBB\u04D9\u04A2\u04A3\u04AF\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F"
      },
      "tcvn": {
        "type": "_sbcs",
        "chars": "\0\xDA\u1EE4\u1EEA\u1EEC\u1EEE\x07\b	\n\v\f\r\u1EE8\u1EF0\u1EF2\u1EF6\u1EF8\xDD\u1EF4\x1B !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7F\xC0\u1EA2\xC3\xC1\u1EA0\u1EB6\u1EAC\xC8\u1EBA\u1EBC\xC9\u1EB8\u1EC6\xCC\u1EC8\u0128\xCD\u1ECA\xD2\u1ECE\xD5\xD3\u1ECC\u1ED8\u1EDC\u1EDE\u1EE0\u1EDA\u1EE2\xD9\u1EE6\u0168\xA0\u0102\xC2\xCA\xD4\u01A0\u01AF\u0110\u0103\xE2\xEA\xF4\u01A1\u01B0\u0111\u1EB0\u0300\u0309\u0303\u0301\u0323\xE0\u1EA3\xE3\xE1\u1EA1\u1EB2\u1EB1\u1EB3\u1EB5\u1EAF\u1EB4\u1EAE\u1EA6\u1EA8\u1EAA\u1EA4\u1EC0\u1EB7\u1EA7\u1EA9\u1EAB\u1EA5\u1EAD\xE8\u1EC2\u1EBB\u1EBD\xE9\u1EB9\u1EC1\u1EC3\u1EC5\u1EBF\u1EC7\xEC\u1EC9\u1EC4\u1EBE\u1ED2\u0129\xED\u1ECB\xF2\u1ED4\u1ECF\xF5\xF3\u1ECD\u1ED3\u1ED5\u1ED7\u1ED1\u1ED9\u1EDD\u1EDF\u1EE1\u1EDB\u1EE3\xF9\u1ED6\u1EE7\u0169\xFA\u1EE5\u1EEB\u1EED\u1EEF\u1EE9\u1EF1\u1EF3\u1EF7\u1EF9\xFD\u1EF5\u1ED0"
      },
      "georgianacademy": {
        "type": "_sbcs",
        "chars": "\x80\x81\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\u0160\u2039\u0152\x8D\x8E\x8F\x90\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u02DC\u2122\u0161\u203A\u0153\x9D\x9E\u0178\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\u10D0\u10D1\u10D2\u10D3\u10D4\u10D5\u10D6\u10D7\u10D8\u10D9\u10DA\u10DB\u10DC\u10DD\u10DE\u10DF\u10E0\u10E1\u10E2\u10E3\u10E4\u10E5\u10E6\u10E7\u10E8\u10E9\u10EA\u10EB\u10EC\u10ED\u10EE\u10EF\u10F0\u10F1\u10F2\u10F3\u10F4\u10F5\u10F6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"
      },
      "georgianps": {
        "type": "_sbcs",
        "chars": "\x80\x81\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\u0160\u2039\u0152\x8D\x8E\x8F\x90\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u02DC\u2122\u0161\u203A\u0153\x9D\x9E\u0178\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\u10D0\u10D1\u10D2\u10D3\u10D4\u10D5\u10D6\u10F1\u10D7\u10D8\u10D9\u10DA\u10DB\u10DC\u10F2\u10DD\u10DE\u10DF\u10E0\u10E1\u10E2\u10F3\u10E3\u10E4\u10E5\u10E6\u10E7\u10E8\u10E9\u10EA\u10EB\u10EC\u10ED\u10EE\u10F4\u10EF\u10F0\u10F5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"
      },
      "pt154": {
        "type": "_sbcs",
        "chars": "\u0496\u0492\u04EE\u0493\u201E\u2026\u04B6\u04AE\u04B2\u04AF\u04A0\u04E2\u04A2\u049A\u04BA\u04B8\u0497\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u04B3\u04B7\u04A1\u04E3\u04A3\u049B\u04BB\u04B9\xA0\u040E\u045E\u0408\u04E8\u0498\u04B0\xA7\u0401\xA9\u04D8\xAB\xAC\u04EF\xAE\u049C\xB0\u04B1\u0406\u0456\u0499\u04E9\xB6\xB7\u0451\u2116\u04D9\xBB\u0458\u04AA\u04AB\u049D\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F"
      },
      "viscii": {
        "type": "_sbcs",
        "chars": "\0\u1EB2\u1EB4\u1EAA\x07\b	\n\v\f\r\u1EF6\u1EF8\x1B\u1EF4 !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7F\u1EA0\u1EAE\u1EB0\u1EB6\u1EA4\u1EA6\u1EA8\u1EAC\u1EBC\u1EB8\u1EBE\u1EC0\u1EC2\u1EC4\u1EC6\u1ED0\u1ED2\u1ED4\u1ED6\u1ED8\u1EE2\u1EDA\u1EDC\u1EDE\u1ECA\u1ECE\u1ECC\u1EC8\u1EE6\u0168\u1EE4\u1EF2\xD5\u1EAF\u1EB1\u1EB7\u1EA5\u1EA7\u1EA9\u1EAD\u1EBD\u1EB9\u1EBF\u1EC1\u1EC3\u1EC5\u1EC7\u1ED1\u1ED3\u1ED5\u1ED7\u1EE0\u01A0\u1ED9\u1EDD\u1EDF\u1ECB\u1EF0\u1EE8\u1EEA\u1EEC\u01A1\u1EDB\u01AF\xC0\xC1\xC2\xC3\u1EA2\u0102\u1EB3\u1EB5\xC8\xC9\xCA\u1EBA\xCC\xCD\u0128\u1EF3\u0110\u1EE9\xD2\xD3\xD4\u1EA1\u1EF7\u1EEB\u1EED\xD9\xDA\u1EF9\u1EF5\xDD\u1EE1\u01B0\xE0\xE1\xE2\xE3\u1EA3\u0103\u1EEF\u1EAB\xE8\xE9\xEA\u1EBB\xEC\xED\u0129\u1EC9\u0111\u1EF1\xF2\xF3\xF4\xF5\u1ECF\u1ECD\u1EE5\xF9\xFA\u0169\u1EE7\xFD\u1EE3\u1EEE"
      },
      "iso646cn": {
        "type": "_sbcs",
        "chars": "\0\x07\b	\n\v\f\r\x1B !\"#\xA5%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}\u203E\x7F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"
      },
      "iso646jp": {
        "type": "_sbcs",
        "chars": "\0\x07\b	\n\v\f\r\x1B !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\xA5]^_`abcdefghijklmnopqrstuvwxyz{|}\u203E\x7F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"
      },
      "hproman8": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xC0\xC2\xC8\xCA\xCB\xCE\xCF\xB4\u02CB\u02C6\xA8\u02DC\xD9\xDB\u20A4\xAF\xDD\xFD\xB0\xC7\xE7\xD1\xF1\xA1\xBF\xA4\xA3\xA5\xA7\u0192\xA2\xE2\xEA\xF4\xFB\xE1\xE9\xF3\xFA\xE0\xE8\xF2\xF9\xE4\xEB\xF6\xFC\xC5\xEE\xD8\xC6\xE5\xED\xF8\xE6\xC4\xEC\xD6\xDC\xC9\xEF\xDF\xD4\xC1\xC3\xE3\xD0\xF0\xCD\xCC\xD3\xD2\xD5\xF5\u0160\u0161\xDA\u0178\xFF\xDE\xFE\xB7\xB5\xB6\xBE\u2014\xBC\xBD\xAA\xBA\xAB\u25A0\xBB\xB1\uFFFD"
      },
      "macintosh": {
        "type": "_sbcs",
        "chars": "\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC\u2020\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\xB4\xA8\u2260\xC6\xD8\u221E\xB1\u2264\u2265\xA5\xB5\u2202\u2211\u220F\u03C0\u222B\xAA\xBA\u2126\xE6\xF8\xBF\xA1\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\xC0\xC3\xD5\u0152\u0153\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\xFF\u0178\u2044\xA4\u2039\u203A\uFB01\uFB02\u2021\xB7\u201A\u201E\u2030\xC2\xCA\xC1\xCB\xC8\xCD\xCE\xCF\xCC\xD3\xD4\uFFFD\xD2\xDA\xDB\xD9\u0131\u02C6\u02DC\xAF\u02D8\u02D9\u02DA\xB8\u02DD\u02DB\u02C7"
      },
      "ascii": {
        "type": "_sbcs",
        "chars": "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"
      },
      "tis620": {
        "type": "_sbcs",
        "chars": "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0E01\u0E02\u0E03\u0E04\u0E05\u0E06\u0E07\u0E08\u0E09\u0E0A\u0E0B\u0E0C\u0E0D\u0E0E\u0E0F\u0E10\u0E11\u0E12\u0E13\u0E14\u0E15\u0E16\u0E17\u0E18\u0E19\u0E1A\u0E1B\u0E1C\u0E1D\u0E1E\u0E1F\u0E20\u0E21\u0E22\u0E23\u0E24\u0E25\u0E26\u0E27\u0E28\u0E29\u0E2A\u0E2B\u0E2C\u0E2D\u0E2E\u0E2F\u0E30\u0E31\u0E32\u0E33\u0E34\u0E35\u0E36\u0E37\u0E38\u0E39\u0E3A\uFFFD\uFFFD\uFFFD\uFFFD\u0E3F\u0E40\u0E41\u0E42\u0E43\u0E44\u0E45\u0E46\u0E47\u0E48\u0E49\u0E4A\u0E4B\u0E4C\u0E4D\u0E4E\u0E4F\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59\u0E5A\u0E5B\uFFFD\uFFFD\uFFFD\uFFFD"
      }
    };
  }
});

// ../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/dbcs-codec.js
var require_dbcs_codec = __commonJS({
  "../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/dbcs-codec.js"(exports) {
    "use strict";
    var Buffer3 = require_safer().Buffer;
    exports._dbcs = DBCSCodec;
    var UNASSIGNED = -1;
    var GB18030_CODE = -2;
    var SEQ_START = -10;
    var NODE_START = -1e3;
    var UNASSIGNED_NODE = new Array(256);
    var DEF_CHAR = -1;
    for (i = 0; i < 256; i++)
      UNASSIGNED_NODE[i] = UNASSIGNED;
    var i;
    function DBCSCodec(codecOptions, iconv) {
      this.encodingName = codecOptions.encodingName;
      if (!codecOptions)
        throw new Error("DBCS codec is called without the data.");
      if (!codecOptions.table)
        throw new Error("Encoding '" + this.encodingName + "' has no data.");
      var mappingTable = codecOptions.table();
      this.decodeTables = [];
      this.decodeTables[0] = UNASSIGNED_NODE.slice(0);
      this.decodeTableSeq = [];
      for (var i2 = 0; i2 < mappingTable.length; i2++)
        this._addDecodeChunk(mappingTable[i2]);
      this.defaultCharUnicode = iconv.defaultCharUnicode;
      this.encodeTable = [];
      this.encodeTableSeq = [];
      var skipEncodeChars = {};
      if (codecOptions.encodeSkipVals)
        for (var i2 = 0; i2 < codecOptions.encodeSkipVals.length; i2++) {
          var val = codecOptions.encodeSkipVals[i2];
          if (typeof val === "number")
            skipEncodeChars[val] = true;
          else
            for (var j = val.from; j <= val.to; j++)
              skipEncodeChars[j] = true;
        }
      this._fillEncodeTable(0, 0, skipEncodeChars);
      if (codecOptions.encodeAdd) {
        for (var uChar in codecOptions.encodeAdd)
          if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar))
            this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]);
      }
      this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)];
      if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]["?"];
      if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0);
      if (typeof codecOptions.gb18030 === "function") {
        this.gb18030 = codecOptions.gb18030();
        var thirdByteNodeIdx = this.decodeTables.length;
        var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0);
        var fourthByteNodeIdx = this.decodeTables.length;
        var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0);
        for (var i2 = 129; i2 <= 254; i2++) {
          var secondByteNodeIdx = NODE_START - this.decodeTables[0][i2];
          var secondByteNode = this.decodeTables[secondByteNodeIdx];
          for (var j = 48; j <= 57; j++)
            secondByteNode[j] = NODE_START - thirdByteNodeIdx;
        }
        for (var i2 = 129; i2 <= 254; i2++)
          thirdByteNode[i2] = NODE_START - fourthByteNodeIdx;
        for (var i2 = 48; i2 <= 57; i2++)
          fourthByteNode[i2] = GB18030_CODE;
      }
    }
    DBCSCodec.prototype.encoder = DBCSEncoder;
    DBCSCodec.prototype.decoder = DBCSDecoder;
    DBCSCodec.prototype._getDecodeTrieNode = function(addr) {
      var bytes = [];
      for (; addr > 0; addr >>= 8)
        bytes.push(addr & 255);
      if (bytes.length == 0)
        bytes.push(0);
      var node = this.decodeTables[0];
      for (var i2 = bytes.length - 1; i2 > 0; i2--) {
        var val = node[bytes[i2]];
        if (val == UNASSIGNED) {
          node[bytes[i2]] = NODE_START - this.decodeTables.length;
          this.decodeTables.push(node = UNASSIGNED_NODE.slice(0));
        } else if (val <= NODE_START) {
          node = this.decodeTables[NODE_START - val];
        } else
          throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16));
      }
      return node;
    };
    DBCSCodec.prototype._addDecodeChunk = function(chunk2) {
      var curAddr = parseInt(chunk2[0], 16);
      var writeTable = this._getDecodeTrieNode(curAddr);
      curAddr = curAddr & 255;
      for (var k = 1; k < chunk2.length; k++) {
        var part = chunk2[k];
        if (typeof part === "string") {
          for (var l = 0; l < part.length; ) {
            var code = part.charCodeAt(l++);
            if (55296 <= code && code < 56320) {
              var codeTrail = part.charCodeAt(l++);
              if (56320 <= codeTrail && codeTrail < 57344)
                writeTable[curAddr++] = 65536 + (code - 55296) * 1024 + (codeTrail - 56320);
              else
                throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk2[0]);
            } else if (4080 < code && code <= 4095) {
              var len = 4095 - code + 2;
              var seq = [];
              for (var m = 0; m < len; m++)
                seq.push(part.charCodeAt(l++));
              writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length;
              this.decodeTableSeq.push(seq);
            } else
              writeTable[curAddr++] = code;
          }
        } else if (typeof part === "number") {
          var charCode = writeTable[curAddr - 1] + 1;
          for (var l = 0; l < part; l++)
            writeTable[curAddr++] = charCode++;
        } else
          throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk2[0]);
      }
      if (curAddr > 255)
        throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk2[0] + ": too long" + curAddr);
    };
    DBCSCodec.prototype._getEncodeBucket = function(uCode) {
      var high = uCode >> 8;
      if (this.encodeTable[high] === void 0)
        this.encodeTable[high] = UNASSIGNED_NODE.slice(0);
      return this.encodeTable[high];
    };
    DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) {
      var bucket = this._getEncodeBucket(uCode);
      var low = uCode & 255;
      if (bucket[low] <= SEQ_START)
        this.encodeTableSeq[SEQ_START - bucket[low]][DEF_CHAR] = dbcsCode;
      else if (bucket[low] == UNASSIGNED)
        bucket[low] = dbcsCode;
    };
    DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) {
      var uCode = seq[0];
      var bucket = this._getEncodeBucket(uCode);
      var low = uCode & 255;
      var node;
      if (bucket[low] <= SEQ_START) {
        node = this.encodeTableSeq[SEQ_START - bucket[low]];
      } else {
        node = {};
        if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low];
        bucket[low] = SEQ_START - this.encodeTableSeq.length;
        this.encodeTableSeq.push(node);
      }
      for (var j = 1; j < seq.length - 1; j++) {
        var oldVal = node[uCode];
        if (typeof oldVal === "object")
          node = oldVal;
        else {
          node = node[uCode] = {};
          if (oldVal !== void 0)
            node[DEF_CHAR] = oldVal;
        }
      }
      uCode = seq[seq.length - 1];
      node[uCode] = dbcsCode;
    };
    DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) {
      var node = this.decodeTables[nodeIdx];
      for (var i2 = 0; i2 < 256; i2++) {
        var uCode = node[i2];
        var mbCode = prefix + i2;
        if (skipEncodeChars[mbCode])
          continue;
        if (uCode >= 0)
          this._setEncodeChar(uCode, mbCode);
        else if (uCode <= NODE_START)
          this._fillEncodeTable(NODE_START - uCode, mbCode << 8, skipEncodeChars);
        else if (uCode <= SEQ_START)
          this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode);
      }
    };
    function DBCSEncoder(options, codec) {
      this.leadSurrogate = -1;
      this.seqObj = void 0;
      this.encodeTable = codec.encodeTable;
      this.encodeTableSeq = codec.encodeTableSeq;
      this.defaultCharSingleByte = codec.defCharSB;
      this.gb18030 = codec.gb18030;
    }
    DBCSEncoder.prototype.write = function(str) {
      var newBuf = Buffer3.alloc(str.length * (this.gb18030 ? 4 : 3)), leadSurrogate = this.leadSurrogate, seqObj = this.seqObj, nextChar = -1, i2 = 0, j = 0;
      while (true) {
        if (nextChar === -1) {
          if (i2 == str.length) break;
          var uCode = str.charCodeAt(i2++);
        } else {
          var uCode = nextChar;
          nextChar = -1;
        }
        if (55296 <= uCode && uCode < 57344) {
          if (uCode < 56320) {
            if (leadSurrogate === -1) {
              leadSurrogate = uCode;
              continue;
            } else {
              leadSurrogate = uCode;
              uCode = UNASSIGNED;
            }
          } else {
            if (leadSurrogate !== -1) {
              uCode = 65536 + (leadSurrogate - 55296) * 1024 + (uCode - 56320);
              leadSurrogate = -1;
            } else {
              uCode = UNASSIGNED;
            }
          }
        } else if (leadSurrogate !== -1) {
          nextChar = uCode;
          uCode = UNASSIGNED;
          leadSurrogate = -1;
        }
        var dbcsCode = UNASSIGNED;
        if (seqObj !== void 0 && uCode != UNASSIGNED) {
          var resCode = seqObj[uCode];
          if (typeof resCode === "object") {
            seqObj = resCode;
            continue;
          } else if (typeof resCode == "number") {
            dbcsCode = resCode;
          } else if (resCode == void 0) {
            resCode = seqObj[DEF_CHAR];
            if (resCode !== void 0) {
              dbcsCode = resCode;
              nextChar = uCode;
            } else {
            }
          }
          seqObj = void 0;
        } else if (uCode >= 0) {
          var subtable = this.encodeTable[uCode >> 8];
          if (subtable !== void 0)
            dbcsCode = subtable[uCode & 255];
          if (dbcsCode <= SEQ_START) {
            seqObj = this.encodeTableSeq[SEQ_START - dbcsCode];
            continue;
          }
          if (dbcsCode == UNASSIGNED && this.gb18030) {
            var idx = findIdx(this.gb18030.uChars, uCode);
            if (idx != -1) {
              var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]);
              newBuf[j++] = 129 + Math.floor(dbcsCode / 12600);
              dbcsCode = dbcsCode % 12600;
              newBuf[j++] = 48 + Math.floor(dbcsCode / 1260);
              dbcsCode = dbcsCode % 1260;
              newBuf[j++] = 129 + Math.floor(dbcsCode / 10);
              dbcsCode = dbcsCode % 10;
              newBuf[j++] = 48 + dbcsCode;
              continue;
            }
          }
        }
        if (dbcsCode === UNASSIGNED)
          dbcsCode = this.defaultCharSingleByte;
        if (dbcsCode < 256) {
          newBuf[j++] = dbcsCode;
        } else if (dbcsCode < 65536) {
          newBuf[j++] = dbcsCode >> 8;
          newBuf[j++] = dbcsCode & 255;
        } else {
          newBuf[j++] = dbcsCode >> 16;
          newBuf[j++] = dbcsCode >> 8 & 255;
          newBuf[j++] = dbcsCode & 255;
        }
      }
      this.seqObj = seqObj;
      this.leadSurrogate = leadSurrogate;
      return newBuf.slice(0, j);
    };
    DBCSEncoder.prototype.end = function() {
      if (this.leadSurrogate === -1 && this.seqObj === void 0)
        return;
      var newBuf = Buffer3.alloc(10), j = 0;
      if (this.seqObj) {
        var dbcsCode = this.seqObj[DEF_CHAR];
        if (dbcsCode !== void 0) {
          if (dbcsCode < 256) {
            newBuf[j++] = dbcsCode;
          } else {
            newBuf[j++] = dbcsCode >> 8;
            newBuf[j++] = dbcsCode & 255;
          }
        } else {
        }
        this.seqObj = void 0;
      }
      if (this.leadSurrogate !== -1) {
        newBuf[j++] = this.defaultCharSingleByte;
        this.leadSurrogate = -1;
      }
      return newBuf.slice(0, j);
    };
    DBCSEncoder.prototype.findIdx = findIdx;
    function DBCSDecoder(options, codec) {
      this.nodeIdx = 0;
      this.prevBuf = Buffer3.alloc(0);
      this.decodeTables = codec.decodeTables;
      this.decodeTableSeq = codec.decodeTableSeq;
      this.defaultCharUnicode = codec.defaultCharUnicode;
      this.gb18030 = codec.gb18030;
    }
    DBCSDecoder.prototype.write = function(buf) {
      var newBuf = Buffer3.alloc(buf.length * 2), nodeIdx = this.nodeIdx, prevBuf = this.prevBuf, prevBufOffset = this.prevBuf.length, seqStart = -this.prevBuf.length, uCode;
      if (prevBufOffset > 0)
        prevBuf = Buffer3.concat([prevBuf, buf.slice(0, 10)]);
      for (var i2 = 0, j = 0; i2 < buf.length; i2++) {
        var curByte = i2 >= 0 ? buf[i2] : prevBuf[i2 + prevBufOffset];
        var uCode = this.decodeTables[nodeIdx][curByte];
        if (uCode >= 0) {
        } else if (uCode === UNASSIGNED) {
          i2 = seqStart;
          uCode = this.defaultCharUnicode.charCodeAt(0);
        } else if (uCode === GB18030_CODE) {
          var curSeq = seqStart >= 0 ? buf.slice(seqStart, i2 + 1) : prevBuf.slice(seqStart + prevBufOffset, i2 + 1 + prevBufOffset);
          var ptr = (curSeq[0] - 129) * 12600 + (curSeq[1] - 48) * 1260 + (curSeq[2] - 129) * 10 + (curSeq[3] - 48);
          var idx = findIdx(this.gb18030.gbChars, ptr);
          uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx];
        } else if (uCode <= NODE_START) {
          nodeIdx = NODE_START - uCode;
          continue;
        } else if (uCode <= SEQ_START) {
          var seq = this.decodeTableSeq[SEQ_START - uCode];
          for (var k = 0; k < seq.length - 1; k++) {
            uCode = seq[k];
            newBuf[j++] = uCode & 255;
            newBuf[j++] = uCode >> 8;
          }
          uCode = seq[seq.length - 1];
        } else
          throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte);
        if (uCode > 65535) {
          uCode -= 65536;
          var uCodeLead = 55296 + Math.floor(uCode / 1024);
          newBuf[j++] = uCodeLead & 255;
          newBuf[j++] = uCodeLead >> 8;
          uCode = 56320 + uCode % 1024;
        }
        newBuf[j++] = uCode & 255;
        newBuf[j++] = uCode >> 8;
        nodeIdx = 0;
        seqStart = i2 + 1;
      }
      this.nodeIdx = nodeIdx;
      this.prevBuf = seqStart >= 0 ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset);
      return newBuf.slice(0, j).toString("ucs2");
    };
    DBCSDecoder.prototype.end = function() {
      var ret = "";
      while (this.prevBuf.length > 0) {
        ret += this.defaultCharUnicode;
        var buf = this.prevBuf.slice(1);
        this.prevBuf = Buffer3.alloc(0);
        this.nodeIdx = 0;
        if (buf.length > 0)
          ret += this.write(buf);
      }
      this.nodeIdx = 0;
      return ret;
    };
    function findIdx(table, val) {
      if (table[0] > val)
        return -1;
      var l = 0, r = table.length;
      while (l < r - 1) {
        var mid = l + Math.floor((r - l + 1) / 2);
        if (table[mid] <= val)
          l = mid;
        else
          r = mid;
      }
      return l;
    }
  }
});

// ../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/tables/shiftjis.json
var require_shiftjis = __commonJS({
  "../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/tables/shiftjis.json"(exports, module) {
    module.exports = [
      ["0", "\0", 128],
      ["a1", "\uFF61", 62],
      ["8140", "\u3000\u3001\u3002\uFF0C\uFF0E\u30FB\uFF1A\uFF1B\uFF1F\uFF01\u309B\u309C\xB4\uFF40\xA8\uFF3E\uFFE3\uFF3F\u30FD\u30FE\u309D\u309E\u3003\u4EDD\u3005\u3006\u3007\u30FC\u2015\u2010\uFF0F\uFF3C\uFF5E\u2225\uFF5C\u2026\u2025\u2018\u2019\u201C\u201D\uFF08\uFF09\u3014\u3015\uFF3B\uFF3D\uFF5B\uFF5D\u3008", 9, "\uFF0B\uFF0D\xB1\xD7"],
      ["8180", "\xF7\uFF1D\u2260\uFF1C\uFF1E\u2266\u2267\u221E\u2234\u2642\u2640\xB0\u2032\u2033\u2103\uFFE5\uFF04\uFFE0\uFFE1\uFF05\uFF03\uFF06\uFF0A\uFF20\xA7\u2606\u2605\u25CB\u25CF\u25CE\u25C7\u25C6\u25A1\u25A0\u25B3\u25B2\u25BD\u25BC\u203B\u3012\u2192\u2190\u2191\u2193\u3013"],
      ["81b8", "\u2208\u220B\u2286\u2287\u2282\u2283\u222A\u2229"],
      ["81c8", "\u2227\u2228\uFFE2\u21D2\u21D4\u2200\u2203"],
      ["81da", "\u2220\u22A5\u2312\u2202\u2207\u2261\u2252\u226A\u226B\u221A\u223D\u221D\u2235\u222B\u222C"],
      ["81f0", "\u212B\u2030\u266F\u266D\u266A\u2020\u2021\xB6"],
      ["81fc", "\u25EF"],
      ["824f", "\uFF10", 9],
      ["8260", "\uFF21", 25],
      ["8281", "\uFF41", 25],
      ["829f", "\u3041", 82],
      ["8340", "\u30A1", 62],
      ["8380", "\u30E0", 22],
      ["839f", "\u0391", 16, "\u03A3", 6],
      ["83bf", "\u03B1", 16, "\u03C3", 6],
      ["8440", "\u0410", 5, "\u0401\u0416", 25],
      ["8470", "\u0430", 5, "\u0451\u0436", 7],
      ["8480", "\u043E", 17],
      ["849f", "\u2500\u2502\u250C\u2510\u2518\u2514\u251C\u252C\u2524\u2534\u253C\u2501\u2503\u250F\u2513\u251B\u2517\u2523\u2533\u252B\u253B\u254B\u2520\u252F\u2528\u2537\u253F\u251D\u2530\u2525\u2538\u2542"],
      ["8740", "\u2460", 19, "\u2160", 9],
      ["875f", "\u3349\u3314\u3322\u334D\u3318\u3327\u3303\u3336\u3351\u3357\u330D\u3326\u3323\u332B\u334A\u333B\u339C\u339D\u339E\u338E\u338F\u33C4\u33A1"],
      ["877e", "\u337B"],
      ["8780", "\u301D\u301F\u2116\u33CD\u2121\u32A4", 4, "\u3231\u3232\u3239\u337E\u337D\u337C\u2252\u2261\u222B\u222E\u2211\u221A\u22A5\u2220\u221F\u22BF\u2235\u2229\u222A"],
      ["889f", "\u4E9C\u5516\u5A03\u963F\u54C0\u611B\u6328\u59F6\u9022\u8475\u831C\u7A50\u60AA\u63E1\u6E25\u65ED\u8466\u82A6\u9BF5\u6893\u5727\u65A1\u6271\u5B9B\u59D0\u867B\u98F4\u7D62\u7DBE\u9B8E\u6216\u7C9F\u88B7\u5B89\u5EB5\u6309\u6697\u6848\u95C7\u978D\u674F\u4EE5\u4F0A\u4F4D\u4F9D\u5049\u56F2\u5937\u59D4\u5A01\u5C09\u60DF\u610F\u6170\u6613\u6905\u70BA\u754F\u7570\u79FB\u7DAD\u7DEF\u80C3\u840E\u8863\u8B02\u9055\u907A\u533B\u4E95\u4EA5\u57DF\u80B2\u90C1\u78EF\u4E00\u58F1\u6EA2\u9038\u7A32\u8328\u828B\u9C2F\u5141\u5370\u54BD\u54E1\u56E0\u59FB\u5F15\u98F2\u6DEB\u80E4\u852D"],
      ["8940", "\u9662\u9670\u96A0\u97FB\u540B\u53F3\u5B87\u70CF\u7FBD\u8FC2\u96E8\u536F\u9D5C\u7ABA\u4E11\u7893\u81FC\u6E26\u5618\u5504\u6B1D\u851A\u9C3B\u59E5\u53A9\u6D66\u74DC\u958F\u5642\u4E91\u904B\u96F2\u834F\u990C\u53E1\u55B6\u5B30\u5F71\u6620\u66F3\u6804\u6C38\u6CF3\u6D29\u745B\u76C8\u7A4E\u9834\u82F1\u885B\u8A60\u92ED\u6DB2\u75AB\u76CA\u99C5\u60A6\u8B01\u8D8A\u95B2\u698E\u53AD\u5186"],
      ["8980", "\u5712\u5830\u5944\u5BB4\u5EF6\u6028\u63A9\u63F4\u6CBF\u6F14\u708E\u7114\u7159\u71D5\u733F\u7E01\u8276\u82D1\u8597\u9060\u925B\u9D1B\u5869\u65BC\u6C5A\u7525\u51F9\u592E\u5965\u5F80\u5FDC\u62BC\u65FA\u6A2A\u6B27\u6BB4\u738B\u7FC1\u8956\u9D2C\u9D0E\u9EC4\u5CA1\u6C96\u837B\u5104\u5C4B\u61B6\u81C6\u6876\u7261\u4E59\u4FFA\u5378\u6069\u6E29\u7A4F\u97F3\u4E0B\u5316\u4EEE\u4F55\u4F3D\u4FA1\u4F73\u52A0\u53EF\u5609\u590F\u5AC1\u5BB6\u5BE1\u79D1\u6687\u679C\u67B6\u6B4C\u6CB3\u706B\u73C2\u798D\u79BE\u7A3C\u7B87\u82B1\u82DB\u8304\u8377\u83EF\u83D3\u8766\u8AB2\u5629\u8CA8\u8FE6\u904E\u971E\u868A\u4FC4\u5CE8\u6211\u7259\u753B\u81E5\u82BD\u86FE\u8CC0\u96C5\u9913\u99D5\u4ECB\u4F1A\u89E3\u56DE\u584A\u58CA\u5EFB\u5FEB\u602A\u6094\u6062\u61D0\u6212\u62D0\u6539"],
      ["8a40", "\u9B41\u6666\u68B0\u6D77\u7070\u754C\u7686\u7D75\u82A5\u87F9\u958B\u968E\u8C9D\u51F1\u52BE\u5916\u54B3\u5BB3\u5D16\u6168\u6982\u6DAF\u788D\u84CB\u8857\u8A72\u93A7\u9AB8\u6D6C\u99A8\u86D9\u57A3\u67FF\u86CE\u920E\u5283\u5687\u5404\u5ED3\u62E1\u64B9\u683C\u6838\u6BBB\u7372\u78BA\u7A6B\u899A\u89D2\u8D6B\u8F03\u90ED\u95A3\u9694\u9769\u5B66\u5CB3\u697D\u984D\u984E\u639B\u7B20\u6A2B"],
      ["8a80", "\u6A7F\u68B6\u9C0D\u6F5F\u5272\u559D\u6070\u62EC\u6D3B\u6E07\u6ED1\u845B\u8910\u8F44\u4E14\u9C39\u53F6\u691B\u6A3A\u9784\u682A\u515C\u7AC3\u84B2\u91DC\u938C\u565B\u9D28\u6822\u8305\u8431\u7CA5\u5208\u82C5\u74E6\u4E7E\u4F83\u51A0\u5BD2\u520A\u52D8\u52E7\u5DFB\u559A\u582A\u59E6\u5B8C\u5B98\u5BDB\u5E72\u5E79\u60A3\u611F\u6163\u61BE\u63DB\u6562\u67D1\u6853\u68FA\u6B3E\u6B53\u6C57\u6F22\u6F97\u6F45\u74B0\u7518\u76E3\u770B\u7AFF\u7BA1\u7C21\u7DE9\u7F36\u7FF0\u809D\u8266\u839E\u89B3\u8ACC\u8CAB\u9084\u9451\u9593\u9591\u95A2\u9665\u97D3\u9928\u8218\u4E38\u542B\u5CB8\u5DCC\u73A9\u764C\u773C\u5CA9\u7FEB\u8D0B\u96C1\u9811\u9854\u9858\u4F01\u4F0E\u5371\u559C\u5668\u57FA\u5947\u5B09\u5BC4\u5C90\u5E0C\u5E7E\u5FCC\u63EE\u673A\u65D7\u65E2\u671F\u68CB\u68C4"],
      ["8b40", "\u6A5F\u5E30\u6BC5\u6C17\u6C7D\u757F\u7948\u5B63\u7A00\u7D00\u5FBD\u898F\u8A18\u8CB4\u8D77\u8ECC\u8F1D\u98E2\u9A0E\u9B3C\u4E80\u507D\u5100\u5993\u5B9C\u622F\u6280\u64EC\u6B3A\u72A0\u7591\u7947\u7FA9\u87FB\u8ABC\u8B70\u63AC\u83CA\u97A0\u5409\u5403\u55AB\u6854\u6A58\u8A70\u7827\u6775\u9ECD\u5374\u5BA2\u811A\u8650\u9006\u4E18\u4E45\u4EC7\u4F11\u53CA\u5438\u5BAE\u5F13\u6025\u6551"],
      ["8b80", "\u673D\u6C42\u6C72\u6CE3\u7078\u7403\u7A76\u7AAE\u7B08\u7D1A\u7CFE\u7D66\u65E7\u725B\u53BB\u5C45\u5DE8\u62D2\u62E0\u6319\u6E20\u865A\u8A31\u8DDD\u92F8\u6F01\u79A6\u9B5A\u4EA8\u4EAB\u4EAC\u4F9B\u4FA0\u50D1\u5147\u7AF6\u5171\u51F6\u5354\u5321\u537F\u53EB\u55AC\u5883\u5CE1\u5F37\u5F4A\u602F\u6050\u606D\u631F\u6559\u6A4B\u6CC1\u72C2\u72ED\u77EF\u80F8\u8105\u8208\u854E\u90F7\u93E1\u97FF\u9957\u9A5A\u4EF0\u51DD\u5C2D\u6681\u696D\u5C40\u66F2\u6975\u7389\u6850\u7C81\u50C5\u52E4\u5747\u5DFE\u9326\u65A4\u6B23\u6B3D\u7434\u7981\u79BD\u7B4B\u7DCA\u82B9\u83CC\u887F\u895F\u8B39\u8FD1\u91D1\u541F\u9280\u4E5D\u5036\u53E5\u533A\u72D7\u7396\u77E9\u82E6\u8EAF\u99C6\u99C8\u99D2\u5177\u611A\u865E\u55B0\u7A7A\u5076\u5BD3\u9047\u9685\u4E32\u6ADB\u91E7\u5C51\u5C48"],
      ["8c40", "\u6398\u7A9F\u6C93\u9774\u8F61\u7AAA\u718A\u9688\u7C82\u6817\u7E70\u6851\u936C\u52F2\u541B\u85AB\u8A13\u7FA4\u8ECD\u90E1\u5366\u8888\u7941\u4FC2\u50BE\u5211\u5144\u5553\u572D\u73EA\u578B\u5951\u5F62\u5F84\u6075\u6176\u6167\u61A9\u63B2\u643A\u656C\u666F\u6842\u6E13\u7566\u7A3D\u7CFB\u7D4C\u7D99\u7E4B\u7F6B\u830E\u834A\u86CD\u8A08\u8A63\u8B66\u8EFD\u981A\u9D8F\u82B8\u8FCE\u9BE8"],
      ["8c80", "\u5287\u621F\u6483\u6FC0\u9699\u6841\u5091\u6B20\u6C7A\u6F54\u7A74\u7D50\u8840\u8A23\u6708\u4EF6\u5039\u5026\u5065\u517C\u5238\u5263\u55A7\u570F\u5805\u5ACC\u5EFA\u61B2\u61F8\u62F3\u6372\u691C\u6A29\u727D\u72AC\u732E\u7814\u786F\u7D79\u770C\u80A9\u898B\u8B19\u8CE2\u8ED2\u9063\u9375\u967A\u9855\u9A13\u9E78\u5143\u539F\u53B3\u5E7B\u5F26\u6E1B\u6E90\u7384\u73FE\u7D43\u8237\u8A00\u8AFA\u9650\u4E4E\u500B\u53E4\u547C\u56FA\u59D1\u5B64\u5DF1\u5EAB\u5F27\u6238\u6545\u67AF\u6E56\u72D0\u7CCA\u88B4\u80A1\u80E1\u83F0\u864E\u8A87\u8DE8\u9237\u96C7\u9867\u9F13\u4E94\u4E92\u4F0D\u5348\u5449\u543E\u5A2F\u5F8C\u5FA1\u609F\u68A7\u6A8E\u745A\u7881\u8A9E\u8AA4\u8B77\u9190\u4E5E\u9BC9\u4EA4\u4F7C\u4FAF\u5019\u5016\u5149\u516C\u529F\u52B9\u52FE\u539A\u53E3\u5411"],
      ["8d40", "\u540E\u5589\u5751\u57A2\u597D\u5B54\u5B5D\u5B8F\u5DE5\u5DE7\u5DF7\u5E78\u5E83\u5E9A\u5EB7\u5F18\u6052\u614C\u6297\u62D8\u63A7\u653B\u6602\u6643\u66F4\u676D\u6821\u6897\u69CB\u6C5F\u6D2A\u6D69\u6E2F\u6E9D\u7532\u7687\u786C\u7A3F\u7CE0\u7D05\u7D18\u7D5E\u7DB1\u8015\u8003\u80AF\u80B1\u8154\u818F\u822A\u8352\u884C\u8861\u8B1B\u8CA2\u8CFC\u90CA\u9175\u9271\u783F\u92FC\u95A4\u964D"],
      ["8d80", "\u9805\u9999\u9AD8\u9D3B\u525B\u52AB\u53F7\u5408\u58D5\u62F7\u6FE0\u8C6A\u8F5F\u9EB9\u514B\u523B\u544A\u56FD\u7A40\u9177\u9D60\u9ED2\u7344\u6F09\u8170\u7511\u5FFD\u60DA\u9AA8\u72DB\u8FBC\u6B64\u9803\u4ECA\u56F0\u5764\u58BE\u5A5A\u6068\u61C7\u660F\u6606\u6839\u68B1\u6DF7\u75D5\u7D3A\u826E\u9B42\u4E9B\u4F50\u53C9\u5506\u5D6F\u5DE6\u5DEE\u67FB\u6C99\u7473\u7802\u8A50\u9396\u88DF\u5750\u5EA7\u632B\u50B5\u50AC\u518D\u6700\u54C9\u585E\u59BB\u5BB0\u5F69\u624D\u63A1\u683D\u6B73\u6E08\u707D\u91C7\u7280\u7815\u7826\u796D\u658E\u7D30\u83DC\u88C1\u8F09\u969B\u5264\u5728\u6750\u7F6A\u8CA1\u51B4\u5742\u962A\u583A\u698A\u80B4\u54B2\u5D0E\u57FC\u7895\u9DFA\u4F5C\u524A\u548B\u643E\u6628\u6714\u67F5\u7A84\u7B56\u7D22\u932F\u685C\u9BAD\u7B39\u5319\u518A\u5237"],
      ["8e40", "\u5BDF\u62F6\u64AE\u64E6\u672D\u6BBA\u85A9\u96D1\u7690\u9BD6\u634C\u9306\u9BAB\u76BF\u6652\u4E09\u5098\u53C2\u5C71\u60E8\u6492\u6563\u685F\u71E6\u73CA\u7523\u7B97\u7E82\u8695\u8B83\u8CDB\u9178\u9910\u65AC\u66AB\u6B8B\u4ED5\u4ED4\u4F3A\u4F7F\u523A\u53F8\u53F2\u55E3\u56DB\u58EB\u59CB\u59C9\u59FF\u5B50\u5C4D\u5E02\u5E2B\u5FD7\u601D\u6307\u652F\u5B5C\u65AF\u65BD\u65E8\u679D\u6B62"],
      ["8e80", "\u6B7B\u6C0F\u7345\u7949\u79C1\u7CF8\u7D19\u7D2B\u80A2\u8102\u81F3\u8996\u8A5E\u8A69\u8A66\u8A8C\u8AEE\u8CC7\u8CDC\u96CC\u98FC\u6B6F\u4E8B\u4F3C\u4F8D\u5150\u5B57\u5BFA\u6148\u6301\u6642\u6B21\u6ECB\u6CBB\u723E\u74BD\u75D4\u78C1\u793A\u800C\u8033\u81EA\u8494\u8F9E\u6C50\u9E7F\u5F0F\u8B58\u9D2B\u7AFA\u8EF8\u5B8D\u96EB\u4E03\u53F1\u57F7\u5931\u5AC9\u5BA4\u6089\u6E7F\u6F06\u75BE\u8CEA\u5B9F\u8500\u7BE0\u5072\u67F4\u829D\u5C61\u854A\u7E1E\u820E\u5199\u5C04\u6368\u8D66\u659C\u716E\u793E\u7D17\u8005\u8B1D\u8ECA\u906E\u86C7\u90AA\u501F\u52FA\u5C3A\u6753\u707C\u7235\u914C\u91C8\u932B\u82E5\u5BC2\u5F31\u60F9\u4E3B\u53D6\u5B88\u624B\u6731\u6B8A\u72E9\u73E0\u7A2E\u816B\u8DA3\u9152\u9996\u5112\u53D7\u546A\u5BFF\u6388\u6A39\u7DAC\u9700\u56DA\u53CE\u5468"],
      ["8f40", "\u5B97\u5C31\u5DDE\u4FEE\u6101\u62FE\u6D32\u79C0\u79CB\u7D42\u7E4D\u7FD2\u81ED\u821F\u8490\u8846\u8972\u8B90\u8E74\u8F2F\u9031\u914B\u916C\u96C6\u919C\u4EC0\u4F4F\u5145\u5341\u5F93\u620E\u67D4\u6C41\u6E0B\u7363\u7E26\u91CD\u9283\u53D4\u5919\u5BBF\u6DD1\u795D\u7E2E\u7C9B\u587E\u719F\u51FA\u8853\u8FF0\u4FCA\u5CFB\u6625\u77AC\u7AE3\u821C\u99FF\u51C6\u5FAA\u65EC\u696F\u6B89\u6DF3"],
      ["8f80", "\u6E96\u6F64\u76FE\u7D14\u5DE1\u9075\u9187\u9806\u51E6\u521D\u6240\u6691\u66D9\u6E1A\u5EB6\u7DD2\u7F72\u66F8\u85AF\u85F7\u8AF8\u52A9\u53D9\u5973\u5E8F\u5F90\u6055\u92E4\u9664\u50B7\u511F\u52DD\u5320\u5347\u53EC\u54E8\u5546\u5531\u5617\u5968\u59BE\u5A3C\u5BB5\u5C06\u5C0F\u5C11\u5C1A\u5E84\u5E8A\u5EE0\u5F70\u627F\u6284\u62DB\u638C\u6377\u6607\u660C\u662D\u6676\u677E\u68A2\u6A1F\u6A35\u6CBC\u6D88\u6E09\u6E58\u713C\u7126\u7167\u75C7\u7701\u785D\u7901\u7965\u79F0\u7AE0\u7B11\u7CA7\u7D39\u8096\u83D6\u848B\u8549\u885D\u88F3\u8A1F\u8A3C\u8A54\u8A73\u8C61\u8CDE\u91A4\u9266\u937E\u9418\u969C\u9798\u4E0A\u4E08\u4E1E\u4E57\u5197\u5270\u57CE\u5834\u58CC\u5B22\u5E38\u60C5\u64FE\u6761\u6756\u6D44\u72B6\u7573\u7A63\u84B8\u8B72\u91B8\u9320\u5631\u57F4\u98FE"],
      ["9040", "\u62ED\u690D\u6B96\u71ED\u7E54\u8077\u8272\u89E6\u98DF\u8755\u8FB1\u5C3B\u4F38\u4FE1\u4FB5\u5507\u5A20\u5BDD\u5BE9\u5FC3\u614E\u632F\u65B0\u664B\u68EE\u699B\u6D78\u6DF1\u7533\u75B9\u771F\u795E\u79E6\u7D33\u81E3\u82AF\u85AA\u89AA\u8A3A\u8EAB\u8F9B\u9032\u91DD\u9707\u4EBA\u4EC1\u5203\u5875\u58EC\u5C0B\u751A\u5C3D\u814E\u8A0A\u8FC5\u9663\u976D\u7B25\u8ACF\u9808\u9162\u56F3\u53A8"],
      ["9080", "\u9017\u5439\u5782\u5E25\u63A8\u6C34\u708A\u7761\u7C8B\u7FE0\u8870\u9042\u9154\u9310\u9318\u968F\u745E\u9AC4\u5D07\u5D69\u6570\u67A2\u8DA8\u96DB\u636E\u6749\u6919\u83C5\u9817\u96C0\u88FE\u6F84\u647A\u5BF8\u4E16\u702C\u755D\u662F\u51C4\u5236\u52E2\u59D3\u5F81\u6027\u6210\u653F\u6574\u661F\u6674\u68F2\u6816\u6B63\u6E05\u7272\u751F\u76DB\u7CBE\u8056\u58F0\u88FD\u897F\u8AA0\u8A93\u8ACB\u901D\u9192\u9752\u9759\u6589\u7A0E\u8106\u96BB\u5E2D\u60DC\u621A\u65A5\u6614\u6790\u77F3\u7A4D\u7C4D\u7E3E\u810A\u8CAC\u8D64\u8DE1\u8E5F\u78A9\u5207\u62D9\u63A5\u6442\u6298\u8A2D\u7A83\u7BC0\u8AAC\u96EA\u7D76\u820C\u8749\u4ED9\u5148\u5343\u5360\u5BA3\u5C02\u5C16\u5DDD\u6226\u6247\u64B0\u6813\u6834\u6CC9\u6D45\u6D17\u67D3\u6F5C\u714E\u717D\u65CB\u7A7F\u7BAD\u7DDA"],
      ["9140", "\u7E4A\u7FA8\u817A\u821B\u8239\u85A6\u8A6E\u8CCE\u8DF5\u9078\u9077\u92AD\u9291\u9583\u9BAE\u524D\u5584\u6F38\u7136\u5168\u7985\u7E55\u81B3\u7CCE\u564C\u5851\u5CA8\u63AA\u66FE\u66FD\u695A\u72D9\u758F\u758E\u790E\u7956\u79DF\u7C97\u7D20\u7D44\u8607\u8A34\u963B\u9061\u9F20\u50E7\u5275\u53CC\u53E2\u5009\u55AA\u58EE\u594F\u723D\u5B8B\u5C64\u531D\u60E3\u60F3\u635C\u6383\u633F\u63BB"],
      ["9180", "\u64CD\u65E9\u66F9\u5DE3\u69CD\u69FD\u6F15\u71E5\u4E89\u75E9\u76F8\u7A93\u7CDF\u7DCF\u7D9C\u8061\u8349\u8358\u846C\u84BC\u85FB\u88C5\u8D70\u9001\u906D\u9397\u971C\u9A12\u50CF\u5897\u618E\u81D3\u8535\u8D08\u9020\u4FC3\u5074\u5247\u5373\u606F\u6349\u675F\u6E2C\u8DB3\u901F\u4FD7\u5C5E\u8CCA\u65CF\u7D9A\u5352\u8896\u5176\u63C3\u5B58\u5B6B\u5C0A\u640D\u6751\u905C\u4ED6\u591A\u592A\u6C70\u8A51\u553E\u5815\u59A5\u60F0\u6253\u67C1\u8235\u6955\u9640\u99C4\u9A28\u4F53\u5806\u5BFE\u8010\u5CB1\u5E2F\u5F85\u6020\u614B\u6234\u66FF\u6CF0\u6EDE\u80CE\u817F\u82D4\u888B\u8CB8\u9000\u902E\u968A\u9EDB\u9BDB\u4EE3\u53F0\u5927\u7B2C\u918D\u984C\u9DF9\u6EDD\u7027\u5353\u5544\u5B85\u6258\u629E\u62D3\u6CA2\u6FEF\u7422\u8A17\u9438\u6FC1\u8AFE\u8338\u51E7\u86F8\u53EA"],
      ["9240", "\u53E9\u4F46\u9054\u8FB0\u596A\u8131\u5DFD\u7AEA\u8FBF\u68DA\u8C37\u72F8\u9C48\u6A3D\u8AB0\u4E39\u5358\u5606\u5766\u62C5\u63A2\u65E6\u6B4E\u6DE1\u6E5B\u70AD\u77ED\u7AEF\u7BAA\u7DBB\u803D\u80C6\u86CB\u8A95\u935B\u56E3\u58C7\u5F3E\u65AD\u6696\u6A80\u6BB5\u7537\u8AC7\u5024\u77E5\u5730\u5F1B\u6065\u667A\u6C60\u75F4\u7A1A\u7F6E\u81F4\u8718\u9045\u99B3\u7BC9\u755C\u7AF9\u7B51\u84C4"],
      ["9280", "\u9010\u79E9\u7A92\u8336\u5AE1\u7740\u4E2D\u4EF2\u5B99\u5FE0\u62BD\u663C\u67F1\u6CE8\u866B\u8877\u8A3B\u914E\u92F3\u99D0\u6A17\u7026\u732A\u82E7\u8457\u8CAF\u4E01\u5146\u51CB\u558B\u5BF5\u5E16\u5E33\u5E81\u5F14\u5F35\u5F6B\u5FB4\u61F2\u6311\u66A2\u671D\u6F6E\u7252\u753A\u773A\u8074\u8139\u8178\u8776\u8ABF\u8ADC\u8D85\u8DF3\u929A\u9577\u9802\u9CE5\u52C5\u6357\u76F4\u6715\u6C88\u73CD\u8CC3\u93AE\u9673\u6D25\u589C\u690E\u69CC\u8FFD\u939A\u75DB\u901A\u585A\u6802\u63B4\u69FB\u4F43\u6F2C\u67D8\u8FBB\u8526\u7DB4\u9354\u693F\u6F70\u576A\u58F7\u5B2C\u7D2C\u722A\u540A\u91E3\u9DB4\u4EAD\u4F4E\u505C\u5075\u5243\u8C9E\u5448\u5824\u5B9A\u5E1D\u5E95\u5EAD\u5EF7\u5F1F\u608C\u62B5\u633A\u63D0\u68AF\u6C40\u7887\u798E\u7A0B\u7DE0\u8247\u8A02\u8AE6\u8E44\u9013"],
      ["9340", "\u90B8\u912D\u91D8\u9F0E\u6CE5\u6458\u64E2\u6575\u6EF4\u7684\u7B1B\u9069\u93D1\u6EBA\u54F2\u5FB9\u64A4\u8F4D\u8FED\u9244\u5178\u586B\u5929\u5C55\u5E97\u6DFB\u7E8F\u751C\u8CBC\u8EE2\u985B\u70B9\u4F1D\u6BBF\u6FB1\u7530\u96FB\u514E\u5410\u5835\u5857\u59AC\u5C60\u5F92\u6597\u675C\u6E21\u767B\u83DF\u8CED\u9014\u90FD\u934D\u7825\u783A\u52AA\u5EA6\u571F\u5974\u6012\u5012\u515A\u51AC"],
      ["9380", "\u51CD\u5200\u5510\u5854\u5858\u5957\u5B95\u5CF6\u5D8B\u60BC\u6295\u642D\u6771\u6843\u68BC\u68DF\u76D7\u6DD8\u6E6F\u6D9B\u706F\u71C8\u5F53\u75D8\u7977\u7B49\u7B54\u7B52\u7CD6\u7D71\u5230\u8463\u8569\u85E4\u8A0E\u8B04\u8C46\u8E0F\u9003\u900F\u9419\u9676\u982D\u9A30\u95D8\u50CD\u52D5\u540C\u5802\u5C0E\u61A7\u649E\u6D1E\u77B3\u7AE5\u80F4\u8404\u9053\u9285\u5CE0\u9D07\u533F\u5F97\u5FB3\u6D9C\u7279\u7763\u79BF\u7BE4\u6BD2\u72EC\u8AAD\u6803\u6A61\u51F8\u7A81\u6934\u5C4A\u9CF6\u82EB\u5BC5\u9149\u701E\u5678\u5C6F\u60C7\u6566\u6C8C\u8C5A\u9041\u9813\u5451\u66C7\u920D\u5948\u90A3\u5185\u4E4D\u51EA\u8599\u8B0E\u7058\u637A\u934B\u6962\u99B4\u7E04\u7577\u5357\u6960\u8EDF\u96E3\u6C5D\u4E8C\u5C3C\u5F10\u8FE9\u5302\u8CD1\u8089\u8679\u5EFF\u65E5\u4E73\u5165"],
      ["9440", "\u5982\u5C3F\u97EE\u4EFB\u598A\u5FCD\u8A8D\u6FE1\u79B0\u7962\u5BE7\u8471\u732B\u71B1\u5E74\u5FF5\u637B\u649A\u71C3\u7C98\u4E43\u5EFC\u4E4B\u57DC\u56A2\u60A9\u6FC3\u7D0D\u80FD\u8133\u81BF\u8FB2\u8997\u86A4\u5DF4\u628A\u64AD\u8987\u6777\u6CE2\u6D3E\u7436\u7834\u5A46\u7F75\u82AD\u99AC\u4FF3\u5EC3\u62DD\u6392\u6557\u676F\u76C3\u724C\u80CC\u80BA\u8F29\u914D\u500D\u57F9\u5A92\u6885"],
      ["9480", "\u6973\u7164\u72FD\u8CB7\u58F2\u8CE0\u966A\u9019\u877F\u79E4\u77E7\u8429\u4F2F\u5265\u535A\u62CD\u67CF\u6CCA\u767D\u7B94\u7C95\u8236\u8584\u8FEB\u66DD\u6F20\u7206\u7E1B\u83AB\u99C1\u9EA6\u51FD\u7BB1\u7872\u7BB8\u8087\u7B48\u6AE8\u5E61\u808C\u7551\u7560\u516B\u9262\u6E8C\u767A\u9197\u9AEA\u4F10\u7F70\u629C\u7B4F\u95A5\u9CE9\u567A\u5859\u86E4\u96BC\u4F34\u5224\u534A\u53CD\u53DB\u5E06\u642C\u6591\u677F\u6C3E\u6C4E\u7248\u72AF\u73ED\u7554\u7E41\u822C\u85E9\u8CA9\u7BC4\u91C6\u7169\u9812\u98EF\u633D\u6669\u756A\u76E4\u78D0\u8543\u86EE\u532A\u5351\u5426\u5983\u5E87\u5F7C\u60B2\u6249\u6279\u62AB\u6590\u6BD4\u6CCC\u75B2\u76AE\u7891\u79D8\u7DCB\u7F77\u80A5\u88AB\u8AB9\u8CBB\u907F\u975E\u98DB\u6A0B\u7C38\u5099\u5C3E\u5FAE\u6787\u6BD8\u7435\u7709\u7F8E"],
      ["9540", "\u9F3B\u67CA\u7A17\u5339\u758B\u9AED\u5F66\u819D\u83F1\u8098\u5F3C\u5FC5\u7562\u7B46\u903C\u6867\u59EB\u5A9B\u7D10\u767E\u8B2C\u4FF5\u5F6A\u6A19\u6C37\u6F02\u74E2\u7968\u8868\u8A55\u8C79\u5EDF\u63CF\u75C5\u79D2\u82D7\u9328\u92F2\u849C\u86ED\u9C2D\u54C1\u5F6C\u658C\u6D5C\u7015\u8CA7\u8CD3\u983B\u654F\u74F6\u4E0D\u4ED8\u57E0\u592B\u5A66\u5BCC\u51A8\u5E03\u5E9C\u6016\u6276\u6577"],
      ["9580", "\u65A7\u666E\u6D6E\u7236\u7B26\u8150\u819A\u8299\u8B5C\u8CA0\u8CE6\u8D74\u961C\u9644\u4FAE\u64AB\u6B66\u821E\u8461\u856A\u90E8\u5C01\u6953\u98A8\u847A\u8557\u4F0F\u526F\u5FA9\u5E45\u670D\u798F\u8179\u8907\u8986\u6DF5\u5F17\u6255\u6CB8\u4ECF\u7269\u9B92\u5206\u543B\u5674\u58B3\u61A4\u626E\u711A\u596E\u7C89\u7CDE\u7D1B\u96F0\u6587\u805E\u4E19\u4F75\u5175\u5840\u5E63\u5E73\u5F0A\u67C4\u4E26\u853D\u9589\u965B\u7C73\u9801\u50FB\u58C1\u7656\u78A7\u5225\u77A5\u8511\u7B86\u504F\u5909\u7247\u7BC7\u7DE8\u8FBA\u8FD4\u904D\u4FBF\u52C9\u5A29\u5F01\u97AD\u4FDD\u8217\u92EA\u5703\u6355\u6B69\u752B\u88DC\u8F14\u7A42\u52DF\u5893\u6155\u620A\u66AE\u6BCD\u7C3F\u83E9\u5023\u4FF8\u5305\u5446\u5831\u5949\u5B9D\u5CF0\u5CEF\u5D29\u5E96\u62B1\u6367\u653E\u65B9\u670B"],
      ["9640", "\u6CD5\u6CE1\u70F9\u7832\u7E2B\u80DE\u82B3\u840C\u84EC\u8702\u8912\u8A2A\u8C4A\u90A6\u92D2\u98FD\u9CF3\u9D6C\u4E4F\u4EA1\u508D\u5256\u574A\u59A8\u5E3D\u5FD8\u5FD9\u623F\u66B4\u671B\u67D0\u68D2\u5192\u7D21\u80AA\u81A8\u8B00\u8C8C\u8CBF\u927E\u9632\u5420\u982C\u5317\u50D5\u535C\u58A8\u64B2\u6734\u7267\u7766\u7A46\u91E6\u52C3\u6CA1\u6B86\u5800\u5E4C\u5954\u672C\u7FFB\u51E1\u76C6"],
      ["9680", "\u6469\u78E8\u9B54\u9EBB\u57CB\u59B9\u6627\u679A\u6BCE\u54E9\u69D9\u5E55\u819C\u6795\u9BAA\u67FE\u9C52\u685D\u4EA6\u4FE3\u53C8\u62B9\u672B\u6CAB\u8FC4\u4FAD\u7E6D\u9EBF\u4E07\u6162\u6E80\u6F2B\u8513\u5473\u672A\u9B45\u5DF3\u7B95\u5CAC\u5BC6\u871C\u6E4A\u84D1\u7A14\u8108\u5999\u7C8D\u6C11\u7720\u52D9\u5922\u7121\u725F\u77DB\u9727\u9D61\u690B\u5A7F\u5A18\u51A5\u540D\u547D\u660E\u76DF\u8FF7\u9298\u9CF4\u59EA\u725D\u6EC5\u514D\u68C9\u7DBF\u7DEC\u9762\u9EBA\u6478\u6A21\u8302\u5984\u5B5F\u6BDB\u731B\u76F2\u7DB2\u8017\u8499\u5132\u6728\u9ED9\u76EE\u6762\u52FF\u9905\u5C24\u623B\u7C7E\u8CB0\u554F\u60B6\u7D0B\u9580\u5301\u4E5F\u51B6\u591C\u723A\u8036\u91CE\u5F25\u77E2\u5384\u5F79\u7D04\u85AC\u8A33\u8E8D\u9756\u67F3\u85AE\u9453\u6109\u6108\u6CB9\u7652"],
      ["9740", "\u8AED\u8F38\u552F\u4F51\u512A\u52C7\u53CB\u5BA5\u5E7D\u60A0\u6182\u63D6\u6709\u67DA\u6E67\u6D8C\u7336\u7337\u7531\u7950\u88D5\u8A98\u904A\u9091\u90F5\u96C4\u878D\u5915\u4E88\u4F59\u4E0E\u8A89\u8F3F\u9810\u50AD\u5E7C\u5996\u5BB9\u5EB8\u63DA\u63FA\u64C1\u66DC\u694A\u69D8\u6D0B\u6EB6\u7194\u7528\u7AAF\u7F8A\u8000\u8449\u84C9\u8981\u8B21\u8E0A\u9065\u967D\u990A\u617E\u6291\u6B32"],
      ["9780", "\u6C83\u6D74\u7FCC\u7FFC\u6DC0\u7F85\u87BA\u88F8\u6765\u83B1\u983C\u96F7\u6D1B\u7D61\u843D\u916A\u4E71\u5375\u5D50\u6B04\u6FEB\u85CD\u862D\u89A7\u5229\u540F\u5C65\u674E\u68A8\u7406\u7483\u75E2\u88CF\u88E1\u91CC\u96E2\u9678\u5F8B\u7387\u7ACB\u844E\u63A0\u7565\u5289\u6D41\u6E9C\u7409\u7559\u786B\u7C92\u9686\u7ADC\u9F8D\u4FB6\u616E\u65C5\u865C\u4E86\u4EAE\u50DA\u4E21\u51CC\u5BEE\u6599\u6881\u6DBC\u731F\u7642\u77AD\u7A1C\u7CE7\u826F\u8AD2\u907C\u91CF\u9675\u9818\u529B\u7DD1\u502B\u5398\u6797\u6DCB\u71D0\u7433\u81E8\u8F2A\u96A3\u9C57\u9E9F\u7460\u5841\u6D99\u7D2F\u985E\u4EE4\u4F36\u4F8B\u51B7\u52B1\u5DBA\u601C\u73B2\u793C\u82D3\u9234\u96B7\u96F6\u970A\u9E97\u9F62\u66A6\u6B74\u5217\u52A3\u70C8\u88C2\u5EC9\u604B\u6190\u6F23\u7149\u7C3E\u7DF4\u806F"],
      ["9840", "\u84EE\u9023\u932C\u5442\u9B6F\u6AD3\u7089\u8CC2\u8DEF\u9732\u52B4\u5A41\u5ECA\u5F04\u6717\u697C\u6994\u6D6A\u6F0F\u7262\u72FC\u7BED\u8001\u807E\u874B\u90CE\u516D\u9E93\u7984\u808B\u9332\u8AD6\u502D\u548C\u8A71\u6B6A\u8CC4\u8107\u60D1\u67A0\u9DF2\u4E99\u4E98\u9C10\u8A6B\u85C1\u8568\u6900\u6E7E\u7897\u8155"],
      ["989f", "\u5F0C\u4E10\u4E15\u4E2A\u4E31\u4E36\u4E3C\u4E3F\u4E42\u4E56\u4E58\u4E82\u4E85\u8C6B\u4E8A\u8212\u5F0D\u4E8E\u4E9E\u4E9F\u4EA0\u4EA2\u4EB0\u4EB3\u4EB6\u4ECE\u4ECD\u4EC4\u4EC6\u4EC2\u4ED7\u4EDE\u4EED\u4EDF\u4EF7\u4F09\u4F5A\u4F30\u4F5B\u4F5D\u4F57\u4F47\u4F76\u4F88\u4F8F\u4F98\u4F7B\u4F69\u4F70\u4F91\u4F6F\u4F86\u4F96\u5118\u4FD4\u4FDF\u4FCE\u4FD8\u4FDB\u4FD1\u4FDA\u4FD0\u4FE4\u4FE5\u501A\u5028\u5014\u502A\u5025\u5005\u4F1C\u4FF6\u5021\u5029\u502C\u4FFE\u4FEF\u5011\u5006\u5043\u5047\u6703\u5055\u5050\u5048\u505A\u5056\u506C\u5078\u5080\u509A\u5085\u50B4\u50B2"],
      ["9940", "\u50C9\u50CA\u50B3\u50C2\u50D6\u50DE\u50E5\u50ED\u50E3\u50EE\u50F9\u50F5\u5109\u5101\u5102\u5116\u5115\u5114\u511A\u5121\u513A\u5137\u513C\u513B\u513F\u5140\u5152\u514C\u5154\u5162\u7AF8\u5169\u516A\u516E\u5180\u5182\u56D8\u518C\u5189\u518F\u5191\u5193\u5195\u5196\u51A4\u51A6\u51A2\u51A9\u51AA\u51AB\u51B3\u51B1\u51B2\u51B0\u51B5\u51BD\u51C5\u51C9\u51DB\u51E0\u8655\u51E9\u51ED"],
      ["9980", "\u51F0\u51F5\u51FE\u5204\u520B\u5214\u520E\u5227\u522A\u522E\u5233\u5239\u524F\u5244\u524B\u524C\u525E\u5254\u526A\u5274\u5269\u5273\u527F\u527D\u528D\u5294\u5292\u5271\u5288\u5291\u8FA8\u8FA7\u52AC\u52AD\u52BC\u52B5\u52C1\u52CD\u52D7\u52DE\u52E3\u52E6\u98ED\u52E0\u52F3\u52F5\u52F8\u52F9\u5306\u5308\u7538\u530D\u5310\u530F\u5315\u531A\u5323\u532F\u5331\u5333\u5338\u5340\u5346\u5345\u4E17\u5349\u534D\u51D6\u535E\u5369\u536E\u5918\u537B\u5377\u5382\u5396\u53A0\u53A6\u53A5\u53AE\u53B0\u53B6\u53C3\u7C12\u96D9\u53DF\u66FC\u71EE\u53EE\u53E8\u53ED\u53FA\u5401\u543D\u5440\u542C\u542D\u543C\u542E\u5436\u5429\u541D\u544E\u548F\u5475\u548E\u545F\u5471\u5477\u5470\u5492\u547B\u5480\u5476\u5484\u5490\u5486\u54C7\u54A2\u54B8\u54A5\u54AC\u54C4\u54C8\u54A8"],
      ["9a40", "\u54AB\u54C2\u54A4\u54BE\u54BC\u54D8\u54E5\u54E6\u550F\u5514\u54FD\u54EE\u54ED\u54FA\u54E2\u5539\u5540\u5563\u554C\u552E\u555C\u5545\u5556\u5557\u5538\u5533\u555D\u5599\u5580\u54AF\u558A\u559F\u557B\u557E\u5598\u559E\u55AE\u557C\u5583\u55A9\u5587\u55A8\u55DA\u55C5\u55DF\u55C4\u55DC\u55E4\u55D4\u5614\u55F7\u5616\u55FE\u55FD\u561B\u55F9\u564E\u5650\u71DF\u5634\u5636\u5632\u5638"],
      ["9a80", "\u566B\u5664\u562F\u566C\u566A\u5686\u5680\u568A\u56A0\u5694\u568F\u56A5\u56AE\u56B6\u56B4\u56C2\u56BC\u56C1\u56C3\u56C0\u56C8\u56CE\u56D1\u56D3\u56D7\u56EE\u56F9\u5700\u56FF\u5704\u5709\u5708\u570B\u570D\u5713\u5718\u5716\u55C7\u571C\u5726\u5737\u5738\u574E\u573B\u5740\u574F\u5769\u57C0\u5788\u5761\u577F\u5789\u5793\u57A0\u57B3\u57A4\u57AA\u57B0\u57C3\u57C6\u57D4\u57D2\u57D3\u580A\u57D6\u57E3\u580B\u5819\u581D\u5872\u5821\u5862\u584B\u5870\u6BC0\u5852\u583D\u5879\u5885\u58B9\u589F\u58AB\u58BA\u58DE\u58BB\u58B8\u58AE\u58C5\u58D3\u58D1\u58D7\u58D9\u58D8\u58E5\u58DC\u58E4\u58DF\u58EF\u58FA\u58F9\u58FB\u58FC\u58FD\u5902\u590A\u5910\u591B\u68A6\u5925\u592C\u592D\u5932\u5938\u593E\u7AD2\u5955\u5950\u594E\u595A\u5958\u5962\u5960\u5967\u596C\u5969"],
      ["9b40", "\u5978\u5981\u599D\u4F5E\u4FAB\u59A3\u59B2\u59C6\u59E8\u59DC\u598D\u59D9\u59DA\u5A25\u5A1F\u5A11\u5A1C\u5A09\u5A1A\u5A40\u5A6C\u5A49\u5A35\u5A36\u5A62\u5A6A\u5A9A\u5ABC\u5ABE\u5ACB\u5AC2\u5ABD\u5AE3\u5AD7\u5AE6\u5AE9\u5AD6\u5AFA\u5AFB\u5B0C\u5B0B\u5B16\u5B32\u5AD0\u5B2A\u5B36\u5B3E\u5B43\u5B45\u5B40\u5B51\u5B55\u5B5A\u5B5B\u5B65\u5B69\u5B70\u5B73\u5B75\u5B78\u6588\u5B7A\u5B80"],
      ["9b80", "\u5B83\u5BA6\u5BB8\u5BC3\u5BC7\u5BC9\u5BD4\u5BD0\u5BE4\u5BE6\u5BE2\u5BDE\u5BE5\u5BEB\u5BF0\u5BF6\u5BF3\u5C05\u5C07\u5C08\u5C0D\u5C13\u5C20\u5C22\u5C28\u5C38\u5C39\u5C41\u5C46\u5C4E\u5C53\u5C50\u5C4F\u5B71\u5C6C\u5C6E\u4E62\u5C76\u5C79\u5C8C\u5C91\u5C94\u599B\u5CAB\u5CBB\u5CB6\u5CBC\u5CB7\u5CC5\u5CBE\u5CC7\u5CD9\u5CE9\u5CFD\u5CFA\u5CED\u5D8C\u5CEA\u5D0B\u5D15\u5D17\u5D5C\u5D1F\u5D1B\u5D11\u5D14\u5D22\u5D1A\u5D19\u5D18\u5D4C\u5D52\u5D4E\u5D4B\u5D6C\u5D73\u5D76\u5D87\u5D84\u5D82\u5DA2\u5D9D\u5DAC\u5DAE\u5DBD\u5D90\u5DB7\u5DBC\u5DC9\u5DCD\u5DD3\u5DD2\u5DD6\u5DDB\u5DEB\u5DF2\u5DF5\u5E0B\u5E1A\u5E19\u5E11\u5E1B\u5E36\u5E37\u5E44\u5E43\u5E40\u5E4E\u5E57\u5E54\u5E5F\u5E62\u5E64\u5E47\u5E75\u5E76\u5E7A\u9EBC\u5E7F\u5EA0\u5EC1\u5EC2\u5EC8\u5ED0\u5ECF"],
      ["9c40", "\u5ED6\u5EE3\u5EDD\u5EDA\u5EDB\u5EE2\u5EE1\u5EE8\u5EE9\u5EEC\u5EF1\u5EF3\u5EF0\u5EF4\u5EF8\u5EFE\u5F03\u5F09\u5F5D\u5F5C\u5F0B\u5F11\u5F16\u5F29\u5F2D\u5F38\u5F41\u5F48\u5F4C\u5F4E\u5F2F\u5F51\u5F56\u5F57\u5F59\u5F61\u5F6D\u5F73\u5F77\u5F83\u5F82\u5F7F\u5F8A\u5F88\u5F91\u5F87\u5F9E\u5F99\u5F98\u5FA0\u5FA8\u5FAD\u5FBC\u5FD6\u5FFB\u5FE4\u5FF8\u5FF1\u5FDD\u60B3\u5FFF\u6021\u6060"],
      ["9c80", "\u6019\u6010\u6029\u600E\u6031\u601B\u6015\u602B\u6026\u600F\u603A\u605A\u6041\u606A\u6077\u605F\u604A\u6046\u604D\u6063\u6043\u6064\u6042\u606C\u606B\u6059\u6081\u608D\u60E7\u6083\u609A\u6084\u609B\u6096\u6097\u6092\u60A7\u608B\u60E1\u60B8\u60E0\u60D3\u60B4\u5FF0\u60BD\u60C6\u60B5\u60D8\u614D\u6115\u6106\u60F6\u60F7\u6100\u60F4\u60FA\u6103\u6121\u60FB\u60F1\u610D\u610E\u6147\u613E\u6128\u6127\u614A\u613F\u613C\u612C\u6134\u613D\u6142\u6144\u6173\u6177\u6158\u6159\u615A\u616B\u6174\u616F\u6165\u6171\u615F\u615D\u6153\u6175\u6199\u6196\u6187\u61AC\u6194\u619A\u618A\u6191\u61AB\u61AE\u61CC\u61CA\u61C9\u61F7\u61C8\u61C3\u61C6\u61BA\u61CB\u7F79\u61CD\u61E6\u61E3\u61F6\u61FA\u61F4\u61FF\u61FD\u61FC\u61FE\u6200\u6208\u6209\u620D\u620C\u6214\u621B"],
      ["9d40", "\u621E\u6221\u622A\u622E\u6230\u6232\u6233\u6241\u624E\u625E\u6263\u625B\u6260\u6268\u627C\u6282\u6289\u627E\u6292\u6293\u6296\u62D4\u6283\u6294\u62D7\u62D1\u62BB\u62CF\u62FF\u62C6\u64D4\u62C8\u62DC\u62CC\u62CA\u62C2\u62C7\u629B\u62C9\u630C\u62EE\u62F1\u6327\u6302\u6308\u62EF\u62F5\u6350\u633E\u634D\u641C\u634F\u6396\u638E\u6380\u63AB\u6376\u63A3\u638F\u6389\u639F\u63B5\u636B"],
      ["9d80", "\u6369\u63BE\u63E9\u63C0\u63C6\u63E3\u63C9\u63D2\u63F6\u63C4\u6416\u6434\u6406\u6413\u6426\u6436\u651D\u6417\u6428\u640F\u6467\u646F\u6476\u644E\u652A\u6495\u6493\u64A5\u64A9\u6488\u64BC\u64DA\u64D2\u64C5\u64C7\u64BB\u64D8\u64C2\u64F1\u64E7\u8209\u64E0\u64E1\u62AC\u64E3\u64EF\u652C\u64F6\u64F4\u64F2\u64FA\u6500\u64FD\u6518\u651C\u6505\u6524\u6523\u652B\u6534\u6535\u6537\u6536\u6538\u754B\u6548\u6556\u6555\u654D\u6558\u655E\u655D\u6572\u6578\u6582\u6583\u8B8A\u659B\u659F\u65AB\u65B7\u65C3\u65C6\u65C1\u65C4\u65CC\u65D2\u65DB\u65D9\u65E0\u65E1\u65F1\u6772\u660A\u6603\u65FB\u6773\u6635\u6636\u6634\u661C\u664F\u6644\u6649\u6641\u665E\u665D\u6664\u6667\u6668\u665F\u6662\u6670\u6683\u6688\u668E\u6689\u6684\u6698\u669D\u66C1\u66B9\u66C9\u66BE\u66BC"],
      ["9e40", "\u66C4\u66B8\u66D6\u66DA\u66E0\u663F\u66E6\u66E9\u66F0\u66F5\u66F7\u670F\u6716\u671E\u6726\u6727\u9738\u672E\u673F\u6736\u6741\u6738\u6737\u6746\u675E\u6760\u6759\u6763\u6764\u6789\u6770\u67A9\u677C\u676A\u678C\u678B\u67A6\u67A1\u6785\u67B7\u67EF\u67B4\u67EC\u67B3\u67E9\u67B8\u67E4\u67DE\u67DD\u67E2\u67EE\u67B9\u67CE\u67C6\u67E7\u6A9C\u681E\u6846\u6829\u6840\u684D\u6832\u684E"],
      ["9e80", "\u68B3\u682B\u6859\u6863\u6877\u687F\u689F\u688F\u68AD\u6894\u689D\u689B\u6883\u6AAE\u68B9\u6874\u68B5\u68A0\u68BA\u690F\u688D\u687E\u6901\u68CA\u6908\u68D8\u6922\u6926\u68E1\u690C\u68CD\u68D4\u68E7\u68D5\u6936\u6912\u6904\u68D7\u68E3\u6925\u68F9\u68E0\u68EF\u6928\u692A\u691A\u6923\u6921\u68C6\u6979\u6977\u695C\u6978\u696B\u6954\u697E\u696E\u6939\u6974\u693D\u6959\u6930\u6961\u695E\u695D\u6981\u696A\u69B2\u69AE\u69D0\u69BF\u69C1\u69D3\u69BE\u69CE\u5BE8\u69CA\u69DD\u69BB\u69C3\u69A7\u6A2E\u6991\u69A0\u699C\u6995\u69B4\u69DE\u69E8\u6A02\u6A1B\u69FF\u6B0A\u69F9\u69F2\u69E7\u6A05\u69B1\u6A1E\u69ED\u6A14\u69EB\u6A0A\u6A12\u6AC1\u6A23\u6A13\u6A44\u6A0C\u6A72\u6A36\u6A78\u6A47\u6A62\u6A59\u6A66\u6A48\u6A38\u6A22\u6A90\u6A8D\u6AA0\u6A84\u6AA2\u6AA3"],
      ["9f40", "\u6A97\u8617\u6ABB\u6AC3\u6AC2\u6AB8\u6AB3\u6AAC\u6ADE\u6AD1\u6ADF\u6AAA\u6ADA\u6AEA\u6AFB\u6B05\u8616\u6AFA\u6B12\u6B16\u9B31\u6B1F\u6B38\u6B37\u76DC\u6B39\u98EE\u6B47\u6B43\u6B49\u6B50\u6B59\u6B54\u6B5B\u6B5F\u6B61\u6B78\u6B79\u6B7F\u6B80\u6B84\u6B83\u6B8D\u6B98\u6B95\u6B9E\u6BA4\u6BAA\u6BAB\u6BAF\u6BB2\u6BB1\u6BB3\u6BB7\u6BBC\u6BC6\u6BCB\u6BD3\u6BDF\u6BEC\u6BEB\u6BF3\u6BEF"],
      ["9f80", "\u9EBE\u6C08\u6C13\u6C14\u6C1B\u6C24\u6C23\u6C5E\u6C55\u6C62\u6C6A\u6C82\u6C8D\u6C9A\u6C81\u6C9B\u6C7E\u6C68\u6C73\u6C92\u6C90\u6CC4\u6CF1\u6CD3\u6CBD\u6CD7\u6CC5\u6CDD\u6CAE\u6CB1\u6CBE\u6CBA\u6CDB\u6CEF\u6CD9\u6CEA\u6D1F\u884D\u6D36\u6D2B\u6D3D\u6D38\u6D19\u6D35\u6D33\u6D12\u6D0C\u6D63\u6D93\u6D64\u6D5A\u6D79\u6D59\u6D8E\u6D95\u6FE4\u6D85\u6DF9\u6E15\u6E0A\u6DB5\u6DC7\u6DE6\u6DB8\u6DC6\u6DEC\u6DDE\u6DCC\u6DE8\u6DD2\u6DC5\u6DFA\u6DD9\u6DE4\u6DD5\u6DEA\u6DEE\u6E2D\u6E6E\u6E2E\u6E19\u6E72\u6E5F\u6E3E\u6E23\u6E6B\u6E2B\u6E76\u6E4D\u6E1F\u6E43\u6E3A\u6E4E\u6E24\u6EFF\u6E1D\u6E38\u6E82\u6EAA\u6E98\u6EC9\u6EB7\u6ED3\u6EBD\u6EAF\u6EC4\u6EB2\u6ED4\u6ED5\u6E8F\u6EA5\u6EC2\u6E9F\u6F41\u6F11\u704C\u6EEC\u6EF8\u6EFE\u6F3F\u6EF2\u6F31\u6EEF\u6F32\u6ECC"],
      ["e040", "\u6F3E\u6F13\u6EF7\u6F86\u6F7A\u6F78\u6F81\u6F80\u6F6F\u6F5B\u6FF3\u6F6D\u6F82\u6F7C\u6F58\u6F8E\u6F91\u6FC2\u6F66\u6FB3\u6FA3\u6FA1\u6FA4\u6FB9\u6FC6\u6FAA\u6FDF\u6FD5\u6FEC\u6FD4\u6FD8\u6FF1\u6FEE\u6FDB\u7009\u700B\u6FFA\u7011\u7001\u700F\u6FFE\u701B\u701A\u6F74\u701D\u7018\u701F\u7030\u703E\u7032\u7051\u7063\u7099\u7092\u70AF\u70F1\u70AC\u70B8\u70B3\u70AE\u70DF\u70CB\u70DD"],
      ["e080", "\u70D9\u7109\u70FD\u711C\u7119\u7165\u7155\u7188\u7166\u7162\u714C\u7156\u716C\u718F\u71FB\u7184\u7195\u71A8\u71AC\u71D7\u71B9\u71BE\u71D2\u71C9\u71D4\u71CE\u71E0\u71EC\u71E7\u71F5\u71FC\u71F9\u71FF\u720D\u7210\u721B\u7228\u722D\u722C\u7230\u7232\u723B\u723C\u723F\u7240\u7246\u724B\u7258\u7274\u727E\u7282\u7281\u7287\u7292\u7296\u72A2\u72A7\u72B9\u72B2\u72C3\u72C6\u72C4\u72CE\u72D2\u72E2\u72E0\u72E1\u72F9\u72F7\u500F\u7317\u730A\u731C\u7316\u731D\u7334\u732F\u7329\u7325\u733E\u734E\u734F\u9ED8\u7357\u736A\u7368\u7370\u7378\u7375\u737B\u737A\u73C8\u73B3\u73CE\u73BB\u73C0\u73E5\u73EE\u73DE\u74A2\u7405\u746F\u7425\u73F8\u7432\u743A\u7455\u743F\u745F\u7459\u7441\u745C\u7469\u7470\u7463\u746A\u7476\u747E\u748B\u749E\u74A7\u74CA\u74CF\u74D4\u73F1"],
      ["e140", "\u74E0\u74E3\u74E7\u74E9\u74EE\u74F2\u74F0\u74F1\u74F8\u74F7\u7504\u7503\u7505\u750C\u750E\u750D\u7515\u7513\u751E\u7526\u752C\u753C\u7544\u754D\u754A\u7549\u755B\u7546\u755A\u7569\u7564\u7567\u756B\u756D\u7578\u7576\u7586\u7587\u7574\u758A\u7589\u7582\u7594\u759A\u759D\u75A5\u75A3\u75C2\u75B3\u75C3\u75B5\u75BD\u75B8\u75BC\u75B1\u75CD\u75CA\u75D2\u75D9\u75E3\u75DE\u75FE\u75FF"],
      ["e180", "\u75FC\u7601\u75F0\u75FA\u75F2\u75F3\u760B\u760D\u7609\u761F\u7627\u7620\u7621\u7622\u7624\u7634\u7630\u763B\u7647\u7648\u7646\u765C\u7658\u7661\u7662\u7668\u7669\u766A\u7667\u766C\u7670\u7672\u7676\u7678\u767C\u7680\u7683\u7688\u768B\u768E\u7696\u7693\u7699\u769A\u76B0\u76B4\u76B8\u76B9\u76BA\u76C2\u76CD\u76D6\u76D2\u76DE\u76E1\u76E5\u76E7\u76EA\u862F\u76FB\u7708\u7707\u7704\u7729\u7724\u771E\u7725\u7726\u771B\u7737\u7738\u7747\u775A\u7768\u776B\u775B\u7765\u777F\u777E\u7779\u778E\u778B\u7791\u77A0\u779E\u77B0\u77B6\u77B9\u77BF\u77BC\u77BD\u77BB\u77C7\u77CD\u77D7\u77DA\u77DC\u77E3\u77EE\u77FC\u780C\u7812\u7926\u7820\u792A\u7845\u788E\u7874\u7886\u787C\u789A\u788C\u78A3\u78B5\u78AA\u78AF\u78D1\u78C6\u78CB\u78D4\u78BE\u78BC\u78C5\u78CA\u78EC"],
      ["e240", "\u78E7\u78DA\u78FD\u78F4\u7907\u7912\u7911\u7919\u792C\u792B\u7940\u7960\u7957\u795F\u795A\u7955\u7953\u797A\u797F\u798A\u799D\u79A7\u9F4B\u79AA\u79AE\u79B3\u79B9\u79BA\u79C9\u79D5\u79E7\u79EC\u79E1\u79E3\u7A08\u7A0D\u7A18\u7A19\u7A20\u7A1F\u7980\u7A31\u7A3B\u7A3E\u7A37\u7A43\u7A57\u7A49\u7A61\u7A62\u7A69\u9F9D\u7A70\u7A79\u7A7D\u7A88\u7A97\u7A95\u7A98\u7A96\u7AA9\u7AC8\u7AB0"],
      ["e280", "\u7AB6\u7AC5\u7AC4\u7ABF\u9083\u7AC7\u7ACA\u7ACD\u7ACF\u7AD5\u7AD3\u7AD9\u7ADA\u7ADD\u7AE1\u7AE2\u7AE6\u7AED\u7AF0\u7B02\u7B0F\u7B0A\u7B06\u7B33\u7B18\u7B19\u7B1E\u7B35\u7B28\u7B36\u7B50\u7B7A\u7B04\u7B4D\u7B0B\u7B4C\u7B45\u7B75\u7B65\u7B74\u7B67\u7B70\u7B71\u7B6C\u7B6E\u7B9D\u7B98\u7B9F\u7B8D\u7B9C\u7B9A\u7B8B\u7B92\u7B8F\u7B5D\u7B99\u7BCB\u7BC1\u7BCC\u7BCF\u7BB4\u7BC6\u7BDD\u7BE9\u7C11\u7C14\u7BE6\u7BE5\u7C60\u7C00\u7C07\u7C13\u7BF3\u7BF7\u7C17\u7C0D\u7BF6\u7C23\u7C27\u7C2A\u7C1F\u7C37\u7C2B\u7C3D\u7C4C\u7C43\u7C54\u7C4F\u7C40\u7C50\u7C58\u7C5F\u7C64\u7C56\u7C65\u7C6C\u7C75\u7C83\u7C90\u7CA4\u7CAD\u7CA2\u7CAB\u7CA1\u7CA8\u7CB3\u7CB2\u7CB1\u7CAE\u7CB9\u7CBD\u7CC0\u7CC5\u7CC2\u7CD8\u7CD2\u7CDC\u7CE2\u9B3B\u7CEF\u7CF2\u7CF4\u7CF6\u7CFA\u7D06"],
      ["e340", "\u7D02\u7D1C\u7D15\u7D0A\u7D45\u7D4B\u7D2E\u7D32\u7D3F\u7D35\u7D46\u7D73\u7D56\u7D4E\u7D72\u7D68\u7D6E\u7D4F\u7D63\u7D93\u7D89\u7D5B\u7D8F\u7D7D\u7D9B\u7DBA\u7DAE\u7DA3\u7DB5\u7DC7\u7DBD\u7DAB\u7E3D\u7DA2\u7DAF\u7DDC\u7DB8\u7D9F\u7DB0\u7DD8\u7DDD\u7DE4\u7DDE\u7DFB\u7DF2\u7DE1\u7E05\u7E0A\u7E23\u7E21\u7E12\u7E31\u7E1F\u7E09\u7E0B\u7E22\u7E46\u7E66\u7E3B\u7E35\u7E39\u7E43\u7E37"],
      ["e380", "\u7E32\u7E3A\u7E67\u7E5D\u7E56\u7E5E\u7E59\u7E5A\u7E79\u7E6A\u7E69\u7E7C\u7E7B\u7E83\u7DD5\u7E7D\u8FAE\u7E7F\u7E88\u7E89\u7E8C\u7E92\u7E90\u7E93\u7E94\u7E96\u7E8E\u7E9B\u7E9C\u7F38\u7F3A\u7F45\u7F4C\u7F4D\u7F4E\u7F50\u7F51\u7F55\u7F54\u7F58\u7F5F\u7F60\u7F68\u7F69\u7F67\u7F78\u7F82\u7F86\u7F83\u7F88\u7F87\u7F8C\u7F94\u7F9E\u7F9D\u7F9A\u7FA3\u7FAF\u7FB2\u7FB9\u7FAE\u7FB6\u7FB8\u8B71\u7FC5\u7FC6\u7FCA\u7FD5\u7FD4\u7FE1\u7FE6\u7FE9\u7FF3\u7FF9\u98DC\u8006\u8004\u800B\u8012\u8018\u8019\u801C\u8021\u8028\u803F\u803B\u804A\u8046\u8052\u8058\u805A\u805F\u8062\u8068\u8073\u8072\u8070\u8076\u8079\u807D\u807F\u8084\u8086\u8085\u809B\u8093\u809A\u80AD\u5190\u80AC\u80DB\u80E5\u80D9\u80DD\u80C4\u80DA\u80D6\u8109\u80EF\u80F1\u811B\u8129\u8123\u812F\u814B"],
      ["e440", "\u968B\u8146\u813E\u8153\u8151\u80FC\u8171\u816E\u8165\u8166\u8174\u8183\u8188\u818A\u8180\u8182\u81A0\u8195\u81A4\u81A3\u815F\u8193\u81A9\u81B0\u81B5\u81BE\u81B8\u81BD\u81C0\u81C2\u81BA\u81C9\u81CD\u81D1\u81D9\u81D8\u81C8\u81DA\u81DF\u81E0\u81E7\u81FA\u81FB\u81FE\u8201\u8202\u8205\u8207\u820A\u820D\u8210\u8216\u8229\u822B\u8238\u8233\u8240\u8259\u8258\u825D\u825A\u825F\u8264"],
      ["e480", "\u8262\u8268\u826A\u826B\u822E\u8271\u8277\u8278\u827E\u828D\u8292\u82AB\u829F\u82BB\u82AC\u82E1\u82E3\u82DF\u82D2\u82F4\u82F3\u82FA\u8393\u8303\u82FB\u82F9\u82DE\u8306\u82DC\u8309\u82D9\u8335\u8334\u8316\u8332\u8331\u8340\u8339\u8350\u8345\u832F\u832B\u8317\u8318\u8385\u839A\u83AA\u839F\u83A2\u8396\u8323\u838E\u8387\u838A\u837C\u83B5\u8373\u8375\u83A0\u8389\u83A8\u83F4\u8413\u83EB\u83CE\u83FD\u8403\u83D8\u840B\u83C1\u83F7\u8407\u83E0\u83F2\u840D\u8422\u8420\u83BD\u8438\u8506\u83FB\u846D\u842A\u843C\u855A\u8484\u8477\u846B\u84AD\u846E\u8482\u8469\u8446\u842C\u846F\u8479\u8435\u84CA\u8462\u84B9\u84BF\u849F\u84D9\u84CD\u84BB\u84DA\u84D0\u84C1\u84C6\u84D6\u84A1\u8521\u84FF\u84F4\u8517\u8518\u852C\u851F\u8515\u8514\u84FC\u8540\u8563\u8558\u8548"],
      ["e540", "\u8541\u8602\u854B\u8555\u8580\u85A4\u8588\u8591\u858A\u85A8\u856D\u8594\u859B\u85EA\u8587\u859C\u8577\u857E\u8590\u85C9\u85BA\u85CF\u85B9\u85D0\u85D5\u85DD\u85E5\u85DC\u85F9\u860A\u8613\u860B\u85FE\u85FA\u8606\u8622\u861A\u8630\u863F\u864D\u4E55\u8654\u865F\u8667\u8671\u8693\u86A3\u86A9\u86AA\u868B\u868C\u86B6\u86AF\u86C4\u86C6\u86B0\u86C9\u8823\u86AB\u86D4\u86DE\u86E9\u86EC"],
      ["e580", "\u86DF\u86DB\u86EF\u8712\u8706\u8708\u8700\u8703\u86FB\u8711\u8709\u870D\u86F9\u870A\u8734\u873F\u8737\u873B\u8725\u8729\u871A\u8760\u875F\u8778\u874C\u874E\u8774\u8757\u8768\u876E\u8759\u8753\u8763\u876A\u8805\u87A2\u879F\u8782\u87AF\u87CB\u87BD\u87C0\u87D0\u96D6\u87AB\u87C4\u87B3\u87C7\u87C6\u87BB\u87EF\u87F2\u87E0\u880F\u880D\u87FE\u87F6\u87F7\u880E\u87D2\u8811\u8816\u8815\u8822\u8821\u8831\u8836\u8839\u8827\u883B\u8844\u8842\u8852\u8859\u885E\u8862\u886B\u8881\u887E\u889E\u8875\u887D\u88B5\u8872\u8882\u8897\u8892\u88AE\u8899\u88A2\u888D\u88A4\u88B0\u88BF\u88B1\u88C3\u88C4\u88D4\u88D8\u88D9\u88DD\u88F9\u8902\u88FC\u88F4\u88E8\u88F2\u8904\u890C\u890A\u8913\u8943\u891E\u8925\u892A\u892B\u8941\u8944\u893B\u8936\u8938\u894C\u891D\u8960\u895E"],
      ["e640", "\u8966\u8964\u896D\u896A\u896F\u8974\u8977\u897E\u8983\u8988\u898A\u8993\u8998\u89A1\u89A9\u89A6\u89AC\u89AF\u89B2\u89BA\u89BD\u89BF\u89C0\u89DA\u89DC\u89DD\u89E7\u89F4\u89F8\u8A03\u8A16\u8A10\u8A0C\u8A1B\u8A1D\u8A25\u8A36\u8A41\u8A5B\u8A52\u8A46\u8A48\u8A7C\u8A6D\u8A6C\u8A62\u8A85\u8A82\u8A84\u8AA8\u8AA1\u8A91\u8AA5\u8AA6\u8A9A\u8AA3\u8AC4\u8ACD\u8AC2\u8ADA\u8AEB\u8AF3\u8AE7"],
      ["e680", "\u8AE4\u8AF1\u8B14\u8AE0\u8AE2\u8AF7\u8ADE\u8ADB\u8B0C\u8B07\u8B1A\u8AE1\u8B16\u8B10\u8B17\u8B20\u8B33\u97AB\u8B26\u8B2B\u8B3E\u8B28\u8B41\u8B4C\u8B4F\u8B4E\u8B49\u8B56\u8B5B\u8B5A\u8B6B\u8B5F\u8B6C\u8B6F\u8B74\u8B7D\u8B80\u8B8C\u8B8E\u8B92\u8B93\u8B96\u8B99\u8B9A\u8C3A\u8C41\u8C3F\u8C48\u8C4C\u8C4E\u8C50\u8C55\u8C62\u8C6C\u8C78\u8C7A\u8C82\u8C89\u8C85\u8C8A\u8C8D\u8C8E\u8C94\u8C7C\u8C98\u621D\u8CAD\u8CAA\u8CBD\u8CB2\u8CB3\u8CAE\u8CB6\u8CC8\u8CC1\u8CE4\u8CE3\u8CDA\u8CFD\u8CFA\u8CFB\u8D04\u8D05\u8D0A\u8D07\u8D0F\u8D0D\u8D10\u9F4E\u8D13\u8CCD\u8D14\u8D16\u8D67\u8D6D\u8D71\u8D73\u8D81\u8D99\u8DC2\u8DBE\u8DBA\u8DCF\u8DDA\u8DD6\u8DCC\u8DDB\u8DCB\u8DEA\u8DEB\u8DDF\u8DE3\u8DFC\u8E08\u8E09\u8DFF\u8E1D\u8E1E\u8E10\u8E1F\u8E42\u8E35\u8E30\u8E34\u8E4A"],
      ["e740", "\u8E47\u8E49\u8E4C\u8E50\u8E48\u8E59\u8E64\u8E60\u8E2A\u8E63\u8E55\u8E76\u8E72\u8E7C\u8E81\u8E87\u8E85\u8E84\u8E8B\u8E8A\u8E93\u8E91\u8E94\u8E99\u8EAA\u8EA1\u8EAC\u8EB0\u8EC6\u8EB1\u8EBE\u8EC5\u8EC8\u8ECB\u8EDB\u8EE3\u8EFC\u8EFB\u8EEB\u8EFE\u8F0A\u8F05\u8F15\u8F12\u8F19\u8F13\u8F1C\u8F1F\u8F1B\u8F0C\u8F26\u8F33\u8F3B\u8F39\u8F45\u8F42\u8F3E\u8F4C\u8F49\u8F46\u8F4E\u8F57\u8F5C"],
      ["e780", "\u8F62\u8F63\u8F64\u8F9C\u8F9F\u8FA3\u8FAD\u8FAF\u8FB7\u8FDA\u8FE5\u8FE2\u8FEA\u8FEF\u9087\u8FF4\u9005\u8FF9\u8FFA\u9011\u9015\u9021\u900D\u901E\u9016\u900B\u9027\u9036\u9035\u9039\u8FF8\u904F\u9050\u9051\u9052\u900E\u9049\u903E\u9056\u9058\u905E\u9068\u906F\u9076\u96A8\u9072\u9082\u907D\u9081\u9080\u908A\u9089\u908F\u90A8\u90AF\u90B1\u90B5\u90E2\u90E4\u6248\u90DB\u9102\u9112\u9119\u9132\u9130\u914A\u9156\u9158\u9163\u9165\u9169\u9173\u9172\u918B\u9189\u9182\u91A2\u91AB\u91AF\u91AA\u91B5\u91B4\u91BA\u91C0\u91C1\u91C9\u91CB\u91D0\u91D6\u91DF\u91E1\u91DB\u91FC\u91F5\u91F6\u921E\u91FF\u9214\u922C\u9215\u9211\u925E\u9257\u9245\u9249\u9264\u9248\u9295\u923F\u924B\u9250\u929C\u9296\u9293\u929B\u925A\u92CF\u92B9\u92B7\u92E9\u930F\u92FA\u9344\u932E"],
      ["e840", "\u9319\u9322\u931A\u9323\u933A\u9335\u933B\u935C\u9360\u937C\u936E\u9356\u93B0\u93AC\u93AD\u9394\u93B9\u93D6\u93D7\u93E8\u93E5\u93D8\u93C3\u93DD\u93D0\u93C8\u93E4\u941A\u9414\u9413\u9403\u9407\u9410\u9436\u942B\u9435\u9421\u943A\u9441\u9452\u9444\u945B\u9460\u9462\u945E\u946A\u9229\u9470\u9475\u9477\u947D\u945A\u947C\u947E\u9481\u947F\u9582\u9587\u958A\u9594\u9596\u9598\u9599"],
      ["e880", "\u95A0\u95A8\u95A7\u95AD\u95BC\u95BB\u95B9\u95BE\u95CA\u6FF6\u95C3\u95CD\u95CC\u95D5\u95D4\u95D6\u95DC\u95E1\u95E5\u95E2\u9621\u9628\u962E\u962F\u9642\u964C\u964F\u964B\u9677\u965C\u965E\u965D\u965F\u9666\u9672\u966C\u968D\u9698\u9695\u9697\u96AA\u96A7\u96B1\u96B2\u96B0\u96B4\u96B6\u96B8\u96B9\u96CE\u96CB\u96C9\u96CD\u894D\u96DC\u970D\u96D5\u96F9\u9704\u9706\u9708\u9713\u970E\u9711\u970F\u9716\u9719\u9724\u972A\u9730\u9739\u973D\u973E\u9744\u9746\u9748\u9742\u9749\u975C\u9760\u9764\u9766\u9768\u52D2\u976B\u9771\u9779\u9785\u977C\u9781\u977A\u9786\u978B\u978F\u9790\u979C\u97A8\u97A6\u97A3\u97B3\u97B4\u97C3\u97C6\u97C8\u97CB\u97DC\u97ED\u9F4F\u97F2\u7ADF\u97F6\u97F5\u980F\u980C\u9838\u9824\u9821\u9837\u983D\u9846\u984F\u984B\u986B\u986F\u9870"],
      ["e940", "\u9871\u9874\u9873\u98AA\u98AF\u98B1\u98B6\u98C4\u98C3\u98C6\u98E9\u98EB\u9903\u9909\u9912\u9914\u9918\u9921\u991D\u991E\u9924\u9920\u992C\u992E\u993D\u993E\u9942\u9949\u9945\u9950\u994B\u9951\u9952\u994C\u9955\u9997\u9998\u99A5\u99AD\u99AE\u99BC\u99DF\u99DB\u99DD\u99D8\u99D1\u99ED\u99EE\u99F1\u99F2\u99FB\u99F8\u9A01\u9A0F\u9A05\u99E2\u9A19\u9A2B\u9A37\u9A45\u9A42\u9A40\u9A43"],
      ["e980", "\u9A3E\u9A55\u9A4D\u9A5B\u9A57\u9A5F\u9A62\u9A65\u9A64\u9A69\u9A6B\u9A6A\u9AAD\u9AB0\u9ABC\u9AC0\u9ACF\u9AD1\u9AD3\u9AD4\u9ADE\u9ADF\u9AE2\u9AE3\u9AE6\u9AEF\u9AEB\u9AEE\u9AF4\u9AF1\u9AF7\u9AFB\u9B06\u9B18\u9B1A\u9B1F\u9B22\u9B23\u9B25\u9B27\u9B28\u9B29\u9B2A\u9B2E\u9B2F\u9B32\u9B44\u9B43\u9B4F\u9B4D\u9B4E\u9B51\u9B58\u9B74\u9B93\u9B83\u9B91\u9B96\u9B97\u9B9F\u9BA0\u9BA8\u9BB4\u9BC0\u9BCA\u9BB9\u9BC6\u9BCF\u9BD1\u9BD2\u9BE3\u9BE2\u9BE4\u9BD4\u9BE1\u9C3A\u9BF2\u9BF1\u9BF0\u9C15\u9C14\u9C09\u9C13\u9C0C\u9C06\u9C08\u9C12\u9C0A\u9C04\u9C2E\u9C1B\u9C25\u9C24\u9C21\u9C30\u9C47\u9C32\u9C46\u9C3E\u9C5A\u9C60\u9C67\u9C76\u9C78\u9CE7\u9CEC\u9CF0\u9D09\u9D08\u9CEB\u9D03\u9D06\u9D2A\u9D26\u9DAF\u9D23\u9D1F\u9D44\u9D15\u9D12\u9D41\u9D3F\u9D3E\u9D46\u9D48"],
      ["ea40", "\u9D5D\u9D5E\u9D64\u9D51\u9D50\u9D59\u9D72\u9D89\u9D87\u9DAB\u9D6F\u9D7A\u9D9A\u9DA4\u9DA9\u9DB2\u9DC4\u9DC1\u9DBB\u9DB8\u9DBA\u9DC6\u9DCF\u9DC2\u9DD9\u9DD3\u9DF8\u9DE6\u9DED\u9DEF\u9DFD\u9E1A\u9E1B\u9E1E\u9E75\u9E79\u9E7D\u9E81\u9E88\u9E8B\u9E8C\u9E92\u9E95\u9E91\u9E9D\u9EA5\u9EA9\u9EB8\u9EAA\u9EAD\u9761\u9ECC\u9ECE\u9ECF\u9ED0\u9ED4\u9EDC\u9EDE\u9EDD\u9EE0\u9EE5\u9EE8\u9EEF"],
      ["ea80", "\u9EF4\u9EF6\u9EF7\u9EF9\u9EFB\u9EFC\u9EFD\u9F07\u9F08\u76B7\u9F15\u9F21\u9F2C\u9F3E\u9F4A\u9F52\u9F54\u9F63\u9F5F\u9F60\u9F61\u9F66\u9F67\u9F6C\u9F6A\u9F77\u9F72\u9F76\u9F95\u9F9C\u9FA0\u582F\u69C7\u9059\u7464\u51DC\u7199"],
      ["ed40", "\u7E8A\u891C\u9348\u9288\u84DC\u4FC9\u70BB\u6631\u68C8\u92F9\u66FB\u5F45\u4E28\u4EE1\u4EFC\u4F00\u4F03\u4F39\u4F56\u4F92\u4F8A\u4F9A\u4F94\u4FCD\u5040\u5022\u4FFF\u501E\u5046\u5070\u5042\u5094\u50F4\u50D8\u514A\u5164\u519D\u51BE\u51EC\u5215\u529C\u52A6\u52C0\u52DB\u5300\u5307\u5324\u5372\u5393\u53B2\u53DD\uFA0E\u549C\u548A\u54A9\u54FF\u5586\u5759\u5765\u57AC\u57C8\u57C7\uFA0F"],
      ["ed80", "\uFA10\u589E\u58B2\u590B\u5953\u595B\u595D\u5963\u59A4\u59BA\u5B56\u5BC0\u752F\u5BD8\u5BEC\u5C1E\u5CA6\u5CBA\u5CF5\u5D27\u5D53\uFA11\u5D42\u5D6D\u5DB8\u5DB9\u5DD0\u5F21\u5F34\u5F67\u5FB7\u5FDE\u605D\u6085\u608A\u60DE\u60D5\u6120\u60F2\u6111\u6137\u6130\u6198\u6213\u62A6\u63F5\u6460\u649D\u64CE\u654E\u6600\u6615\u663B\u6609\u662E\u661E\u6624\u6665\u6657\u6659\uFA12\u6673\u6699\u66A0\u66B2\u66BF\u66FA\u670E\uF929\u6766\u67BB\u6852\u67C0\u6801\u6844\u68CF\uFA13\u6968\uFA14\u6998\u69E2\u6A30\u6A6B\u6A46\u6A73\u6A7E\u6AE2\u6AE4\u6BD6\u6C3F\u6C5C\u6C86\u6C6F\u6CDA\u6D04\u6D87\u6D6F\u6D96\u6DAC\u6DCF\u6DF8\u6DF2\u6DFC\u6E39\u6E5C\u6E27\u6E3C\u6EBF\u6F88\u6FB5\u6FF5\u7005\u7007\u7028\u7085\u70AB\u710F\u7104\u715C\u7146\u7147\uFA15\u71C1\u71FE\u72B1"],
      ["ee40", "\u72BE\u7324\uFA16\u7377\u73BD\u73C9\u73D6\u73E3\u73D2\u7407\u73F5\u7426\u742A\u7429\u742E\u7462\u7489\u749F\u7501\u756F\u7682\u769C\u769E\u769B\u76A6\uFA17\u7746\u52AF\u7821\u784E\u7864\u787A\u7930\uFA18\uFA19\uFA1A\u7994\uFA1B\u799B\u7AD1\u7AE7\uFA1C\u7AEB\u7B9E\uFA1D\u7D48\u7D5C\u7DB7\u7DA0\u7DD6\u7E52\u7F47\u7FA1\uFA1E\u8301\u8362\u837F\u83C7\u83F6\u8448\u84B4\u8553\u8559"],
      ["ee80", "\u856B\uFA1F\u85B0\uFA20\uFA21\u8807\u88F5\u8A12\u8A37\u8A79\u8AA7\u8ABE\u8ADF\uFA22\u8AF6\u8B53\u8B7F\u8CF0\u8CF4\u8D12\u8D76\uFA23\u8ECF\uFA24\uFA25\u9067\u90DE\uFA26\u9115\u9127\u91DA\u91D7\u91DE\u91ED\u91EE\u91E4\u91E5\u9206\u9210\u920A\u923A\u9240\u923C\u924E\u9259\u9251\u9239\u9267\u92A7\u9277\u9278\u92E7\u92D7\u92D9\u92D0\uFA27\u92D5\u92E0\u92D3\u9325\u9321\u92FB\uFA28\u931E\u92FF\u931D\u9302\u9370\u9357\u93A4\u93C6\u93DE\u93F8\u9431\u9445\u9448\u9592\uF9DC\uFA29\u969D\u96AF\u9733\u973B\u9743\u974D\u974F\u9751\u9755\u9857\u9865\uFA2A\uFA2B\u9927\uFA2C\u999E\u9A4E\u9AD9\u9ADC\u9B75\u9B72\u9B8F\u9BB1\u9BBB\u9C00\u9D70\u9D6B\uFA2D\u9E19\u9ED1"],
      ["eeef", "\u2170", 9, "\uFFE2\uFFE4\uFF07\uFF02"],
      ["f040", "\uE000", 62],
      ["f080", "\uE03F", 124],
      ["f140", "\uE0BC", 62],
      ["f180", "\uE0FB", 124],
      ["f240", "\uE178", 62],
      ["f280", "\uE1B7", 124],
      ["f340", "\uE234", 62],
      ["f380", "\uE273", 124],
      ["f440", "\uE2F0", 62],
      ["f480", "\uE32F", 124],
      ["f540", "\uE3AC", 62],
      ["f580", "\uE3EB", 124],
      ["f640", "\uE468", 62],
      ["f680", "\uE4A7", 124],
      ["f740", "\uE524", 62],
      ["f780", "\uE563", 124],
      ["f840", "\uE5E0", 62],
      ["f880", "\uE61F", 124],
      ["f940", "\uE69C"],
      ["fa40", "\u2170", 9, "\u2160", 9, "\uFFE2\uFFE4\uFF07\uFF02\u3231\u2116\u2121\u2235\u7E8A\u891C\u9348\u9288\u84DC\u4FC9\u70BB\u6631\u68C8\u92F9\u66FB\u5F45\u4E28\u4EE1\u4EFC\u4F00\u4F03\u4F39\u4F56\u4F92\u4F8A\u4F9A\u4F94\u4FCD\u5040\u5022\u4FFF\u501E\u5046\u5070\u5042\u5094\u50F4\u50D8\u514A"],
      ["fa80", "\u5164\u519D\u51BE\u51EC\u5215\u529C\u52A6\u52C0\u52DB\u5300\u5307\u5324\u5372\u5393\u53B2\u53DD\uFA0E\u549C\u548A\u54A9\u54FF\u5586\u5759\u5765\u57AC\u57C8\u57C7\uFA0F\uFA10\u589E\u58B2\u590B\u5953\u595B\u595D\u5963\u59A4\u59BA\u5B56\u5BC0\u752F\u5BD8\u5BEC\u5C1E\u5CA6\u5CBA\u5CF5\u5D27\u5D53\uFA11\u5D42\u5D6D\u5DB8\u5DB9\u5DD0\u5F21\u5F34\u5F67\u5FB7\u5FDE\u605D\u6085\u608A\u60DE\u60D5\u6120\u60F2\u6111\u6137\u6130\u6198\u6213\u62A6\u63F5\u6460\u649D\u64CE\u654E\u6600\u6615\u663B\u6609\u662E\u661E\u6624\u6665\u6657\u6659\uFA12\u6673\u6699\u66A0\u66B2\u66BF\u66FA\u670E\uF929\u6766\u67BB\u6852\u67C0\u6801\u6844\u68CF\uFA13\u6968\uFA14\u6998\u69E2\u6A30\u6A6B\u6A46\u6A73\u6A7E\u6AE2\u6AE4\u6BD6\u6C3F\u6C5C\u6C86\u6C6F\u6CDA\u6D04\u6D87\u6D6F"],
      ["fb40", "\u6D96\u6DAC\u6DCF\u6DF8\u6DF2\u6DFC\u6E39\u6E5C\u6E27\u6E3C\u6EBF\u6F88\u6FB5\u6FF5\u7005\u7007\u7028\u7085\u70AB\u710F\u7104\u715C\u7146\u7147\uFA15\u71C1\u71FE\u72B1\u72BE\u7324\uFA16\u7377\u73BD\u73C9\u73D6\u73E3\u73D2\u7407\u73F5\u7426\u742A\u7429\u742E\u7462\u7489\u749F\u7501\u756F\u7682\u769C\u769E\u769B\u76A6\uFA17\u7746\u52AF\u7821\u784E\u7864\u787A\u7930\uFA18\uFA19"],
      ["fb80", "\uFA1A\u7994\uFA1B\u799B\u7AD1\u7AE7\uFA1C\u7AEB\u7B9E\uFA1D\u7D48\u7D5C\u7DB7\u7DA0\u7DD6\u7E52\u7F47\u7FA1\uFA1E\u8301\u8362\u837F\u83C7\u83F6\u8448\u84B4\u8553\u8559\u856B\uFA1F\u85B0\uFA20\uFA21\u8807\u88F5\u8A12\u8A37\u8A79\u8AA7\u8ABE\u8ADF\uFA22\u8AF6\u8B53\u8B7F\u8CF0\u8CF4\u8D12\u8D76\uFA23\u8ECF\uFA24\uFA25\u9067\u90DE\uFA26\u9115\u9127\u91DA\u91D7\u91DE\u91ED\u91EE\u91E4\u91E5\u9206\u9210\u920A\u923A\u9240\u923C\u924E\u9259\u9251\u9239\u9267\u92A7\u9277\u9278\u92E7\u92D7\u92D9\u92D0\uFA27\u92D5\u92E0\u92D3\u9325\u9321\u92FB\uFA28\u931E\u92FF\u931D\u9302\u9370\u9357\u93A4\u93C6\u93DE\u93F8\u9431\u9445\u9448\u9592\uF9DC\uFA29\u969D\u96AF\u9733\u973B\u9743\u974D\u974F\u9751\u9755\u9857\u9865\uFA2A\uFA2B\u9927\uFA2C\u999E\u9A4E\u9AD9"],
      ["fc40", "\u9ADC\u9B75\u9B72\u9B8F\u9BB1\u9BBB\u9C00\u9D70\u9D6B\uFA2D\u9E19\u9ED1"]
    ];
  }
});

// ../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/tables/eucjp.json
var require_eucjp = __commonJS({
  "../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/tables/eucjp.json"(exports, module) {
    module.exports = [
      ["0", "\0", 127],
      ["8ea1", "\uFF61", 62],
      ["a1a1", "\u3000\u3001\u3002\uFF0C\uFF0E\u30FB\uFF1A\uFF1B\uFF1F\uFF01\u309B\u309C\xB4\uFF40\xA8\uFF3E\uFFE3\uFF3F\u30FD\u30FE\u309D\u309E\u3003\u4EDD\u3005\u3006\u3007\u30FC\u2015\u2010\uFF0F\uFF3C\uFF5E\u2225\uFF5C\u2026\u2025\u2018\u2019\u201C\u201D\uFF08\uFF09\u3014\u3015\uFF3B\uFF3D\uFF5B\uFF5D\u3008", 9, "\uFF0B\uFF0D\xB1\xD7\xF7\uFF1D\u2260\uFF1C\uFF1E\u2266\u2267\u221E\u2234\u2642\u2640\xB0\u2032\u2033\u2103\uFFE5\uFF04\uFFE0\uFFE1\uFF05\uFF03\uFF06\uFF0A\uFF20\xA7\u2606\u2605\u25CB\u25CF\u25CE\u25C7"],
      ["a2a1", "\u25C6\u25A1\u25A0\u25B3\u25B2\u25BD\u25BC\u203B\u3012\u2192\u2190\u2191\u2193\u3013"],
      ["a2ba", "\u2208\u220B\u2286\u2287\u2282\u2283\u222A\u2229"],
      ["a2ca", "\u2227\u2228\uFFE2\u21D2\u21D4\u2200\u2203"],
      ["a2dc", "\u2220\u22A5\u2312\u2202\u2207\u2261\u2252\u226A\u226B\u221A\u223D\u221D\u2235\u222B\u222C"],
      ["a2f2", "\u212B\u2030\u266F\u266D\u266A\u2020\u2021\xB6"],
      ["a2fe", "\u25EF"],
      ["a3b0", "\uFF10", 9],
      ["a3c1", "\uFF21", 25],
      ["a3e1", "\uFF41", 25],
      ["a4a1", "\u3041", 82],
      ["a5a1", "\u30A1", 85],
      ["a6a1", "\u0391", 16, "\u03A3", 6],
      ["a6c1", "\u03B1", 16, "\u03C3", 6],
      ["a7a1", "\u0410", 5, "\u0401\u0416", 25],
      ["a7d1", "\u0430", 5, "\u0451\u0436", 25],
      ["a8a1", "\u2500\u2502\u250C\u2510\u2518\u2514\u251C\u252C\u2524\u2534\u253C\u2501\u2503\u250F\u2513\u251B\u2517\u2523\u2533\u252B\u253B\u254B\u2520\u252F\u2528\u2537\u253F\u251D\u2530\u2525\u2538\u2542"],
      ["ada1", "\u2460", 19, "\u2160", 9],
      ["adc0", "\u3349\u3314\u3322\u334D\u3318\u3327\u3303\u3336\u3351\u3357\u330D\u3326\u3323\u332B\u334A\u333B\u339C\u339D\u339E\u338E\u338F\u33C4\u33A1"],
      ["addf", "\u337B\u301D\u301F\u2116\u33CD\u2121\u32A4", 4, "\u3231\u3232\u3239\u337E\u337D\u337C\u2252\u2261\u222B\u222E\u2211\u221A\u22A5\u2220\u221F\u22BF\u2235\u2229\u222A"],
      ["b0a1", "\u4E9C\u5516\u5A03\u963F\u54C0\u611B\u6328\u59F6\u9022\u8475\u831C\u7A50\u60AA\u63E1\u6E25\u65ED\u8466\u82A6\u9BF5\u6893\u5727\u65A1\u6271\u5B9B\u59D0\u867B\u98F4\u7D62\u7DBE\u9B8E\u6216\u7C9F\u88B7\u5B89\u5EB5\u6309\u6697\u6848\u95C7\u978D\u674F\u4EE5\u4F0A\u4F4D\u4F9D\u5049\u56F2\u5937\u59D4\u5A01\u5C09\u60DF\u610F\u6170\u6613\u6905\u70BA\u754F\u7570\u79FB\u7DAD\u7DEF\u80C3\u840E\u8863\u8B02\u9055\u907A\u533B\u4E95\u4EA5\u57DF\u80B2\u90C1\u78EF\u4E00\u58F1\u6EA2\u9038\u7A32\u8328\u828B\u9C2F\u5141\u5370\u54BD\u54E1\u56E0\u59FB\u5F15\u98F2\u6DEB\u80E4\u852D"],
      ["b1a1", "\u9662\u9670\u96A0\u97FB\u540B\u53F3\u5B87\u70CF\u7FBD\u8FC2\u96E8\u536F\u9D5C\u7ABA\u4E11\u7893\u81FC\u6E26\u5618\u5504\u6B1D\u851A\u9C3B\u59E5\u53A9\u6D66\u74DC\u958F\u5642\u4E91\u904B\u96F2\u834F\u990C\u53E1\u55B6\u5B30\u5F71\u6620\u66F3\u6804\u6C38\u6CF3\u6D29\u745B\u76C8\u7A4E\u9834\u82F1\u885B\u8A60\u92ED\u6DB2\u75AB\u76CA\u99C5\u60A6\u8B01\u8D8A\u95B2\u698E\u53AD\u5186\u5712\u5830\u5944\u5BB4\u5EF6\u6028\u63A9\u63F4\u6CBF\u6F14\u708E\u7114\u7159\u71D5\u733F\u7E01\u8276\u82D1\u8597\u9060\u925B\u9D1B\u5869\u65BC\u6C5A\u7525\u51F9\u592E\u5965\u5F80\u5FDC"],
      ["b2a1", "\u62BC\u65FA\u6A2A\u6B27\u6BB4\u738B\u7FC1\u8956\u9D2C\u9D0E\u9EC4\u5CA1\u6C96\u837B\u5104\u5C4B\u61B6\u81C6\u6876\u7261\u4E59\u4FFA\u5378\u6069\u6E29\u7A4F\u97F3\u4E0B\u5316\u4EEE\u4F55\u4F3D\u4FA1\u4F73\u52A0\u53EF\u5609\u590F\u5AC1\u5BB6\u5BE1\u79D1\u6687\u679C\u67B6\u6B4C\u6CB3\u706B\u73C2\u798D\u79BE\u7A3C\u7B87\u82B1\u82DB\u8304\u8377\u83EF\u83D3\u8766\u8AB2\u5629\u8CA8\u8FE6\u904E\u971E\u868A\u4FC4\u5CE8\u6211\u7259\u753B\u81E5\u82BD\u86FE\u8CC0\u96C5\u9913\u99D5\u4ECB\u4F1A\u89E3\u56DE\u584A\u58CA\u5EFB\u5FEB\u602A\u6094\u6062\u61D0\u6212\u62D0\u6539"],
      ["b3a1", "\u9B41\u6666\u68B0\u6D77\u7070\u754C\u7686\u7D75\u82A5\u87F9\u958B\u968E\u8C9D\u51F1\u52BE\u5916\u54B3\u5BB3\u5D16\u6168\u6982\u6DAF\u788D\u84CB\u8857\u8A72\u93A7\u9AB8\u6D6C\u99A8\u86D9\u57A3\u67FF\u86CE\u920E\u5283\u5687\u5404\u5ED3\u62E1\u64B9\u683C\u6838\u6BBB\u7372\u78BA\u7A6B\u899A\u89D2\u8D6B\u8F03\u90ED\u95A3\u9694\u9769\u5B66\u5CB3\u697D\u984D\u984E\u639B\u7B20\u6A2B\u6A7F\u68B6\u9C0D\u6F5F\u5272\u559D\u6070\u62EC\u6D3B\u6E07\u6ED1\u845B\u8910\u8F44\u4E14\u9C39\u53F6\u691B\u6A3A\u9784\u682A\u515C\u7AC3\u84B2\u91DC\u938C\u565B\u9D28\u6822\u8305\u8431"],
      ["b4a1", "\u7CA5\u5208\u82C5\u74E6\u4E7E\u4F83\u51A0\u5BD2\u520A\u52D8\u52E7\u5DFB\u559A\u582A\u59E6\u5B8C\u5B98\u5BDB\u5E72\u5E79\u60A3\u611F\u6163\u61BE\u63DB\u6562\u67D1\u6853\u68FA\u6B3E\u6B53\u6C57\u6F22\u6F97\u6F45\u74B0\u7518\u76E3\u770B\u7AFF\u7BA1\u7C21\u7DE9\u7F36\u7FF0\u809D\u8266\u839E\u89B3\u8ACC\u8CAB\u9084\u9451\u9593\u9591\u95A2\u9665\u97D3\u9928\u8218\u4E38\u542B\u5CB8\u5DCC\u73A9\u764C\u773C\u5CA9\u7FEB\u8D0B\u96C1\u9811\u9854\u9858\u4F01\u4F0E\u5371\u559C\u5668\u57FA\u5947\u5B09\u5BC4\u5C90\u5E0C\u5E7E\u5FCC\u63EE\u673A\u65D7\u65E2\u671F\u68CB\u68C4"],
      ["b5a1", "\u6A5F\u5E30\u6BC5\u6C17\u6C7D\u757F\u7948\u5B63\u7A00\u7D00\u5FBD\u898F\u8A18\u8CB4\u8D77\u8ECC\u8F1D\u98E2\u9A0E\u9B3C\u4E80\u507D\u5100\u5993\u5B9C\u622F\u6280\u64EC\u6B3A\u72A0\u7591\u7947\u7FA9\u87FB\u8ABC\u8B70\u63AC\u83CA\u97A0\u5409\u5403\u55AB\u6854\u6A58\u8A70\u7827\u6775\u9ECD\u5374\u5BA2\u811A\u8650\u9006\u4E18\u4E45\u4EC7\u4F11\u53CA\u5438\u5BAE\u5F13\u6025\u6551\u673D\u6C42\u6C72\u6CE3\u7078\u7403\u7A76\u7AAE\u7B08\u7D1A\u7CFE\u7D66\u65E7\u725B\u53BB\u5C45\u5DE8\u62D2\u62E0\u6319\u6E20\u865A\u8A31\u8DDD\u92F8\u6F01\u79A6\u9B5A\u4EA8\u4EAB\u4EAC"],
      ["b6a1", "\u4F9B\u4FA0\u50D1\u5147\u7AF6\u5171\u51F6\u5354\u5321\u537F\u53EB\u55AC\u5883\u5CE1\u5F37\u5F4A\u602F\u6050\u606D\u631F\u6559\u6A4B\u6CC1\u72C2\u72ED\u77EF\u80F8\u8105\u8208\u854E\u90F7\u93E1\u97FF\u9957\u9A5A\u4EF0\u51DD\u5C2D\u6681\u696D\u5C40\u66F2\u6975\u7389\u6850\u7C81\u50C5\u52E4\u5747\u5DFE\u9326\u65A4\u6B23\u6B3D\u7434\u7981\u79BD\u7B4B\u7DCA\u82B9\u83CC\u887F\u895F\u8B39\u8FD1\u91D1\u541F\u9280\u4E5D\u5036\u53E5\u533A\u72D7\u7396\u77E9\u82E6\u8EAF\u99C6\u99C8\u99D2\u5177\u611A\u865E\u55B0\u7A7A\u5076\u5BD3\u9047\u9685\u4E32\u6ADB\u91E7\u5C51\u5C48"],
      ["b7a1", "\u6398\u7A9F\u6C93\u9774\u8F61\u7AAA\u718A\u9688\u7C82\u6817\u7E70\u6851\u936C\u52F2\u541B\u85AB\u8A13\u7FA4\u8ECD\u90E1\u5366\u8888\u7941\u4FC2\u50BE\u5211\u5144\u5553\u572D\u73EA\u578B\u5951\u5F62\u5F84\u6075\u6176\u6167\u61A9\u63B2\u643A\u656C\u666F\u6842\u6E13\u7566\u7A3D\u7CFB\u7D4C\u7D99\u7E4B\u7F6B\u830E\u834A\u86CD\u8A08\u8A63\u8B66\u8EFD\u981A\u9D8F\u82B8\u8FCE\u9BE8\u5287\u621F\u6483\u6FC0\u9699\u6841\u5091\u6B20\u6C7A\u6F54\u7A74\u7D50\u8840\u8A23\u6708\u4EF6\u5039\u5026\u5065\u517C\u5238\u5263\u55A7\u570F\u5805\u5ACC\u5EFA\u61B2\u61F8\u62F3\u6372"],
      ["b8a1", "\u691C\u6A29\u727D\u72AC\u732E\u7814\u786F\u7D79\u770C\u80A9\u898B\u8B19\u8CE2\u8ED2\u9063\u9375\u967A\u9855\u9A13\u9E78\u5143\u539F\u53B3\u5E7B\u5F26\u6E1B\u6E90\u7384\u73FE\u7D43\u8237\u8A00\u8AFA\u9650\u4E4E\u500B\u53E4\u547C\u56FA\u59D1\u5B64\u5DF1\u5EAB\u5F27\u6238\u6545\u67AF\u6E56\u72D0\u7CCA\u88B4\u80A1\u80E1\u83F0\u864E\u8A87\u8DE8\u9237\u96C7\u9867\u9F13\u4E94\u4E92\u4F0D\u5348\u5449\u543E\u5A2F\u5F8C\u5FA1\u609F\u68A7\u6A8E\u745A\u7881\u8A9E\u8AA4\u8B77\u9190\u4E5E\u9BC9\u4EA4\u4F7C\u4FAF\u5019\u5016\u5149\u516C\u529F\u52B9\u52FE\u539A\u53E3\u5411"],
      ["b9a1", "\u540E\u5589\u5751\u57A2\u597D\u5B54\u5B5D\u5B8F\u5DE5\u5DE7\u5DF7\u5E78\u5E83\u5E9A\u5EB7\u5F18\u6052\u614C\u6297\u62D8\u63A7\u653B\u6602\u6643\u66F4\u676D\u6821\u6897\u69CB\u6C5F\u6D2A\u6D69\u6E2F\u6E9D\u7532\u7687\u786C\u7A3F\u7CE0\u7D05\u7D18\u7D5E\u7DB1\u8015\u8003\u80AF\u80B1\u8154\u818F\u822A\u8352\u884C\u8861\u8B1B\u8CA2\u8CFC\u90CA\u9175\u9271\u783F\u92FC\u95A4\u964D\u9805\u9999\u9AD8\u9D3B\u525B\u52AB\u53F7\u5408\u58D5\u62F7\u6FE0\u8C6A\u8F5F\u9EB9\u514B\u523B\u544A\u56FD\u7A40\u9177\u9D60\u9ED2\u7344\u6F09\u8170\u7511\u5FFD\u60DA\u9AA8\u72DB\u8FBC"],
      ["baa1", "\u6B64\u9803\u4ECA\u56F0\u5764\u58BE\u5A5A\u6068\u61C7\u660F\u6606\u6839\u68B1\u6DF7\u75D5\u7D3A\u826E\u9B42\u4E9B\u4F50\u53C9\u5506\u5D6F\u5DE6\u5DEE\u67FB\u6C99\u7473\u7802\u8A50\u9396\u88DF\u5750\u5EA7\u632B\u50B5\u50AC\u518D\u6700\u54C9\u585E\u59BB\u5BB0\u5F69\u624D\u63A1\u683D\u6B73\u6E08\u707D\u91C7\u7280\u7815\u7826\u796D\u658E\u7D30\u83DC\u88C1\u8F09\u969B\u5264\u5728\u6750\u7F6A\u8CA1\u51B4\u5742\u962A\u583A\u698A\u80B4\u54B2\u5D0E\u57FC\u7895\u9DFA\u4F5C\u524A\u548B\u643E\u6628\u6714\u67F5\u7A84\u7B56\u7D22\u932F\u685C\u9BAD\u7B39\u5319\u518A\u5237"],
      ["bba1", "\u5BDF\u62F6\u64AE\u64E6\u672D\u6BBA\u85A9\u96D1\u7690\u9BD6\u634C\u9306\u9BAB\u76BF\u6652\u4E09\u5098\u53C2\u5C71\u60E8\u6492\u6563\u685F\u71E6\u73CA\u7523\u7B97\u7E82\u8695\u8B83\u8CDB\u9178\u9910\u65AC\u66AB\u6B8B\u4ED5\u4ED4\u4F3A\u4F7F\u523A\u53F8\u53F2\u55E3\u56DB\u58EB\u59CB\u59C9\u59FF\u5B50\u5C4D\u5E02\u5E2B\u5FD7\u601D\u6307\u652F\u5B5C\u65AF\u65BD\u65E8\u679D\u6B62\u6B7B\u6C0F\u7345\u7949\u79C1\u7CF8\u7D19\u7D2B\u80A2\u8102\u81F3\u8996\u8A5E\u8A69\u8A66\u8A8C\u8AEE\u8CC7\u8CDC\u96CC\u98FC\u6B6F\u4E8B\u4F3C\u4F8D\u5150\u5B57\u5BFA\u6148\u6301\u6642"],
      ["bca1", "\u6B21\u6ECB\u6CBB\u723E\u74BD\u75D4\u78C1\u793A\u800C\u8033\u81EA\u8494\u8F9E\u6C50\u9E7F\u5F0F\u8B58\u9D2B\u7AFA\u8EF8\u5B8D\u96EB\u4E03\u53F1\u57F7\u5931\u5AC9\u5BA4\u6089\u6E7F\u6F06\u75BE\u8CEA\u5B9F\u8500\u7BE0\u5072\u67F4\u829D\u5C61\u854A\u7E1E\u820E\u5199\u5C04\u6368\u8D66\u659C\u716E\u793E\u7D17\u8005\u8B1D\u8ECA\u906E\u86C7\u90AA\u501F\u52FA\u5C3A\u6753\u707C\u7235\u914C\u91C8\u932B\u82E5\u5BC2\u5F31\u60F9\u4E3B\u53D6\u5B88\u624B\u6731\u6B8A\u72E9\u73E0\u7A2E\u816B\u8DA3\u9152\u9996\u5112\u53D7\u546A\u5BFF\u6388\u6A39\u7DAC\u9700\u56DA\u53CE\u5468"],
      ["bda1", "\u5B97\u5C31\u5DDE\u4FEE\u6101\u62FE\u6D32\u79C0\u79CB\u7D42\u7E4D\u7FD2\u81ED\u821F\u8490\u8846\u8972\u8B90\u8E74\u8F2F\u9031\u914B\u916C\u96C6\u919C\u4EC0\u4F4F\u5145\u5341\u5F93\u620E\u67D4\u6C41\u6E0B\u7363\u7E26\u91CD\u9283\u53D4\u5919\u5BBF\u6DD1\u795D\u7E2E\u7C9B\u587E\u719F\u51FA\u8853\u8FF0\u4FCA\u5CFB\u6625\u77AC\u7AE3\u821C\u99FF\u51C6\u5FAA\u65EC\u696F\u6B89\u6DF3\u6E96\u6F64\u76FE\u7D14\u5DE1\u9075\u9187\u9806\u51E6\u521D\u6240\u6691\u66D9\u6E1A\u5EB6\u7DD2\u7F72\u66F8\u85AF\u85F7\u8AF8\u52A9\u53D9\u5973\u5E8F\u5F90\u6055\u92E4\u9664\u50B7\u511F"],
      ["bea1", "\u52DD\u5320\u5347\u53EC\u54E8\u5546\u5531\u5617\u5968\u59BE\u5A3C\u5BB5\u5C06\u5C0F\u5C11\u5C1A\u5E84\u5E8A\u5EE0\u5F70\u627F\u6284\u62DB\u638C\u6377\u6607\u660C\u662D\u6676\u677E\u68A2\u6A1F\u6A35\u6CBC\u6D88\u6E09\u6E58\u713C\u7126\u7167\u75C7\u7701\u785D\u7901\u7965\u79F0\u7AE0\u7B11\u7CA7\u7D39\u8096\u83D6\u848B\u8549\u885D\u88F3\u8A1F\u8A3C\u8A54\u8A73\u8C61\u8CDE\u91A4\u9266\u937E\u9418\u969C\u9798\u4E0A\u4E08\u4E1E\u4E57\u5197\u5270\u57CE\u5834\u58CC\u5B22\u5E38\u60C5\u64FE\u6761\u6756\u6D44\u72B6\u7573\u7A63\u84B8\u8B72\u91B8\u9320\u5631\u57F4\u98FE"],
      ["bfa1", "\u62ED\u690D\u6B96\u71ED\u7E54\u8077\u8272\u89E6\u98DF\u8755\u8FB1\u5C3B\u4F38\u4FE1\u4FB5\u5507\u5A20\u5BDD\u5BE9\u5FC3\u614E\u632F\u65B0\u664B\u68EE\u699B\u6D78\u6DF1\u7533\u75B9\u771F\u795E\u79E6\u7D33\u81E3\u82AF\u85AA\u89AA\u8A3A\u8EAB\u8F9B\u9032\u91DD\u9707\u4EBA\u4EC1\u5203\u5875\u58EC\u5C0B\u751A\u5C3D\u814E\u8A0A\u8FC5\u9663\u976D\u7B25\u8ACF\u9808\u9162\u56F3\u53A8\u9017\u5439\u5782\u5E25\u63A8\u6C34\u708A\u7761\u7C8B\u7FE0\u8870\u9042\u9154\u9310\u9318\u968F\u745E\u9AC4\u5D07\u5D69\u6570\u67A2\u8DA8\u96DB\u636E\u6749\u6919\u83C5\u9817\u96C0\u88FE"],
      ["c0a1", "\u6F84\u647A\u5BF8\u4E16\u702C\u755D\u662F\u51C4\u5236\u52E2\u59D3\u5F81\u6027\u6210\u653F\u6574\u661F\u6674\u68F2\u6816\u6B63\u6E05\u7272\u751F\u76DB\u7CBE\u8056\u58F0\u88FD\u897F\u8AA0\u8A93\u8ACB\u901D\u9192\u9752\u9759\u6589\u7A0E\u8106\u96BB\u5E2D\u60DC\u621A\u65A5\u6614\u6790\u77F3\u7A4D\u7C4D\u7E3E\u810A\u8CAC\u8D64\u8DE1\u8E5F\u78A9\u5207\u62D9\u63A5\u6442\u6298\u8A2D\u7A83\u7BC0\u8AAC\u96EA\u7D76\u820C\u8749\u4ED9\u5148\u5343\u5360\u5BA3\u5C02\u5C16\u5DDD\u6226\u6247\u64B0\u6813\u6834\u6CC9\u6D45\u6D17\u67D3\u6F5C\u714E\u717D\u65CB\u7A7F\u7BAD\u7DDA"],
      ["c1a1", "\u7E4A\u7FA8\u817A\u821B\u8239\u85A6\u8A6E\u8CCE\u8DF5\u9078\u9077\u92AD\u9291\u9583\u9BAE\u524D\u5584\u6F38\u7136\u5168\u7985\u7E55\u81B3\u7CCE\u564C\u5851\u5CA8\u63AA\u66FE\u66FD\u695A\u72D9\u758F\u758E\u790E\u7956\u79DF\u7C97\u7D20\u7D44\u8607\u8A34\u963B\u9061\u9F20\u50E7\u5275\u53CC\u53E2\u5009\u55AA\u58EE\u594F\u723D\u5B8B\u5C64\u531D\u60E3\u60F3\u635C\u6383\u633F\u63BB\u64CD\u65E9\u66F9\u5DE3\u69CD\u69FD\u6F15\u71E5\u4E89\u75E9\u76F8\u7A93\u7CDF\u7DCF\u7D9C\u8061\u8349\u8358\u846C\u84BC\u85FB\u88C5\u8D70\u9001\u906D\u9397\u971C\u9A12\u50CF\u5897\u618E"],
      ["c2a1", "\u81D3\u8535\u8D08\u9020\u4FC3\u5074\u5247\u5373\u606F\u6349\u675F\u6E2C\u8DB3\u901F\u4FD7\u5C5E\u8CCA\u65CF\u7D9A\u5352\u8896\u5176\u63C3\u5B58\u5B6B\u5C0A\u640D\u6751\u905C\u4ED6\u591A\u592A\u6C70\u8A51\u553E\u5815\u59A5\u60F0\u6253\u67C1\u8235\u6955\u9640\u99C4\u9A28\u4F53\u5806\u5BFE\u8010\u5CB1\u5E2F\u5F85\u6020\u614B\u6234\u66FF\u6CF0\u6EDE\u80CE\u817F\u82D4\u888B\u8CB8\u9000\u902E\u968A\u9EDB\u9BDB\u4EE3\u53F0\u5927\u7B2C\u918D\u984C\u9DF9\u6EDD\u7027\u5353\u5544\u5B85\u6258\u629E\u62D3\u6CA2\u6FEF\u7422\u8A17\u9438\u6FC1\u8AFE\u8338\u51E7\u86F8\u53EA"],
      ["c3a1", "\u53E9\u4F46\u9054\u8FB0\u596A\u8131\u5DFD\u7AEA\u8FBF\u68DA\u8C37\u72F8\u9C48\u6A3D\u8AB0\u4E39\u5358\u5606\u5766\u62C5\u63A2\u65E6\u6B4E\u6DE1\u6E5B\u70AD\u77ED\u7AEF\u7BAA\u7DBB\u803D\u80C6\u86CB\u8A95\u935B\u56E3\u58C7\u5F3E\u65AD\u6696\u6A80\u6BB5\u7537\u8AC7\u5024\u77E5\u5730\u5F1B\u6065\u667A\u6C60\u75F4\u7A1A\u7F6E\u81F4\u8718\u9045\u99B3\u7BC9\u755C\u7AF9\u7B51\u84C4\u9010\u79E9\u7A92\u8336\u5AE1\u7740\u4E2D\u4EF2\u5B99\u5FE0\u62BD\u663C\u67F1\u6CE8\u866B\u8877\u8A3B\u914E\u92F3\u99D0\u6A17\u7026\u732A\u82E7\u8457\u8CAF\u4E01\u5146\u51CB\u558B\u5BF5"],
      ["c4a1", "\u5E16\u5E33\u5E81\u5F14\u5F35\u5F6B\u5FB4\u61F2\u6311\u66A2\u671D\u6F6E\u7252\u753A\u773A\u8074\u8139\u8178\u8776\u8ABF\u8ADC\u8D85\u8DF3\u929A\u9577\u9802\u9CE5\u52C5\u6357\u76F4\u6715\u6C88\u73CD\u8CC3\u93AE\u9673\u6D25\u589C\u690E\u69CC\u8FFD\u939A\u75DB\u901A\u585A\u6802\u63B4\u69FB\u4F43\u6F2C\u67D8\u8FBB\u8526\u7DB4\u9354\u693F\u6F70\u576A\u58F7\u5B2C\u7D2C\u722A\u540A\u91E3\u9DB4\u4EAD\u4F4E\u505C\u5075\u5243\u8C9E\u5448\u5824\u5B9A\u5E1D\u5E95\u5EAD\u5EF7\u5F1F\u608C\u62B5\u633A\u63D0\u68AF\u6C40\u7887\u798E\u7A0B\u7DE0\u8247\u8A02\u8AE6\u8E44\u9013"],
      ["c5a1", "\u90B8\u912D\u91D8\u9F0E\u6CE5\u6458\u64E2\u6575\u6EF4\u7684\u7B1B\u9069\u93D1\u6EBA\u54F2\u5FB9\u64A4\u8F4D\u8FED\u9244\u5178\u586B\u5929\u5C55\u5E97\u6DFB\u7E8F\u751C\u8CBC\u8EE2\u985B\u70B9\u4F1D\u6BBF\u6FB1\u7530\u96FB\u514E\u5410\u5835\u5857\u59AC\u5C60\u5F92\u6597\u675C\u6E21\u767B\u83DF\u8CED\u9014\u90FD\u934D\u7825\u783A\u52AA\u5EA6\u571F\u5974\u6012\u5012\u515A\u51AC\u51CD\u5200\u5510\u5854\u5858\u5957\u5B95\u5CF6\u5D8B\u60BC\u6295\u642D\u6771\u6843\u68BC\u68DF\u76D7\u6DD8\u6E6F\u6D9B\u706F\u71C8\u5F53\u75D8\u7977\u7B49\u7B54\u7B52\u7CD6\u7D71\u5230"],
      ["c6a1", "\u8463\u8569\u85E4\u8A0E\u8B04\u8C46\u8E0F\u9003\u900F\u9419\u9676\u982D\u9A30\u95D8\u50CD\u52D5\u540C\u5802\u5C0E\u61A7\u649E\u6D1E\u77B3\u7AE5\u80F4\u8404\u9053\u9285\u5CE0\u9D07\u533F\u5F97\u5FB3\u6D9C\u7279\u7763\u79BF\u7BE4\u6BD2\u72EC\u8AAD\u6803\u6A61\u51F8\u7A81\u6934\u5C4A\u9CF6\u82EB\u5BC5\u9149\u701E\u5678\u5C6F\u60C7\u6566\u6C8C\u8C5A\u9041\u9813\u5451\u66C7\u920D\u5948\u90A3\u5185\u4E4D\u51EA\u8599\u8B0E\u7058\u637A\u934B\u6962\u99B4\u7E04\u7577\u5357\u6960\u8EDF\u96E3\u6C5D\u4E8C\u5C3C\u5F10\u8FE9\u5302\u8CD1\u8089\u8679\u5EFF\u65E5\u4E73\u5165"],
      ["c7a1", "\u5982\u5C3F\u97EE\u4EFB\u598A\u5FCD\u8A8D\u6FE1\u79B0\u7962\u5BE7\u8471\u732B\u71B1\u5E74\u5FF5\u637B\u649A\u71C3\u7C98\u4E43\u5EFC\u4E4B\u57DC\u56A2\u60A9\u6FC3\u7D0D\u80FD\u8133\u81BF\u8FB2\u8997\u86A4\u5DF4\u628A\u64AD\u8987\u6777\u6CE2\u6D3E\u7436\u7834\u5A46\u7F75\u82AD\u99AC\u4FF3\u5EC3\u62DD\u6392\u6557\u676F\u76C3\u724C\u80CC\u80BA\u8F29\u914D\u500D\u57F9\u5A92\u6885\u6973\u7164\u72FD\u8CB7\u58F2\u8CE0\u966A\u9019\u877F\u79E4\u77E7\u8429\u4F2F\u5265\u535A\u62CD\u67CF\u6CCA\u767D\u7B94\u7C95\u8236\u8584\u8FEB\u66DD\u6F20\u7206\u7E1B\u83AB\u99C1\u9EA6"],
      ["c8a1", "\u51FD\u7BB1\u7872\u7BB8\u8087\u7B48\u6AE8\u5E61\u808C\u7551\u7560\u516B\u9262\u6E8C\u767A\u9197\u9AEA\u4F10\u7F70\u629C\u7B4F\u95A5\u9CE9\u567A\u5859\u86E4\u96BC\u4F34\u5224\u534A\u53CD\u53DB\u5E06\u642C\u6591\u677F\u6C3E\u6C4E\u7248\u72AF\u73ED\u7554\u7E41\u822C\u85E9\u8CA9\u7BC4\u91C6\u7169\u9812\u98EF\u633D\u6669\u756A\u76E4\u78D0\u8543\u86EE\u532A\u5351\u5426\u5983\u5E87\u5F7C\u60B2\u6249\u6279\u62AB\u6590\u6BD4\u6CCC\u75B2\u76AE\u7891\u79D8\u7DCB\u7F77\u80A5\u88AB\u8AB9\u8CBB\u907F\u975E\u98DB\u6A0B\u7C38\u5099\u5C3E\u5FAE\u6787\u6BD8\u7435\u7709\u7F8E"],
      ["c9a1", "\u9F3B\u67CA\u7A17\u5339\u758B\u9AED\u5F66\u819D\u83F1\u8098\u5F3C\u5FC5\u7562\u7B46\u903C\u6867\u59EB\u5A9B\u7D10\u767E\u8B2C\u4FF5\u5F6A\u6A19\u6C37\u6F02\u74E2\u7968\u8868\u8A55\u8C79\u5EDF\u63CF\u75C5\u79D2\u82D7\u9328\u92F2\u849C\u86ED\u9C2D\u54C1\u5F6C\u658C\u6D5C\u7015\u8CA7\u8CD3\u983B\u654F\u74F6\u4E0D\u4ED8\u57E0\u592B\u5A66\u5BCC\u51A8\u5E03\u5E9C\u6016\u6276\u6577\u65A7\u666E\u6D6E\u7236\u7B26\u8150\u819A\u8299\u8B5C\u8CA0\u8CE6\u8D74\u961C\u9644\u4FAE\u64AB\u6B66\u821E\u8461\u856A\u90E8\u5C01\u6953\u98A8\u847A\u8557\u4F0F\u526F\u5FA9\u5E45\u670D"],
      ["caa1", "\u798F\u8179\u8907\u8986\u6DF5\u5F17\u6255\u6CB8\u4ECF\u7269\u9B92\u5206\u543B\u5674\u58B3\u61A4\u626E\u711A\u596E\u7C89\u7CDE\u7D1B\u96F0\u6587\u805E\u4E19\u4F75\u5175\u5840\u5E63\u5E73\u5F0A\u67C4\u4E26\u853D\u9589\u965B\u7C73\u9801\u50FB\u58C1\u7656\u78A7\u5225\u77A5\u8511\u7B86\u504F\u5909\u7247\u7BC7\u7DE8\u8FBA\u8FD4\u904D\u4FBF\u52C9\u5A29\u5F01\u97AD\u4FDD\u8217\u92EA\u5703\u6355\u6B69\u752B\u88DC\u8F14\u7A42\u52DF\u5893\u6155\u620A\u66AE\u6BCD\u7C3F\u83E9\u5023\u4FF8\u5305\u5446\u5831\u5949\u5B9D\u5CF0\u5CEF\u5D29\u5E96\u62B1\u6367\u653E\u65B9\u670B"],
      ["cba1", "\u6CD5\u6CE1\u70F9\u7832\u7E2B\u80DE\u82B3\u840C\u84EC\u8702\u8912\u8A2A\u8C4A\u90A6\u92D2\u98FD\u9CF3\u9D6C\u4E4F\u4EA1\u508D\u5256\u574A\u59A8\u5E3D\u5FD8\u5FD9\u623F\u66B4\u671B\u67D0\u68D2\u5192\u7D21\u80AA\u81A8\u8B00\u8C8C\u8CBF\u927E\u9632\u5420\u982C\u5317\u50D5\u535C\u58A8\u64B2\u6734\u7267\u7766\u7A46\u91E6\u52C3\u6CA1\u6B86\u5800\u5E4C\u5954\u672C\u7FFB\u51E1\u76C6\u6469\u78E8\u9B54\u9EBB\u57CB\u59B9\u6627\u679A\u6BCE\u54E9\u69D9\u5E55\u819C\u6795\u9BAA\u67FE\u9C52\u685D\u4EA6\u4FE3\u53C8\u62B9\u672B\u6CAB\u8FC4\u4FAD\u7E6D\u9EBF\u4E07\u6162\u6E80"],
      ["cca1", "\u6F2B\u8513\u5473\u672A\u9B45\u5DF3\u7B95\u5CAC\u5BC6\u871C\u6E4A\u84D1\u7A14\u8108\u5999\u7C8D\u6C11\u7720\u52D9\u5922\u7121\u725F\u77DB\u9727\u9D61\u690B\u5A7F\u5A18\u51A5\u540D\u547D\u660E\u76DF\u8FF7\u9298\u9CF4\u59EA\u725D\u6EC5\u514D\u68C9\u7DBF\u7DEC\u9762\u9EBA\u6478\u6A21\u8302\u5984\u5B5F\u6BDB\u731B\u76F2\u7DB2\u8017\u8499\u5132\u6728\u9ED9\u76EE\u6762\u52FF\u9905\u5C24\u623B\u7C7E\u8CB0\u554F\u60B6\u7D0B\u9580\u5301\u4E5F\u51B6\u591C\u723A\u8036\u91CE\u5F25\u77E2\u5384\u5F79\u7D04\u85AC\u8A33\u8E8D\u9756\u67F3\u85AE\u9453\u6109\u6108\u6CB9\u7652"],
      ["cda1", "\u8AED\u8F38\u552F\u4F51\u512A\u52C7\u53CB\u5BA5\u5E7D\u60A0\u6182\u63D6\u6709\u67DA\u6E67\u6D8C\u7336\u7337\u7531\u7950\u88D5\u8A98\u904A\u9091\u90F5\u96C4\u878D\u5915\u4E88\u4F59\u4E0E\u8A89\u8F3F\u9810\u50AD\u5E7C\u5996\u5BB9\u5EB8\u63DA\u63FA\u64C1\u66DC\u694A\u69D8\u6D0B\u6EB6\u7194\u7528\u7AAF\u7F8A\u8000\u8449\u84C9\u8981\u8B21\u8E0A\u9065\u967D\u990A\u617E\u6291\u6B32\u6C83\u6D74\u7FCC\u7FFC\u6DC0\u7F85\u87BA\u88F8\u6765\u83B1\u983C\u96F7\u6D1B\u7D61\u843D\u916A\u4E71\u5375\u5D50\u6B04\u6FEB\u85CD\u862D\u89A7\u5229\u540F\u5C65\u674E\u68A8\u7406\u7483"],
      ["cea1", "\u75E2\u88CF\u88E1\u91CC\u96E2\u9678\u5F8B\u7387\u7ACB\u844E\u63A0\u7565\u5289\u6D41\u6E9C\u7409\u7559\u786B\u7C92\u9686\u7ADC\u9F8D\u4FB6\u616E\u65C5\u865C\u4E86\u4EAE\u50DA\u4E21\u51CC\u5BEE\u6599\u6881\u6DBC\u731F\u7642\u77AD\u7A1C\u7CE7\u826F\u8AD2\u907C\u91CF\u9675\u9818\u529B\u7DD1\u502B\u5398\u6797\u6DCB\u71D0\u7433\u81E8\u8F2A\u96A3\u9C57\u9E9F\u7460\u5841\u6D99\u7D2F\u985E\u4EE4\u4F36\u4F8B\u51B7\u52B1\u5DBA\u601C\u73B2\u793C\u82D3\u9234\u96B7\u96F6\u970A\u9E97\u9F62\u66A6\u6B74\u5217\u52A3\u70C8\u88C2\u5EC9\u604B\u6190\u6F23\u7149\u7C3E\u7DF4\u806F"],
      ["cfa1", "\u84EE\u9023\u932C\u5442\u9B6F\u6AD3\u7089\u8CC2\u8DEF\u9732\u52B4\u5A41\u5ECA\u5F04\u6717\u697C\u6994\u6D6A\u6F0F\u7262\u72FC\u7BED\u8001\u807E\u874B\u90CE\u516D\u9E93\u7984\u808B\u9332\u8AD6\u502D\u548C\u8A71\u6B6A\u8CC4\u8107\u60D1\u67A0\u9DF2\u4E99\u4E98\u9C10\u8A6B\u85C1\u8568\u6900\u6E7E\u7897\u8155"],
      ["d0a1", "\u5F0C\u4E10\u4E15\u4E2A\u4E31\u4E36\u4E3C\u4E3F\u4E42\u4E56\u4E58\u4E82\u4E85\u8C6B\u4E8A\u8212\u5F0D\u4E8E\u4E9E\u4E9F\u4EA0\u4EA2\u4EB0\u4EB3\u4EB6\u4ECE\u4ECD\u4EC4\u4EC6\u4EC2\u4ED7\u4EDE\u4EED\u4EDF\u4EF7\u4F09\u4F5A\u4F30\u4F5B\u4F5D\u4F57\u4F47\u4F76\u4F88\u4F8F\u4F98\u4F7B\u4F69\u4F70\u4F91\u4F6F\u4F86\u4F96\u5118\u4FD4\u4FDF\u4FCE\u4FD8\u4FDB\u4FD1\u4FDA\u4FD0\u4FE4\u4FE5\u501A\u5028\u5014\u502A\u5025\u5005\u4F1C\u4FF6\u5021\u5029\u502C\u4FFE\u4FEF\u5011\u5006\u5043\u5047\u6703\u5055\u5050\u5048\u505A\u5056\u506C\u5078\u5080\u509A\u5085\u50B4\u50B2"],
      ["d1a1", "\u50C9\u50CA\u50B3\u50C2\u50D6\u50DE\u50E5\u50ED\u50E3\u50EE\u50F9\u50F5\u5109\u5101\u5102\u5116\u5115\u5114\u511A\u5121\u513A\u5137\u513C\u513B\u513F\u5140\u5152\u514C\u5154\u5162\u7AF8\u5169\u516A\u516E\u5180\u5182\u56D8\u518C\u5189\u518F\u5191\u5193\u5195\u5196\u51A4\u51A6\u51A2\u51A9\u51AA\u51AB\u51B3\u51B1\u51B2\u51B0\u51B5\u51BD\u51C5\u51C9\u51DB\u51E0\u8655\u51E9\u51ED\u51F0\u51F5\u51FE\u5204\u520B\u5214\u520E\u5227\u522A\u522E\u5233\u5239\u524F\u5244\u524B\u524C\u525E\u5254\u526A\u5274\u5269\u5273\u527F\u527D\u528D\u5294\u5292\u5271\u5288\u5291\u8FA8"],
      ["d2a1", "\u8FA7\u52AC\u52AD\u52BC\u52B5\u52C1\u52CD\u52D7\u52DE\u52E3\u52E6\u98ED\u52E0\u52F3\u52F5\u52F8\u52F9\u5306\u5308\u7538\u530D\u5310\u530F\u5315\u531A\u5323\u532F\u5331\u5333\u5338\u5340\u5346\u5345\u4E17\u5349\u534D\u51D6\u535E\u5369\u536E\u5918\u537B\u5377\u5382\u5396\u53A0\u53A6\u53A5\u53AE\u53B0\u53B6\u53C3\u7C12\u96D9\u53DF\u66FC\u71EE\u53EE\u53E8\u53ED\u53FA\u5401\u543D\u5440\u542C\u542D\u543C\u542E\u5436\u5429\u541D\u544E\u548F\u5475\u548E\u545F\u5471\u5477\u5470\u5492\u547B\u5480\u5476\u5484\u5490\u5486\u54C7\u54A2\u54B8\u54A5\u54AC\u54C4\u54C8\u54A8"],
      ["d3a1", "\u54AB\u54C2\u54A4\u54BE\u54BC\u54D8\u54E5\u54E6\u550F\u5514\u54FD\u54EE\u54ED\u54FA\u54E2\u5539\u5540\u5563\u554C\u552E\u555C\u5545\u5556\u5557\u5538\u5533\u555D\u5599\u5580\u54AF\u558A\u559F\u557B\u557E\u5598\u559E\u55AE\u557C\u5583\u55A9\u5587\u55A8\u55DA\u55C5\u55DF\u55C4\u55DC\u55E4\u55D4\u5614\u55F7\u5616\u55FE\u55FD\u561B\u55F9\u564E\u5650\u71DF\u5634\u5636\u5632\u5638\u566B\u5664\u562F\u566C\u566A\u5686\u5680\u568A\u56A0\u5694\u568F\u56A5\u56AE\u56B6\u56B4\u56C2\u56BC\u56C1\u56C3\u56C0\u56C8\u56CE\u56D1\u56D3\u56D7\u56EE\u56F9\u5700\u56FF\u5704\u5709"],
      ["d4a1", "\u5708\u570B\u570D\u5713\u5718\u5716\u55C7\u571C\u5726\u5737\u5738\u574E\u573B\u5740\u574F\u5769\u57C0\u5788\u5761\u577F\u5789\u5793\u57A0\u57B3\u57A4\u57AA\u57B0\u57C3\u57C6\u57D4\u57D2\u57D3\u580A\u57D6\u57E3\u580B\u5819\u581D\u5872\u5821\u5862\u584B\u5870\u6BC0\u5852\u583D\u5879\u5885\u58B9\u589F\u58AB\u58BA\u58DE\u58BB\u58B8\u58AE\u58C5\u58D3\u58D1\u58D7\u58D9\u58D8\u58E5\u58DC\u58E4\u58DF\u58EF\u58FA\u58F9\u58FB\u58FC\u58FD\u5902\u590A\u5910\u591B\u68A6\u5925\u592C\u592D\u5932\u5938\u593E\u7AD2\u5955\u5950\u594E\u595A\u5958\u5962\u5960\u5967\u596C\u5969"],
      ["d5a1", "\u5978\u5981\u599D\u4F5E\u4FAB\u59A3\u59B2\u59C6\u59E8\u59DC\u598D\u59D9\u59DA\u5A25\u5A1F\u5A11\u5A1C\u5A09\u5A1A\u5A40\u5A6C\u5A49\u5A35\u5A36\u5A62\u5A6A\u5A9A\u5ABC\u5ABE\u5ACB\u5AC2\u5ABD\u5AE3\u5AD7\u5AE6\u5AE9\u5AD6\u5AFA\u5AFB\u5B0C\u5B0B\u5B16\u5B32\u5AD0\u5B2A\u5B36\u5B3E\u5B43\u5B45\u5B40\u5B51\u5B55\u5B5A\u5B5B\u5B65\u5B69\u5B70\u5B73\u5B75\u5B78\u6588\u5B7A\u5B80\u5B83\u5BA6\u5BB8\u5BC3\u5BC7\u5BC9\u5BD4\u5BD0\u5BE4\u5BE6\u5BE2\u5BDE\u5BE5\u5BEB\u5BF0\u5BF6\u5BF3\u5C05\u5C07\u5C08\u5C0D\u5C13\u5C20\u5C22\u5C28\u5C38\u5C39\u5C41\u5C46\u5C4E\u5C53"],
      ["d6a1", "\u5C50\u5C4F\u5B71\u5C6C\u5C6E\u4E62\u5C76\u5C79\u5C8C\u5C91\u5C94\u599B\u5CAB\u5CBB\u5CB6\u5CBC\u5CB7\u5CC5\u5CBE\u5CC7\u5CD9\u5CE9\u5CFD\u5CFA\u5CED\u5D8C\u5CEA\u5D0B\u5D15\u5D17\u5D5C\u5D1F\u5D1B\u5D11\u5D14\u5D22\u5D1A\u5D19\u5D18\u5D4C\u5D52\u5D4E\u5D4B\u5D6C\u5D73\u5D76\u5D87\u5D84\u5D82\u5DA2\u5D9D\u5DAC\u5DAE\u5DBD\u5D90\u5DB7\u5DBC\u5DC9\u5DCD\u5DD3\u5DD2\u5DD6\u5DDB\u5DEB\u5DF2\u5DF5\u5E0B\u5E1A\u5E19\u5E11\u5E1B\u5E36\u5E37\u5E44\u5E43\u5E40\u5E4E\u5E57\u5E54\u5E5F\u5E62\u5E64\u5E47\u5E75\u5E76\u5E7A\u9EBC\u5E7F\u5EA0\u5EC1\u5EC2\u5EC8\u5ED0\u5ECF"],
      ["d7a1", "\u5ED6\u5EE3\u5EDD\u5EDA\u5EDB\u5EE2\u5EE1\u5EE8\u5EE9\u5EEC\u5EF1\u5EF3\u5EF0\u5EF4\u5EF8\u5EFE\u5F03\u5F09\u5F5D\u5F5C\u5F0B\u5F11\u5F16\u5F29\u5F2D\u5F38\u5F41\u5F48\u5F4C\u5F4E\u5F2F\u5F51\u5F56\u5F57\u5F59\u5F61\u5F6D\u5F73\u5F77\u5F83\u5F82\u5F7F\u5F8A\u5F88\u5F91\u5F87\u5F9E\u5F99\u5F98\u5FA0\u5FA8\u5FAD\u5FBC\u5FD6\u5FFB\u5FE4\u5FF8\u5FF1\u5FDD\u60B3\u5FFF\u6021\u6060\u6019\u6010\u6029\u600E\u6031\u601B\u6015\u602B\u6026\u600F\u603A\u605A\u6041\u606A\u6077\u605F\u604A\u6046\u604D\u6063\u6043\u6064\u6042\u606C\u606B\u6059\u6081\u608D\u60E7\u6083\u609A"],
      ["d8a1", "\u6084\u609B\u6096\u6097\u6092\u60A7\u608B\u60E1\u60B8\u60E0\u60D3\u60B4\u5FF0\u60BD\u60C6\u60B5\u60D8\u614D\u6115\u6106\u60F6\u60F7\u6100\u60F4\u60FA\u6103\u6121\u60FB\u60F1\u610D\u610E\u6147\u613E\u6128\u6127\u614A\u613F\u613C\u612C\u6134\u613D\u6142\u6144\u6173\u6177\u6158\u6159\u615A\u616B\u6174\u616F\u6165\u6171\u615F\u615D\u6153\u6175\u6199\u6196\u6187\u61AC\u6194\u619A\u618A\u6191\u61AB\u61AE\u61CC\u61CA\u61C9\u61F7\u61C8\u61C3\u61C6\u61BA\u61CB\u7F79\u61CD\u61E6\u61E3\u61F6\u61FA\u61F4\u61FF\u61FD\u61FC\u61FE\u6200\u6208\u6209\u620D\u620C\u6214\u621B"],
      ["d9a1", "\u621E\u6221\u622A\u622E\u6230\u6232\u6233\u6241\u624E\u625E\u6263\u625B\u6260\u6268\u627C\u6282\u6289\u627E\u6292\u6293\u6296\u62D4\u6283\u6294\u62D7\u62D1\u62BB\u62CF\u62FF\u62C6\u64D4\u62C8\u62DC\u62CC\u62CA\u62C2\u62C7\u629B\u62C9\u630C\u62EE\u62F1\u6327\u6302\u6308\u62EF\u62F5\u6350\u633E\u634D\u641C\u634F\u6396\u638E\u6380\u63AB\u6376\u63A3\u638F\u6389\u639F\u63B5\u636B\u6369\u63BE\u63E9\u63C0\u63C6\u63E3\u63C9\u63D2\u63F6\u63C4\u6416\u6434\u6406\u6413\u6426\u6436\u651D\u6417\u6428\u640F\u6467\u646F\u6476\u644E\u652A\u6495\u6493\u64A5\u64A9\u6488\u64BC"],
      ["daa1", "\u64DA\u64D2\u64C5\u64C7\u64BB\u64D8\u64C2\u64F1\u64E7\u8209\u64E0\u64E1\u62AC\u64E3\u64EF\u652C\u64F6\u64F4\u64F2\u64FA\u6500\u64FD\u6518\u651C\u6505\u6524\u6523\u652B\u6534\u6535\u6537\u6536\u6538\u754B\u6548\u6556\u6555\u654D\u6558\u655E\u655D\u6572\u6578\u6582\u6583\u8B8A\u659B\u659F\u65AB\u65B7\u65C3\u65C6\u65C1\u65C4\u65CC\u65D2\u65DB\u65D9\u65E0\u65E1\u65F1\u6772\u660A\u6603\u65FB\u6773\u6635\u6636\u6634\u661C\u664F\u6644\u6649\u6641\u665E\u665D\u6664\u6667\u6668\u665F\u6662\u6670\u6683\u6688\u668E\u6689\u6684\u6698\u669D\u66C1\u66B9\u66C9\u66BE\u66BC"],
      ["dba1", "\u66C4\u66B8\u66D6\u66DA\u66E0\u663F\u66E6\u66E9\u66F0\u66F5\u66F7\u670F\u6716\u671E\u6726\u6727\u9738\u672E\u673F\u6736\u6741\u6738\u6737\u6746\u675E\u6760\u6759\u6763\u6764\u6789\u6770\u67A9\u677C\u676A\u678C\u678B\u67A6\u67A1\u6785\u67B7\u67EF\u67B4\u67EC\u67B3\u67E9\u67B8\u67E4\u67DE\u67DD\u67E2\u67EE\u67B9\u67CE\u67C6\u67E7\u6A9C\u681E\u6846\u6829\u6840\u684D\u6832\u684E\u68B3\u682B\u6859\u6863\u6877\u687F\u689F\u688F\u68AD\u6894\u689D\u689B\u6883\u6AAE\u68B9\u6874\u68B5\u68A0\u68BA\u690F\u688D\u687E\u6901\u68CA\u6908\u68D8\u6922\u6926\u68E1\u690C\u68CD"],
      ["dca1", "\u68D4\u68E7\u68D5\u6936\u6912\u6904\u68D7\u68E3\u6925\u68F9\u68E0\u68EF\u6928\u692A\u691A\u6923\u6921\u68C6\u6979\u6977\u695C\u6978\u696B\u6954\u697E\u696E\u6939\u6974\u693D\u6959\u6930\u6961\u695E\u695D\u6981\u696A\u69B2\u69AE\u69D0\u69BF\u69C1\u69D3\u69BE\u69CE\u5BE8\u69CA\u69DD\u69BB\u69C3\u69A7\u6A2E\u6991\u69A0\u699C\u6995\u69B4\u69DE\u69E8\u6A02\u6A1B\u69FF\u6B0A\u69F9\u69F2\u69E7\u6A05\u69B1\u6A1E\u69ED\u6A14\u69EB\u6A0A\u6A12\u6AC1\u6A23\u6A13\u6A44\u6A0C\u6A72\u6A36\u6A78\u6A47\u6A62\u6A59\u6A66\u6A48\u6A38\u6A22\u6A90\u6A8D\u6AA0\u6A84\u6AA2\u6AA3"],
      ["dda1", "\u6A97\u8617\u6ABB\u6AC3\u6AC2\u6AB8\u6AB3\u6AAC\u6ADE\u6AD1\u6ADF\u6AAA\u6ADA\u6AEA\u6AFB\u6B05\u8616\u6AFA\u6B12\u6B16\u9B31\u6B1F\u6B38\u6B37\u76DC\u6B39\u98EE\u6B47\u6B43\u6B49\u6B50\u6B59\u6B54\u6B5B\u6B5F\u6B61\u6B78\u6B79\u6B7F\u6B80\u6B84\u6B83\u6B8D\u6B98\u6B95\u6B9E\u6BA4\u6BAA\u6BAB\u6BAF\u6BB2\u6BB1\u6BB3\u6BB7\u6BBC\u6BC6\u6BCB\u6BD3\u6BDF\u6BEC\u6BEB\u6BF3\u6BEF\u9EBE\u6C08\u6C13\u6C14\u6C1B\u6C24\u6C23\u6C5E\u6C55\u6C62\u6C6A\u6C82\u6C8D\u6C9A\u6C81\u6C9B\u6C7E\u6C68\u6C73\u6C92\u6C90\u6CC4\u6CF1\u6CD3\u6CBD\u6CD7\u6CC5\u6CDD\u6CAE\u6CB1\u6CBE"],
      ["dea1", "\u6CBA\u6CDB\u6CEF\u6CD9\u6CEA\u6D1F\u884D\u6D36\u6D2B\u6D3D\u6D38\u6D19\u6D35\u6D33\u6D12\u6D0C\u6D63\u6D93\u6D64\u6D5A\u6D79\u6D59\u6D8E\u6D95\u6FE4\u6D85\u6DF9\u6E15\u6E0A\u6DB5\u6DC7\u6DE6\u6DB8\u6DC6\u6DEC\u6DDE\u6DCC\u6DE8\u6DD2\u6DC5\u6DFA\u6DD9\u6DE4\u6DD5\u6DEA\u6DEE\u6E2D\u6E6E\u6E2E\u6E19\u6E72\u6E5F\u6E3E\u6E23\u6E6B\u6E2B\u6E76\u6E4D\u6E1F\u6E43\u6E3A\u6E4E\u6E24\u6EFF\u6E1D\u6E38\u6E82\u6EAA\u6E98\u6EC9\u6EB7\u6ED3\u6EBD\u6EAF\u6EC4\u6EB2\u6ED4\u6ED5\u6E8F\u6EA5\u6EC2\u6E9F\u6F41\u6F11\u704C\u6EEC\u6EF8\u6EFE\u6F3F\u6EF2\u6F31\u6EEF\u6F32\u6ECC"],
      ["dfa1", "\u6F3E\u6F13\u6EF7\u6F86\u6F7A\u6F78\u6F81\u6F80\u6F6F\u6F5B\u6FF3\u6F6D\u6F82\u6F7C\u6F58\u6F8E\u6F91\u6FC2\u6F66\u6FB3\u6FA3\u6FA1\u6FA4\u6FB9\u6FC6\u6FAA\u6FDF\u6FD5\u6FEC\u6FD4\u6FD8\u6FF1\u6FEE\u6FDB\u7009\u700B\u6FFA\u7011\u7001\u700F\u6FFE\u701B\u701A\u6F74\u701D\u7018\u701F\u7030\u703E\u7032\u7051\u7063\u7099\u7092\u70AF\u70F1\u70AC\u70B8\u70B3\u70AE\u70DF\u70CB\u70DD\u70D9\u7109\u70FD\u711C\u7119\u7165\u7155\u7188\u7166\u7162\u714C\u7156\u716C\u718F\u71FB\u7184\u7195\u71A8\u71AC\u71D7\u71B9\u71BE\u71D2\u71C9\u71D4\u71CE\u71E0\u71EC\u71E7\u71F5\u71FC"],
      ["e0a1", "\u71F9\u71FF\u720D\u7210\u721B\u7228\u722D\u722C\u7230\u7232\u723B\u723C\u723F\u7240\u7246\u724B\u7258\u7274\u727E\u7282\u7281\u7287\u7292\u7296\u72A2\u72A7\u72B9\u72B2\u72C3\u72C6\u72C4\u72CE\u72D2\u72E2\u72E0\u72E1\u72F9\u72F7\u500F\u7317\u730A\u731C\u7316\u731D\u7334\u732F\u7329\u7325\u733E\u734E\u734F\u9ED8\u7357\u736A\u7368\u7370\u7378\u7375\u737B\u737A\u73C8\u73B3\u73CE\u73BB\u73C0\u73E5\u73EE\u73DE\u74A2\u7405\u746F\u7425\u73F8\u7432\u743A\u7455\u743F\u745F\u7459\u7441\u745C\u7469\u7470\u7463\u746A\u7476\u747E\u748B\u749E\u74A7\u74CA\u74CF\u74D4\u73F1"],
      ["e1a1", "\u74E0\u74E3\u74E7\u74E9\u74EE\u74F2\u74F0\u74F1\u74F8\u74F7\u7504\u7503\u7505\u750C\u750E\u750D\u7515\u7513\u751E\u7526\u752C\u753C\u7544\u754D\u754A\u7549\u755B\u7546\u755A\u7569\u7564\u7567\u756B\u756D\u7578\u7576\u7586\u7587\u7574\u758A\u7589\u7582\u7594\u759A\u759D\u75A5\u75A3\u75C2\u75B3\u75C3\u75B5\u75BD\u75B8\u75BC\u75B1\u75CD\u75CA\u75D2\u75D9\u75E3\u75DE\u75FE\u75FF\u75FC\u7601\u75F0\u75FA\u75F2\u75F3\u760B\u760D\u7609\u761F\u7627\u7620\u7621\u7622\u7624\u7634\u7630\u763B\u7647\u7648\u7646\u765C\u7658\u7661\u7662\u7668\u7669\u766A\u7667\u766C\u7670"],
      ["e2a1", "\u7672\u7676\u7678\u767C\u7680\u7683\u7688\u768B\u768E\u7696\u7693\u7699\u769A\u76B0\u76B4\u76B8\u76B9\u76BA\u76C2\u76CD\u76D6\u76D2\u76DE\u76E1\u76E5\u76E7\u76EA\u862F\u76FB\u7708\u7707\u7704\u7729\u7724\u771E\u7725\u7726\u771B\u7737\u7738\u7747\u775A\u7768\u776B\u775B\u7765\u777F\u777E\u7779\u778E\u778B\u7791\u77A0\u779E\u77B0\u77B6\u77B9\u77BF\u77BC\u77BD\u77BB\u77C7\u77CD\u77D7\u77DA\u77DC\u77E3\u77EE\u77FC\u780C\u7812\u7926\u7820\u792A\u7845\u788E\u7874\u7886\u787C\u789A\u788C\u78A3\u78B5\u78AA\u78AF\u78D1\u78C6\u78CB\u78D4\u78BE\u78BC\u78C5\u78CA\u78EC"],
      ["e3a1", "\u78E7\u78DA\u78FD\u78F4\u7907\u7912\u7911\u7919\u792C\u792B\u7940\u7960\u7957\u795F\u795A\u7955\u7953\u797A\u797F\u798A\u799D\u79A7\u9F4B\u79AA\u79AE\u79B3\u79B9\u79BA\u79C9\u79D5\u79E7\u79EC\u79E1\u79E3\u7A08\u7A0D\u7A18\u7A19\u7A20\u7A1F\u7980\u7A31\u7A3B\u7A3E\u7A37\u7A43\u7A57\u7A49\u7A61\u7A62\u7A69\u9F9D\u7A70\u7A79\u7A7D\u7A88\u7A97\u7A95\u7A98\u7A96\u7AA9\u7AC8\u7AB0\u7AB6\u7AC5\u7AC4\u7ABF\u9083\u7AC7\u7ACA\u7ACD\u7ACF\u7AD5\u7AD3\u7AD9\u7ADA\u7ADD\u7AE1\u7AE2\u7AE6\u7AED\u7AF0\u7B02\u7B0F\u7B0A\u7B06\u7B33\u7B18\u7B19\u7B1E\u7B35\u7B28\u7B36\u7B50"],
      ["e4a1", "\u7B7A\u7B04\u7B4D\u7B0B\u7B4C\u7B45\u7B75\u7B65\u7B74\u7B67\u7B70\u7B71\u7B6C\u7B6E\u7B9D\u7B98\u7B9F\u7B8D\u7B9C\u7B9A\u7B8B\u7B92\u7B8F\u7B5D\u7B99\u7BCB\u7BC1\u7BCC\u7BCF\u7BB4\u7BC6\u7BDD\u7BE9\u7C11\u7C14\u7BE6\u7BE5\u7C60\u7C00\u7C07\u7C13\u7BF3\u7BF7\u7C17\u7C0D\u7BF6\u7C23\u7C27\u7C2A\u7C1F\u7C37\u7C2B\u7C3D\u7C4C\u7C43\u7C54\u7C4F\u7C40\u7C50\u7C58\u7C5F\u7C64\u7C56\u7C65\u7C6C\u7C75\u7C83\u7C90\u7CA4\u7CAD\u7CA2\u7CAB\u7CA1\u7CA8\u7CB3\u7CB2\u7CB1\u7CAE\u7CB9\u7CBD\u7CC0\u7CC5\u7CC2\u7CD8\u7CD2\u7CDC\u7CE2\u9B3B\u7CEF\u7CF2\u7CF4\u7CF6\u7CFA\u7D06"],
      ["e5a1", "\u7D02\u7D1C\u7D15\u7D0A\u7D45\u7D4B\u7D2E\u7D32\u7D3F\u7D35\u7D46\u7D73\u7D56\u7D4E\u7D72\u7D68\u7D6E\u7D4F\u7D63\u7D93\u7D89\u7D5B\u7D8F\u7D7D\u7D9B\u7DBA\u7DAE\u7DA3\u7DB5\u7DC7\u7DBD\u7DAB\u7E3D\u7DA2\u7DAF\u7DDC\u7DB8\u7D9F\u7DB0\u7DD8\u7DDD\u7DE4\u7DDE\u7DFB\u7DF2\u7DE1\u7E05\u7E0A\u7E23\u7E21\u7E12\u7E31\u7E1F\u7E09\u7E0B\u7E22\u7E46\u7E66\u7E3B\u7E35\u7E39\u7E43\u7E37\u7E32\u7E3A\u7E67\u7E5D\u7E56\u7E5E\u7E59\u7E5A\u7E79\u7E6A\u7E69\u7E7C\u7E7B\u7E83\u7DD5\u7E7D\u8FAE\u7E7F\u7E88\u7E89\u7E8C\u7E92\u7E90\u7E93\u7E94\u7E96\u7E8E\u7E9B\u7E9C\u7F38\u7F3A"],
      ["e6a1", "\u7F45\u7F4C\u7F4D\u7F4E\u7F50\u7F51\u7F55\u7F54\u7F58\u7F5F\u7F60\u7F68\u7F69\u7F67\u7F78\u7F82\u7F86\u7F83\u7F88\u7F87\u7F8C\u7F94\u7F9E\u7F9D\u7F9A\u7FA3\u7FAF\u7FB2\u7FB9\u7FAE\u7FB6\u7FB8\u8B71\u7FC5\u7FC6\u7FCA\u7FD5\u7FD4\u7FE1\u7FE6\u7FE9\u7FF3\u7FF9\u98DC\u8006\u8004\u800B\u8012\u8018\u8019\u801C\u8021\u8028\u803F\u803B\u804A\u8046\u8052\u8058\u805A\u805F\u8062\u8068\u8073\u8072\u8070\u8076\u8079\u807D\u807F\u8084\u8086\u8085\u809B\u8093\u809A\u80AD\u5190\u80AC\u80DB\u80E5\u80D9\u80DD\u80C4\u80DA\u80D6\u8109\u80EF\u80F1\u811B\u8129\u8123\u812F\u814B"],
      ["e7a1", "\u968B\u8146\u813E\u8153\u8151\u80FC\u8171\u816E\u8165\u8166\u8174\u8183\u8188\u818A\u8180\u8182\u81A0\u8195\u81A4\u81A3\u815F\u8193\u81A9\u81B0\u81B5\u81BE\u81B8\u81BD\u81C0\u81C2\u81BA\u81C9\u81CD\u81D1\u81D9\u81D8\u81C8\u81DA\u81DF\u81E0\u81E7\u81FA\u81FB\u81FE\u8201\u8202\u8205\u8207\u820A\u820D\u8210\u8216\u8229\u822B\u8238\u8233\u8240\u8259\u8258\u825D\u825A\u825F\u8264\u8262\u8268\u826A\u826B\u822E\u8271\u8277\u8278\u827E\u828D\u8292\u82AB\u829F\u82BB\u82AC\u82E1\u82E3\u82DF\u82D2\u82F4\u82F3\u82FA\u8393\u8303\u82FB\u82F9\u82DE\u8306\u82DC\u8309\u82D9"],
      ["e8a1", "\u8335\u8334\u8316\u8332\u8331\u8340\u8339\u8350\u8345\u832F\u832B\u8317\u8318\u8385\u839A\u83AA\u839F\u83A2\u8396\u8323\u838E\u8387\u838A\u837C\u83B5\u8373\u8375\u83A0\u8389\u83A8\u83F4\u8413\u83EB\u83CE\u83FD\u8403\u83D8\u840B\u83C1\u83F7\u8407\u83E0\u83F2\u840D\u8422\u8420\u83BD\u8438\u8506\u83FB\u846D\u842A\u843C\u855A\u8484\u8477\u846B\u84AD\u846E\u8482\u8469\u8446\u842C\u846F\u8479\u8435\u84CA\u8462\u84B9\u84BF\u849F\u84D9\u84CD\u84BB\u84DA\u84D0\u84C1\u84C6\u84D6\u84A1\u8521\u84FF\u84F4\u8517\u8518\u852C\u851F\u8515\u8514\u84FC\u8540\u8563\u8558\u8548"],
      ["e9a1", "\u8541\u8602\u854B\u8555\u8580\u85A4\u8588\u8591\u858A\u85A8\u856D\u8594\u859B\u85EA\u8587\u859C\u8577\u857E\u8590\u85C9\u85BA\u85CF\u85B9\u85D0\u85D5\u85DD\u85E5\u85DC\u85F9\u860A\u8613\u860B\u85FE\u85FA\u8606\u8622\u861A\u8630\u863F\u864D\u4E55\u8654\u865F\u8667\u8671\u8693\u86A3\u86A9\u86AA\u868B\u868C\u86B6\u86AF\u86C4\u86C6\u86B0\u86C9\u8823\u86AB\u86D4\u86DE\u86E9\u86EC\u86DF\u86DB\u86EF\u8712\u8706\u8708\u8700\u8703\u86FB\u8711\u8709\u870D\u86F9\u870A\u8734\u873F\u8737\u873B\u8725\u8729\u871A\u8760\u875F\u8778\u874C\u874E\u8774\u8757\u8768\u876E\u8759"],
      ["eaa1", "\u8753\u8763\u876A\u8805\u87A2\u879F\u8782\u87AF\u87CB\u87BD\u87C0\u87D0\u96D6\u87AB\u87C4\u87B3\u87C7\u87C6\u87BB\u87EF\u87F2\u87E0\u880F\u880D\u87FE\u87F6\u87F7\u880E\u87D2\u8811\u8816\u8815\u8822\u8821\u8831\u8836\u8839\u8827\u883B\u8844\u8842\u8852\u8859\u885E\u8862\u886B\u8881\u887E\u889E\u8875\u887D\u88B5\u8872\u8882\u8897\u8892\u88AE\u8899\u88A2\u888D\u88A4\u88B0\u88BF\u88B1\u88C3\u88C4\u88D4\u88D8\u88D9\u88DD\u88F9\u8902\u88FC\u88F4\u88E8\u88F2\u8904\u890C\u890A\u8913\u8943\u891E\u8925\u892A\u892B\u8941\u8944\u893B\u8936\u8938\u894C\u891D\u8960\u895E"],
      ["eba1", "\u8966\u8964\u896D\u896A\u896F\u8974\u8977\u897E\u8983\u8988\u898A\u8993\u8998\u89A1\u89A9\u89A6\u89AC\u89AF\u89B2\u89BA\u89BD\u89BF\u89C0\u89DA\u89DC\u89DD\u89E7\u89F4\u89F8\u8A03\u8A16\u8A10\u8A0C\u8A1B\u8A1D\u8A25\u8A36\u8A41\u8A5B\u8A52\u8A46\u8A48\u8A7C\u8A6D\u8A6C\u8A62\u8A85\u8A82\u8A84\u8AA8\u8AA1\u8A91\u8AA5\u8AA6\u8A9A\u8AA3\u8AC4\u8ACD\u8AC2\u8ADA\u8AEB\u8AF3\u8AE7\u8AE4\u8AF1\u8B14\u8AE0\u8AE2\u8AF7\u8ADE\u8ADB\u8B0C\u8B07\u8B1A\u8AE1\u8B16\u8B10\u8B17\u8B20\u8B33\u97AB\u8B26\u8B2B\u8B3E\u8B28\u8B41\u8B4C\u8B4F\u8B4E\u8B49\u8B56\u8B5B\u8B5A\u8B6B"],
      ["eca1", "\u8B5F\u8B6C\u8B6F\u8B74\u8B7D\u8B80\u8B8C\u8B8E\u8B92\u8B93\u8B96\u8B99\u8B9A\u8C3A\u8C41\u8C3F\u8C48\u8C4C\u8C4E\u8C50\u8C55\u8C62\u8C6C\u8C78\u8C7A\u8C82\u8C89\u8C85\u8C8A\u8C8D\u8C8E\u8C94\u8C7C\u8C98\u621D\u8CAD\u8CAA\u8CBD\u8CB2\u8CB3\u8CAE\u8CB6\u8CC8\u8CC1\u8CE4\u8CE3\u8CDA\u8CFD\u8CFA\u8CFB\u8D04\u8D05\u8D0A\u8D07\u8D0F\u8D0D\u8D10\u9F4E\u8D13\u8CCD\u8D14\u8D16\u8D67\u8D6D\u8D71\u8D73\u8D81\u8D99\u8DC2\u8DBE\u8DBA\u8DCF\u8DDA\u8DD6\u8DCC\u8DDB\u8DCB\u8DEA\u8DEB\u8DDF\u8DE3\u8DFC\u8E08\u8E09\u8DFF\u8E1D\u8E1E\u8E10\u8E1F\u8E42\u8E35\u8E30\u8E34\u8E4A"],
      ["eda1", "\u8E47\u8E49\u8E4C\u8E50\u8E48\u8E59\u8E64\u8E60\u8E2A\u8E63\u8E55\u8E76\u8E72\u8E7C\u8E81\u8E87\u8E85\u8E84\u8E8B\u8E8A\u8E93\u8E91\u8E94\u8E99\u8EAA\u8EA1\u8EAC\u8EB0\u8EC6\u8EB1\u8EBE\u8EC5\u8EC8\u8ECB\u8EDB\u8EE3\u8EFC\u8EFB\u8EEB\u8EFE\u8F0A\u8F05\u8F15\u8F12\u8F19\u8F13\u8F1C\u8F1F\u8F1B\u8F0C\u8F26\u8F33\u8F3B\u8F39\u8F45\u8F42\u8F3E\u8F4C\u8F49\u8F46\u8F4E\u8F57\u8F5C\u8F62\u8F63\u8F64\u8F9C\u8F9F\u8FA3\u8FAD\u8FAF\u8FB7\u8FDA\u8FE5\u8FE2\u8FEA\u8FEF\u9087\u8FF4\u9005\u8FF9\u8FFA\u9011\u9015\u9021\u900D\u901E\u9016\u900B\u9027\u9036\u9035\u9039\u8FF8"],
      ["eea1", "\u904F\u9050\u9051\u9052\u900E\u9049\u903E\u9056\u9058\u905E\u9068\u906F\u9076\u96A8\u9072\u9082\u907D\u9081\u9080\u908A\u9089\u908F\u90A8\u90AF\u90B1\u90B5\u90E2\u90E4\u6248\u90DB\u9102\u9112\u9119\u9132\u9130\u914A\u9156\u9158\u9163\u9165\u9169\u9173\u9172\u918B\u9189\u9182\u91A2\u91AB\u91AF\u91AA\u91B5\u91B4\u91BA\u91C0\u91C1\u91C9\u91CB\u91D0\u91D6\u91DF\u91E1\u91DB\u91FC\u91F5\u91F6\u921E\u91FF\u9214\u922C\u9215\u9211\u925E\u9257\u9245\u9249\u9264\u9248\u9295\u923F\u924B\u9250\u929C\u9296\u9293\u929B\u925A\u92CF\u92B9\u92B7\u92E9\u930F\u92FA\u9344\u932E"],
      ["efa1", "\u9319\u9322\u931A\u9323\u933A\u9335\u933B\u935C\u9360\u937C\u936E\u9356\u93B0\u93AC\u93AD\u9394\u93B9\u93D6\u93D7\u93E8\u93E5\u93D8\u93C3\u93DD\u93D0\u93C8\u93E4\u941A\u9414\u9413\u9403\u9407\u9410\u9436\u942B\u9435\u9421\u943A\u9441\u9452\u9444\u945B\u9460\u9462\u945E\u946A\u9229\u9470\u9475\u9477\u947D\u945A\u947C\u947E\u9481\u947F\u9582\u9587\u958A\u9594\u9596\u9598\u9599\u95A0\u95A8\u95A7\u95AD\u95BC\u95BB\u95B9\u95BE\u95CA\u6FF6\u95C3\u95CD\u95CC\u95D5\u95D4\u95D6\u95DC\u95E1\u95E5\u95E2\u9621\u9628\u962E\u962F\u9642\u964C\u964F\u964B\u9677\u965C\u965E"],
      ["f0a1", "\u965D\u965F\u9666\u9672\u966C\u968D\u9698\u9695\u9697\u96AA\u96A7\u96B1\u96B2\u96B0\u96B4\u96B6\u96B8\u96B9\u96CE\u96CB\u96C9\u96CD\u894D\u96DC\u970D\u96D5\u96F9\u9704\u9706\u9708\u9713\u970E\u9711\u970F\u9716\u9719\u9724\u972A\u9730\u9739\u973D\u973E\u9744\u9746\u9748\u9742\u9749\u975C\u9760\u9764\u9766\u9768\u52D2\u976B\u9771\u9779\u9785\u977C\u9781\u977A\u9786\u978B\u978F\u9790\u979C\u97A8\u97A6\u97A3\u97B3\u97B4\u97C3\u97C6\u97C8\u97CB\u97DC\u97ED\u9F4F\u97F2\u7ADF\u97F6\u97F5\u980F\u980C\u9838\u9824\u9821\u9837\u983D\u9846\u984F\u984B\u986B\u986F\u9870"],
      ["f1a1", "\u9871\u9874\u9873\u98AA\u98AF\u98B1\u98B6\u98C4\u98C3\u98C6\u98E9\u98EB\u9903\u9909\u9912\u9914\u9918\u9921\u991D\u991E\u9924\u9920\u992C\u992E\u993D\u993E\u9942\u9949\u9945\u9950\u994B\u9951\u9952\u994C\u9955\u9997\u9998\u99A5\u99AD\u99AE\u99BC\u99DF\u99DB\u99DD\u99D8\u99D1\u99ED\u99EE\u99F1\u99F2\u99FB\u99F8\u9A01\u9A0F\u9A05\u99E2\u9A19\u9A2B\u9A37\u9A45\u9A42\u9A40\u9A43\u9A3E\u9A55\u9A4D\u9A5B\u9A57\u9A5F\u9A62\u9A65\u9A64\u9A69\u9A6B\u9A6A\u9AAD\u9AB0\u9ABC\u9AC0\u9ACF\u9AD1\u9AD3\u9AD4\u9ADE\u9ADF\u9AE2\u9AE3\u9AE6\u9AEF\u9AEB\u9AEE\u9AF4\u9AF1\u9AF7"],
      ["f2a1", "\u9AFB\u9B06\u9B18\u9B1A\u9B1F\u9B22\u9B23\u9B25\u9B27\u9B28\u9B29\u9B2A\u9B2E\u9B2F\u9B32\u9B44\u9B43\u9B4F\u9B4D\u9B4E\u9B51\u9B58\u9B74\u9B93\u9B83\u9B91\u9B96\u9B97\u9B9F\u9BA0\u9BA8\u9BB4\u9BC0\u9BCA\u9BB9\u9BC6\u9BCF\u9BD1\u9BD2\u9BE3\u9BE2\u9BE4\u9BD4\u9BE1\u9C3A\u9BF2\u9BF1\u9BF0\u9C15\u9C14\u9C09\u9C13\u9C0C\u9C06\u9C08\u9C12\u9C0A\u9C04\u9C2E\u9C1B\u9C25\u9C24\u9C21\u9C30\u9C47\u9C32\u9C46\u9C3E\u9C5A\u9C60\u9C67\u9C76\u9C78\u9CE7\u9CEC\u9CF0\u9D09\u9D08\u9CEB\u9D03\u9D06\u9D2A\u9D26\u9DAF\u9D23\u9D1F\u9D44\u9D15\u9D12\u9D41\u9D3F\u9D3E\u9D46\u9D48"],
      ["f3a1", "\u9D5D\u9D5E\u9D64\u9D51\u9D50\u9D59\u9D72\u9D89\u9D87\u9DAB\u9D6F\u9D7A\u9D9A\u9DA4\u9DA9\u9DB2\u9DC4\u9DC1\u9DBB\u9DB8\u9DBA\u9DC6\u9DCF\u9DC2\u9DD9\u9DD3\u9DF8\u9DE6\u9DED\u9DEF\u9DFD\u9E1A\u9E1B\u9E1E\u9E75\u9E79\u9E7D\u9E81\u9E88\u9E8B\u9E8C\u9E92\u9E95\u9E91\u9E9D\u9EA5\u9EA9\u9EB8\u9EAA\u9EAD\u9761\u9ECC\u9ECE\u9ECF\u9ED0\u9ED4\u9EDC\u9EDE\u9EDD\u9EE0\u9EE5\u9EE8\u9EEF\u9EF4\u9EF6\u9EF7\u9EF9\u9EFB\u9EFC\u9EFD\u9F07\u9F08\u76B7\u9F15\u9F21\u9F2C\u9F3E\u9F4A\u9F52\u9F54\u9F63\u9F5F\u9F60\u9F61\u9F66\u9F67\u9F6C\u9F6A\u9F77\u9F72\u9F76\u9F95\u9F9C\u9FA0"],
      ["f4a1", "\u582F\u69C7\u9059\u7464\u51DC\u7199"],
      ["f9a1", "\u7E8A\u891C\u9348\u9288\u84DC\u4FC9\u70BB\u6631\u68C8\u92F9\u66FB\u5F45\u4E28\u4EE1\u4EFC\u4F00\u4F03\u4F39\u4F56\u4F92\u4F8A\u4F9A\u4F94\u4FCD\u5040\u5022\u4FFF\u501E\u5046\u5070\u5042\u5094\u50F4\u50D8\u514A\u5164\u519D\u51BE\u51EC\u5215\u529C\u52A6\u52C0\u52DB\u5300\u5307\u5324\u5372\u5393\u53B2\u53DD\uFA0E\u549C\u548A\u54A9\u54FF\u5586\u5759\u5765\u57AC\u57C8\u57C7\uFA0F\uFA10\u589E\u58B2\u590B\u5953\u595B\u595D\u5963\u59A4\u59BA\u5B56\u5BC0\u752F\u5BD8\u5BEC\u5C1E\u5CA6\u5CBA\u5CF5\u5D27\u5D53\uFA11\u5D42\u5D6D\u5DB8\u5DB9\u5DD0\u5F21\u5F34\u5F67\u5FB7"],
      ["faa1", "\u5FDE\u605D\u6085\u608A\u60DE\u60D5\u6120\u60F2\u6111\u6137\u6130\u6198\u6213\u62A6\u63F5\u6460\u649D\u64CE\u654E\u6600\u6615\u663B\u6609\u662E\u661E\u6624\u6665\u6657\u6659\uFA12\u6673\u6699\u66A0\u66B2\u66BF\u66FA\u670E\uF929\u6766\u67BB\u6852\u67C0\u6801\u6844\u68CF\uFA13\u6968\uFA14\u6998\u69E2\u6A30\u6A6B\u6A46\u6A73\u6A7E\u6AE2\u6AE4\u6BD6\u6C3F\u6C5C\u6C86\u6C6F\u6CDA\u6D04\u6D87\u6D6F\u6D96\u6DAC\u6DCF\u6DF8\u6DF2\u6DFC\u6E39\u6E5C\u6E27\u6E3C\u6EBF\u6F88\u6FB5\u6FF5\u7005\u7007\u7028\u7085\u70AB\u710F\u7104\u715C\u7146\u7147\uFA15\u71C1\u71FE\u72B1"],
      ["fba1", "\u72BE\u7324\uFA16\u7377\u73BD\u73C9\u73D6\u73E3\u73D2\u7407\u73F5\u7426\u742A\u7429\u742E\u7462\u7489\u749F\u7501\u756F\u7682\u769C\u769E\u769B\u76A6\uFA17\u7746\u52AF\u7821\u784E\u7864\u787A\u7930\uFA18\uFA19\uFA1A\u7994\uFA1B\u799B\u7AD1\u7AE7\uFA1C\u7AEB\u7B9E\uFA1D\u7D48\u7D5C\u7DB7\u7DA0\u7DD6\u7E52\u7F47\u7FA1\uFA1E\u8301\u8362\u837F\u83C7\u83F6\u8448\u84B4\u8553\u8559\u856B\uFA1F\u85B0\uFA20\uFA21\u8807\u88F5\u8A12\u8A37\u8A79\u8AA7\u8ABE\u8ADF\uFA22\u8AF6\u8B53\u8B7F\u8CF0\u8CF4\u8D12\u8D76\uFA23\u8ECF\uFA24\uFA25\u9067\u90DE\uFA26\u9115\u9127\u91DA"],
      ["fca1", "\u91D7\u91DE\u91ED\u91EE\u91E4\u91E5\u9206\u9210\u920A\u923A\u9240\u923C\u924E\u9259\u9251\u9239\u9267\u92A7\u9277\u9278\u92E7\u92D7\u92D9\u92D0\uFA27\u92D5\u92E0\u92D3\u9325\u9321\u92FB\uFA28\u931E\u92FF\u931D\u9302\u9370\u9357\u93A4\u93C6\u93DE\u93F8\u9431\u9445\u9448\u9592\uF9DC\uFA29\u969D\u96AF\u9733\u973B\u9743\u974D\u974F\u9751\u9755\u9857\u9865\uFA2A\uFA2B\u9927\uFA2C\u999E\u9A4E\u9AD9\u9ADC\u9B75\u9B72\u9B8F\u9BB1\u9BBB\u9C00\u9D70\u9D6B\uFA2D\u9E19\u9ED1"],
      ["fcf1", "\u2170", 9, "\uFFE2\uFFE4\uFF07\uFF02"],
      ["8fa2af", "\u02D8\u02C7\xB8\u02D9\u02DD\xAF\u02DB\u02DA\uFF5E\u0384\u0385"],
      ["8fa2c2", "\xA1\xA6\xBF"],
      ["8fa2eb", "\xBA\xAA\xA9\xAE\u2122\xA4\u2116"],
      ["8fa6e1", "\u0386\u0388\u0389\u038A\u03AA"],
      ["8fa6e7", "\u038C"],
      ["8fa6e9", "\u038E\u03AB"],
      ["8fa6ec", "\u038F"],
      ["8fa6f1", "\u03AC\u03AD\u03AE\u03AF\u03CA\u0390\u03CC\u03C2\u03CD\u03CB\u03B0\u03CE"],
      ["8fa7c2", "\u0402", 10, "\u040E\u040F"],
      ["8fa7f2", "\u0452", 10, "\u045E\u045F"],
      ["8fa9a1", "\xC6\u0110"],
      ["8fa9a4", "\u0126"],
      ["8fa9a6", "\u0132"],
      ["8fa9a8", "\u0141\u013F"],
      ["8fa9ab", "\u014A\xD8\u0152"],
      ["8fa9af", "\u0166\xDE"],
      ["8fa9c1", "\xE6\u0111\xF0\u0127\u0131\u0133\u0138\u0142\u0140\u0149\u014B\xF8\u0153\xDF\u0167\xFE"],
      ["8faaa1", "\xC1\xC0\xC4\xC2\u0102\u01CD\u0100\u0104\xC5\xC3\u0106\u0108\u010C\xC7\u010A\u010E\xC9\xC8\xCB\xCA\u011A\u0116\u0112\u0118"],
      ["8faaba", "\u011C\u011E\u0122\u0120\u0124\xCD\xCC\xCF\xCE\u01CF\u0130\u012A\u012E\u0128\u0134\u0136\u0139\u013D\u013B\u0143\u0147\u0145\xD1\xD3\xD2\xD6\xD4\u01D1\u0150\u014C\xD5\u0154\u0158\u0156\u015A\u015C\u0160\u015E\u0164\u0162\xDA\xD9\xDC\xDB\u016C\u01D3\u0170\u016A\u0172\u016E\u0168\u01D7\u01DB\u01D9\u01D5\u0174\xDD\u0178\u0176\u0179\u017D\u017B"],
      ["8faba1", "\xE1\xE0\xE4\xE2\u0103\u01CE\u0101\u0105\xE5\xE3\u0107\u0109\u010D\xE7\u010B\u010F\xE9\xE8\xEB\xEA\u011B\u0117\u0113\u0119\u01F5\u011D\u011F"],
      ["8fabbd", "\u0121\u0125\xED\xEC\xEF\xEE\u01D0"],
      ["8fabc5", "\u012B\u012F\u0129\u0135\u0137\u013A\u013E\u013C\u0144\u0148\u0146\xF1\xF3\xF2\xF6\xF4\u01D2\u0151\u014D\xF5\u0155\u0159\u0157\u015B\u015D\u0161\u015F\u0165\u0163\xFA\xF9\xFC\xFB\u016D\u01D4\u0171\u016B\u0173\u016F\u0169\u01D8\u01DC\u01DA\u01D6\u0175\xFD\xFF\u0177\u017A\u017E\u017C"],
      ["8fb0a1", "\u4E02\u4E04\u4E05\u4E0C\u4E12\u4E1F\u4E23\u4E24\u4E28\u4E2B\u4E2E\u4E2F\u4E30\u4E35\u4E40\u4E41\u4E44\u4E47\u4E51\u4E5A\u4E5C\u4E63\u4E68\u4E69\u4E74\u4E75\u4E79\u4E7F\u4E8D\u4E96\u4E97\u4E9D\u4EAF\u4EB9\u4EC3\u4ED0\u4EDA\u4EDB\u4EE0\u4EE1\u4EE2\u4EE8\u4EEF\u4EF1\u4EF3\u4EF5\u4EFD\u4EFE\u4EFF\u4F00\u4F02\u4F03\u4F08\u4F0B\u4F0C\u4F12\u4F15\u4F16\u4F17\u4F19\u4F2E\u4F31\u4F60\u4F33\u4F35\u4F37\u4F39\u4F3B\u4F3E\u4F40\u4F42\u4F48\u4F49\u4F4B\u4F4C\u4F52\u4F54\u4F56\u4F58\u4F5F\u4F63\u4F6A\u4F6C\u4F6E\u4F71\u4F77\u4F78\u4F79\u4F7A\u4F7D\u4F7E\u4F81\u4F82\u4F84"],
      ["8fb1a1", "\u4F85\u4F89\u4F8A\u4F8C\u4F8E\u4F90\u4F92\u4F93\u4F94\u4F97\u4F99\u4F9A\u4F9E\u4F9F\u4FB2\u4FB7\u4FB9\u4FBB\u4FBC\u4FBD\u4FBE\u4FC0\u4FC1\u4FC5\u4FC6\u4FC8\u4FC9\u4FCB\u4FCC\u4FCD\u4FCF\u4FD2\u4FDC\u4FE0\u4FE2\u4FF0\u4FF2\u4FFC\u4FFD\u4FFF\u5000\u5001\u5004\u5007\u500A\u500C\u500E\u5010\u5013\u5017\u5018\u501B\u501C\u501D\u501E\u5022\u5027\u502E\u5030\u5032\u5033\u5035\u5040\u5041\u5042\u5045\u5046\u504A\u504C\u504E\u5051\u5052\u5053\u5057\u5059\u505F\u5060\u5062\u5063\u5066\u5067\u506A\u506D\u5070\u5071\u503B\u5081\u5083\u5084\u5086\u508A\u508E\u508F\u5090"],
      ["8fb2a1", "\u5092\u5093\u5094\u5096\u509B\u509C\u509E", 4, "\u50AA\u50AF\u50B0\u50B9\u50BA\u50BD\u50C0\u50C3\u50C4\u50C7\u50CC\u50CE\u50D0\u50D3\u50D4\u50D8\u50DC\u50DD\u50DF\u50E2\u50E4\u50E6\u50E8\u50E9\u50EF\u50F1\u50F6\u50FA\u50FE\u5103\u5106\u5107\u5108\u510B\u510C\u510D\u510E\u50F2\u5110\u5117\u5119\u511B\u511C\u511D\u511E\u5123\u5127\u5128\u512C\u512D\u512F\u5131\u5133\u5134\u5135\u5138\u5139\u5142\u514A\u514F\u5153\u5155\u5157\u5158\u515F\u5164\u5166\u517E\u5183\u5184\u518B\u518E\u5198\u519D\u51A1\u51A3\u51AD\u51B8\u51BA\u51BC\u51BE\u51BF\u51C2"],
      ["8fb3a1", "\u51C8\u51CF\u51D1\u51D2\u51D3\u51D5\u51D8\u51DE\u51E2\u51E5\u51EE\u51F2\u51F3\u51F4\u51F7\u5201\u5202\u5205\u5212\u5213\u5215\u5216\u5218\u5222\u5228\u5231\u5232\u5235\u523C\u5245\u5249\u5255\u5257\u5258\u525A\u525C\u525F\u5260\u5261\u5266\u526E\u5277\u5278\u5279\u5280\u5282\u5285\u528A\u528C\u5293\u5295\u5296\u5297\u5298\u529A\u529C\u52A4\u52A5\u52A6\u52A7\u52AF\u52B0\u52B6\u52B7\u52B8\u52BA\u52BB\u52BD\u52C0\u52C4\u52C6\u52C8\u52CC\u52CF\u52D1\u52D4\u52D6\u52DB\u52DC\u52E1\u52E5\u52E8\u52E9\u52EA\u52EC\u52F0\u52F1\u52F4\u52F6\u52F7\u5300\u5303\u530A\u530B"],
      ["8fb4a1", "\u530C\u5311\u5313\u5318\u531B\u531C\u531E\u531F\u5325\u5327\u5328\u5329\u532B\u532C\u532D\u5330\u5332\u5335\u533C\u533D\u533E\u5342\u534C\u534B\u5359\u535B\u5361\u5363\u5365\u536C\u536D\u5372\u5379\u537E\u5383\u5387\u5388\u538E\u5393\u5394\u5399\u539D\u53A1\u53A4\u53AA\u53AB\u53AF\u53B2\u53B4\u53B5\u53B7\u53B8\u53BA\u53BD\u53C0\u53C5\u53CF\u53D2\u53D3\u53D5\u53DA\u53DD\u53DE\u53E0\u53E6\u53E7\u53F5\u5402\u5413\u541A\u5421\u5427\u5428\u542A\u542F\u5431\u5434\u5435\u5443\u5444\u5447\u544D\u544F\u545E\u5462\u5464\u5466\u5467\u5469\u546B\u546D\u546E\u5474\u547F"],
      ["8fb5a1", "\u5481\u5483\u5485\u5488\u5489\u548D\u5491\u5495\u5496\u549C\u549F\u54A1\u54A6\u54A7\u54A9\u54AA\u54AD\u54AE\u54B1\u54B7\u54B9\u54BA\u54BB\u54BF\u54C6\u54CA\u54CD\u54CE\u54E0\u54EA\u54EC\u54EF\u54F6\u54FC\u54FE\u54FF\u5500\u5501\u5505\u5508\u5509\u550C\u550D\u550E\u5515\u552A\u552B\u5532\u5535\u5536\u553B\u553C\u553D\u5541\u5547\u5549\u554A\u554D\u5550\u5551\u5558\u555A\u555B\u555E\u5560\u5561\u5564\u5566\u557F\u5581\u5582\u5586\u5588\u558E\u558F\u5591\u5592\u5593\u5594\u5597\u55A3\u55A4\u55AD\u55B2\u55BF\u55C1\u55C3\u55C6\u55C9\u55CB\u55CC\u55CE\u55D1\u55D2"],
      ["8fb6a1", "\u55D3\u55D7\u55D8\u55DB\u55DE\u55E2\u55E9\u55F6\u55FF\u5605\u5608\u560A\u560D", 5, "\u5619\u562C\u5630\u5633\u5635\u5637\u5639\u563B\u563C\u563D\u563F\u5640\u5641\u5643\u5644\u5646\u5649\u564B\u564D\u564F\u5654\u565E\u5660\u5661\u5662\u5663\u5666\u5669\u566D\u566F\u5671\u5672\u5675\u5684\u5685\u5688\u568B\u568C\u5695\u5699\u569A\u569D\u569E\u569F\u56A6\u56A7\u56A8\u56A9\u56AB\u56AC\u56AD\u56B1\u56B3\u56B7\u56BE\u56C5\u56C9\u56CA\u56CB\u56CF\u56D0\u56CC\u56CD\u56D9\u56DC\u56DD\u56DF\u56E1\u56E4", 4, "\u56F1\u56EB\u56ED"],
      ["8fb7a1", "\u56F6\u56F7\u5701\u5702\u5707\u570A\u570C\u5711\u5715\u571A\u571B\u571D\u5720\u5722\u5723\u5724\u5725\u5729\u572A\u572C\u572E\u572F\u5733\u5734\u573D\u573E\u573F\u5745\u5746\u574C\u574D\u5752\u5762\u5765\u5767\u5768\u576B\u576D", 4, "\u5773\u5774\u5775\u5777\u5779\u577A\u577B\u577C\u577E\u5781\u5783\u578C\u5794\u5797\u5799\u579A\u579C\u579D\u579E\u579F\u57A1\u5795\u57A7\u57A8\u57A9\u57AC\u57B8\u57BD\u57C7\u57C8\u57CC\u57CF\u57D5\u57DD\u57DE\u57E4\u57E6\u57E7\u57E9\u57ED\u57F0\u57F5\u57F6\u57F8\u57FD\u57FE\u57FF\u5803\u5804\u5808\u5809\u57E1"],
      ["8fb8a1", "\u580C\u580D\u581B\u581E\u581F\u5820\u5826\u5827\u582D\u5832\u5839\u583F\u5849\u584C\u584D\u584F\u5850\u5855\u585F\u5861\u5864\u5867\u5868\u5878\u587C\u587F\u5880\u5881\u5887\u5888\u5889\u588A\u588C\u588D\u588F\u5890\u5894\u5896\u589D\u58A0\u58A1\u58A2\u58A6\u58A9\u58B1\u58B2\u58C4\u58BC\u58C2\u58C8\u58CD\u58CE\u58D0\u58D2\u58D4\u58D6\u58DA\u58DD\u58E1\u58E2\u58E9\u58F3\u5905\u5906\u590B\u590C\u5912\u5913\u5914\u8641\u591D\u5921\u5923\u5924\u5928\u592F\u5930\u5933\u5935\u5936\u593F\u5943\u5946\u5952\u5953\u5959\u595B\u595D\u595E\u595F\u5961\u5963\u596B\u596D"],
      ["8fb9a1", "\u596F\u5972\u5975\u5976\u5979\u597B\u597C\u598B\u598C\u598E\u5992\u5995\u5997\u599F\u59A4\u59A7\u59AD\u59AE\u59AF\u59B0\u59B3\u59B7\u59BA\u59BC\u59C1\u59C3\u59C4\u59C8\u59CA\u59CD\u59D2\u59DD\u59DE\u59DF\u59E3\u59E4\u59E7\u59EE\u59EF\u59F1\u59F2\u59F4\u59F7\u5A00\u5A04\u5A0C\u5A0D\u5A0E\u5A12\u5A13\u5A1E\u5A23\u5A24\u5A27\u5A28\u5A2A\u5A2D\u5A30\u5A44\u5A45\u5A47\u5A48\u5A4C\u5A50\u5A55\u5A5E\u5A63\u5A65\u5A67\u5A6D\u5A77\u5A7A\u5A7B\u5A7E\u5A8B\u5A90\u5A93\u5A96\u5A99\u5A9C\u5A9E\u5A9F\u5AA0\u5AA2\u5AA7\u5AAC\u5AB1\u5AB2\u5AB3\u5AB5\u5AB8\u5ABA\u5ABB\u5ABF"],
      ["8fbaa1", "\u5AC4\u5AC6\u5AC8\u5ACF\u5ADA\u5ADC\u5AE0\u5AE5\u5AEA\u5AEE\u5AF5\u5AF6\u5AFD\u5B00\u5B01\u5B08\u5B17\u5B34\u5B19\u5B1B\u5B1D\u5B21\u5B25\u5B2D\u5B38\u5B41\u5B4B\u5B4C\u5B52\u5B56\u5B5E\u5B68\u5B6E\u5B6F\u5B7C\u5B7D\u5B7E\u5B7F\u5B81\u5B84\u5B86\u5B8A\u5B8E\u5B90\u5B91\u5B93\u5B94\u5B96\u5BA8\u5BA9\u5BAC\u5BAD\u5BAF\u5BB1\u5BB2\u5BB7\u5BBA\u5BBC\u5BC0\u5BC1\u5BCD\u5BCF\u5BD6", 4, "\u5BE0\u5BEF\u5BF1\u5BF4\u5BFD\u5C0C\u5C17\u5C1E\u5C1F\u5C23\u5C26\u5C29\u5C2B\u5C2C\u5C2E\u5C30\u5C32\u5C35\u5C36\u5C59\u5C5A\u5C5C\u5C62\u5C63\u5C67\u5C68\u5C69"],
      ["8fbba1", "\u5C6D\u5C70\u5C74\u5C75\u5C7A\u5C7B\u5C7C\u5C7D\u5C87\u5C88\u5C8A\u5C8F\u5C92\u5C9D\u5C9F\u5CA0\u5CA2\u5CA3\u5CA6\u5CAA\u5CB2\u5CB4\u5CB5\u5CBA\u5CC9\u5CCB\u5CD2\u5CDD\u5CD7\u5CEE\u5CF1\u5CF2\u5CF4\u5D01\u5D06\u5D0D\u5D12\u5D2B\u5D23\u5D24\u5D26\u5D27\u5D31\u5D34\u5D39\u5D3D\u5D3F\u5D42\u5D43\u5D46\u5D48\u5D55\u5D51\u5D59\u5D4A\u5D5F\u5D60\u5D61\u5D62\u5D64\u5D6A\u5D6D\u5D70\u5D79\u5D7A\u5D7E\u5D7F\u5D81\u5D83\u5D88\u5D8A\u5D92\u5D93\u5D94\u5D95\u5D99\u5D9B\u5D9F\u5DA0\u5DA7\u5DAB\u5DB0\u5DB4\u5DB8\u5DB9\u5DC3\u5DC7\u5DCB\u5DD0\u5DCE\u5DD8\u5DD9\u5DE0\u5DE4"],
      ["8fbca1", "\u5DE9\u5DF8\u5DF9\u5E00\u5E07\u5E0D\u5E12\u5E14\u5E15\u5E18\u5E1F\u5E20\u5E2E\u5E28\u5E32\u5E35\u5E3E\u5E4B\u5E50\u5E49\u5E51\u5E56\u5E58\u5E5B\u5E5C\u5E5E\u5E68\u5E6A", 4, "\u5E70\u5E80\u5E8B\u5E8E\u5EA2\u5EA4\u5EA5\u5EA8\u5EAA\u5EAC\u5EB1\u5EB3\u5EBD\u5EBE\u5EBF\u5EC6\u5ECC\u5ECB\u5ECE\u5ED1\u5ED2\u5ED4\u5ED5\u5EDC\u5EDE\u5EE5\u5EEB\u5F02\u5F06\u5F07\u5F08\u5F0E\u5F19\u5F1C\u5F1D\u5F21\u5F22\u5F23\u5F24\u5F28\u5F2B\u5F2C\u5F2E\u5F30\u5F34\u5F36\u5F3B\u5F3D\u5F3F\u5F40\u5F44\u5F45\u5F47\u5F4D\u5F50\u5F54\u5F58\u5F5B\u5F60\u5F63\u5F64\u5F67"],
      ["8fbda1", "\u5F6F\u5F72\u5F74\u5F75\u5F78\u5F7A\u5F7D\u5F7E\u5F89\u5F8D\u5F8F\u5F96\u5F9C\u5F9D\u5FA2\u5FA7\u5FAB\u5FA4\u5FAC\u5FAF\u5FB0\u5FB1\u5FB8\u5FC4\u5FC7\u5FC8\u5FC9\u5FCB\u5FD0", 4, "\u5FDE\u5FE1\u5FE2\u5FE8\u5FE9\u5FEA\u5FEC\u5FED\u5FEE\u5FEF\u5FF2\u5FF3\u5FF6\u5FFA\u5FFC\u6007\u600A\u600D\u6013\u6014\u6017\u6018\u601A\u601F\u6024\u602D\u6033\u6035\u6040\u6047\u6048\u6049\u604C\u6051\u6054\u6056\u6057\u605D\u6061\u6067\u6071\u607E\u607F\u6082\u6086\u6088\u608A\u608E\u6091\u6093\u6095\u6098\u609D\u609E\u60A2\u60A4\u60A5\u60A8\u60B0\u60B1\u60B7"],
      ["8fbea1", "\u60BB\u60BE\u60C2\u60C4\u60C8\u60C9\u60CA\u60CB\u60CE\u60CF\u60D4\u60D5\u60D9\u60DB\u60DD\u60DE\u60E2\u60E5\u60F2\u60F5\u60F8\u60FC\u60FD\u6102\u6107\u610A\u610C\u6110", 4, "\u6116\u6117\u6119\u611C\u611E\u6122\u612A\u612B\u6130\u6131\u6135\u6136\u6137\u6139\u6141\u6145\u6146\u6149\u615E\u6160\u616C\u6172\u6178\u617B\u617C\u617F\u6180\u6181\u6183\u6184\u618B\u618D\u6192\u6193\u6197\u6198\u619C\u619D\u619F\u61A0\u61A5\u61A8\u61AA\u61AD\u61B8\u61B9\u61BC\u61C0\u61C1\u61C2\u61CE\u61CF\u61D5\u61DC\u61DD\u61DE\u61DF\u61E1\u61E2\u61E7\u61E9\u61E5"],
      ["8fbfa1", "\u61EC\u61ED\u61EF\u6201\u6203\u6204\u6207\u6213\u6215\u621C\u6220\u6222\u6223\u6227\u6229\u622B\u6239\u623D\u6242\u6243\u6244\u6246\u624C\u6250\u6251\u6252\u6254\u6256\u625A\u625C\u6264\u626D\u626F\u6273\u627A\u627D\u628D\u628E\u628F\u6290\u62A6\u62A8\u62B3\u62B6\u62B7\u62BA\u62BE\u62BF\u62C4\u62CE\u62D5\u62D6\u62DA\u62EA\u62F2\u62F4\u62FC\u62FD\u6303\u6304\u630A\u630B\u630D\u6310\u6313\u6316\u6318\u6329\u632A\u632D\u6335\u6336\u6339\u633C\u6341\u6342\u6343\u6344\u6346\u634A\u634B\u634E\u6352\u6353\u6354\u6358\u635B\u6365\u6366\u636C\u636D\u6371\u6374\u6375"],
      ["8fc0a1", "\u6378\u637C\u637D\u637F\u6382\u6384\u6387\u638A\u6390\u6394\u6395\u6399\u639A\u639E\u63A4\u63A6\u63AD\u63AE\u63AF\u63BD\u63C1\u63C5\u63C8\u63CE\u63D1\u63D3\u63D4\u63D5\u63DC\u63E0\u63E5\u63EA\u63EC\u63F2\u63F3\u63F5\u63F8\u63F9\u6409\u640A\u6410\u6412\u6414\u6418\u641E\u6420\u6422\u6424\u6425\u6429\u642A\u642F\u6430\u6435\u643D\u643F\u644B\u644F\u6451\u6452\u6453\u6454\u645A\u645B\u645C\u645D\u645F\u6460\u6461\u6463\u646D\u6473\u6474\u647B\u647D\u6485\u6487\u648F\u6490\u6491\u6498\u6499\u649B\u649D\u649F\u64A1\u64A3\u64A6\u64A8\u64AC\u64B3\u64BD\u64BE\u64BF"],
      ["8fc1a1", "\u64C4\u64C9\u64CA\u64CB\u64CC\u64CE\u64D0\u64D1\u64D5\u64D7\u64E4\u64E5\u64E9\u64EA\u64ED\u64F0\u64F5\u64F7\u64FB\u64FF\u6501\u6504\u6508\u6509\u650A\u650F\u6513\u6514\u6516\u6519\u651B\u651E\u651F\u6522\u6526\u6529\u652E\u6531\u653A\u653C\u653D\u6543\u6547\u6549\u6550\u6552\u6554\u655F\u6560\u6567\u656B\u657A\u657D\u6581\u6585\u658A\u6592\u6595\u6598\u659D\u65A0\u65A3\u65A6\u65AE\u65B2\u65B3\u65B4\u65BF\u65C2\u65C8\u65C9\u65CE\u65D0\u65D4\u65D6\u65D8\u65DF\u65F0\u65F2\u65F4\u65F5\u65F9\u65FE\u65FF\u6600\u6604\u6608\u6609\u660D\u6611\u6612\u6615\u6616\u661D"],
      ["8fc2a1", "\u661E\u6621\u6622\u6623\u6624\u6626\u6629\u662A\u662B\u662C\u662E\u6630\u6631\u6633\u6639\u6637\u6640\u6645\u6646\u664A\u664C\u6651\u664E\u6657\u6658\u6659\u665B\u665C\u6660\u6661\u66FB\u666A\u666B\u666C\u667E\u6673\u6675\u667F\u6677\u6678\u6679\u667B\u6680\u667C\u668B\u668C\u668D\u6690\u6692\u6699\u669A\u669B\u669C\u669F\u66A0\u66A4\u66AD\u66B1\u66B2\u66B5\u66BB\u66BF\u66C0\u66C2\u66C3\u66C8\u66CC\u66CE\u66CF\u66D4\u66DB\u66DF\u66E8\u66EB\u66EC\u66EE\u66FA\u6705\u6707\u670E\u6713\u6719\u671C\u6720\u6722\u6733\u673E\u6745\u6747\u6748\u674C\u6754\u6755\u675D"],
      ["8fc3a1", "\u6766\u676C\u676E\u6774\u6776\u677B\u6781\u6784\u678E\u678F\u6791\u6793\u6796\u6798\u6799\u679B\u67B0\u67B1\u67B2\u67B5\u67BB\u67BC\u67BD\u67F9\u67C0\u67C2\u67C3\u67C5\u67C8\u67C9\u67D2\u67D7\u67D9\u67DC\u67E1\u67E6\u67F0\u67F2\u67F6\u67F7\u6852\u6814\u6819\u681D\u681F\u6828\u6827\u682C\u682D\u682F\u6830\u6831\u6833\u683B\u683F\u6844\u6845\u684A\u684C\u6855\u6857\u6858\u685B\u686B\u686E", 4, "\u6875\u6879\u687A\u687B\u687C\u6882\u6884\u6886\u6888\u6896\u6898\u689A\u689C\u68A1\u68A3\u68A5\u68A9\u68AA\u68AE\u68B2\u68BB\u68C5\u68C8\u68CC\u68CF"],
      ["8fc4a1", "\u68D0\u68D1\u68D3\u68D6\u68D9\u68DC\u68DD\u68E5\u68E8\u68EA\u68EB\u68EC\u68ED\u68F0\u68F1\u68F5\u68F6\u68FB\u68FC\u68FD\u6906\u6909\u690A\u6910\u6911\u6913\u6916\u6917\u6931\u6933\u6935\u6938\u693B\u6942\u6945\u6949\u694E\u6957\u695B\u6963\u6964\u6965\u6966\u6968\u6969\u696C\u6970\u6971\u6972\u697A\u697B\u697F\u6980\u698D\u6992\u6996\u6998\u69A1\u69A5\u69A6\u69A8\u69AB\u69AD\u69AF\u69B7\u69B8\u69BA\u69BC\u69C5\u69C8\u69D1\u69D6\u69D7\u69E2\u69E5\u69EE\u69EF\u69F1\u69F3\u69F5\u69FE\u6A00\u6A01\u6A03\u6A0F\u6A11\u6A15\u6A1A\u6A1D\u6A20\u6A24\u6A28\u6A30\u6A32"],
      ["8fc5a1", "\u6A34\u6A37\u6A3B\u6A3E\u6A3F\u6A45\u6A46\u6A49\u6A4A\u6A4E\u6A50\u6A51\u6A52\u6A55\u6A56\u6A5B\u6A64\u6A67\u6A6A\u6A71\u6A73\u6A7E\u6A81\u6A83\u6A86\u6A87\u6A89\u6A8B\u6A91\u6A9B\u6A9D\u6A9E\u6A9F\u6AA5\u6AAB\u6AAF\u6AB0\u6AB1\u6AB4\u6ABD\u6ABE\u6ABF\u6AC6\u6AC9\u6AC8\u6ACC\u6AD0\u6AD4\u6AD5\u6AD6\u6ADC\u6ADD\u6AE4\u6AE7\u6AEC\u6AF0\u6AF1\u6AF2\u6AFC\u6AFD\u6B02\u6B03\u6B06\u6B07\u6B09\u6B0F\u6B10\u6B11\u6B17\u6B1B\u6B1E\u6B24\u6B28\u6B2B\u6B2C\u6B2F\u6B35\u6B36\u6B3B\u6B3F\u6B46\u6B4A\u6B4D\u6B52\u6B56\u6B58\u6B5D\u6B60\u6B67\u6B6B\u6B6E\u6B70\u6B75\u6B7D"],
      ["8fc6a1", "\u6B7E\u6B82\u6B85\u6B97\u6B9B\u6B9F\u6BA0\u6BA2\u6BA3\u6BA8\u6BA9\u6BAC\u6BAD\u6BAE\u6BB0\u6BB8\u6BB9\u6BBD\u6BBE\u6BC3\u6BC4\u6BC9\u6BCC\u6BD6\u6BDA\u6BE1\u6BE3\u6BE6\u6BE7\u6BEE\u6BF1\u6BF7\u6BF9\u6BFF\u6C02\u6C04\u6C05\u6C09\u6C0D\u6C0E\u6C10\u6C12\u6C19\u6C1F\u6C26\u6C27\u6C28\u6C2C\u6C2E\u6C33\u6C35\u6C36\u6C3A\u6C3B\u6C3F\u6C4A\u6C4B\u6C4D\u6C4F\u6C52\u6C54\u6C59\u6C5B\u6C5C\u6C6B\u6C6D\u6C6F\u6C74\u6C76\u6C78\u6C79\u6C7B\u6C85\u6C86\u6C87\u6C89\u6C94\u6C95\u6C97\u6C98\u6C9C\u6C9F\u6CB0\u6CB2\u6CB4\u6CC2\u6CC6\u6CCD\u6CCF\u6CD0\u6CD1\u6CD2\u6CD4\u6CD6"],
      ["8fc7a1", "\u6CDA\u6CDC\u6CE0\u6CE7\u6CE9\u6CEB\u6CEC\u6CEE\u6CF2\u6CF4\u6D04\u6D07\u6D0A\u6D0E\u6D0F\u6D11\u6D13\u6D1A\u6D26\u6D27\u6D28\u6C67\u6D2E\u6D2F\u6D31\u6D39\u6D3C\u6D3F\u6D57\u6D5E\u6D5F\u6D61\u6D65\u6D67\u6D6F\u6D70\u6D7C\u6D82\u6D87\u6D91\u6D92\u6D94\u6D96\u6D97\u6D98\u6DAA\u6DAC\u6DB4\u6DB7\u6DB9\u6DBD\u6DBF\u6DC4\u6DC8\u6DCA\u6DCE\u6DCF\u6DD6\u6DDB\u6DDD\u6DDF\u6DE0\u6DE2\u6DE5\u6DE9\u6DEF\u6DF0\u6DF4\u6DF6\u6DFC\u6E00\u6E04\u6E1E\u6E22\u6E27\u6E32\u6E36\u6E39\u6E3B\u6E3C\u6E44\u6E45\u6E48\u6E49\u6E4B\u6E4F\u6E51\u6E52\u6E53\u6E54\u6E57\u6E5C\u6E5D\u6E5E"],
      ["8fc8a1", "\u6E62\u6E63\u6E68\u6E73\u6E7B\u6E7D\u6E8D\u6E93\u6E99\u6EA0\u6EA7\u6EAD\u6EAE\u6EB1\u6EB3\u6EBB\u6EBF\u6EC0\u6EC1\u6EC3\u6EC7\u6EC8\u6ECA\u6ECD\u6ECE\u6ECF\u6EEB\u6EED\u6EEE\u6EF9\u6EFB\u6EFD\u6F04\u6F08\u6F0A\u6F0C\u6F0D\u6F16\u6F18\u6F1A\u6F1B\u6F26\u6F29\u6F2A\u6F2F\u6F30\u6F33\u6F36\u6F3B\u6F3C\u6F2D\u6F4F\u6F51\u6F52\u6F53\u6F57\u6F59\u6F5A\u6F5D\u6F5E\u6F61\u6F62\u6F68\u6F6C\u6F7D\u6F7E\u6F83\u6F87\u6F88\u6F8B\u6F8C\u6F8D\u6F90\u6F92\u6F93\u6F94\u6F96\u6F9A\u6F9F\u6FA0\u6FA5\u6FA6\u6FA7\u6FA8\u6FAE\u6FAF\u6FB0\u6FB5\u6FB6\u6FBC\u6FC5\u6FC7\u6FC8\u6FCA"],
      ["8fc9a1", "\u6FDA\u6FDE\u6FE8\u6FE9\u6FF0\u6FF5\u6FF9\u6FFC\u6FFD\u7000\u7005\u7006\u7007\u700D\u7017\u7020\u7023\u702F\u7034\u7037\u7039\u703C\u7043\u7044\u7048\u7049\u704A\u704B\u7054\u7055\u705D\u705E\u704E\u7064\u7065\u706C\u706E\u7075\u7076\u707E\u7081\u7085\u7086\u7094", 4, "\u709B\u70A4\u70AB\u70B0\u70B1\u70B4\u70B7\u70CA\u70D1\u70D3\u70D4\u70D5\u70D6\u70D8\u70DC\u70E4\u70FA\u7103", 4, "\u710B\u710C\u710F\u711E\u7120\u712B\u712D\u712F\u7130\u7131\u7138\u7141\u7145\u7146\u7147\u714A\u714B\u7150\u7152\u7157\u715A\u715C\u715E\u7160"],
      ["8fcaa1", "\u7168\u7179\u7180\u7185\u7187\u718C\u7192\u719A\u719B\u71A0\u71A2\u71AF\u71B0\u71B2\u71B3\u71BA\u71BF\u71C0\u71C1\u71C4\u71CB\u71CC\u71D3\u71D6\u71D9\u71DA\u71DC\u71F8\u71FE\u7200\u7207\u7208\u7209\u7213\u7217\u721A\u721D\u721F\u7224\u722B\u722F\u7234\u7238\u7239\u7241\u7242\u7243\u7245\u724E\u724F\u7250\u7253\u7255\u7256\u725A\u725C\u725E\u7260\u7263\u7268\u726B\u726E\u726F\u7271\u7277\u7278\u727B\u727C\u727F\u7284\u7289\u728D\u728E\u7293\u729B\u72A8\u72AD\u72AE\u72B1\u72B4\u72BE\u72C1\u72C7\u72C9\u72CC\u72D5\u72D6\u72D8\u72DF\u72E5\u72F3\u72F4\u72FA\u72FB"],
      ["8fcba1", "\u72FE\u7302\u7304\u7305\u7307\u730B\u730D\u7312\u7313\u7318\u7319\u731E\u7322\u7324\u7327\u7328\u732C\u7331\u7332\u7335\u733A\u733B\u733D\u7343\u734D\u7350\u7352\u7356\u7358\u735D\u735E\u735F\u7360\u7366\u7367\u7369\u736B\u736C\u736E\u736F\u7371\u7377\u7379\u737C\u7380\u7381\u7383\u7385\u7386\u738E\u7390\u7393\u7395\u7397\u7398\u739C\u739E\u739F\u73A0\u73A2\u73A5\u73A6\u73AA\u73AB\u73AD\u73B5\u73B7\u73B9\u73BC\u73BD\u73BF\u73C5\u73C6\u73C9\u73CB\u73CC\u73CF\u73D2\u73D3\u73D6\u73D9\u73DD\u73E1\u73E3\u73E6\u73E7\u73E9\u73F4\u73F5\u73F7\u73F9\u73FA\u73FB\u73FD"],
      ["8fcca1", "\u73FF\u7400\u7401\u7404\u7407\u740A\u7411\u741A\u741B\u7424\u7426\u7428", 9, "\u7439\u7440\u7443\u7444\u7446\u7447\u744B\u744D\u7451\u7452\u7457\u745D\u7462\u7466\u7467\u7468\u746B\u746D\u746E\u7471\u7472\u7480\u7481\u7485\u7486\u7487\u7489\u748F\u7490\u7491\u7492\u7498\u7499\u749A\u749C\u749F\u74A0\u74A1\u74A3\u74A6\u74A8\u74A9\u74AA\u74AB\u74AE\u74AF\u74B1\u74B2\u74B5\u74B9\u74BB\u74BF\u74C8\u74C9\u74CC\u74D0\u74D3\u74D8\u74DA\u74DB\u74DE\u74DF\u74E4\u74E8\u74EA\u74EB\u74EF\u74F4\u74FA\u74FB\u74FC\u74FF\u7506"],
      ["8fcda1", "\u7512\u7516\u7517\u7520\u7521\u7524\u7527\u7529\u752A\u752F\u7536\u7539\u753D\u753E\u753F\u7540\u7543\u7547\u7548\u754E\u7550\u7552\u7557\u755E\u755F\u7561\u756F\u7571\u7579", 5, "\u7581\u7585\u7590\u7592\u7593\u7595\u7599\u759C\u75A2\u75A4\u75B4\u75BA\u75BF\u75C0\u75C1\u75C4\u75C6\u75CC\u75CE\u75CF\u75D7\u75DC\u75DF\u75E0\u75E1\u75E4\u75E7\u75EC\u75EE\u75EF\u75F1\u75F9\u7600\u7602\u7603\u7604\u7607\u7608\u760A\u760C\u760F\u7612\u7613\u7615\u7616\u7619\u761B\u761C\u761D\u761E\u7623\u7625\u7626\u7629\u762D\u7632\u7633\u7635\u7638\u7639"],
      ["8fcea1", "\u763A\u763C\u764A\u7640\u7641\u7643\u7644\u7645\u7649\u764B\u7655\u7659\u765F\u7664\u7665\u766D\u766E\u766F\u7671\u7674\u7681\u7685\u768C\u768D\u7695\u769B\u769C\u769D\u769F\u76A0\u76A2", 6, "\u76AA\u76AD\u76BD\u76C1\u76C5\u76C9\u76CB\u76CC\u76CE\u76D4\u76D9\u76E0\u76E6\u76E8\u76EC\u76F0\u76F1\u76F6\u76F9\u76FC\u7700\u7706\u770A\u770E\u7712\u7714\u7715\u7717\u7719\u771A\u771C\u7722\u7728\u772D\u772E\u772F\u7734\u7735\u7736\u7739\u773D\u773E\u7742\u7745\u7746\u774A\u774D\u774E\u774F\u7752\u7756\u7757\u775C\u775E\u775F\u7760\u7762"],
      ["8fcfa1", "\u7764\u7767\u776A\u776C\u7770\u7772\u7773\u7774\u777A\u777D\u7780\u7784\u778C\u778D\u7794\u7795\u7796\u779A\u779F\u77A2\u77A7\u77AA\u77AE\u77AF\u77B1\u77B5\u77BE\u77C3\u77C9\u77D1\u77D2\u77D5\u77D9\u77DE\u77DF\u77E0\u77E4\u77E6\u77EA\u77EC\u77F0\u77F1\u77F4\u77F8\u77FB\u7805\u7806\u7809\u780D\u780E\u7811\u781D\u7821\u7822\u7823\u782D\u782E\u7830\u7835\u7837\u7843\u7844\u7847\u7848\u784C\u784E\u7852\u785C\u785E\u7860\u7861\u7863\u7864\u7868\u786A\u786E\u787A\u787E\u788A\u788F\u7894\u7898\u78A1\u789D\u789E\u789F\u78A4\u78A8\u78AC\u78AD\u78B0\u78B1\u78B2\u78B3"],
      ["8fd0a1", "\u78BB\u78BD\u78BF\u78C7\u78C8\u78C9\u78CC\u78CE\u78D2\u78D3\u78D5\u78D6\u78E4\u78DB\u78DF\u78E0\u78E1\u78E6\u78EA\u78F2\u78F3\u7900\u78F6\u78F7\u78FA\u78FB\u78FF\u7906\u790C\u7910\u791A\u791C\u791E\u791F\u7920\u7925\u7927\u7929\u792D\u7931\u7934\u7935\u793B\u793D\u793F\u7944\u7945\u7946\u794A\u794B\u794F\u7951\u7954\u7958\u795B\u795C\u7967\u7969\u796B\u7972\u7979\u797B\u797C\u797E\u798B\u798C\u7991\u7993\u7994\u7995\u7996\u7998\u799B\u799C\u79A1\u79A8\u79A9\u79AB\u79AF\u79B1\u79B4\u79B8\u79BB\u79C2\u79C4\u79C7\u79C8\u79CA\u79CF\u79D4\u79D6\u79DA\u79DD\u79DE"],
      ["8fd1a1", "\u79E0\u79E2\u79E5\u79EA\u79EB\u79ED\u79F1\u79F8\u79FC\u7A02\u7A03\u7A07\u7A09\u7A0A\u7A0C\u7A11\u7A15\u7A1B\u7A1E\u7A21\u7A27\u7A2B\u7A2D\u7A2F\u7A30\u7A34\u7A35\u7A38\u7A39\u7A3A\u7A44\u7A45\u7A47\u7A48\u7A4C\u7A55\u7A56\u7A59\u7A5C\u7A5D\u7A5F\u7A60\u7A65\u7A67\u7A6A\u7A6D\u7A75\u7A78\u7A7E\u7A80\u7A82\u7A85\u7A86\u7A8A\u7A8B\u7A90\u7A91\u7A94\u7A9E\u7AA0\u7AA3\u7AAC\u7AB3\u7AB5\u7AB9\u7ABB\u7ABC\u7AC6\u7AC9\u7ACC\u7ACE\u7AD1\u7ADB\u7AE8\u7AE9\u7AEB\u7AEC\u7AF1\u7AF4\u7AFB\u7AFD\u7AFE\u7B07\u7B14\u7B1F\u7B23\u7B27\u7B29\u7B2A\u7B2B\u7B2D\u7B2E\u7B2F\u7B30"],
      ["8fd2a1", "\u7B31\u7B34\u7B3D\u7B3F\u7B40\u7B41\u7B47\u7B4E\u7B55\u7B60\u7B64\u7B66\u7B69\u7B6A\u7B6D\u7B6F\u7B72\u7B73\u7B77\u7B84\u7B89\u7B8E\u7B90\u7B91\u7B96\u7B9B\u7B9E\u7BA0\u7BA5\u7BAC\u7BAF\u7BB0\u7BB2\u7BB5\u7BB6\u7BBA\u7BBB\u7BBC\u7BBD\u7BC2\u7BC5\u7BC8\u7BCA\u7BD4\u7BD6\u7BD7\u7BD9\u7BDA\u7BDB\u7BE8\u7BEA\u7BF2\u7BF4\u7BF5\u7BF8\u7BF9\u7BFA\u7BFC\u7BFE\u7C01\u7C02\u7C03\u7C04\u7C06\u7C09\u7C0B\u7C0C\u7C0E\u7C0F\u7C19\u7C1B\u7C20\u7C25\u7C26\u7C28\u7C2C\u7C31\u7C33\u7C34\u7C36\u7C39\u7C3A\u7C46\u7C4A\u7C55\u7C51\u7C52\u7C53\u7C59", 5],
      ["8fd3a1", "\u7C61\u7C63\u7C67\u7C69\u7C6D\u7C6E\u7C70\u7C72\u7C79\u7C7C\u7C7D\u7C86\u7C87\u7C8F\u7C94\u7C9E\u7CA0\u7CA6\u7CB0\u7CB6\u7CB7\u7CBA\u7CBB\u7CBC\u7CBF\u7CC4\u7CC7\u7CC8\u7CC9\u7CCD\u7CCF\u7CD3\u7CD4\u7CD5\u7CD7\u7CD9\u7CDA\u7CDD\u7CE6\u7CE9\u7CEB\u7CF5\u7D03\u7D07\u7D08\u7D09\u7D0F\u7D11\u7D12\u7D13\u7D16\u7D1D\u7D1E\u7D23\u7D26\u7D2A\u7D2D\u7D31\u7D3C\u7D3D\u7D3E\u7D40\u7D41\u7D47\u7D48\u7D4D\u7D51\u7D53\u7D57\u7D59\u7D5A\u7D5C\u7D5D\u7D65\u7D67\u7D6A\u7D70\u7D78\u7D7A\u7D7B\u7D7F\u7D81\u7D82\u7D83\u7D85\u7D86\u7D88\u7D8B\u7D8C\u7D8D\u7D91\u7D96\u7D97\u7D9D"],
      ["8fd4a1", "\u7D9E\u7DA6\u7DA7\u7DAA\u7DB3\u7DB6\u7DB7\u7DB9\u7DC2", 4, "\u7DCC\u7DCD\u7DCE\u7DD7\u7DD9\u7E00\u7DE2\u7DE5\u7DE6\u7DEA\u7DEB\u7DED\u7DF1\u7DF5\u7DF6\u7DF9\u7DFA\u7E08\u7E10\u7E11\u7E15\u7E17\u7E1C\u7E1D\u7E20\u7E27\u7E28\u7E2C\u7E2D\u7E2F\u7E33\u7E36\u7E3F\u7E44\u7E45\u7E47\u7E4E\u7E50\u7E52\u7E58\u7E5F\u7E61\u7E62\u7E65\u7E6B\u7E6E\u7E6F\u7E73\u7E78\u7E7E\u7E81\u7E86\u7E87\u7E8A\u7E8D\u7E91\u7E95\u7E98\u7E9A\u7E9D\u7E9E\u7F3C\u7F3B\u7F3D\u7F3E\u7F3F\u7F43\u7F44\u7F47\u7F4F\u7F52\u7F53\u7F5B\u7F5C\u7F5D\u7F61\u7F63\u7F64\u7F65\u7F66\u7F6D"],
      ["8fd5a1", "\u7F71\u7F7D\u7F7E\u7F7F\u7F80\u7F8B\u7F8D\u7F8F\u7F90\u7F91\u7F96\u7F97\u7F9C\u7FA1\u7FA2\u7FA6\u7FAA\u7FAD\u7FB4\u7FBC\u7FBF\u7FC0\u7FC3\u7FC8\u7FCE\u7FCF\u7FDB\u7FDF\u7FE3\u7FE5\u7FE8\u7FEC\u7FEE\u7FEF\u7FF2\u7FFA\u7FFD\u7FFE\u7FFF\u8007\u8008\u800A\u800D\u800E\u800F\u8011\u8013\u8014\u8016\u801D\u801E\u801F\u8020\u8024\u8026\u802C\u802E\u8030\u8034\u8035\u8037\u8039\u803A\u803C\u803E\u8040\u8044\u8060\u8064\u8066\u806D\u8071\u8075\u8081\u8088\u808E\u809C\u809E\u80A6\u80A7\u80AB\u80B8\u80B9\u80C8\u80CD\u80CF\u80D2\u80D4\u80D5\u80D7\u80D8\u80E0\u80ED\u80EE"],
      ["8fd6a1", "\u80F0\u80F2\u80F3\u80F6\u80F9\u80FA\u80FE\u8103\u810B\u8116\u8117\u8118\u811C\u811E\u8120\u8124\u8127\u812C\u8130\u8135\u813A\u813C\u8145\u8147\u814A\u814C\u8152\u8157\u8160\u8161\u8167\u8168\u8169\u816D\u816F\u8177\u8181\u8190\u8184\u8185\u8186\u818B\u818E\u8196\u8198\u819B\u819E\u81A2\u81AE\u81B2\u81B4\u81BB\u81CB\u81C3\u81C5\u81CA\u81CE\u81CF\u81D5\u81D7\u81DB\u81DD\u81DE\u81E1\u81E4\u81EB\u81EC\u81F0\u81F1\u81F2\u81F5\u81F6\u81F8\u81F9\u81FD\u81FF\u8200\u8203\u820F\u8213\u8214\u8219\u821A\u821D\u8221\u8222\u8228\u8232\u8234\u823A\u8243\u8244\u8245\u8246"],
      ["8fd7a1", "\u824B\u824E\u824F\u8251\u8256\u825C\u8260\u8263\u8267\u826D\u8274\u827B\u827D\u827F\u8280\u8281\u8283\u8284\u8287\u8289\u828A\u828E\u8291\u8294\u8296\u8298\u829A\u829B\u82A0\u82A1\u82A3\u82A4\u82A7\u82A8\u82A9\u82AA\u82AE\u82B0\u82B2\u82B4\u82B7\u82BA\u82BC\u82BE\u82BF\u82C6\u82D0\u82D5\u82DA\u82E0\u82E2\u82E4\u82E8\u82EA\u82ED\u82EF\u82F6\u82F7\u82FD\u82FE\u8300\u8301\u8307\u8308\u830A\u830B\u8354\u831B\u831D\u831E\u831F\u8321\u8322\u832C\u832D\u832E\u8330\u8333\u8337\u833A\u833C\u833D\u8342\u8343\u8344\u8347\u834D\u834E\u8351\u8355\u8356\u8357\u8370\u8378"],
      ["8fd8a1", "\u837D\u837F\u8380\u8382\u8384\u8386\u838D\u8392\u8394\u8395\u8398\u8399\u839B\u839C\u839D\u83A6\u83A7\u83A9\u83AC\u83BE\u83BF\u83C0\u83C7\u83C9\u83CF\u83D0\u83D1\u83D4\u83DD\u8353\u83E8\u83EA\u83F6\u83F8\u83F9\u83FC\u8401\u8406\u840A\u840F\u8411\u8415\u8419\u83AD\u842F\u8439\u8445\u8447\u8448\u844A\u844D\u844F\u8451\u8452\u8456\u8458\u8459\u845A\u845C\u8460\u8464\u8465\u8467\u846A\u8470\u8473\u8474\u8476\u8478\u847C\u847D\u8481\u8485\u8492\u8493\u8495\u849E\u84A6\u84A8\u84A9\u84AA\u84AF\u84B1\u84B4\u84BA\u84BD\u84BE\u84C0\u84C2\u84C7\u84C8\u84CC\u84CF\u84D3"],
      ["8fd9a1", "\u84DC\u84E7\u84EA\u84EF\u84F0\u84F1\u84F2\u84F7\u8532\u84FA\u84FB\u84FD\u8502\u8503\u8507\u850C\u850E\u8510\u851C\u851E\u8522\u8523\u8524\u8525\u8527\u852A\u852B\u852F\u8533\u8534\u8536\u853F\u8546\u854F", 4, "\u8556\u8559\u855C", 6, "\u8564\u856B\u856F\u8579\u857A\u857B\u857D\u857F\u8581\u8585\u8586\u8589\u858B\u858C\u858F\u8593\u8598\u859D\u859F\u85A0\u85A2\u85A5\u85A7\u85B4\u85B6\u85B7\u85B8\u85BC\u85BD\u85BE\u85BF\u85C2\u85C7\u85CA\u85CB\u85CE\u85AD\u85D8\u85DA\u85DF\u85E0\u85E6\u85E8\u85ED\u85F3\u85F6\u85FC"],
      ["8fdaa1", "\u85FF\u8600\u8604\u8605\u860D\u860E\u8610\u8611\u8612\u8618\u8619\u861B\u861E\u8621\u8627\u8629\u8636\u8638\u863A\u863C\u863D\u8640\u8642\u8646\u8652\u8653\u8656\u8657\u8658\u8659\u865D\u8660", 4, "\u8669\u866C\u866F\u8675\u8676\u8677\u867A\u868D\u8691\u8696\u8698\u869A\u869C\u86A1\u86A6\u86A7\u86A8\u86AD\u86B1\u86B3\u86B4\u86B5\u86B7\u86B8\u86B9\u86BF\u86C0\u86C1\u86C3\u86C5\u86D1\u86D2\u86D5\u86D7\u86DA\u86DC\u86E0\u86E3\u86E5\u86E7\u8688\u86FA\u86FC\u86FD\u8704\u8705\u8707\u870B\u870E\u870F\u8710\u8713\u8714\u8719\u871E\u871F\u8721\u8723"],
      ["8fdba1", "\u8728\u872E\u872F\u8731\u8732\u8739\u873A\u873C\u873D\u873E\u8740\u8743\u8745\u874D\u8758\u875D\u8761\u8764\u8765\u876F\u8771\u8772\u877B\u8783", 6, "\u878B\u878C\u8790\u8793\u8795\u8797\u8798\u8799\u879E\u87A0\u87A3\u87A7\u87AC\u87AD\u87AE\u87B1\u87B5\u87BE\u87BF\u87C1\u87C8\u87C9\u87CA\u87CE\u87D5\u87D6\u87D9\u87DA\u87DC\u87DF\u87E2\u87E3\u87E4\u87EA\u87EB\u87ED\u87F1\u87F3\u87F8\u87FA\u87FF\u8801\u8803\u8806\u8809\u880A\u880B\u8810\u8819\u8812\u8813\u8814\u8818\u881A\u881B\u881C\u881E\u881F\u8828\u882D\u882E\u8830\u8832\u8835"],
      ["8fdca1", "\u883A\u883C\u8841\u8843\u8845\u8848\u8849\u884A\u884B\u884E\u8851\u8855\u8856\u8858\u885A\u885C\u885F\u8860\u8864\u8869\u8871\u8879\u887B\u8880\u8898\u889A\u889B\u889C\u889F\u88A0\u88A8\u88AA\u88BA\u88BD\u88BE\u88C0\u88CA", 4, "\u88D1\u88D2\u88D3\u88DB\u88DE\u88E7\u88EF\u88F0\u88F1\u88F5\u88F7\u8901\u8906\u890D\u890E\u890F\u8915\u8916\u8918\u8919\u891A\u891C\u8920\u8926\u8927\u8928\u8930\u8931\u8932\u8935\u8939\u893A\u893E\u8940\u8942\u8945\u8946\u8949\u894F\u8952\u8957\u895A\u895B\u895C\u8961\u8962\u8963\u896B\u896E\u8970\u8973\u8975\u897A"],
      ["8fdda1", "\u897B\u897C\u897D\u8989\u898D\u8990\u8994\u8995\u899B\u899C\u899F\u89A0\u89A5\u89B0\u89B4\u89B5\u89B6\u89B7\u89BC\u89D4", 4, "\u89E5\u89E9\u89EB\u89ED\u89F1\u89F3\u89F6\u89F9\u89FD\u89FF\u8A04\u8A05\u8A07\u8A0F\u8A11\u8A12\u8A14\u8A15\u8A1E\u8A20\u8A22\u8A24\u8A26\u8A2B\u8A2C\u8A2F\u8A35\u8A37\u8A3D\u8A3E\u8A40\u8A43\u8A45\u8A47\u8A49\u8A4D\u8A4E\u8A53\u8A56\u8A57\u8A58\u8A5C\u8A5D\u8A61\u8A65\u8A67\u8A75\u8A76\u8A77\u8A79\u8A7A\u8A7B\u8A7E\u8A7F\u8A80\u8A83\u8A86\u8A8B\u8A8F\u8A90\u8A92\u8A96\u8A97\u8A99\u8A9F\u8AA7\u8AA9\u8AAE\u8AAF\u8AB3"],
      ["8fdea1", "\u8AB6\u8AB7\u8ABB\u8ABE\u8AC3\u8AC6\u8AC8\u8AC9\u8ACA\u8AD1\u8AD3\u8AD4\u8AD5\u8AD7\u8ADD\u8ADF\u8AEC\u8AF0\u8AF4\u8AF5\u8AF6\u8AFC\u8AFF\u8B05\u8B06\u8B0B\u8B11\u8B1C\u8B1E\u8B1F\u8B0A\u8B2D\u8B30\u8B37\u8B3C\u8B42", 4, "\u8B48\u8B52\u8B53\u8B54\u8B59\u8B4D\u8B5E\u8B63\u8B6D\u8B76\u8B78\u8B79\u8B7C\u8B7E\u8B81\u8B84\u8B85\u8B8B\u8B8D\u8B8F\u8B94\u8B95\u8B9C\u8B9E\u8B9F\u8C38\u8C39\u8C3D\u8C3E\u8C45\u8C47\u8C49\u8C4B\u8C4F\u8C51\u8C53\u8C54\u8C57\u8C58\u8C5B\u8C5D\u8C59\u8C63\u8C64\u8C66\u8C68\u8C69\u8C6D\u8C73\u8C75\u8C76\u8C7B\u8C7E\u8C86"],
      ["8fdfa1", "\u8C87\u8C8B\u8C90\u8C92\u8C93\u8C99\u8C9B\u8C9C\u8CA4\u8CB9\u8CBA\u8CC5\u8CC6\u8CC9\u8CCB\u8CCF\u8CD6\u8CD5\u8CD9\u8CDD\u8CE1\u8CE8\u8CEC\u8CEF\u8CF0\u8CF2\u8CF5\u8CF7\u8CF8\u8CFE\u8CFF\u8D01\u8D03\u8D09\u8D12\u8D17\u8D1B\u8D65\u8D69\u8D6C\u8D6E\u8D7F\u8D82\u8D84\u8D88\u8D8D\u8D90\u8D91\u8D95\u8D9E\u8D9F\u8DA0\u8DA6\u8DAB\u8DAC\u8DAF\u8DB2\u8DB5\u8DB7\u8DB9\u8DBB\u8DC0\u8DC5\u8DC6\u8DC7\u8DC8\u8DCA\u8DCE\u8DD1\u8DD4\u8DD5\u8DD7\u8DD9\u8DE4\u8DE5\u8DE7\u8DEC\u8DF0\u8DBC\u8DF1\u8DF2\u8DF4\u8DFD\u8E01\u8E04\u8E05\u8E06\u8E0B\u8E11\u8E14\u8E16\u8E20\u8E21\u8E22"],
      ["8fe0a1", "\u8E23\u8E26\u8E27\u8E31\u8E33\u8E36\u8E37\u8E38\u8E39\u8E3D\u8E40\u8E41\u8E4B\u8E4D\u8E4E\u8E4F\u8E54\u8E5B\u8E5C\u8E5D\u8E5E\u8E61\u8E62\u8E69\u8E6C\u8E6D\u8E6F\u8E70\u8E71\u8E79\u8E7A\u8E7B\u8E82\u8E83\u8E89\u8E90\u8E92\u8E95\u8E9A\u8E9B\u8E9D\u8E9E\u8EA2\u8EA7\u8EA9\u8EAD\u8EAE\u8EB3\u8EB5\u8EBA\u8EBB\u8EC0\u8EC1\u8EC3\u8EC4\u8EC7\u8ECF\u8ED1\u8ED4\u8EDC\u8EE8\u8EEE\u8EF0\u8EF1\u8EF7\u8EF9\u8EFA\u8EED\u8F00\u8F02\u8F07\u8F08\u8F0F\u8F10\u8F16\u8F17\u8F18\u8F1E\u8F20\u8F21\u8F23\u8F25\u8F27\u8F28\u8F2C\u8F2D\u8F2E\u8F34\u8F35\u8F36\u8F37\u8F3A\u8F40\u8F41"],
      ["8fe1a1", "\u8F43\u8F47\u8F4F\u8F51", 4, "\u8F58\u8F5D\u8F5E\u8F65\u8F9D\u8FA0\u8FA1\u8FA4\u8FA5\u8FA6\u8FB5\u8FB6\u8FB8\u8FBE\u8FC0\u8FC1\u8FC6\u8FCA\u8FCB\u8FCD\u8FD0\u8FD2\u8FD3\u8FD5\u8FE0\u8FE3\u8FE4\u8FE8\u8FEE\u8FF1\u8FF5\u8FF6\u8FFB\u8FFE\u9002\u9004\u9008\u900C\u9018\u901B\u9028\u9029\u902F\u902A\u902C\u902D\u9033\u9034\u9037\u903F\u9043\u9044\u904C\u905B\u905D\u9062\u9066\u9067\u906C\u9070\u9074\u9079\u9085\u9088\u908B\u908C\u908E\u9090\u9095\u9097\u9098\u9099\u909B\u90A0\u90A1\u90A2\u90A5\u90B0\u90B2\u90B3\u90B4\u90B6\u90BD\u90CC\u90BE\u90C3"],
      ["8fe2a1", "\u90C4\u90C5\u90C7\u90C8\u90D5\u90D7\u90D8\u90D9\u90DC\u90DD\u90DF\u90E5\u90D2\u90F6\u90EB\u90EF\u90F0\u90F4\u90FE\u90FF\u9100\u9104\u9105\u9106\u9108\u910D\u9110\u9114\u9116\u9117\u9118\u911A\u911C\u911E\u9120\u9125\u9122\u9123\u9127\u9129\u912E\u912F\u9131\u9134\u9136\u9137\u9139\u913A\u913C\u913D\u9143\u9147\u9148\u914F\u9153\u9157\u9159\u915A\u915B\u9161\u9164\u9167\u916D\u9174\u9179\u917A\u917B\u9181\u9183\u9185\u9186\u918A\u918E\u9191\u9193\u9194\u9195\u9198\u919E\u91A1\u91A6\u91A8\u91AC\u91AD\u91AE\u91B0\u91B1\u91B2\u91B3\u91B6\u91BB\u91BC\u91BD\u91BF"],
      ["8fe3a1", "\u91C2\u91C3\u91C5\u91D3\u91D4\u91D7\u91D9\u91DA\u91DE\u91E4\u91E5\u91E9\u91EA\u91EC", 5, "\u91F7\u91F9\u91FB\u91FD\u9200\u9201\u9204\u9205\u9206\u9207\u9209\u920A\u920C\u9210\u9212\u9213\u9216\u9218\u921C\u921D\u9223\u9224\u9225\u9226\u9228\u922E\u922F\u9230\u9233\u9235\u9236\u9238\u9239\u923A\u923C\u923E\u9240\u9242\u9243\u9246\u9247\u924A\u924D\u924E\u924F\u9251\u9258\u9259\u925C\u925D\u9260\u9261\u9265\u9267\u9268\u9269\u926E\u926F\u9270\u9275", 4, "\u927B\u927C\u927D\u927F\u9288\u9289\u928A\u928D\u928E\u9292\u9297"],
      ["8fe4a1", "\u9299\u929F\u92A0\u92A4\u92A5\u92A7\u92A8\u92AB\u92AF\u92B2\u92B6\u92B8\u92BA\u92BB\u92BC\u92BD\u92BF", 4, "\u92C5\u92C6\u92C7\u92C8\u92CB\u92CC\u92CD\u92CE\u92D0\u92D3\u92D5\u92D7\u92D8\u92D9\u92DC\u92DD\u92DF\u92E0\u92E1\u92E3\u92E5\u92E7\u92E8\u92EC\u92EE\u92F0\u92F9\u92FB\u92FF\u9300\u9302\u9308\u930D\u9311\u9314\u9315\u931C\u931D\u931E\u931F\u9321\u9324\u9325\u9327\u9329\u932A\u9333\u9334\u9336\u9337\u9347\u9348\u9349\u9350\u9351\u9352\u9355\u9357\u9358\u935A\u935E\u9364\u9365\u9367\u9369\u936A\u936D\u936F\u9370\u9371\u9373\u9374\u9376"],
      ["8fe5a1", "\u937A\u937D\u937F\u9380\u9381\u9382\u9388\u938A\u938B\u938D\u938F\u9392\u9395\u9398\u939B\u939E\u93A1\u93A3\u93A4\u93A6\u93A8\u93AB\u93B4\u93B5\u93B6\u93BA\u93A9\u93C1\u93C4\u93C5\u93C6\u93C7\u93C9", 4, "\u93D3\u93D9\u93DC\u93DE\u93DF\u93E2\u93E6\u93E7\u93F9\u93F7\u93F8\u93FA\u93FB\u93FD\u9401\u9402\u9404\u9408\u9409\u940D\u940E\u940F\u9415\u9416\u9417\u941F\u942E\u942F\u9431\u9432\u9433\u9434\u943B\u943F\u943D\u9443\u9445\u9448\u944A\u944C\u9455\u9459\u945C\u945F\u9461\u9463\u9468\u946B\u946D\u946E\u946F\u9471\u9472\u9484\u9483\u9578\u9579"],
      ["8fe6a1", "\u957E\u9584\u9588\u958C\u958D\u958E\u959D\u959E\u959F\u95A1\u95A6\u95A9\u95AB\u95AC\u95B4\u95B6\u95BA\u95BD\u95BF\u95C6\u95C8\u95C9\u95CB\u95D0\u95D1\u95D2\u95D3\u95D9\u95DA\u95DD\u95DE\u95DF\u95E0\u95E4\u95E6\u961D\u961E\u9622\u9624\u9625\u9626\u962C\u9631\u9633\u9637\u9638\u9639\u963A\u963C\u963D\u9641\u9652\u9654\u9656\u9657\u9658\u9661\u966E\u9674\u967B\u967C\u967E\u967F\u9681\u9682\u9683\u9684\u9689\u9691\u9696\u969A\u969D\u969F\u96A4\u96A5\u96A6\u96A9\u96AE\u96AF\u96B3\u96BA\u96CA\u96D2\u5DB2\u96D8\u96DA\u96DD\u96DE\u96DF\u96E9\u96EF\u96F1\u96FA\u9702"],
      ["8fe7a1", "\u9703\u9705\u9709\u971A\u971B\u971D\u9721\u9722\u9723\u9728\u9731\u9733\u9741\u9743\u974A\u974E\u974F\u9755\u9757\u9758\u975A\u975B\u9763\u9767\u976A\u976E\u9773\u9776\u9777\u9778\u977B\u977D\u977F\u9780\u9789\u9795\u9796\u9797\u9799\u979A\u979E\u979F\u97A2\u97AC\u97AE\u97B1\u97B2\u97B5\u97B6\u97B8\u97B9\u97BA\u97BC\u97BE\u97BF\u97C1\u97C4\u97C5\u97C7\u97C9\u97CA\u97CC\u97CD\u97CE\u97D0\u97D1\u97D4\u97D7\u97D8\u97D9\u97DD\u97DE\u97E0\u97DB\u97E1\u97E4\u97EF\u97F1\u97F4\u97F7\u97F8\u97FA\u9807\u980A\u9819\u980D\u980E\u9814\u9816\u981C\u981E\u9820\u9823\u9826"],
      ["8fe8a1", "\u982B\u982E\u982F\u9830\u9832\u9833\u9835\u9825\u983E\u9844\u9847\u984A\u9851\u9852\u9853\u9856\u9857\u9859\u985A\u9862\u9863\u9865\u9866\u986A\u986C\u98AB\u98AD\u98AE\u98B0\u98B4\u98B7\u98B8\u98BA\u98BB\u98BF\u98C2\u98C5\u98C8\u98CC\u98E1\u98E3\u98E5\u98E6\u98E7\u98EA\u98F3\u98F6\u9902\u9907\u9908\u9911\u9915\u9916\u9917\u991A\u991B\u991C\u991F\u9922\u9926\u9927\u992B\u9931", 4, "\u9939\u993A\u993B\u993C\u9940\u9941\u9946\u9947\u9948\u994D\u994E\u9954\u9958\u9959\u995B\u995C\u995E\u995F\u9960\u999B\u999D\u999F\u99A6\u99B0\u99B1\u99B2\u99B5"],
      ["8fe9a1", "\u99B9\u99BA\u99BD\u99BF\u99C3\u99C9\u99D3\u99D4\u99D9\u99DA\u99DC\u99DE\u99E7\u99EA\u99EB\u99EC\u99F0\u99F4\u99F5\u99F9\u99FD\u99FE\u9A02\u9A03\u9A04\u9A0B\u9A0C\u9A10\u9A11\u9A16\u9A1E\u9A20\u9A22\u9A23\u9A24\u9A27\u9A2D\u9A2E\u9A33\u9A35\u9A36\u9A38\u9A47\u9A41\u9A44\u9A4A\u9A4B\u9A4C\u9A4E\u9A51\u9A54\u9A56\u9A5D\u9AAA\u9AAC\u9AAE\u9AAF\u9AB2\u9AB4\u9AB5\u9AB6\u9AB9\u9ABB\u9ABE\u9ABF\u9AC1\u9AC3\u9AC6\u9AC8\u9ACE\u9AD0\u9AD2\u9AD5\u9AD6\u9AD7\u9ADB\u9ADC\u9AE0\u9AE4\u9AE5\u9AE7\u9AE9\u9AEC\u9AF2\u9AF3\u9AF5\u9AF9\u9AFA\u9AFD\u9AFF", 4],
      ["8feaa1", "\u9B04\u9B05\u9B08\u9B09\u9B0B\u9B0C\u9B0D\u9B0E\u9B10\u9B12\u9B16\u9B19\u9B1B\u9B1C\u9B20\u9B26\u9B2B\u9B2D\u9B33\u9B34\u9B35\u9B37\u9B39\u9B3A\u9B3D\u9B48\u9B4B\u9B4C\u9B55\u9B56\u9B57\u9B5B\u9B5E\u9B61\u9B63\u9B65\u9B66\u9B68\u9B6A", 4, "\u9B73\u9B75\u9B77\u9B78\u9B79\u9B7F\u9B80\u9B84\u9B85\u9B86\u9B87\u9B89\u9B8A\u9B8B\u9B8D\u9B8F\u9B90\u9B94\u9B9A\u9B9D\u9B9E\u9BA6\u9BA7\u9BA9\u9BAC\u9BB0\u9BB1\u9BB2\u9BB7\u9BB8\u9BBB\u9BBC\u9BBE\u9BBF\u9BC1\u9BC7\u9BC8\u9BCE\u9BD0\u9BD7\u9BD8\u9BDD\u9BDF\u9BE5\u9BE7\u9BEA\u9BEB\u9BEF\u9BF3\u9BF7\u9BF8"],
      ["8feba1", "\u9BF9\u9BFA\u9BFD\u9BFF\u9C00\u9C02\u9C0B\u9C0F\u9C11\u9C16\u9C18\u9C19\u9C1A\u9C1C\u9C1E\u9C22\u9C23\u9C26", 4, "\u9C31\u9C35\u9C36\u9C37\u9C3D\u9C41\u9C43\u9C44\u9C45\u9C49\u9C4A\u9C4E\u9C4F\u9C50\u9C53\u9C54\u9C56\u9C58\u9C5B\u9C5D\u9C5E\u9C5F\u9C63\u9C69\u9C6A\u9C5C\u9C6B\u9C68\u9C6E\u9C70\u9C72\u9C75\u9C77\u9C7B\u9CE6\u9CF2\u9CF7\u9CF9\u9D0B\u9D02\u9D11\u9D17\u9D18\u9D1C\u9D1D\u9D1E\u9D2F\u9D30\u9D32\u9D33\u9D34\u9D3A\u9D3C\u9D45\u9D3D\u9D42\u9D43\u9D47\u9D4A\u9D53\u9D54\u9D5F\u9D63\u9D62\u9D65\u9D69\u9D6A\u9D6B\u9D70\u9D76\u9D77\u9D7B"],
      ["8feca1", "\u9D7C\u9D7E\u9D83\u9D84\u9D86\u9D8A\u9D8D\u9D8E\u9D92\u9D93\u9D95\u9D96\u9D97\u9D98\u9DA1\u9DAA\u9DAC\u9DAE\u9DB1\u9DB5\u9DB9\u9DBC\u9DBF\u9DC3\u9DC7\u9DC9\u9DCA\u9DD4\u9DD5\u9DD6\u9DD7\u9DDA\u9DDE\u9DDF\u9DE0\u9DE5\u9DE7\u9DE9\u9DEB\u9DEE\u9DF0\u9DF3\u9DF4\u9DFE\u9E0A\u9E02\u9E07\u9E0E\u9E10\u9E11\u9E12\u9E15\u9E16\u9E19\u9E1C\u9E1D\u9E7A\u9E7B\u9E7C\u9E80\u9E82\u9E83\u9E84\u9E85\u9E87\u9E8E\u9E8F\u9E96\u9E98\u9E9B\u9E9E\u9EA4\u9EA8\u9EAC\u9EAE\u9EAF\u9EB0\u9EB3\u9EB4\u9EB5\u9EC6\u9EC8\u9ECB\u9ED5\u9EDF\u9EE4\u9EE7\u9EEC\u9EED\u9EEE\u9EF0\u9EF1\u9EF2\u9EF5"],
      ["8feda1", "\u9EF8\u9EFF\u9F02\u9F03\u9F09\u9F0F\u9F10\u9F11\u9F12\u9F14\u9F16\u9F17\u9F19\u9F1A\u9F1B\u9F1F\u9F22\u9F26\u9F2A\u9F2B\u9F2F\u9F31\u9F32\u9F34\u9F37\u9F39\u9F3A\u9F3C\u9F3D\u9F3F\u9F41\u9F43", 4, "\u9F53\u9F55\u9F56\u9F57\u9F58\u9F5A\u9F5D\u9F5E\u9F68\u9F69\u9F6D", 4, "\u9F73\u9F75\u9F7A\u9F7D\u9F8F\u9F90\u9F91\u9F92\u9F94\u9F96\u9F97\u9F9E\u9FA1\u9FA2\u9FA3\u9FA5"]
    ];
  }
});

// ../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/tables/cp936.json
var require_cp936 = __commonJS({
  "../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/tables/cp936.json"(exports, module) {
    module.exports = [
      ["0", "\0", 127, "\u20AC"],
      ["8140", "\u4E02\u4E04\u4E05\u4E06\u4E0F\u4E12\u4E17\u4E1F\u4E20\u4E21\u4E23\u4E26\u4E29\u4E2E\u4E2F\u4E31\u4E33\u4E35\u4E37\u4E3C\u4E40\u4E41\u4E42\u4E44\u4E46\u4E4A\u4E51\u4E55\u4E57\u4E5A\u4E5B\u4E62\u4E63\u4E64\u4E65\u4E67\u4E68\u4E6A", 5, "\u4E72\u4E74", 9, "\u4E7F", 6, "\u4E87\u4E8A"],
      ["8180", "\u4E90\u4E96\u4E97\u4E99\u4E9C\u4E9D\u4E9E\u4EA3\u4EAA\u4EAF\u4EB0\u4EB1\u4EB4\u4EB6\u4EB7\u4EB8\u4EB9\u4EBC\u4EBD\u4EBE\u4EC8\u4ECC\u4ECF\u4ED0\u4ED2\u4EDA\u4EDB\u4EDC\u4EE0\u4EE2\u4EE6\u4EE7\u4EE9\u4EED\u4EEE\u4EEF\u4EF1\u4EF4\u4EF8\u4EF9\u4EFA\u4EFC\u4EFE\u4F00\u4F02", 6, "\u4F0B\u4F0C\u4F12", 4, "\u4F1C\u4F1D\u4F21\u4F23\u4F28\u4F29\u4F2C\u4F2D\u4F2E\u4F31\u4F33\u4F35\u4F37\u4F39\u4F3B\u4F3E", 4, "\u4F44\u4F45\u4F47", 5, "\u4F52\u4F54\u4F56\u4F61\u4F62\u4F66\u4F68\u4F6A\u4F6B\u4F6D\u4F6E\u4F71\u4F72\u4F75\u4F77\u4F78\u4F79\u4F7A\u4F7D\u4F80\u4F81\u4F82\u4F85\u4F86\u4F87\u4F8A\u4F8C\u4F8E\u4F90\u4F92\u4F93\u4F95\u4F96\u4F98\u4F99\u4F9A\u4F9C\u4F9E\u4F9F\u4FA1\u4FA2"],
      ["8240", "\u4FA4\u4FAB\u4FAD\u4FB0", 4, "\u4FB6", 8, "\u4FC0\u4FC1\u4FC2\u4FC6\u4FC7\u4FC8\u4FC9\u4FCB\u4FCC\u4FCD\u4FD2", 4, "\u4FD9\u4FDB\u4FE0\u4FE2\u4FE4\u4FE5\u4FE7\u4FEB\u4FEC\u4FF0\u4FF2\u4FF4\u4FF5\u4FF6\u4FF7\u4FF9\u4FFB\u4FFC\u4FFD\u4FFF", 11],
      ["8280", "\u500B\u500E\u5010\u5011\u5013\u5015\u5016\u5017\u501B\u501D\u501E\u5020\u5022\u5023\u5024\u5027\u502B\u502F", 10, "\u503B\u503D\u503F\u5040\u5041\u5042\u5044\u5045\u5046\u5049\u504A\u504B\u504D\u5050", 4, "\u5056\u5057\u5058\u5059\u505B\u505D", 7, "\u5066", 5, "\u506D", 8, "\u5078\u5079\u507A\u507C\u507D\u5081\u5082\u5083\u5084\u5086\u5087\u5089\u508A\u508B\u508C\u508E", 20, "\u50A4\u50A6\u50AA\u50AB\u50AD", 4, "\u50B3", 6, "\u50BC"],
      ["8340", "\u50BD", 17, "\u50D0", 5, "\u50D7\u50D8\u50D9\u50DB", 10, "\u50E8\u50E9\u50EA\u50EB\u50EF\u50F0\u50F1\u50F2\u50F4\u50F6", 4, "\u50FC", 9, "\u5108"],
      ["8380", "\u5109\u510A\u510C", 5, "\u5113", 13, "\u5122", 28, "\u5142\u5147\u514A\u514C\u514E\u514F\u5150\u5152\u5153\u5157\u5158\u5159\u515B\u515D", 4, "\u5163\u5164\u5166\u5167\u5169\u516A\u516F\u5172\u517A\u517E\u517F\u5183\u5184\u5186\u5187\u518A\u518B\u518E\u518F\u5190\u5191\u5193\u5194\u5198\u519A\u519D\u519E\u519F\u51A1\u51A3\u51A6", 4, "\u51AD\u51AE\u51B4\u51B8\u51B9\u51BA\u51BE\u51BF\u51C1\u51C2\u51C3\u51C5\u51C8\u51CA\u51CD\u51CE\u51D0\u51D2", 5],
      ["8440", "\u51D8\u51D9\u51DA\u51DC\u51DE\u51DF\u51E2\u51E3\u51E5", 5, "\u51EC\u51EE\u51F1\u51F2\u51F4\u51F7\u51FE\u5204\u5205\u5209\u520B\u520C\u520F\u5210\u5213\u5214\u5215\u521C\u521E\u521F\u5221\u5222\u5223\u5225\u5226\u5227\u522A\u522C\u522F\u5231\u5232\u5234\u5235\u523C\u523E\u5244", 5, "\u524B\u524E\u524F\u5252\u5253\u5255\u5257\u5258"],
      ["8480", "\u5259\u525A\u525B\u525D\u525F\u5260\u5262\u5263\u5264\u5266\u5268\u526B\u526C\u526D\u526E\u5270\u5271\u5273", 9, "\u527E\u5280\u5283", 4, "\u5289", 6, "\u5291\u5292\u5294", 6, "\u529C\u52A4\u52A5\u52A6\u52A7\u52AE\u52AF\u52B0\u52B4", 9, "\u52C0\u52C1\u52C2\u52C4\u52C5\u52C6\u52C8\u52CA\u52CC\u52CD\u52CE\u52CF\u52D1\u52D3\u52D4\u52D5\u52D7\u52D9", 5, "\u52E0\u52E1\u52E2\u52E3\u52E5", 10, "\u52F1", 7, "\u52FB\u52FC\u52FD\u5301\u5302\u5303\u5304\u5307\u5309\u530A\u530B\u530C\u530E"],
      ["8540", "\u5311\u5312\u5313\u5314\u5318\u531B\u531C\u531E\u531F\u5322\u5324\u5325\u5327\u5328\u5329\u532B\u532C\u532D\u532F", 9, "\u533C\u533D\u5340\u5342\u5344\u5346\u534B\u534C\u534D\u5350\u5354\u5358\u5359\u535B\u535D\u5365\u5368\u536A\u536C\u536D\u5372\u5376\u5379\u537B\u537C\u537D\u537E\u5380\u5381\u5383\u5387\u5388\u538A\u538E\u538F"],
      ["8580", "\u5390", 4, "\u5396\u5397\u5399\u539B\u539C\u539E\u53A0\u53A1\u53A4\u53A7\u53AA\u53AB\u53AC\u53AD\u53AF", 6, "\u53B7\u53B8\u53B9\u53BA\u53BC\u53BD\u53BE\u53C0\u53C3", 4, "\u53CE\u53CF\u53D0\u53D2\u53D3\u53D5\u53DA\u53DC\u53DD\u53DE\u53E1\u53E2\u53E7\u53F4\u53FA\u53FE\u53FF\u5400\u5402\u5405\u5407\u540B\u5414\u5418\u5419\u541A\u541C\u5422\u5424\u5425\u542A\u5430\u5433\u5436\u5437\u543A\u543D\u543F\u5441\u5442\u5444\u5445\u5447\u5449\u544C\u544D\u544E\u544F\u5451\u545A\u545D", 4, "\u5463\u5465\u5467\u5469", 7, "\u5474\u5479\u547A\u547E\u547F\u5481\u5483\u5485\u5487\u5488\u5489\u548A\u548D\u5491\u5493\u5497\u5498\u549C\u549E\u549F\u54A0\u54A1"],
      ["8640", "\u54A2\u54A5\u54AE\u54B0\u54B2\u54B5\u54B6\u54B7\u54B9\u54BA\u54BC\u54BE\u54C3\u54C5\u54CA\u54CB\u54D6\u54D8\u54DB\u54E0", 4, "\u54EB\u54EC\u54EF\u54F0\u54F1\u54F4", 5, "\u54FB\u54FE\u5500\u5502\u5503\u5504\u5505\u5508\u550A", 4, "\u5512\u5513\u5515", 5, "\u551C\u551D\u551E\u551F\u5521\u5525\u5526"],
      ["8680", "\u5528\u5529\u552B\u552D\u5532\u5534\u5535\u5536\u5538\u5539\u553A\u553B\u553D\u5540\u5542\u5545\u5547\u5548\u554B", 4, "\u5551\u5552\u5553\u5554\u5557", 4, "\u555D\u555E\u555F\u5560\u5562\u5563\u5568\u5569\u556B\u556F", 5, "\u5579\u557A\u557D\u557F\u5585\u5586\u558C\u558D\u558E\u5590\u5592\u5593\u5595\u5596\u5597\u559A\u559B\u559E\u55A0", 6, "\u55A8", 8, "\u55B2\u55B4\u55B6\u55B8\u55BA\u55BC\u55BF", 4, "\u55C6\u55C7\u55C8\u55CA\u55CB\u55CE\u55CF\u55D0\u55D5\u55D7", 4, "\u55DE\u55E0\u55E2\u55E7\u55E9\u55ED\u55EE\u55F0\u55F1\u55F4\u55F6\u55F8", 4, "\u55FF\u5602\u5603\u5604\u5605"],
      ["8740", "\u5606\u5607\u560A\u560B\u560D\u5610", 7, "\u5619\u561A\u561C\u561D\u5620\u5621\u5622\u5625\u5626\u5628\u5629\u562A\u562B\u562E\u562F\u5630\u5633\u5635\u5637\u5638\u563A\u563C\u563D\u563E\u5640", 11, "\u564F", 4, "\u5655\u5656\u565A\u565B\u565D", 4],
      ["8780", "\u5663\u5665\u5666\u5667\u566D\u566E\u566F\u5670\u5672\u5673\u5674\u5675\u5677\u5678\u5679\u567A\u567D", 7, "\u5687", 6, "\u5690\u5691\u5692\u5694", 14, "\u56A4", 10, "\u56B0", 6, "\u56B8\u56B9\u56BA\u56BB\u56BD", 12, "\u56CB", 8, "\u56D5\u56D6\u56D8\u56D9\u56DC\u56E3\u56E5", 5, "\u56EC\u56EE\u56EF\u56F2\u56F3\u56F6\u56F7\u56F8\u56FB\u56FC\u5700\u5701\u5702\u5705\u5707\u570B", 6],
      ["8840", "\u5712", 9, "\u571D\u571E\u5720\u5721\u5722\u5724\u5725\u5726\u5727\u572B\u5731\u5732\u5734", 4, "\u573C\u573D\u573F\u5741\u5743\u5744\u5745\u5746\u5748\u5749\u574B\u5752", 4, "\u5758\u5759\u5762\u5763\u5765\u5767\u576C\u576E\u5770\u5771\u5772\u5774\u5775\u5778\u5779\u577A\u577D\u577E\u577F\u5780"],
      ["8880", "\u5781\u5787\u5788\u5789\u578A\u578D", 4, "\u5794", 6, "\u579C\u579D\u579E\u579F\u57A5\u57A8\u57AA\u57AC\u57AF\u57B0\u57B1\u57B3\u57B5\u57B6\u57B7\u57B9", 8, "\u57C4", 6, "\u57CC\u57CD\u57D0\u57D1\u57D3\u57D6\u57D7\u57DB\u57DC\u57DE\u57E1\u57E2\u57E3\u57E5", 7, "\u57EE\u57F0\u57F1\u57F2\u57F3\u57F5\u57F6\u57F7\u57FB\u57FC\u57FE\u57FF\u5801\u5803\u5804\u5805\u5808\u5809\u580A\u580C\u580E\u580F\u5810\u5812\u5813\u5814\u5816\u5817\u5818\u581A\u581B\u581C\u581D\u581F\u5822\u5823\u5825", 4, "\u582B", 4, "\u5831\u5832\u5833\u5834\u5836", 7],
      ["8940", "\u583E", 5, "\u5845", 6, "\u584E\u584F\u5850\u5852\u5853\u5855\u5856\u5857\u5859", 4, "\u585F", 5, "\u5866", 4, "\u586D", 16, "\u587F\u5882\u5884\u5886\u5887\u5888\u588A\u588B\u588C"],
      ["8980", "\u588D", 4, "\u5894", 4, "\u589B\u589C\u589D\u58A0", 7, "\u58AA", 17, "\u58BD\u58BE\u58BF\u58C0\u58C2\u58C3\u58C4\u58C6", 10, "\u58D2\u58D3\u58D4\u58D6", 13, "\u58E5", 5, "\u58ED\u58EF\u58F1\u58F2\u58F4\u58F5\u58F7\u58F8\u58FA", 7, "\u5903\u5905\u5906\u5908", 4, "\u590E\u5910\u5911\u5912\u5913\u5917\u5918\u591B\u591D\u591E\u5920\u5921\u5922\u5923\u5926\u5928\u592C\u5930\u5932\u5933\u5935\u5936\u593B"],
      ["8a40", "\u593D\u593E\u593F\u5940\u5943\u5945\u5946\u594A\u594C\u594D\u5950\u5952\u5953\u5959\u595B", 4, "\u5961\u5963\u5964\u5966", 12, "\u5975\u5977\u597A\u597B\u597C\u597E\u597F\u5980\u5985\u5989\u598B\u598C\u598E\u598F\u5990\u5991\u5994\u5995\u5998\u599A\u599B\u599C\u599D\u599F\u59A0\u59A1\u59A2\u59A6"],
      ["8a80", "\u59A7\u59AC\u59AD\u59B0\u59B1\u59B3", 5, "\u59BA\u59BC\u59BD\u59BF", 6, "\u59C7\u59C8\u59C9\u59CC\u59CD\u59CE\u59CF\u59D5\u59D6\u59D9\u59DB\u59DE", 4, "\u59E4\u59E6\u59E7\u59E9\u59EA\u59EB\u59ED", 11, "\u59FA\u59FC\u59FD\u59FE\u5A00\u5A02\u5A0A\u5A0B\u5A0D\u5A0E\u5A0F\u5A10\u5A12\u5A14\u5A15\u5A16\u5A17\u5A19\u5A1A\u5A1B\u5A1D\u5A1E\u5A21\u5A22\u5A24\u5A26\u5A27\u5A28\u5A2A", 6, "\u5A33\u5A35\u5A37", 4, "\u5A3D\u5A3E\u5A3F\u5A41", 4, "\u5A47\u5A48\u5A4B", 9, "\u5A56\u5A57\u5A58\u5A59\u5A5B", 5],
      ["8b40", "\u5A61\u5A63\u5A64\u5A65\u5A66\u5A68\u5A69\u5A6B", 8, "\u5A78\u5A79\u5A7B\u5A7C\u5A7D\u5A7E\u5A80", 17, "\u5A93", 6, "\u5A9C", 13, "\u5AAB\u5AAC"],
      ["8b80", "\u5AAD", 4, "\u5AB4\u5AB6\u5AB7\u5AB9", 4, "\u5ABF\u5AC0\u5AC3", 5, "\u5ACA\u5ACB\u5ACD", 4, "\u5AD3\u5AD5\u5AD7\u5AD9\u5ADA\u5ADB\u5ADD\u5ADE\u5ADF\u5AE2\u5AE4\u5AE5\u5AE7\u5AE8\u5AEA\u5AEC", 4, "\u5AF2", 22, "\u5B0A", 11, "\u5B18", 25, "\u5B33\u5B35\u5B36\u5B38", 7, "\u5B41", 6],
      ["8c40", "\u5B48", 7, "\u5B52\u5B56\u5B5E\u5B60\u5B61\u5B67\u5B68\u5B6B\u5B6D\u5B6E\u5B6F\u5B72\u5B74\u5B76\u5B77\u5B78\u5B79\u5B7B\u5B7C\u5B7E\u5B7F\u5B82\u5B86\u5B8A\u5B8D\u5B8E\u5B90\u5B91\u5B92\u5B94\u5B96\u5B9F\u5BA7\u5BA8\u5BA9\u5BAC\u5BAD\u5BAE\u5BAF\u5BB1\u5BB2\u5BB7\u5BBA\u5BBB\u5BBC\u5BC0\u5BC1\u5BC3\u5BC8\u5BC9\u5BCA\u5BCB\u5BCD\u5BCE\u5BCF"],
      ["8c80", "\u5BD1\u5BD4", 8, "\u5BE0\u5BE2\u5BE3\u5BE6\u5BE7\u5BE9", 4, "\u5BEF\u5BF1", 6, "\u5BFD\u5BFE\u5C00\u5C02\u5C03\u5C05\u5C07\u5C08\u5C0B\u5C0C\u5C0D\u5C0E\u5C10\u5C12\u5C13\u5C17\u5C19\u5C1B\u5C1E\u5C1F\u5C20\u5C21\u5C23\u5C26\u5C28\u5C29\u5C2A\u5C2B\u5C2D\u5C2E\u5C2F\u5C30\u5C32\u5C33\u5C35\u5C36\u5C37\u5C43\u5C44\u5C46\u5C47\u5C4C\u5C4D\u5C52\u5C53\u5C54\u5C56\u5C57\u5C58\u5C5A\u5C5B\u5C5C\u5C5D\u5C5F\u5C62\u5C64\u5C67", 6, "\u5C70\u5C72", 6, "\u5C7B\u5C7C\u5C7D\u5C7E\u5C80\u5C83", 4, "\u5C89\u5C8A\u5C8B\u5C8E\u5C8F\u5C92\u5C93\u5C95\u5C9D", 4, "\u5CA4", 4],
      ["8d40", "\u5CAA\u5CAE\u5CAF\u5CB0\u5CB2\u5CB4\u5CB6\u5CB9\u5CBA\u5CBB\u5CBC\u5CBE\u5CC0\u5CC2\u5CC3\u5CC5", 5, "\u5CCC", 5, "\u5CD3", 5, "\u5CDA", 6, "\u5CE2\u5CE3\u5CE7\u5CE9\u5CEB\u5CEC\u5CEE\u5CEF\u5CF1", 9, "\u5CFC", 4],
      ["8d80", "\u5D01\u5D04\u5D05\u5D08", 5, "\u5D0F", 4, "\u5D15\u5D17\u5D18\u5D19\u5D1A\u5D1C\u5D1D\u5D1F", 4, "\u5D25\u5D28\u5D2A\u5D2B\u5D2C\u5D2F", 4, "\u5D35", 7, "\u5D3F", 7, "\u5D48\u5D49\u5D4D", 10, "\u5D59\u5D5A\u5D5C\u5D5E", 10, "\u5D6A\u5D6D\u5D6E\u5D70\u5D71\u5D72\u5D73\u5D75", 12, "\u5D83", 21, "\u5D9A\u5D9B\u5D9C\u5D9E\u5D9F\u5DA0"],
      ["8e40", "\u5DA1", 21, "\u5DB8", 12, "\u5DC6", 6, "\u5DCE", 12, "\u5DDC\u5DDF\u5DE0\u5DE3\u5DE4\u5DEA\u5DEC\u5DED"],
      ["8e80", "\u5DF0\u5DF5\u5DF6\u5DF8", 4, "\u5DFF\u5E00\u5E04\u5E07\u5E09\u5E0A\u5E0B\u5E0D\u5E0E\u5E12\u5E13\u5E17\u5E1E", 7, "\u5E28", 4, "\u5E2F\u5E30\u5E32", 4, "\u5E39\u5E3A\u5E3E\u5E3F\u5E40\u5E41\u5E43\u5E46", 5, "\u5E4D", 6, "\u5E56", 4, "\u5E5C\u5E5D\u5E5F\u5E60\u5E63", 14, "\u5E75\u5E77\u5E79\u5E7E\u5E81\u5E82\u5E83\u5E85\u5E88\u5E89\u5E8C\u5E8D\u5E8E\u5E92\u5E98\u5E9B\u5E9D\u5EA1\u5EA2\u5EA3\u5EA4\u5EA8", 4, "\u5EAE", 4, "\u5EB4\u5EBA\u5EBB\u5EBC\u5EBD\u5EBF", 6],
      ["8f40", "\u5EC6\u5EC7\u5EC8\u5ECB", 5, "\u5ED4\u5ED5\u5ED7\u5ED8\u5ED9\u5EDA\u5EDC", 11, "\u5EE9\u5EEB", 8, "\u5EF5\u5EF8\u5EF9\u5EFB\u5EFC\u5EFD\u5F05\u5F06\u5F07\u5F09\u5F0C\u5F0D\u5F0E\u5F10\u5F12\u5F14\u5F16\u5F19\u5F1A\u5F1C\u5F1D\u5F1E\u5F21\u5F22\u5F23\u5F24"],
      ["8f80", "\u5F28\u5F2B\u5F2C\u5F2E\u5F30\u5F32", 6, "\u5F3B\u5F3D\u5F3E\u5F3F\u5F41", 14, "\u5F51\u5F54\u5F59\u5F5A\u5F5B\u5F5C\u5F5E\u5F5F\u5F60\u5F63\u5F65\u5F67\u5F68\u5F6B\u5F6E\u5F6F\u5F72\u5F74\u5F75\u5F76\u5F78\u5F7A\u5F7D\u5F7E\u5F7F\u5F83\u5F86\u5F8D\u5F8E\u5F8F\u5F91\u5F93\u5F94\u5F96\u5F9A\u5F9B\u5F9D\u5F9E\u5F9F\u5FA0\u5FA2", 5, "\u5FA9\u5FAB\u5FAC\u5FAF", 5, "\u5FB6\u5FB8\u5FB9\u5FBA\u5FBB\u5FBE", 4, "\u5FC7\u5FC8\u5FCA\u5FCB\u5FCE\u5FD3\u5FD4\u5FD5\u5FDA\u5FDB\u5FDC\u5FDE\u5FDF\u5FE2\u5FE3\u5FE5\u5FE6\u5FE8\u5FE9\u5FEC\u5FEF\u5FF0\u5FF2\u5FF3\u5FF4\u5FF6\u5FF7\u5FF9\u5FFA\u5FFC\u6007"],
      ["9040", "\u6008\u6009\u600B\u600C\u6010\u6011\u6013\u6017\u6018\u601A\u601E\u601F\u6022\u6023\u6024\u602C\u602D\u602E\u6030", 4, "\u6036", 4, "\u603D\u603E\u6040\u6044", 6, "\u604C\u604E\u604F\u6051\u6053\u6054\u6056\u6057\u6058\u605B\u605C\u605E\u605F\u6060\u6061\u6065\u6066\u606E\u6071\u6072\u6074\u6075\u6077\u607E\u6080"],
      ["9080", "\u6081\u6082\u6085\u6086\u6087\u6088\u608A\u608B\u608E\u608F\u6090\u6091\u6093\u6095\u6097\u6098\u6099\u609C\u609E\u60A1\u60A2\u60A4\u60A5\u60A7\u60A9\u60AA\u60AE\u60B0\u60B3\u60B5\u60B6\u60B7\u60B9\u60BA\u60BD", 7, "\u60C7\u60C8\u60C9\u60CC", 4, "\u60D2\u60D3\u60D4\u60D6\u60D7\u60D9\u60DB\u60DE\u60E1", 4, "\u60EA\u60F1\u60F2\u60F5\u60F7\u60F8\u60FB", 4, "\u6102\u6103\u6104\u6105\u6107\u610A\u610B\u610C\u6110", 4, "\u6116\u6117\u6118\u6119\u611B\u611C\u611D\u611E\u6121\u6122\u6125\u6128\u6129\u612A\u612C", 18, "\u6140", 6],
      ["9140", "\u6147\u6149\u614B\u614D\u614F\u6150\u6152\u6153\u6154\u6156", 6, "\u615E\u615F\u6160\u6161\u6163\u6164\u6165\u6166\u6169", 6, "\u6171\u6172\u6173\u6174\u6176\u6178", 18, "\u618C\u618D\u618F", 4, "\u6195"],
      ["9180", "\u6196", 6, "\u619E", 8, "\u61AA\u61AB\u61AD", 9, "\u61B8", 5, "\u61BF\u61C0\u61C1\u61C3", 4, "\u61C9\u61CC", 4, "\u61D3\u61D5", 16, "\u61E7", 13, "\u61F6", 8, "\u6200", 5, "\u6207\u6209\u6213\u6214\u6219\u621C\u621D\u621E\u6220\u6223\u6226\u6227\u6228\u6229\u622B\u622D\u622F\u6230\u6231\u6232\u6235\u6236\u6238", 4, "\u6242\u6244\u6245\u6246\u624A"],
      ["9240", "\u624F\u6250\u6255\u6256\u6257\u6259\u625A\u625C", 6, "\u6264\u6265\u6268\u6271\u6272\u6274\u6275\u6277\u6278\u627A\u627B\u627D\u6281\u6282\u6283\u6285\u6286\u6287\u6288\u628B", 5, "\u6294\u6299\u629C\u629D\u629E\u62A3\u62A6\u62A7\u62A9\u62AA\u62AD\u62AE\u62AF\u62B0\u62B2\u62B3\u62B4\u62B6\u62B7\u62B8\u62BA\u62BE\u62C0\u62C1"],
      ["9280", "\u62C3\u62CB\u62CF\u62D1\u62D5\u62DD\u62DE\u62E0\u62E1\u62E4\u62EA\u62EB\u62F0\u62F2\u62F5\u62F8\u62F9\u62FA\u62FB\u6300\u6303\u6304\u6305\u6306\u630A\u630B\u630C\u630D\u630F\u6310\u6312\u6313\u6314\u6315\u6317\u6318\u6319\u631C\u6326\u6327\u6329\u632C\u632D\u632E\u6330\u6331\u6333", 5, "\u633B\u633C\u633E\u633F\u6340\u6341\u6344\u6347\u6348\u634A\u6351\u6352\u6353\u6354\u6356", 7, "\u6360\u6364\u6365\u6366\u6368\u636A\u636B\u636C\u636F\u6370\u6372\u6373\u6374\u6375\u6378\u6379\u637C\u637D\u637E\u637F\u6381\u6383\u6384\u6385\u6386\u638B\u638D\u6391\u6393\u6394\u6395\u6397\u6399", 6, "\u63A1\u63A4\u63A6\u63AB\u63AF\u63B1\u63B2\u63B5\u63B6\u63B9\u63BB\u63BD\u63BF\u63C0"],
      ["9340", "\u63C1\u63C2\u63C3\u63C5\u63C7\u63C8\u63CA\u63CB\u63CC\u63D1\u63D3\u63D4\u63D5\u63D7", 6, "\u63DF\u63E2\u63E4", 4, "\u63EB\u63EC\u63EE\u63EF\u63F0\u63F1\u63F3\u63F5\u63F7\u63F9\u63FA\u63FB\u63FC\u63FE\u6403\u6404\u6406", 4, "\u640D\u640E\u6411\u6412\u6415", 5, "\u641D\u641F\u6422\u6423\u6424"],
      ["9380", "\u6425\u6427\u6428\u6429\u642B\u642E", 5, "\u6435", 4, "\u643B\u643C\u643E\u6440\u6442\u6443\u6449\u644B", 6, "\u6453\u6455\u6456\u6457\u6459", 4, "\u645F", 7, "\u6468\u646A\u646B\u646C\u646E", 9, "\u647B", 6, "\u6483\u6486\u6488", 8, "\u6493\u6494\u6497\u6498\u649A\u649B\u649C\u649D\u649F", 4, "\u64A5\u64A6\u64A7\u64A8\u64AA\u64AB\u64AF\u64B1\u64B2\u64B3\u64B4\u64B6\u64B9\u64BB\u64BD\u64BE\u64BF\u64C1\u64C3\u64C4\u64C6", 6, "\u64CF\u64D1\u64D3\u64D4\u64D5\u64D6\u64D9\u64DA"],
      ["9440", "\u64DB\u64DC\u64DD\u64DF\u64E0\u64E1\u64E3\u64E5\u64E7", 24, "\u6501", 7, "\u650A", 7, "\u6513", 4, "\u6519", 8],
      ["9480", "\u6522\u6523\u6524\u6526", 4, "\u652C\u652D\u6530\u6531\u6532\u6533\u6537\u653A\u653C\u653D\u6540", 4, "\u6546\u6547\u654A\u654B\u654D\u654E\u6550\u6552\u6553\u6554\u6557\u6558\u655A\u655C\u655F\u6560\u6561\u6564\u6565\u6567\u6568\u6569\u656A\u656D\u656E\u656F\u6571\u6573\u6575\u6576\u6578", 14, "\u6588\u6589\u658A\u658D\u658E\u658F\u6592\u6594\u6595\u6596\u6598\u659A\u659D\u659E\u65A0\u65A2\u65A3\u65A6\u65A8\u65AA\u65AC\u65AE\u65B1", 7, "\u65BA\u65BB\u65BE\u65BF\u65C0\u65C2\u65C7\u65C8\u65C9\u65CA\u65CD\u65D0\u65D1\u65D3\u65D4\u65D5\u65D8", 7, "\u65E1\u65E3\u65E4\u65EA\u65EB"],
      ["9540", "\u65F2\u65F3\u65F4\u65F5\u65F8\u65F9\u65FB", 4, "\u6601\u6604\u6605\u6607\u6608\u6609\u660B\u660D\u6610\u6611\u6612\u6616\u6617\u6618\u661A\u661B\u661C\u661E\u6621\u6622\u6623\u6624\u6626\u6629\u662A\u662B\u662C\u662E\u6630\u6632\u6633\u6637", 4, "\u663D\u663F\u6640\u6642\u6644", 6, "\u664D\u664E\u6650\u6651\u6658"],
      ["9580", "\u6659\u665B\u665C\u665D\u665E\u6660\u6662\u6663\u6665\u6667\u6669", 4, "\u6671\u6672\u6673\u6675\u6678\u6679\u667B\u667C\u667D\u667F\u6680\u6681\u6683\u6685\u6686\u6688\u6689\u668A\u668B\u668D\u668E\u668F\u6690\u6692\u6693\u6694\u6695\u6698", 4, "\u669E", 8, "\u66A9", 4, "\u66AF", 4, "\u66B5\u66B6\u66B7\u66B8\u66BA\u66BB\u66BC\u66BD\u66BF", 25, "\u66DA\u66DE", 7, "\u66E7\u66E8\u66EA", 5, "\u66F1\u66F5\u66F6\u66F8\u66FA\u66FB\u66FD\u6701\u6702\u6703"],
      ["9640", "\u6704\u6705\u6706\u6707\u670C\u670E\u670F\u6711\u6712\u6713\u6716\u6718\u6719\u671A\u671C\u671E\u6720", 5, "\u6727\u6729\u672E\u6730\u6732\u6733\u6736\u6737\u6738\u6739\u673B\u673C\u673E\u673F\u6741\u6744\u6745\u6747\u674A\u674B\u674D\u6752\u6754\u6755\u6757", 4, "\u675D\u6762\u6763\u6764\u6766\u6767\u676B\u676C\u676E\u6771\u6774\u6776"],
      ["9680", "\u6778\u6779\u677A\u677B\u677D\u6780\u6782\u6783\u6785\u6786\u6788\u678A\u678C\u678D\u678E\u678F\u6791\u6792\u6793\u6794\u6796\u6799\u679B\u679F\u67A0\u67A1\u67A4\u67A6\u67A9\u67AC\u67AE\u67B1\u67B2\u67B4\u67B9", 7, "\u67C2\u67C5", 9, "\u67D5\u67D6\u67D7\u67DB\u67DF\u67E1\u67E3\u67E4\u67E6\u67E7\u67E8\u67EA\u67EB\u67ED\u67EE\u67F2\u67F5", 7, "\u67FE\u6801\u6802\u6803\u6804\u6806\u680D\u6810\u6812\u6814\u6815\u6818", 4, "\u681E\u681F\u6820\u6822", 6, "\u682B", 6, "\u6834\u6835\u6836\u683A\u683B\u683F\u6847\u684B\u684D\u684F\u6852\u6856", 5],
      ["9740", "\u685C\u685D\u685E\u685F\u686A\u686C", 7, "\u6875\u6878", 8, "\u6882\u6884\u6887", 7, "\u6890\u6891\u6892\u6894\u6895\u6896\u6898", 9, "\u68A3\u68A4\u68A5\u68A9\u68AA\u68AB\u68AC\u68AE\u68B1\u68B2\u68B4\u68B6\u68B7\u68B8"],
      ["9780", "\u68B9", 6, "\u68C1\u68C3", 5, "\u68CA\u68CC\u68CE\u68CF\u68D0\u68D1\u68D3\u68D4\u68D6\u68D7\u68D9\u68DB", 4, "\u68E1\u68E2\u68E4", 9, "\u68EF\u68F2\u68F3\u68F4\u68F6\u68F7\u68F8\u68FB\u68FD\u68FE\u68FF\u6900\u6902\u6903\u6904\u6906", 4, "\u690C\u690F\u6911\u6913", 11, "\u6921\u6922\u6923\u6925", 7, "\u692E\u692F\u6931\u6932\u6933\u6935\u6936\u6937\u6938\u693A\u693B\u693C\u693E\u6940\u6941\u6943", 16, "\u6955\u6956\u6958\u6959\u695B\u695C\u695F"],
      ["9840", "\u6961\u6962\u6964\u6965\u6967\u6968\u6969\u696A\u696C\u696D\u696F\u6970\u6972", 4, "\u697A\u697B\u697D\u697E\u697F\u6981\u6983\u6985\u698A\u698B\u698C\u698E", 5, "\u6996\u6997\u6999\u699A\u699D", 9, "\u69A9\u69AA\u69AC\u69AE\u69AF\u69B0\u69B2\u69B3\u69B5\u69B6\u69B8\u69B9\u69BA\u69BC\u69BD"],
      ["9880", "\u69BE\u69BF\u69C0\u69C2", 7, "\u69CB\u69CD\u69CF\u69D1\u69D2\u69D3\u69D5", 5, "\u69DC\u69DD\u69DE\u69E1", 11, "\u69EE\u69EF\u69F0\u69F1\u69F3", 9, "\u69FE\u6A00", 9, "\u6A0B", 11, "\u6A19", 5, "\u6A20\u6A22", 5, "\u6A29\u6A2B\u6A2C\u6A2D\u6A2E\u6A30\u6A32\u6A33\u6A34\u6A36", 6, "\u6A3F", 4, "\u6A45\u6A46\u6A48", 7, "\u6A51", 6, "\u6A5A"],
      ["9940", "\u6A5C", 4, "\u6A62\u6A63\u6A64\u6A66", 10, "\u6A72", 6, "\u6A7A\u6A7B\u6A7D\u6A7E\u6A7F\u6A81\u6A82\u6A83\u6A85", 8, "\u6A8F\u6A92", 4, "\u6A98", 7, "\u6AA1", 5],
      ["9980", "\u6AA7\u6AA8\u6AAA\u6AAD", 114, "\u6B25\u6B26\u6B28", 6],
      ["9a40", "\u6B2F\u6B30\u6B31\u6B33\u6B34\u6B35\u6B36\u6B38\u6B3B\u6B3C\u6B3D\u6B3F\u6B40\u6B41\u6B42\u6B44\u6B45\u6B48\u6B4A\u6B4B\u6B4D", 11, "\u6B5A", 7, "\u6B68\u6B69\u6B6B", 13, "\u6B7A\u6B7D\u6B7E\u6B7F\u6B80\u6B85\u6B88"],
      ["9a80", "\u6B8C\u6B8E\u6B8F\u6B90\u6B91\u6B94\u6B95\u6B97\u6B98\u6B99\u6B9C", 4, "\u6BA2", 7, "\u6BAB", 7, "\u6BB6\u6BB8", 6, "\u6BC0\u6BC3\u6BC4\u6BC6", 4, "\u6BCC\u6BCE\u6BD0\u6BD1\u6BD8\u6BDA\u6BDC", 4, "\u6BE2", 7, "\u6BEC\u6BED\u6BEE\u6BF0\u6BF1\u6BF2\u6BF4\u6BF6\u6BF7\u6BF8\u6BFA\u6BFB\u6BFC\u6BFE", 6, "\u6C08", 4, "\u6C0E\u6C12\u6C17\u6C1C\u6C1D\u6C1E\u6C20\u6C23\u6C25\u6C2B\u6C2C\u6C2D\u6C31\u6C33\u6C36\u6C37\u6C39\u6C3A\u6C3B\u6C3C\u6C3E\u6C3F\u6C43\u6C44\u6C45\u6C48\u6C4B", 4, "\u6C51\u6C52\u6C53\u6C56\u6C58"],
      ["9b40", "\u6C59\u6C5A\u6C62\u6C63\u6C65\u6C66\u6C67\u6C6B", 4, "\u6C71\u6C73\u6C75\u6C77\u6C78\u6C7A\u6C7B\u6C7C\u6C7F\u6C80\u6C84\u6C87\u6C8A\u6C8B\u6C8D\u6C8E\u6C91\u6C92\u6C95\u6C96\u6C97\u6C98\u6C9A\u6C9C\u6C9D\u6C9E\u6CA0\u6CA2\u6CA8\u6CAC\u6CAF\u6CB0\u6CB4\u6CB5\u6CB6\u6CB7\u6CBA\u6CC0\u6CC1\u6CC2\u6CC3\u6CC6\u6CC7\u6CC8\u6CCB\u6CCD\u6CCE\u6CCF\u6CD1\u6CD2\u6CD8"],
      ["9b80", "\u6CD9\u6CDA\u6CDC\u6CDD\u6CDF\u6CE4\u6CE6\u6CE7\u6CE9\u6CEC\u6CED\u6CF2\u6CF4\u6CF9\u6CFF\u6D00\u6D02\u6D03\u6D05\u6D06\u6D08\u6D09\u6D0A\u6D0D\u6D0F\u6D10\u6D11\u6D13\u6D14\u6D15\u6D16\u6D18\u6D1C\u6D1D\u6D1F", 5, "\u6D26\u6D28\u6D29\u6D2C\u6D2D\u6D2F\u6D30\u6D34\u6D36\u6D37\u6D38\u6D3A\u6D3F\u6D40\u6D42\u6D44\u6D49\u6D4C\u6D50\u6D55\u6D56\u6D57\u6D58\u6D5B\u6D5D\u6D5F\u6D61\u6D62\u6D64\u6D65\u6D67\u6D68\u6D6B\u6D6C\u6D6D\u6D70\u6D71\u6D72\u6D73\u6D75\u6D76\u6D79\u6D7A\u6D7B\u6D7D", 4, "\u6D83\u6D84\u6D86\u6D87\u6D8A\u6D8B\u6D8D\u6D8F\u6D90\u6D92\u6D96", 4, "\u6D9C\u6DA2\u6DA5\u6DAC\u6DAD\u6DB0\u6DB1\u6DB3\u6DB4\u6DB6\u6DB7\u6DB9", 5, "\u6DC1\u6DC2\u6DC3\u6DC8\u6DC9\u6DCA"],
      ["9c40", "\u6DCD\u6DCE\u6DCF\u6DD0\u6DD2\u6DD3\u6DD4\u6DD5\u6DD7\u6DDA\u6DDB\u6DDC\u6DDF\u6DE2\u6DE3\u6DE5\u6DE7\u6DE8\u6DE9\u6DEA\u6DED\u6DEF\u6DF0\u6DF2\u6DF4\u6DF5\u6DF6\u6DF8\u6DFA\u6DFD", 7, "\u6E06\u6E07\u6E08\u6E09\u6E0B\u6E0F\u6E12\u6E13\u6E15\u6E18\u6E19\u6E1B\u6E1C\u6E1E\u6E1F\u6E22\u6E26\u6E27\u6E28\u6E2A\u6E2C\u6E2E\u6E30\u6E31\u6E33\u6E35"],
      ["9c80", "\u6E36\u6E37\u6E39\u6E3B", 7, "\u6E45", 7, "\u6E4F\u6E50\u6E51\u6E52\u6E55\u6E57\u6E59\u6E5A\u6E5C\u6E5D\u6E5E\u6E60", 10, "\u6E6C\u6E6D\u6E6F", 14, "\u6E80\u6E81\u6E82\u6E84\u6E87\u6E88\u6E8A", 4, "\u6E91", 6, "\u6E99\u6E9A\u6E9B\u6E9D\u6E9E\u6EA0\u6EA1\u6EA3\u6EA4\u6EA6\u6EA8\u6EA9\u6EAB\u6EAC\u6EAD\u6EAE\u6EB0\u6EB3\u6EB5\u6EB8\u6EB9\u6EBC\u6EBE\u6EBF\u6EC0\u6EC3\u6EC4\u6EC5\u6EC6\u6EC8\u6EC9\u6ECA\u6ECC\u6ECD\u6ECE\u6ED0\u6ED2\u6ED6\u6ED8\u6ED9\u6EDB\u6EDC\u6EDD\u6EE3\u6EE7\u6EEA", 5],
      ["9d40", "\u6EF0\u6EF1\u6EF2\u6EF3\u6EF5\u6EF6\u6EF7\u6EF8\u6EFA", 7, "\u6F03\u6F04\u6F05\u6F07\u6F08\u6F0A", 4, "\u6F10\u6F11\u6F12\u6F16", 9, "\u6F21\u6F22\u6F23\u6F25\u6F26\u6F27\u6F28\u6F2C\u6F2E\u6F30\u6F32\u6F34\u6F35\u6F37", 6, "\u6F3F\u6F40\u6F41\u6F42"],
      ["9d80", "\u6F43\u6F44\u6F45\u6F48\u6F49\u6F4A\u6F4C\u6F4E", 9, "\u6F59\u6F5A\u6F5B\u6F5D\u6F5F\u6F60\u6F61\u6F63\u6F64\u6F65\u6F67", 5, "\u6F6F\u6F70\u6F71\u6F73\u6F75\u6F76\u6F77\u6F79\u6F7B\u6F7D", 6, "\u6F85\u6F86\u6F87\u6F8A\u6F8B\u6F8F", 12, "\u6F9D\u6F9E\u6F9F\u6FA0\u6FA2", 4, "\u6FA8", 10, "\u6FB4\u6FB5\u6FB7\u6FB8\u6FBA", 5, "\u6FC1\u6FC3", 5, "\u6FCA", 6, "\u6FD3", 10, "\u6FDF\u6FE2\u6FE3\u6FE4\u6FE5"],
      ["9e40", "\u6FE6", 7, "\u6FF0", 32, "\u7012", 7, "\u701C", 6, "\u7024", 6],
      ["9e80", "\u702B", 9, "\u7036\u7037\u7038\u703A", 17, "\u704D\u704E\u7050", 13, "\u705F", 11, "\u706E\u7071\u7072\u7073\u7074\u7077\u7079\u707A\u707B\u707D\u7081\u7082\u7083\u7084\u7086\u7087\u7088\u708B\u708C\u708D\u708F\u7090\u7091\u7093\u7097\u7098\u709A\u709B\u709E", 12, "\u70B0\u70B2\u70B4\u70B5\u70B6\u70BA\u70BE\u70BF\u70C4\u70C5\u70C6\u70C7\u70C9\u70CB", 12, "\u70DA"],
      ["9f40", "\u70DC\u70DD\u70DE\u70E0\u70E1\u70E2\u70E3\u70E5\u70EA\u70EE\u70F0", 6, "\u70F8\u70FA\u70FB\u70FC\u70FE", 10, "\u710B", 4, "\u7111\u7112\u7114\u7117\u711B", 10, "\u7127", 7, "\u7132\u7133\u7134"],
      ["9f80", "\u7135\u7137", 13, "\u7146\u7147\u7148\u7149\u714B\u714D\u714F", 12, "\u715D\u715F", 4, "\u7165\u7169", 4, "\u716F\u7170\u7171\u7174\u7175\u7176\u7177\u7179\u717B\u717C\u717E", 5, "\u7185", 4, "\u718B\u718C\u718D\u718E\u7190\u7191\u7192\u7193\u7195\u7196\u7197\u719A", 4, "\u71A1", 6, "\u71A9\u71AA\u71AB\u71AD", 5, "\u71B4\u71B6\u71B7\u71B8\u71BA", 8, "\u71C4", 9, "\u71CF", 4],
      ["a040", "\u71D6", 9, "\u71E1\u71E2\u71E3\u71E4\u71E6\u71E8", 5, "\u71EF", 9, "\u71FA", 11, "\u7207", 19],
      ["a080", "\u721B\u721C\u721E", 9, "\u7229\u722B\u722D\u722E\u722F\u7232\u7233\u7234\u723A\u723C\u723E\u7240", 6, "\u7249\u724A\u724B\u724E\u724F\u7250\u7251\u7253\u7254\u7255\u7257\u7258\u725A\u725C\u725E\u7260\u7263\u7264\u7265\u7268\u726A\u726B\u726C\u726D\u7270\u7271\u7273\u7274\u7276\u7277\u7278\u727B\u727C\u727D\u7282\u7283\u7285", 4, "\u728C\u728E\u7290\u7291\u7293", 11, "\u72A0", 11, "\u72AE\u72B1\u72B2\u72B3\u72B5\u72BA", 6, "\u72C5\u72C6\u72C7\u72C9\u72CA\u72CB\u72CC\u72CF\u72D1\u72D3\u72D4\u72D5\u72D6\u72D8\u72DA\u72DB"],
      ["a1a1", "\u3000\u3001\u3002\xB7\u02C9\u02C7\xA8\u3003\u3005\u2014\uFF5E\u2016\u2026\u2018\u2019\u201C\u201D\u3014\u3015\u3008", 7, "\u3016\u3017\u3010\u3011\xB1\xD7\xF7\u2236\u2227\u2228\u2211\u220F\u222A\u2229\u2208\u2237\u221A\u22A5\u2225\u2220\u2312\u2299\u222B\u222E\u2261\u224C\u2248\u223D\u221D\u2260\u226E\u226F\u2264\u2265\u221E\u2235\u2234\u2642\u2640\xB0\u2032\u2033\u2103\uFF04\xA4\uFFE0\uFFE1\u2030\xA7\u2116\u2606\u2605\u25CB\u25CF\u25CE\u25C7\u25C6\u25A1\u25A0\u25B3\u25B2\u203B\u2192\u2190\u2191\u2193\u3013"],
      ["a2a1", "\u2170", 9],
      ["a2b1", "\u2488", 19, "\u2474", 19, "\u2460", 9],
      ["a2e5", "\u3220", 9],
      ["a2f1", "\u2160", 11],
      ["a3a1", "\uFF01\uFF02\uFF03\uFFE5\uFF05", 88, "\uFFE3"],
      ["a4a1", "\u3041", 82],
      ["a5a1", "\u30A1", 85],
      ["a6a1", "\u0391", 16, "\u03A3", 6],
      ["a6c1", "\u03B1", 16, "\u03C3", 6],
      ["a6e0", "\uFE35\uFE36\uFE39\uFE3A\uFE3F\uFE40\uFE3D\uFE3E\uFE41\uFE42\uFE43\uFE44"],
      ["a6ee", "\uFE3B\uFE3C\uFE37\uFE38\uFE31"],
      ["a6f4", "\uFE33\uFE34"],
      ["a7a1", "\u0410", 5, "\u0401\u0416", 25],
      ["a7d1", "\u0430", 5, "\u0451\u0436", 25],
      ["a840", "\u02CA\u02CB\u02D9\u2013\u2015\u2025\u2035\u2105\u2109\u2196\u2197\u2198\u2199\u2215\u221F\u2223\u2252\u2266\u2267\u22BF\u2550", 35, "\u2581", 6],
      ["a880", "\u2588", 7, "\u2593\u2594\u2595\u25BC\u25BD\u25E2\u25E3\u25E4\u25E5\u2609\u2295\u3012\u301D\u301E"],
      ["a8a1", "\u0101\xE1\u01CE\xE0\u0113\xE9\u011B\xE8\u012B\xED\u01D0\xEC\u014D\xF3\u01D2\xF2\u016B\xFA\u01D4\xF9\u01D6\u01D8\u01DA\u01DC\xFC\xEA\u0251"],
      ["a8bd", "\u0144\u0148"],
      ["a8c0", "\u0261"],
      ["a8c5", "\u3105", 36],
      ["a940", "\u3021", 8, "\u32A3\u338E\u338F\u339C\u339D\u339E\u33A1\u33C4\u33CE\u33D1\u33D2\u33D5\uFE30\uFFE2\uFFE4"],
      ["a959", "\u2121\u3231"],
      ["a95c", "\u2010"],
      ["a960", "\u30FC\u309B\u309C\u30FD\u30FE\u3006\u309D\u309E\uFE49", 9, "\uFE54\uFE55\uFE56\uFE57\uFE59", 8],
      ["a980", "\uFE62", 4, "\uFE68\uFE69\uFE6A\uFE6B"],
      ["a996", "\u3007"],
      ["a9a4", "\u2500", 75],
      ["aa40", "\u72DC\u72DD\u72DF\u72E2", 5, "\u72EA\u72EB\u72F5\u72F6\u72F9\u72FD\u72FE\u72FF\u7300\u7302\u7304", 5, "\u730B\u730C\u730D\u730F\u7310\u7311\u7312\u7314\u7318\u7319\u731A\u731F\u7320\u7323\u7324\u7326\u7327\u7328\u732D\u732F\u7330\u7332\u7333\u7335\u7336\u733A\u733B\u733C\u733D\u7340", 8],
      ["aa80", "\u7349\u734A\u734B\u734C\u734E\u734F\u7351\u7353\u7354\u7355\u7356\u7358", 7, "\u7361", 10, "\u736E\u7370\u7371"],
      ["ab40", "\u7372", 11, "\u737F", 4, "\u7385\u7386\u7388\u738A\u738C\u738D\u738F\u7390\u7392\u7393\u7394\u7395\u7397\u7398\u7399\u739A\u739C\u739D\u739E\u73A0\u73A1\u73A3", 5, "\u73AA\u73AC\u73AD\u73B1\u73B4\u73B5\u73B6\u73B8\u73B9\u73BC\u73BD\u73BE\u73BF\u73C1\u73C3", 4],
      ["ab80", "\u73CB\u73CC\u73CE\u73D2", 6, "\u73DA\u73DB\u73DC\u73DD\u73DF\u73E1\u73E2\u73E3\u73E4\u73E6\u73E8\u73EA\u73EB\u73EC\u73EE\u73EF\u73F0\u73F1\u73F3", 4],
      ["ac40", "\u73F8", 10, "\u7404\u7407\u7408\u740B\u740C\u740D\u740E\u7411", 8, "\u741C", 5, "\u7423\u7424\u7427\u7429\u742B\u742D\u742F\u7431\u7432\u7437", 4, "\u743D\u743E\u743F\u7440\u7442", 11],
      ["ac80", "\u744E", 6, "\u7456\u7458\u745D\u7460", 12, "\u746E\u746F\u7471", 4, "\u7478\u7479\u747A"],
      ["ad40", "\u747B\u747C\u747D\u747F\u7482\u7484\u7485\u7486\u7488\u7489\u748A\u748C\u748D\u748F\u7491", 10, "\u749D\u749F", 7, "\u74AA", 15, "\u74BB", 12],
      ["ad80", "\u74C8", 9, "\u74D3", 8, "\u74DD\u74DF\u74E1\u74E5\u74E7", 6, "\u74F0\u74F1\u74F2"],
      ["ae40", "\u74F3\u74F5\u74F8", 6, "\u7500\u7501\u7502\u7503\u7505", 7, "\u750E\u7510\u7512\u7514\u7515\u7516\u7517\u751B\u751D\u751E\u7520", 4, "\u7526\u7527\u752A\u752E\u7534\u7536\u7539\u753C\u753D\u753F\u7541\u7542\u7543\u7544\u7546\u7547\u7549\u754A\u754D\u7550\u7551\u7552\u7553\u7555\u7556\u7557\u7558"],
      ["ae80", "\u755D", 7, "\u7567\u7568\u7569\u756B", 6, "\u7573\u7575\u7576\u7577\u757A", 4, "\u7580\u7581\u7582\u7584\u7585\u7587"],
      ["af40", "\u7588\u7589\u758A\u758C\u758D\u758E\u7590\u7593\u7595\u7598\u759B\u759C\u759E\u75A2\u75A6", 4, "\u75AD\u75B6\u75B7\u75BA\u75BB\u75BF\u75C0\u75C1\u75C6\u75CB\u75CC\u75CE\u75CF\u75D0\u75D1\u75D3\u75D7\u75D9\u75DA\u75DC\u75DD\u75DF\u75E0\u75E1\u75E5\u75E9\u75EC\u75ED\u75EE\u75EF\u75F2\u75F3\u75F5\u75F6\u75F7\u75F8\u75FA\u75FB\u75FD\u75FE\u7602\u7604\u7606\u7607"],
      ["af80", "\u7608\u7609\u760B\u760D\u760E\u760F\u7611\u7612\u7613\u7614\u7616\u761A\u761C\u761D\u761E\u7621\u7623\u7627\u7628\u762C\u762E\u762F\u7631\u7632\u7636\u7637\u7639\u763A\u763B\u763D\u7641\u7642\u7644"],
      ["b040", "\u7645", 6, "\u764E", 5, "\u7655\u7657", 4, "\u765D\u765F\u7660\u7661\u7662\u7664", 6, "\u766C\u766D\u766E\u7670", 7, "\u7679\u767A\u767C\u767F\u7680\u7681\u7683\u7685\u7689\u768A\u768C\u768D\u768F\u7690\u7692\u7694\u7695\u7697\u7698\u769A\u769B"],
      ["b080", "\u769C", 7, "\u76A5", 8, "\u76AF\u76B0\u76B3\u76B5", 9, "\u76C0\u76C1\u76C3\u554A\u963F\u57C3\u6328\u54CE\u5509\u54C0\u7691\u764C\u853C\u77EE\u827E\u788D\u7231\u9698\u978D\u6C28\u5B89\u4FFA\u6309\u6697\u5CB8\u80FA\u6848\u80AE\u6602\u76CE\u51F9\u6556\u71AC\u7FF1\u8884\u50B2\u5965\u61CA\u6FB3\u82AD\u634C\u6252\u53ED\u5427\u7B06\u516B\u75A4\u5DF4\u62D4\u8DCB\u9776\u628A\u8019\u575D\u9738\u7F62\u7238\u767D\u67CF\u767E\u6446\u4F70\u8D25\u62DC\u7A17\u6591\u73ED\u642C\u6273\u822C\u9881\u677F\u7248\u626E\u62CC\u4F34\u74E3\u534A\u529E\u7ECA\u90A6\u5E2E\u6886\u699C\u8180\u7ED1\u68D2\u78C5\u868C\u9551\u508D\u8C24\u82DE\u80DE\u5305\u8912\u5265"],
      ["b140", "\u76C4\u76C7\u76C9\u76CB\u76CC\u76D3\u76D5\u76D9\u76DA\u76DC\u76DD\u76DE\u76E0", 4, "\u76E6", 7, "\u76F0\u76F3\u76F5\u76F6\u76F7\u76FA\u76FB\u76FD\u76FF\u7700\u7702\u7703\u7705\u7706\u770A\u770C\u770E", 10, "\u771B\u771C\u771D\u771E\u7721\u7723\u7724\u7725\u7727\u772A\u772B"],
      ["b180", "\u772C\u772E\u7730", 4, "\u7739\u773B\u773D\u773E\u773F\u7742\u7744\u7745\u7746\u7748", 7, "\u7752", 7, "\u775C\u8584\u96F9\u4FDD\u5821\u9971\u5B9D\u62B1\u62A5\u66B4\u8C79\u9C8D\u7206\u676F\u7891\u60B2\u5351\u5317\u8F88\u80CC\u8D1D\u94A1\u500D\u72C8\u5907\u60EB\u7119\u88AB\u5954\u82EF\u672C\u7B28\u5D29\u7EF7\u752D\u6CF5\u8E66\u8FF8\u903C\u9F3B\u6BD4\u9119\u7B14\u5F7C\u78A7\u84D6\u853D\u6BD5\u6BD9\u6BD6\u5E01\u5E87\u75F9\u95ED\u655D\u5F0A\u5FC5\u8F9F\u58C1\u81C2\u907F\u965B\u97AD\u8FB9\u7F16\u8D2C\u6241\u4FBF\u53D8\u535E\u8FA8\u8FA9\u8FAB\u904D\u6807\u5F6A\u8198\u8868\u9CD6\u618B\u522B\u762A\u5F6C\u658C\u6FD2\u6EE8\u5BBE\u6448\u5175\u51B0\u67C4\u4E19\u79C9\u997C\u70B3"],
      ["b240", "\u775D\u775E\u775F\u7760\u7764\u7767\u7769\u776A\u776D", 11, "\u777A\u777B\u777C\u7781\u7782\u7783\u7786", 5, "\u778F\u7790\u7793", 11, "\u77A1\u77A3\u77A4\u77A6\u77A8\u77AB\u77AD\u77AE\u77AF\u77B1\u77B2\u77B4\u77B6", 4],
      ["b280", "\u77BC\u77BE\u77C0", 12, "\u77CE", 8, "\u77D8\u77D9\u77DA\u77DD", 4, "\u77E4\u75C5\u5E76\u73BB\u83E0\u64AD\u62E8\u94B5\u6CE2\u535A\u52C3\u640F\u94C2\u7B94\u4F2F\u5E1B\u8236\u8116\u818A\u6E24\u6CCA\u9A73\u6355\u535C\u54FA\u8865\u57E0\u4E0D\u5E03\u6B65\u7C3F\u90E8\u6016\u64E6\u731C\u88C1\u6750\u624D\u8D22\u776C\u8E29\u91C7\u5F69\u83DC\u8521\u9910\u53C2\u8695\u6B8B\u60ED\u60E8\u707F\u82CD\u8231\u4ED3\u6CA7\u85CF\u64CD\u7CD9\u69FD\u66F9\u8349\u5395\u7B56\u4FA7\u518C\u6D4B\u5C42\u8E6D\u63D2\u53C9\u832C\u8336\u67E5\u78B4\u643D\u5BDF\u5C94\u5DEE\u8BE7\u62C6\u67F4\u8C7A\u6400\u63BA\u8749\u998B\u8C17\u7F20\u94F2\u4EA7\u9610\u98A4\u660C\u7316"],
      ["b340", "\u77E6\u77E8\u77EA\u77EF\u77F0\u77F1\u77F2\u77F4\u77F5\u77F7\u77F9\u77FA\u77FB\u77FC\u7803", 5, "\u780A\u780B\u780E\u780F\u7810\u7813\u7815\u7819\u781B\u781E\u7820\u7821\u7822\u7824\u7828\u782A\u782B\u782E\u782F\u7831\u7832\u7833\u7835\u7836\u783D\u783F\u7841\u7842\u7843\u7844\u7846\u7848\u7849\u784A\u784B\u784D\u784F\u7851\u7853\u7854\u7858\u7859\u785A"],
      ["b380", "\u785B\u785C\u785E", 11, "\u786F", 7, "\u7878\u7879\u787A\u787B\u787D", 6, "\u573A\u5C1D\u5E38\u957F\u507F\u80A0\u5382\u655E\u7545\u5531\u5021\u8D85\u6284\u949E\u671D\u5632\u6F6E\u5DE2\u5435\u7092\u8F66\u626F\u64A4\u63A3\u5F7B\u6F88\u90F4\u81E3\u8FB0\u5C18\u6668\u5FF1\u6C89\u9648\u8D81\u886C\u6491\u79F0\u57CE\u6A59\u6210\u5448\u4E58\u7A0B\u60E9\u6F84\u8BDA\u627F\u901E\u9A8B\u79E4\u5403\u75F4\u6301\u5319\u6C60\u8FDF\u5F1B\u9A70\u803B\u9F7F\u4F88\u5C3A\u8D64\u7FC5\u65A5\u70BD\u5145\u51B2\u866B\u5D07\u5BA0\u62BD\u916C\u7574\u8E0C\u7A20\u6101\u7B79\u4EC7\u7EF8\u7785\u4E11\u81ED\u521D\u51FA\u6A71\u53A8\u8E87\u9504\u96CF\u6EC1\u9664\u695A"],
      ["b440", "\u7884\u7885\u7886\u7888\u788A\u788B\u788F\u7890\u7892\u7894\u7895\u7896\u7899\u789D\u789E\u78A0\u78A2\u78A4\u78A6\u78A8", 7, "\u78B5\u78B6\u78B7\u78B8\u78BA\u78BB\u78BC\u78BD\u78BF\u78C0\u78C2\u78C3\u78C4\u78C6\u78C7\u78C8\u78CC\u78CD\u78CE\u78CF\u78D1\u78D2\u78D3\u78D6\u78D7\u78D8\u78DA", 9],
      ["b480", "\u78E4\u78E5\u78E6\u78E7\u78E9\u78EA\u78EB\u78ED", 4, "\u78F3\u78F5\u78F6\u78F8\u78F9\u78FB", 5, "\u7902\u7903\u7904\u7906", 6, "\u7840\u50A8\u77D7\u6410\u89E6\u5904\u63E3\u5DDD\u7A7F\u693D\u4F20\u8239\u5598\u4E32\u75AE\u7A97\u5E62\u5E8A\u95EF\u521B\u5439\u708A\u6376\u9524\u5782\u6625\u693F\u9187\u5507\u6DF3\u7EAF\u8822\u6233\u7EF0\u75B5\u8328\u78C1\u96CC\u8F9E\u6148\u74F7\u8BCD\u6B64\u523A\u8D50\u6B21\u806A\u8471\u56F1\u5306\u4ECE\u4E1B\u51D1\u7C97\u918B\u7C07\u4FC3\u8E7F\u7BE1\u7A9C\u6467\u5D14\u50AC\u8106\u7601\u7CB9\u6DEC\u7FE0\u6751\u5B58\u5BF8\u78CB\u64AE\u6413\u63AA\u632B\u9519\u642D\u8FBE\u7B54\u7629\u6253\u5927\u5446\u6B79\u50A3\u6234\u5E26\u6B86\u4EE3\u8D37\u888B\u5F85\u902E"],
      ["b540", "\u790D", 5, "\u7914", 9, "\u791F", 4, "\u7925", 14, "\u7935", 4, "\u793D\u793F\u7942\u7943\u7944\u7945\u7947\u794A", 8, "\u7954\u7955\u7958\u7959\u7961\u7963"],
      ["b580", "\u7964\u7966\u7969\u796A\u796B\u796C\u796E\u7970", 6, "\u7979\u797B", 4, "\u7982\u7983\u7986\u7987\u7988\u7989\u798B\u798C\u798D\u798E\u7990\u7991\u7992\u6020\u803D\u62C5\u4E39\u5355\u90F8\u63B8\u80C6\u65E6\u6C2E\u4F46\u60EE\u6DE1\u8BDE\u5F39\u86CB\u5F53\u6321\u515A\u8361\u6863\u5200\u6363\u8E48\u5012\u5C9B\u7977\u5BFC\u5230\u7A3B\u60BC\u9053\u76D7\u5FB7\u5F97\u7684\u8E6C\u706F\u767B\u7B49\u77AA\u51F3\u9093\u5824\u4F4E\u6EF4\u8FEA\u654C\u7B1B\u72C4\u6DA4\u7FDF\u5AE1\u62B5\u5E95\u5730\u8482\u7B2C\u5E1D\u5F1F\u9012\u7F14\u98A0\u6382\u6EC7\u7898\u70B9\u5178\u975B\u57AB\u7535\u4F43\u7538\u5E97\u60E6\u5960\u6DC0\u6BBF\u7889\u53FC\u96D5\u51CB\u5201\u6389\u540A\u9493\u8C03\u8DCC\u7239\u789F\u8776\u8FED\u8C0D\u53E0"],
      ["b640", "\u7993", 6, "\u799B", 11, "\u79A8", 10, "\u79B4", 4, "\u79BC\u79BF\u79C2\u79C4\u79C5\u79C7\u79C8\u79CA\u79CC\u79CE\u79CF\u79D0\u79D3\u79D4\u79D6\u79D7\u79D9", 5, "\u79E0\u79E1\u79E2\u79E5\u79E8\u79EA"],
      ["b680", "\u79EC\u79EE\u79F1", 6, "\u79F9\u79FA\u79FC\u79FE\u79FF\u7A01\u7A04\u7A05\u7A07\u7A08\u7A09\u7A0A\u7A0C\u7A0F", 4, "\u7A15\u7A16\u7A18\u7A19\u7A1B\u7A1C\u4E01\u76EF\u53EE\u9489\u9876\u9F0E\u952D\u5B9A\u8BA2\u4E22\u4E1C\u51AC\u8463\u61C2\u52A8\u680B\u4F97\u606B\u51BB\u6D1E\u515C\u6296\u6597\u9661\u8C46\u9017\u75D8\u90FD\u7763\u6BD2\u728A\u72EC\u8BFB\u5835\u7779\u8D4C\u675C\u9540\u809A\u5EA6\u6E21\u5992\u7AEF\u77ED\u953B\u6BB5\u65AD\u7F0E\u5806\u5151\u961F\u5BF9\u58A9\u5428\u8E72\u6566\u987F\u56E4\u949D\u76FE\u9041\u6387\u54C6\u591A\u593A\u579B\u8EB2\u6735\u8DFA\u8235\u5241\u60F0\u5815\u86FE\u5CE8\u9E45\u4FC4\u989D\u8BB9\u5A25\u6076\u5384\u627C\u904F\u9102\u997F\u6069\u800C\u513F\u8033\u5C14\u9975\u6D31\u4E8C"],
      ["b740", "\u7A1D\u7A1F\u7A21\u7A22\u7A24", 14, "\u7A34\u7A35\u7A36\u7A38\u7A3A\u7A3E\u7A40", 5, "\u7A47", 9, "\u7A52", 4, "\u7A58", 16],
      ["b780", "\u7A69", 6, "\u7A71\u7A72\u7A73\u7A75\u7A7B\u7A7C\u7A7D\u7A7E\u7A82\u7A85\u7A87\u7A89\u7A8A\u7A8B\u7A8C\u7A8E\u7A8F\u7A90\u7A93\u7A94\u7A99\u7A9A\u7A9B\u7A9E\u7AA1\u7AA2\u8D30\u53D1\u7F5A\u7B4F\u4F10\u4E4F\u9600\u6CD5\u73D0\u85E9\u5E06\u756A\u7FFB\u6A0A\u77FE\u9492\u7E41\u51E1\u70E6\u53CD\u8FD4\u8303\u8D29\u72AF\u996D\u6CDB\u574A\u82B3\u65B9\u80AA\u623F\u9632\u59A8\u4EFF\u8BBF\u7EBA\u653E\u83F2\u975E\u5561\u98DE\u80A5\u532A\u8BFD\u5420\u80BA\u5E9F\u6CB8\u8D39\u82AC\u915A\u5429\u6C1B\u5206\u7EB7\u575F\u711A\u6C7E\u7C89\u594B\u4EFD\u5FFF\u6124\u7CAA\u4E30\u5C01\u67AB\u8702\u5CF0\u950B\u98CE\u75AF\u70FD\u9022\u51AF\u7F1D\u8BBD\u5949\u51E4\u4F5B\u5426\u592B\u6577\u80A4\u5B75\u6276\u62C2\u8F90\u5E45\u6C1F\u7B26\u4F0F\u4FD8\u670D"],
      ["b840", "\u7AA3\u7AA4\u7AA7\u7AA9\u7AAA\u7AAB\u7AAE", 4, "\u7AB4", 10, "\u7AC0", 10, "\u7ACC", 9, "\u7AD7\u7AD8\u7ADA\u7ADB\u7ADC\u7ADD\u7AE1\u7AE2\u7AE4\u7AE7", 5, "\u7AEE\u7AF0\u7AF1\u7AF2\u7AF3"],
      ["b880", "\u7AF4", 4, "\u7AFB\u7AFC\u7AFE\u7B00\u7B01\u7B02\u7B05\u7B07\u7B09\u7B0C\u7B0D\u7B0E\u7B10\u7B12\u7B13\u7B16\u7B17\u7B18\u7B1A\u7B1C\u7B1D\u7B1F\u7B21\u7B22\u7B23\u7B27\u7B29\u7B2D\u6D6E\u6DAA\u798F\u88B1\u5F17\u752B\u629A\u8F85\u4FEF\u91DC\u65A7\u812F\u8151\u5E9C\u8150\u8D74\u526F\u8986\u8D4B\u590D\u5085\u4ED8\u961C\u7236\u8179\u8D1F\u5BCC\u8BA3\u9644\u5987\u7F1A\u5490\u5676\u560E\u8BE5\u6539\u6982\u9499\u76D6\u6E89\u5E72\u7518\u6746\u67D1\u7AFF\u809D\u8D76\u611F\u79C6\u6562\u8D63\u5188\u521A\u94A2\u7F38\u809B\u7EB2\u5C97\u6E2F\u6760\u7BD9\u768B\u9AD8\u818F\u7F94\u7CD5\u641E\u9550\u7A3F\u544A\u54E5\u6B4C\u6401\u6208\u9E3D\u80F3\u7599\u5272\u9769\u845B\u683C\u86E4\u9601\u9694\u94EC\u4E2A\u5404\u7ED9\u6839\u8DDF\u8015\u66F4\u5E9A\u7FB9"],
      ["b940", "\u7B2F\u7B30\u7B32\u7B34\u7B35\u7B36\u7B37\u7B39\u7B3B\u7B3D\u7B3F", 5, "\u7B46\u7B48\u7B4A\u7B4D\u7B4E\u7B53\u7B55\u7B57\u7B59\u7B5C\u7B5E\u7B5F\u7B61\u7B63", 10, "\u7B6F\u7B70\u7B73\u7B74\u7B76\u7B78\u7B7A\u7B7C\u7B7D\u7B7F\u7B81\u7B82\u7B83\u7B84\u7B86", 6, "\u7B8E\u7B8F"],
      ["b980", "\u7B91\u7B92\u7B93\u7B96\u7B98\u7B99\u7B9A\u7B9B\u7B9E\u7B9F\u7BA0\u7BA3\u7BA4\u7BA5\u7BAE\u7BAF\u7BB0\u7BB2\u7BB3\u7BB5\u7BB6\u7BB7\u7BB9", 7, "\u7BC2\u7BC3\u7BC4\u57C2\u803F\u6897\u5DE5\u653B\u529F\u606D\u9F9A\u4F9B\u8EAC\u516C\u5BAB\u5F13\u5DE9\u6C5E\u62F1\u8D21\u5171\u94A9\u52FE\u6C9F\u82DF\u72D7\u57A2\u6784\u8D2D\u591F\u8F9C\u83C7\u5495\u7B8D\u4F30\u6CBD\u5B64\u59D1\u9F13\u53E4\u86CA\u9AA8\u8C37\u80A1\u6545\u987E\u56FA\u96C7\u522E\u74DC\u5250\u5BE1\u6302\u8902\u4E56\u62D0\u602A\u68FA\u5173\u5B98\u51A0\u89C2\u7BA1\u9986\u7F50\u60EF\u704C\u8D2F\u5149\u5E7F\u901B\u7470\u89C4\u572D\u7845\u5F52\u9F9F\u95FA\u8F68\u9B3C\u8BE1\u7678\u6842\u67DC\u8DEA\u8D35\u523D\u8F8A\u6EDA\u68CD\u9505\u90ED\u56FD\u679C\u88F9\u8FC7\u54C8"],
      ["ba40", "\u7BC5\u7BC8\u7BC9\u7BCA\u7BCB\u7BCD\u7BCE\u7BCF\u7BD0\u7BD2\u7BD4", 4, "\u7BDB\u7BDC\u7BDE\u7BDF\u7BE0\u7BE2\u7BE3\u7BE4\u7BE7\u7BE8\u7BE9\u7BEB\u7BEC\u7BED\u7BEF\u7BF0\u7BF2", 4, "\u7BF8\u7BF9\u7BFA\u7BFB\u7BFD\u7BFF", 7, "\u7C08\u7C09\u7C0A\u7C0D\u7C0E\u7C10", 5, "\u7C17\u7C18\u7C19"],
      ["ba80", "\u7C1A", 4, "\u7C20", 5, "\u7C28\u7C29\u7C2B", 12, "\u7C39", 5, "\u7C42\u9AB8\u5B69\u6D77\u6C26\u4EA5\u5BB3\u9A87\u9163\u61A8\u90AF\u97E9\u542B\u6DB5\u5BD2\u51FD\u558A\u7F55\u7FF0\u64BC\u634D\u65F1\u61BE\u608D\u710A\u6C57\u6C49\u592F\u676D\u822A\u58D5\u568E\u8C6A\u6BEB\u90DD\u597D\u8017\u53F7\u6D69\u5475\u559D\u8377\u83CF\u6838\u79BE\u548C\u4F55\u5408\u76D2\u8C89\u9602\u6CB3\u6DB8\u8D6B\u8910\u9E64\u8D3A\u563F\u9ED1\u75D5\u5F88\u72E0\u6068\u54FC\u4EA8\u6A2A\u8861\u6052\u8F70\u54C4\u70D8\u8679\u9E3F\u6D2A\u5B8F\u5F18\u7EA2\u5589\u4FAF\u7334\u543C\u539A\u5019\u540E\u547C\u4E4E\u5FFD\u745A\u58F6\u846B\u80E1\u8774\u72D0\u7CCA\u6E56"],
      ["bb40", "\u7C43", 9, "\u7C4E", 36, "\u7C75", 5, "\u7C7E", 9],
      ["bb80", "\u7C88\u7C8A", 6, "\u7C93\u7C94\u7C96\u7C99\u7C9A\u7C9B\u7CA0\u7CA1\u7CA3\u7CA6\u7CA7\u7CA8\u7CA9\u7CAB\u7CAC\u7CAD\u7CAF\u7CB0\u7CB4", 4, "\u7CBA\u7CBB\u5F27\u864E\u552C\u62A4\u4E92\u6CAA\u6237\u82B1\u54D7\u534E\u733E\u6ED1\u753B\u5212\u5316\u8BDD\u69D0\u5F8A\u6000\u6DEE\u574F\u6B22\u73AF\u6853\u8FD8\u7F13\u6362\u60A3\u5524\u75EA\u8C62\u7115\u6DA3\u5BA6\u5E7B\u8352\u614C\u9EC4\u78FA\u8757\u7C27\u7687\u51F0\u60F6\u714C\u6643\u5E4C\u604D\u8C0E\u7070\u6325\u8F89\u5FBD\u6062\u86D4\u56DE\u6BC1\u6094\u6167\u5349\u60E0\u6666\u8D3F\u79FD\u4F1A\u70E9\u6C47\u8BB3\u8BF2\u7ED8\u8364\u660F\u5A5A\u9B42\u6D51\u6DF7\u8C41\u6D3B\u4F19\u706B\u83B7\u6216\u60D1\u970D\u8D27\u7978\u51FB\u573E\u57FA\u673A\u7578\u7A3D\u79EF\u7B95"],
      ["bc40", "\u7CBF\u7CC0\u7CC2\u7CC3\u7CC4\u7CC6\u7CC9\u7CCB\u7CCE", 6, "\u7CD8\u7CDA\u7CDB\u7CDD\u7CDE\u7CE1", 6, "\u7CE9", 5, "\u7CF0", 7, "\u7CF9\u7CFA\u7CFC", 13, "\u7D0B", 5],
      ["bc80", "\u7D11", 14, "\u7D21\u7D23\u7D24\u7D25\u7D26\u7D28\u7D29\u7D2A\u7D2C\u7D2D\u7D2E\u7D30", 6, "\u808C\u9965\u8FF9\u6FC0\u8BA5\u9E21\u59EC\u7EE9\u7F09\u5409\u6781\u68D8\u8F91\u7C4D\u96C6\u53CA\u6025\u75BE\u6C72\u5373\u5AC9\u7EA7\u6324\u51E0\u810A\u5DF1\u84DF\u6280\u5180\u5B63\u4F0E\u796D\u5242\u60B8\u6D4E\u5BC4\u5BC2\u8BA1\u8BB0\u65E2\u5FCC\u9645\u5993\u7EE7\u7EAA\u5609\u67B7\u5939\u4F73\u5BB6\u52A0\u835A\u988A\u8D3E\u7532\u94BE\u5047\u7A3C\u4EF7\u67B6\u9A7E\u5AC1\u6B7C\u76D1\u575A\u5C16\u7B3A\u95F4\u714E\u517C\u80A9\u8270\u5978\u7F04\u8327\u68C0\u67EC\u78B1\u7877\u62E3\u6361\u7B80\u4FED\u526A\u51CF\u8350\u69DB\u9274\u8DF5\u8D31\u89C1\u952E\u7BAD\u4EF6"],
      ["bd40", "\u7D37", 54, "\u7D6F", 7],
      ["bd80", "\u7D78", 32, "\u5065\u8230\u5251\u996F\u6E10\u6E85\u6DA7\u5EFA\u50F5\u59DC\u5C06\u6D46\u6C5F\u7586\u848B\u6868\u5956\u8BB2\u5320\u9171\u964D\u8549\u6912\u7901\u7126\u80F6\u4EA4\u90CA\u6D47\u9A84\u5A07\u56BC\u6405\u94F0\u77EB\u4FA5\u811A\u72E1\u89D2\u997A\u7F34\u7EDE\u527F\u6559\u9175\u8F7F\u8F83\u53EB\u7A96\u63ED\u63A5\u7686\u79F8\u8857\u9636\u622A\u52AB\u8282\u6854\u6770\u6377\u776B\u7AED\u6D01\u7ED3\u89E3\u59D0\u6212\u85C9\u82A5\u754C\u501F\u4ECB\u75A5\u8BEB\u5C4A\u5DFE\u7B4B\u65A4\u91D1\u4ECA\u6D25\u895F\u7D27\u9526\u4EC5\u8C28\u8FDB\u9773\u664B\u7981\u8FD1\u70EC\u6D78"],
      ["be40", "\u7D99", 12, "\u7DA7", 6, "\u7DAF", 42],
      ["be80", "\u7DDA", 32, "\u5C3D\u52B2\u8346\u5162\u830E\u775B\u6676\u9CB8\u4EAC\u60CA\u7CBE\u7CB3\u7ECF\u4E95\u8B66\u666F\u9888\u9759\u5883\u656C\u955C\u5F84\u75C9\u9756\u7ADF\u7ADE\u51C0\u70AF\u7A98\u63EA\u7A76\u7EA0\u7396\u97ED\u4E45\u7078\u4E5D\u9152\u53A9\u6551\u65E7\u81FC\u8205\u548E\u5C31\u759A\u97A0\u62D8\u72D9\u75BD\u5C45\u9A79\u83CA\u5C40\u5480\u77E9\u4E3E\u6CAE\u805A\u62D2\u636E\u5DE8\u5177\u8DDD\u8E1E\u952F\u4FF1\u53E5\u60E7\u70AC\u5267\u6350\u9E43\u5A1F\u5026\u7737\u5377\u7EE2\u6485\u652B\u6289\u6398\u5014\u7235\u89C9\u51B3\u8BC0\u7EDD\u5747\u83CC\u94A7\u519B\u541B\u5CFB"],
      ["bf40", "\u7DFB", 62],
      ["bf80", "\u7E3A\u7E3C", 4, "\u7E42", 4, "\u7E48", 21, "\u4FCA\u7AE3\u6D5A\u90E1\u9A8F\u5580\u5496\u5361\u54AF\u5F00\u63E9\u6977\u51EF\u6168\u520A\u582A\u52D8\u574E\u780D\u770B\u5EB7\u6177\u7CE0\u625B\u6297\u4EA2\u7095\u8003\u62F7\u70E4\u9760\u5777\u82DB\u67EF\u68F5\u78D5\u9897\u79D1\u58F3\u54B3\u53EF\u6E34\u514B\u523B\u5BA2\u8BFE\u80AF\u5543\u57A6\u6073\u5751\u542D\u7A7A\u6050\u5B54\u63A7\u62A0\u53E3\u6263\u5BC7\u67AF\u54ED\u7A9F\u82E6\u9177\u5E93\u88E4\u5938\u57AE\u630E\u8DE8\u80EF\u5757\u7B77\u4FA9\u5FEB\u5BBD\u6B3E\u5321\u7B50\u72C2\u6846\u77FF\u7736\u65F7\u51B5\u4E8F\u76D4\u5CBF\u7AA5\u8475\u594E\u9B41\u5080"],
      ["c040", "\u7E5E", 35, "\u7E83", 23, "\u7E9C\u7E9D\u7E9E"],
      ["c080", "\u7EAE\u7EB4\u7EBB\u7EBC\u7ED6\u7EE4\u7EEC\u7EF9\u7F0A\u7F10\u7F1E\u7F37\u7F39\u7F3B", 6, "\u7F43\u7F46", 9, "\u7F52\u7F53\u9988\u6127\u6E83\u5764\u6606\u6346\u56F0\u62EC\u6269\u5ED3\u9614\u5783\u62C9\u5587\u8721\u814A\u8FA3\u5566\u83B1\u6765\u8D56\u84DD\u5A6A\u680F\u62E6\u7BEE\u9611\u5170\u6F9C\u8C30\u63FD\u89C8\u61D2\u7F06\u70C2\u6EE5\u7405\u6994\u72FC\u5ECA\u90CE\u6717\u6D6A\u635E\u52B3\u7262\u8001\u4F6C\u59E5\u916A\u70D9\u6D9D\u52D2\u4E50\u96F7\u956D\u857E\u78CA\u7D2F\u5121\u5792\u64C2\u808B\u7C7B\u6CEA\u68F1\u695E\u51B7\u5398\u68A8\u7281\u9ECE\u7BF1\u72F8\u79BB\u6F13\u7406\u674E\u91CC\u9CA4\u793C\u8389\u8354\u540F\u6817\u4E3D\u5389\u52B1\u783E\u5386\u5229\u5088\u4F8B\u4FD0"],
      ["c140", "\u7F56\u7F59\u7F5B\u7F5C\u7F5D\u7F5E\u7F60\u7F63", 4, "\u7F6B\u7F6C\u7F6D\u7F6F\u7F70\u7F73\u7F75\u7F76\u7F77\u7F78\u7F7A\u7F7B\u7F7C\u7F7D\u7F7F\u7F80\u7F82", 7, "\u7F8B\u7F8D\u7F8F", 4, "\u7F95", 4, "\u7F9B\u7F9C\u7FA0\u7FA2\u7FA3\u7FA5\u7FA6\u7FA8", 6, "\u7FB1"],
      ["c180", "\u7FB3", 4, "\u7FBA\u7FBB\u7FBE\u7FC0\u7FC2\u7FC3\u7FC4\u7FC6\u7FC7\u7FC8\u7FC9\u7FCB\u7FCD\u7FCF", 4, "\u7FD6\u7FD7\u7FD9", 5, "\u7FE2\u7FE3\u75E2\u7ACB\u7C92\u6CA5\u96B6\u529B\u7483\u54E9\u4FE9\u8054\u83B2\u8FDE\u9570\u5EC9\u601C\u6D9F\u5E18\u655B\u8138\u94FE\u604B\u70BC\u7EC3\u7CAE\u51C9\u6881\u7CB1\u826F\u4E24\u8F86\u91CF\u667E\u4EAE\u8C05\u64A9\u804A\u50DA\u7597\u71CE\u5BE5\u8FBD\u6F66\u4E86\u6482\u9563\u5ED6\u6599\u5217\u88C2\u70C8\u52A3\u730E\u7433\u6797\u78F7\u9716\u4E34\u90BB\u9CDE\u6DCB\u51DB\u8D41\u541D\u62CE\u73B2\u83F1\u96F6\u9F84\u94C3\u4F36\u7F9A\u51CC\u7075\u9675\u5CAD\u9886\u53E6\u4EE4\u6E9C\u7409\u69B4\u786B\u998F\u7559\u5218\u7624\u6D41\u67F3\u516D\u9F99\u804B\u5499\u7B3C\u7ABF"],
      ["c240", "\u7FE4\u7FE7\u7FE8\u7FEA\u7FEB\u7FEC\u7FED\u7FEF\u7FF2\u7FF4", 6, "\u7FFD\u7FFE\u7FFF\u8002\u8007\u8008\u8009\u800A\u800E\u800F\u8011\u8013\u801A\u801B\u801D\u801E\u801F\u8021\u8023\u8024\u802B", 5, "\u8032\u8034\u8039\u803A\u803C\u803E\u8040\u8041\u8044\u8045\u8047\u8048\u8049\u804E\u804F\u8050\u8051\u8053\u8055\u8056\u8057"],
      ["c280", "\u8059\u805B", 13, "\u806B", 5, "\u8072", 11, "\u9686\u5784\u62E2\u9647\u697C\u5A04\u6402\u7BD3\u6F0F\u964B\u82A6\u5362\u9885\u5E90\u7089\u63B3\u5364\u864F\u9C81\u9E93\u788C\u9732\u8DEF\u8D42\u9E7F\u6F5E\u7984\u5F55\u9646\u622E\u9A74\u5415\u94DD\u4FA3\u65C5\u5C65\u5C61\u7F15\u8651\u6C2F\u5F8B\u7387\u6EE4\u7EFF\u5CE6\u631B\u5B6A\u6EE6\u5375\u4E71\u63A0\u7565\u62A1\u8F6E\u4F26\u4ED1\u6CA6\u7EB6\u8BBA\u841D\u87BA\u7F57\u903B\u9523\u7BA9\u9AA1\u88F8\u843D\u6D1B\u9A86\u7EDC\u5988\u9EBB\u739B\u7801\u8682\u9A6C\u9A82\u561B\u5417\u57CB\u4E70\u9EA6\u5356\u8FC8\u8109\u7792\u9992\u86EE\u6EE1\u8513\u66FC\u6162\u6F2B"],
      ["c340", "\u807E\u8081\u8082\u8085\u8088\u808A\u808D", 5, "\u8094\u8095\u8097\u8099\u809E\u80A3\u80A6\u80A7\u80A8\u80AC\u80B0\u80B3\u80B5\u80B6\u80B8\u80B9\u80BB\u80C5\u80C7", 4, "\u80CF", 6, "\u80D8\u80DF\u80E0\u80E2\u80E3\u80E6\u80EE\u80F5\u80F7\u80F9\u80FB\u80FE\u80FF\u8100\u8101\u8103\u8104\u8105\u8107\u8108\u810B"],
      ["c380", "\u810C\u8115\u8117\u8119\u811B\u811C\u811D\u811F", 12, "\u812D\u812E\u8130\u8133\u8134\u8135\u8137\u8139", 4, "\u813F\u8C29\u8292\u832B\u76F2\u6C13\u5FD9\u83BD\u732B\u8305\u951A\u6BDB\u77DB\u94C6\u536F\u8302\u5192\u5E3D\u8C8C\u8D38\u4E48\u73AB\u679A\u6885\u9176\u9709\u7164\u6CA1\u7709\u5A92\u9541\u6BCF\u7F8E\u6627\u5BD0\u59B9\u5A9A\u95E8\u95F7\u4EEC\u840C\u8499\u6AAC\u76DF\u9530\u731B\u68A6\u5B5F\u772F\u919A\u9761\u7CDC\u8FF7\u8C1C\u5F25\u7C73\u79D8\u89C5\u6CCC\u871C\u5BC6\u5E42\u68C9\u7720\u7EF5\u5195\u514D\u52C9\u5A29\u7F05\u9762\u82D7\u63CF\u7784\u85D0\u79D2\u6E3A\u5E99\u5999\u8511\u706D\u6C11\u62BF\u76BF\u654F\u60AF\u95FD\u660E\u879F\u9E23\u94ED\u540D\u547D\u8C2C\u6478"],
      ["c440", "\u8140", 5, "\u8147\u8149\u814D\u814E\u814F\u8152\u8156\u8157\u8158\u815B", 4, "\u8161\u8162\u8163\u8164\u8166\u8168\u816A\u816B\u816C\u816F\u8172\u8173\u8175\u8176\u8177\u8178\u8181\u8183", 4, "\u8189\u818B\u818C\u818D\u818E\u8190\u8192", 5, "\u8199\u819A\u819E", 4, "\u81A4\u81A5"],
      ["c480", "\u81A7\u81A9\u81AB", 7, "\u81B4", 5, "\u81BC\u81BD\u81BE\u81BF\u81C4\u81C5\u81C7\u81C8\u81C9\u81CB\u81CD", 6, "\u6479\u8611\u6A21\u819C\u78E8\u6469\u9B54\u62B9\u672B\u83AB\u58A8\u9ED8\u6CAB\u6F20\u5BDE\u964C\u8C0B\u725F\u67D0\u62C7\u7261\u4EA9\u59C6\u6BCD\u5893\u66AE\u5E55\u52DF\u6155\u6728\u76EE\u7766\u7267\u7A46\u62FF\u54EA\u5450\u94A0\u90A3\u5A1C\u7EB3\u6C16\u4E43\u5976\u8010\u5948\u5357\u7537\u96BE\u56CA\u6320\u8111\u607C\u95F9\u6DD6\u5462\u9981\u5185\u5AE9\u80FD\u59AE\u9713\u502A\u6CE5\u5C3C\u62DF\u4F60\u533F\u817B\u9006\u6EBA\u852B\u62C8\u5E74\u78BE\u64B5\u637B\u5FF5\u5A18\u917F\u9E1F\u5C3F\u634F\u8042\u5B7D\u556E\u954A\u954D\u6D85\u60A8\u67E0\u72DE\u51DD\u5B81"],
      ["c540", "\u81D4", 14, "\u81E4\u81E5\u81E6\u81E8\u81E9\u81EB\u81EE", 4, "\u81F5", 5, "\u81FD\u81FF\u8203\u8207", 4, "\u820E\u820F\u8211\u8213\u8215", 5, "\u821D\u8220\u8224\u8225\u8226\u8227\u8229\u822E\u8232\u823A\u823C\u823D\u823F"],
      ["c580", "\u8240\u8241\u8242\u8243\u8245\u8246\u8248\u824A\u824C\u824D\u824E\u8250", 7, "\u8259\u825B\u825C\u825D\u825E\u8260", 7, "\u8269\u62E7\u6CDE\u725B\u626D\u94AE\u7EBD\u8113\u6D53\u519C\u5F04\u5974\u52AA\u6012\u5973\u6696\u8650\u759F\u632A\u61E6\u7CEF\u8BFA\u54E6\u6B27\u9E25\u6BB4\u85D5\u5455\u5076\u6CA4\u556A\u8DB4\u722C\u5E15\u6015\u7436\u62CD\u6392\u724C\u5F98\u6E43\u6D3E\u6500\u6F58\u76D8\u78D0\u76FC\u7554\u5224\u53DB\u4E53\u5E9E\u65C1\u802A\u80D6\u629B\u5486\u5228\u70AE\u888D\u8DD1\u6CE1\u5478\u80DA\u57F9\u88F4\u8D54\u966A\u914D\u4F69\u6C9B\u55B7\u76C6\u7830\u62A8\u70F9\u6F8E\u5F6D\u84EC\u68DA\u787C\u7BF7\u81A8\u670B\u9E4F\u6367\u78B0\u576F\u7812\u9739\u6279\u62AB\u5288\u7435\u6BD7"],
      ["c640", "\u826A\u826B\u826C\u826D\u8271\u8275\u8276\u8277\u8278\u827B\u827C\u8280\u8281\u8283\u8285\u8286\u8287\u8289\u828C\u8290\u8293\u8294\u8295\u8296\u829A\u829B\u829E\u82A0\u82A2\u82A3\u82A7\u82B2\u82B5\u82B6\u82BA\u82BB\u82BC\u82BF\u82C0\u82C2\u82C3\u82C5\u82C6\u82C9\u82D0\u82D6\u82D9\u82DA\u82DD\u82E2\u82E7\u82E8\u82E9\u82EA\u82EC\u82ED\u82EE\u82F0\u82F2\u82F3\u82F5\u82F6\u82F8"],
      ["c680", "\u82FA\u82FC", 4, "\u830A\u830B\u830D\u8310\u8312\u8313\u8316\u8318\u8319\u831D", 9, "\u8329\u832A\u832E\u8330\u8332\u8337\u833B\u833D\u5564\u813E\u75B2\u76AE\u5339\u75DE\u50FB\u5C41\u8B6C\u7BC7\u504F\u7247\u9A97\u98D8\u6F02\u74E2\u7968\u6487\u77A5\u62FC\u9891\u8D2B\u54C1\u8058\u4E52\u576A\u82F9\u840D\u5E73\u51ED\u74F6\u8BC4\u5C4F\u5761\u6CFC\u9887\u5A46\u7834\u9B44\u8FEB\u7C95\u5256\u6251\u94FA\u4EC6\u8386\u8461\u83E9\u84B2\u57D4\u6734\u5703\u666E\u6D66\u8C31\u66DD\u7011\u671F\u6B3A\u6816\u621A\u59BB\u4E03\u51C4\u6F06\u67D2\u6C8F\u5176\u68CB\u5947\u6B67\u7566\u5D0E\u8110\u9F50\u65D7\u7948\u7941\u9A91\u8D77\u5C82\u4E5E\u4F01\u542F\u5951\u780C\u5668\u6C14\u8FC4\u5F03\u6C7D\u6CE3\u8BAB\u6390"],
      ["c740", "\u833E\u833F\u8341\u8342\u8344\u8345\u8348\u834A", 4, "\u8353\u8355", 4, "\u835D\u8362\u8370", 6, "\u8379\u837A\u837E", 6, "\u8387\u8388\u838A\u838B\u838C\u838D\u838F\u8390\u8391\u8394\u8395\u8396\u8397\u8399\u839A\u839D\u839F\u83A1", 6, "\u83AC\u83AD\u83AE"],
      ["c780", "\u83AF\u83B5\u83BB\u83BE\u83BF\u83C2\u83C3\u83C4\u83C6\u83C8\u83C9\u83CB\u83CD\u83CE\u83D0\u83D1\u83D2\u83D3\u83D5\u83D7\u83D9\u83DA\u83DB\u83DE\u83E2\u83E3\u83E4\u83E6\u83E7\u83E8\u83EB\u83EC\u83ED\u6070\u6D3D\u7275\u6266\u948E\u94C5\u5343\u8FC1\u7B7E\u4EDF\u8C26\u4E7E\u9ED4\u94B1\u94B3\u524D\u6F5C\u9063\u6D45\u8C34\u5811\u5D4C\u6B20\u6B49\u67AA\u545B\u8154\u7F8C\u5899\u8537\u5F3A\u62A2\u6A47\u9539\u6572\u6084\u6865\u77A7\u4E54\u4FA8\u5DE7\u9798\u64AC\u7FD8\u5CED\u4FCF\u7A8D\u5207\u8304\u4E14\u602F\u7A83\u94A6\u4FB5\u4EB2\u79E6\u7434\u52E4\u82B9\u64D2\u79BD\u5BDD\u6C81\u9752\u8F7B\u6C22\u503E\u537F\u6E05\u64CE\u6674\u6C30\u60C5\u9877\u8BF7\u5E86\u743C\u7A77\u79CB\u4E18\u90B1\u7403\u6C42\u56DA\u914B\u6CC5\u8D8B\u533A\u86C6\u66F2\u8EAF\u5C48\u9A71\u6E20"],
      ["c840", "\u83EE\u83EF\u83F3", 4, "\u83FA\u83FB\u83FC\u83FE\u83FF\u8400\u8402\u8405\u8407\u8408\u8409\u840A\u8410\u8412", 5, "\u8419\u841A\u841B\u841E", 5, "\u8429", 7, "\u8432", 5, "\u8439\u843A\u843B\u843E", 7, "\u8447\u8448\u8449"],
      ["c880", "\u844A", 6, "\u8452", 4, "\u8458\u845D\u845E\u845F\u8460\u8462\u8464", 4, "\u846A\u846E\u846F\u8470\u8472\u8474\u8477\u8479\u847B\u847C\u53D6\u5A36\u9F8B\u8DA3\u53BB\u5708\u98A7\u6743\u919B\u6CC9\u5168\u75CA\u62F3\u72AC\u5238\u529D\u7F3A\u7094\u7638\u5374\u9E4A\u69B7\u786E\u96C0\u88D9\u7FA4\u7136\u71C3\u5189\u67D3\u74E4\u58E4\u6518\u56B7\u8BA9\u9976\u6270\u7ED5\u60F9\u70ED\u58EC\u4EC1\u4EBA\u5FCD\u97E7\u4EFB\u8BA4\u5203\u598A\u7EAB\u6254\u4ECD\u65E5\u620E\u8338\u84C9\u8363\u878D\u7194\u6EB6\u5BB9\u7ED2\u5197\u63C9\u67D4\u8089\u8339\u8815\u5112\u5B7A\u5982\u8FB1\u4E73\u6C5D\u5165\u8925\u8F6F\u962E\u854A\u745E\u9510\u95F0\u6DA6\u82E5\u5F31\u6492\u6D12\u8428\u816E\u9CC3\u585E\u8D5B\u4E09\u53C1"],
      ["c940", "\u847D", 4, "\u8483\u8484\u8485\u8486\u848A\u848D\u848F", 7, "\u8498\u849A\u849B\u849D\u849E\u849F\u84A0\u84A2", 12, "\u84B0\u84B1\u84B3\u84B5\u84B6\u84B7\u84BB\u84BC\u84BE\u84C0\u84C2\u84C3\u84C5\u84C6\u84C7\u84C8\u84CB\u84CC\u84CE\u84CF\u84D2\u84D4\u84D5\u84D7"],
      ["c980", "\u84D8", 4, "\u84DE\u84E1\u84E2\u84E4\u84E7", 4, "\u84ED\u84EE\u84EF\u84F1", 10, "\u84FD\u84FE\u8500\u8501\u8502\u4F1E\u6563\u6851\u55D3\u4E27\u6414\u9A9A\u626B\u5AC2\u745F\u8272\u6DA9\u68EE\u50E7\u838E\u7802\u6740\u5239\u6C99\u7EB1\u50BB\u5565\u715E\u7B5B\u6652\u73CA\u82EB\u6749\u5C71\u5220\u717D\u886B\u95EA\u9655\u64C5\u8D61\u81B3\u5584\u6C55\u6247\u7F2E\u5892\u4F24\u5546\u8D4F\u664C\u4E0A\u5C1A\u88F3\u68A2\u634E\u7A0D\u70E7\u828D\u52FA\u97F6\u5C11\u54E8\u90B5\u7ECD\u5962\u8D4A\u86C7\u820C\u820D\u8D66\u6444\u5C04\u6151\u6D89\u793E\u8BBE\u7837\u7533\u547B\u4F38\u8EAB\u6DF1\u5A20\u7EC5\u795E\u6C88\u5BA1\u5A76\u751A\u80BE\u614E\u6E17\u58F0\u751F\u7525\u7272\u5347\u7EF3"],
      ["ca40", "\u8503", 8, "\u850D\u850E\u850F\u8510\u8512\u8514\u8515\u8516\u8518\u8519\u851B\u851C\u851D\u851E\u8520\u8522", 8, "\u852D", 9, "\u853E", 4, "\u8544\u8545\u8546\u8547\u854B", 10],
      ["ca80", "\u8557\u8558\u855A\u855B\u855C\u855D\u855F", 4, "\u8565\u8566\u8567\u8569", 8, "\u8573\u8575\u8576\u8577\u8578\u857C\u857D\u857F\u8580\u8581\u7701\u76DB\u5269\u80DC\u5723\u5E08\u5931\u72EE\u65BD\u6E7F\u8BD7\u5C38\u8671\u5341\u77F3\u62FE\u65F6\u4EC0\u98DF\u8680\u5B9E\u8BC6\u53F2\u77E2\u4F7F\u5C4E\u9A76\u59CB\u5F0F\u793A\u58EB\u4E16\u67FF\u4E8B\u62ED\u8A93\u901D\u52BF\u662F\u55DC\u566C\u9002\u4ED5\u4F8D\u91CA\u9970\u6C0F\u5E02\u6043\u5BA4\u89C6\u8BD5\u6536\u624B\u9996\u5B88\u5BFF\u6388\u552E\u53D7\u7626\u517D\u852C\u67A2\u68B3\u6B8A\u6292\u8F93\u53D4\u8212\u6DD1\u758F\u4E66\u8D4E\u5B70\u719F\u85AF\u6691\u66D9\u7F72\u8700\u9ECD\u9F20\u5C5E\u672F\u8FF0\u6811\u675F\u620D\u7AD6\u5885\u5EB6\u6570\u6F31"],
      ["cb40", "\u8582\u8583\u8586\u8588", 6, "\u8590", 10, "\u859D", 6, "\u85A5\u85A6\u85A7\u85A9\u85AB\u85AC\u85AD\u85B1", 5, "\u85B8\u85BA", 6, "\u85C2", 6, "\u85CA", 4, "\u85D1\u85D2"],
      ["cb80", "\u85D4\u85D6", 5, "\u85DD", 6, "\u85E5\u85E6\u85E7\u85E8\u85EA", 14, "\u6055\u5237\u800D\u6454\u8870\u7529\u5E05\u6813\u62F4\u971C\u53CC\u723D\u8C01\u6C34\u7761\u7A0E\u542E\u77AC\u987A\u821C\u8BF4\u7855\u6714\u70C1\u65AF\u6495\u5636\u601D\u79C1\u53F8\u4E1D\u6B7B\u8086\u5BFA\u55E3\u56DB\u4F3A\u4F3C\u9972\u5DF3\u677E\u8038\u6002\u9882\u9001\u5B8B\u8BBC\u8BF5\u641C\u8258\u64DE\u55FD\u82CF\u9165\u4FD7\u7D20\u901F\u7C9F\u50F3\u5851\u6EAF\u5BBF\u8BC9\u8083\u9178\u849C\u7B97\u867D\u968B\u968F\u7EE5\u9AD3\u788E\u5C81\u7A57\u9042\u96A7\u795F\u5B59\u635F\u7B0B\u84D1\u68AD\u5506\u7F29\u7410\u7D22\u9501\u6240\u584C\u4ED6\u5B83\u5979\u5854"],
      ["cc40", "\u85F9\u85FA\u85FC\u85FD\u85FE\u8600", 4, "\u8606", 10, "\u8612\u8613\u8614\u8615\u8617", 15, "\u8628\u862A", 13, "\u8639\u863A\u863B\u863D\u863E\u863F\u8640"],
      ["cc80", "\u8641", 11, "\u8652\u8653\u8655", 4, "\u865B\u865C\u865D\u865F\u8660\u8661\u8663", 7, "\u736D\u631E\u8E4B\u8E0F\u80CE\u82D4\u62AC\u53F0\u6CF0\u915E\u592A\u6001\u6C70\u574D\u644A\u8D2A\u762B\u6EE9\u575B\u6A80\u75F0\u6F6D\u8C2D\u8C08\u5766\u6BEF\u8892\u78B3\u63A2\u53F9\u70AD\u6C64\u5858\u642A\u5802\u68E0\u819B\u5510\u7CD6\u5018\u8EBA\u6DCC\u8D9F\u70EB\u638F\u6D9B\u6ED4\u7EE6\u8404\u6843\u9003\u6DD8\u9676\u8BA8\u5957\u7279\u85E4\u817E\u75BC\u8A8A\u68AF\u5254\u8E22\u9511\u63D0\u9898\u8E44\u557C\u4F53\u66FF\u568F\u60D5\u6D95\u5243\u5C49\u5929\u6DFB\u586B\u7530\u751C\u606C\u8214\u8146\u6311\u6761\u8FE2\u773A\u8DF3\u8D34\u94C1\u5E16\u5385\u542C\u70C3"],
      ["cd40", "\u866D\u866F\u8670\u8672", 6, "\u8683", 6, "\u868E", 4, "\u8694\u8696", 5, "\u869E", 4, "\u86A5\u86A6\u86AB\u86AD\u86AE\u86B2\u86B3\u86B7\u86B8\u86B9\u86BB", 4, "\u86C1\u86C2\u86C3\u86C5\u86C8\u86CC\u86CD\u86D2\u86D3\u86D5\u86D6\u86D7\u86DA\u86DC"],
      ["cd80", "\u86DD\u86E0\u86E1\u86E2\u86E3\u86E5\u86E6\u86E7\u86E8\u86EA\u86EB\u86EC\u86EF\u86F5\u86F6\u86F7\u86FA\u86FB\u86FC\u86FD\u86FF\u8701\u8704\u8705\u8706\u870B\u870C\u870E\u870F\u8710\u8711\u8714\u8716\u6C40\u5EF7\u505C\u4EAD\u5EAD\u633A\u8247\u901A\u6850\u916E\u77B3\u540C\u94DC\u5F64\u7AE5\u6876\u6345\u7B52\u7EDF\u75DB\u5077\u6295\u5934\u900F\u51F8\u79C3\u7A81\u56FE\u5F92\u9014\u6D82\u5C60\u571F\u5410\u5154\u6E4D\u56E2\u63A8\u9893\u817F\u8715\u892A\u9000\u541E\u5C6F\u81C0\u62D6\u6258\u8131\u9E35\u9640\u9A6E\u9A7C\u692D\u59A5\u62D3\u553E\u6316\u54C7\u86D9\u6D3C\u5A03\u74E6\u889C\u6B6A\u5916\u8C4C\u5F2F\u6E7E\u73A9\u987D\u4E38\u70F7\u5B8C\u7897\u633D\u665A\u7696\u60CB\u5B9B\u5A49\u4E07\u8155\u6C6A\u738B\u4EA1\u6789\u7F51\u5F80\u65FA\u671B\u5FD8\u5984\u5A01"],
      ["ce40", "\u8719\u871B\u871D\u871F\u8720\u8724\u8726\u8727\u8728\u872A\u872B\u872C\u872D\u872F\u8730\u8732\u8733\u8735\u8736\u8738\u8739\u873A\u873C\u873D\u8740", 6, "\u874A\u874B\u874D\u874F\u8750\u8751\u8752\u8754\u8755\u8756\u8758\u875A", 5, "\u8761\u8762\u8766", 7, "\u876F\u8771\u8772\u8773\u8775"],
      ["ce80", "\u8777\u8778\u8779\u877A\u877F\u8780\u8781\u8784\u8786\u8787\u8789\u878A\u878C\u878E", 4, "\u8794\u8795\u8796\u8798", 6, "\u87A0", 4, "\u5DCD\u5FAE\u5371\u97E6\u8FDD\u6845\u56F4\u552F\u60DF\u4E3A\u6F4D\u7EF4\u82C7\u840E\u59D4\u4F1F\u4F2A\u5C3E\u7EAC\u672A\u851A\u5473\u754F\u80C3\u5582\u9B4F\u4F4D\u6E2D\u8C13\u5C09\u6170\u536B\u761F\u6E29\u868A\u6587\u95FB\u7EB9\u543B\u7A33\u7D0A\u95EE\u55E1\u7FC1\u74EE\u631D\u8717\u6DA1\u7A9D\u6211\u65A1\u5367\u63E1\u6C83\u5DEB\u545C\u94A8\u4E4C\u6C61\u8BEC\u5C4B\u65E0\u829C\u68A7\u543E\u5434\u6BCB\u6B66\u4E94\u6342\u5348\u821E\u4F0D\u4FAE\u575E\u620A\u96FE\u6664\u7269\u52FF\u52A1\u609F\u8BEF\u6614\u7199\u6790\u897F\u7852\u77FD\u6670\u563B\u5438\u9521\u727A"],
      ["cf40", "\u87A5\u87A6\u87A7\u87A9\u87AA\u87AE\u87B0\u87B1\u87B2\u87B4\u87B6\u87B7\u87B8\u87B9\u87BB\u87BC\u87BE\u87BF\u87C1", 4, "\u87C7\u87C8\u87C9\u87CC", 4, "\u87D4", 6, "\u87DC\u87DD\u87DE\u87DF\u87E1\u87E2\u87E3\u87E4\u87E6\u87E7\u87E8\u87E9\u87EB\u87EC\u87ED\u87EF", 9],
      ["cf80", "\u87FA\u87FB\u87FC\u87FD\u87FF\u8800\u8801\u8802\u8804", 5, "\u880B", 7, "\u8814\u8817\u8818\u8819\u881A\u881C", 4, "\u8823\u7A00\u606F\u5E0C\u6089\u819D\u5915\u60DC\u7184\u70EF\u6EAA\u6C50\u7280\u6A84\u88AD\u5E2D\u4E60\u5AB3\u559C\u94E3\u6D17\u7CFB\u9699\u620F\u7EC6\u778E\u867E\u5323\u971E\u8F96\u6687\u5CE1\u4FA0\u72ED\u4E0B\u53A6\u590F\u5413\u6380\u9528\u5148\u4ED9\u9C9C\u7EA4\u54B8\u8D24\u8854\u8237\u95F2\u6D8E\u5F26\u5ACC\u663E\u9669\u73B0\u732E\u53BF\u817A\u9985\u7FA1\u5BAA\u9677\u9650\u7EBF\u76F8\u53A2\u9576\u9999\u7BB1\u8944\u6E58\u4E61\u7FD4\u7965\u8BE6\u60F3\u54CD\u4EAB\u9879\u5DF7\u6A61\u50CF\u5411\u8C61\u8427\u785D\u9704\u524A\u54EE\u56A3\u9500\u6D88\u5BB5\u6DC6\u6653"],
      ["d040", "\u8824", 13, "\u8833", 5, "\u883A\u883B\u883D\u883E\u883F\u8841\u8842\u8843\u8846", 5, "\u884E", 5, "\u8855\u8856\u8858\u885A", 6, "\u8866\u8867\u886A\u886D\u886F\u8871\u8873\u8874\u8875\u8876\u8878\u8879\u887A"],
      ["d080", "\u887B\u887C\u8880\u8883\u8886\u8887\u8889\u888A\u888C\u888E\u888F\u8890\u8891\u8893\u8894\u8895\u8897", 4, "\u889D", 4, "\u88A3\u88A5", 5, "\u5C0F\u5B5D\u6821\u8096\u5578\u7B11\u6548\u6954\u4E9B\u6B47\u874E\u978B\u534F\u631F\u643A\u90AA\u659C\u80C1\u8C10\u5199\u68B0\u5378\u87F9\u61C8\u6CC4\u6CFB\u8C22\u5C51\u85AA\u82AF\u950C\u6B23\u8F9B\u65B0\u5FFB\u5FC3\u4FE1\u8845\u661F\u8165\u7329\u60FA\u5174\u5211\u578B\u5F62\u90A2\u884C\u9192\u5E78\u674F\u6027\u59D3\u5144\u51F6\u80F8\u5308\u6C79\u96C4\u718A\u4F11\u4FEE\u7F9E\u673D\u55C5\u9508\u79C0\u8896\u7EE3\u589F\u620C\u9700\u865A\u5618\u987B\u5F90\u8BB8\u84C4\u9157\u53D9\u65ED\u5E8F\u755C\u6064\u7D6E\u5A7F\u7EEA\u7EED\u8F69\u55A7\u5BA3\u60AC\u65CB\u7384"],
      ["d140", "\u88AC\u88AE\u88AF\u88B0\u88B2", 4, "\u88B8\u88B9\u88BA\u88BB\u88BD\u88BE\u88BF\u88C0\u88C3\u88C4\u88C7\u88C8\u88CA\u88CB\u88CC\u88CD\u88CF\u88D0\u88D1\u88D3\u88D6\u88D7\u88DA", 4, "\u88E0\u88E1\u88E6\u88E7\u88E9", 6, "\u88F2\u88F5\u88F6\u88F7\u88FA\u88FB\u88FD\u88FF\u8900\u8901\u8903", 5],
      ["d180", "\u8909\u890B", 4, "\u8911\u8914", 4, "\u891C", 4, "\u8922\u8923\u8924\u8926\u8927\u8928\u8929\u892C\u892D\u892E\u892F\u8931\u8932\u8933\u8935\u8937\u9009\u7663\u7729\u7EDA\u9774\u859B\u5B66\u7A74\u96EA\u8840\u52CB\u718F\u5FAA\u65EC\u8BE2\u5BFB\u9A6F\u5DE1\u6B89\u6C5B\u8BAD\u8BAF\u900A\u8FC5\u538B\u62BC\u9E26\u9E2D\u5440\u4E2B\u82BD\u7259\u869C\u5D16\u8859\u6DAF\u96C5\u54D1\u4E9A\u8BB6\u7109\u54BD\u9609\u70DF\u6DF9\u76D0\u4E25\u7814\u8712\u5CA9\u5EF6\u8A00\u989C\u960E\u708E\u6CBF\u5944\u63A9\u773C\u884D\u6F14\u8273\u5830\u71D5\u538C\u781A\u96C1\u5501\u5F66\u7130\u5BB4\u8C1A\u9A8C\u6B83\u592E\u9E2F\u79E7\u6768\u626C\u4F6F\u75A1\u7F8A\u6D0B\u9633\u6C27\u4EF0\u75D2\u517B\u6837\u6F3E\u9080\u8170\u5996\u7476"],
      ["d240", "\u8938", 8, "\u8942\u8943\u8945", 24, "\u8960", 5, "\u8967", 19, "\u897C"],
      ["d280", "\u897D\u897E\u8980\u8982\u8984\u8985\u8987", 26, "\u6447\u5C27\u9065\u7A91\u8C23\u59DA\u54AC\u8200\u836F\u8981\u8000\u6930\u564E\u8036\u7237\u91CE\u51B6\u4E5F\u9875\u6396\u4E1A\u53F6\u66F3\u814B\u591C\u6DB2\u4E00\u58F9\u533B\u63D6\u94F1\u4F9D\u4F0A\u8863\u9890\u5937\u9057\u79FB\u4EEA\u80F0\u7591\u6C82\u5B9C\u59E8\u5F5D\u6905\u8681\u501A\u5DF2\u4E59\u77E3\u4EE5\u827A\u6291\u6613\u9091\u5C79\u4EBF\u5F79\u81C6\u9038\u8084\u75AB\u4EA6\u88D4\u610F\u6BC5\u5FC6\u4E49\u76CA\u6EA2\u8BE3\u8BAE\u8C0A\u8BD1\u5F02\u7FFC\u7FCC\u7ECE\u8335\u836B\u56E0\u6BB7\u97F3\u9634\u59FB\u541F\u94F6\u6DEB\u5BC5\u996E\u5C39\u5F15\u9690"],
      ["d340", "\u89A2", 30, "\u89C3\u89CD\u89D3\u89D4\u89D5\u89D7\u89D8\u89D9\u89DB\u89DD\u89DF\u89E0\u89E1\u89E2\u89E4\u89E7\u89E8\u89E9\u89EA\u89EC\u89ED\u89EE\u89F0\u89F1\u89F2\u89F4", 6],
      ["d380", "\u89FB", 4, "\u8A01", 5, "\u8A08", 21, "\u5370\u82F1\u6A31\u5A74\u9E70\u5E94\u7F28\u83B9\u8424\u8425\u8367\u8747\u8FCE\u8D62\u76C8\u5F71\u9896\u786C\u6620\u54DF\u62E5\u4F63\u81C3\u75C8\u5EB8\u96CD\u8E0A\u86F9\u548F\u6CF3\u6D8C\u6C38\u607F\u52C7\u7528\u5E7D\u4F18\u60A0\u5FE7\u5C24\u7531\u90AE\u94C0\u72B9\u6CB9\u6E38\u9149\u6709\u53CB\u53F3\u4F51\u91C9\u8BF1\u53C8\u5E7C\u8FC2\u6DE4\u4E8E\u76C2\u6986\u865E\u611A\u8206\u4F59\u4FDE\u903E\u9C7C\u6109\u6E1D\u6E14\u9685\u4E88\u5A31\u96E8\u4E0E\u5C7F\u79B9\u5B87\u8BED\u7FBD\u7389\u57DF\u828B\u90C1\u5401\u9047\u55BB\u5CEA\u5FA1\u6108\u6B32\u72F1\u80B2\u8A89"],
      ["d440", "\u8A1E", 31, "\u8A3F", 8, "\u8A49", 21],
      ["d480", "\u8A5F", 25, "\u8A7A", 6, "\u6D74\u5BD3\u88D5\u9884\u8C6B\u9A6D\u9E33\u6E0A\u51A4\u5143\u57A3\u8881\u539F\u63F4\u8F95\u56ED\u5458\u5706\u733F\u6E90\u7F18\u8FDC\u82D1\u613F\u6028\u9662\u66F0\u7EA6\u8D8A\u8DC3\u94A5\u5CB3\u7CA4\u6708\u60A6\u9605\u8018\u4E91\u90E7\u5300\u9668\u5141\u8FD0\u8574\u915D\u6655\u97F5\u5B55\u531D\u7838\u6742\u683D\u54C9\u707E\u5BB0\u8F7D\u518D\u5728\u54B1\u6512\u6682\u8D5E\u8D43\u810F\u846C\u906D\u7CDF\u51FF\u85FB\u67A3\u65E9\u6FA1\u86A4\u8E81\u566A\u9020\u7682\u7076\u71E5\u8D23\u62E9\u5219\u6CFD\u8D3C\u600E\u589E\u618E\u66FE\u8D60\u624E\u55B3\u6E23\u672D\u8F67"],
      ["d540", "\u8A81", 7, "\u8A8B", 7, "\u8A94", 46],
      ["d580", "\u8AC3", 32, "\u94E1\u95F8\u7728\u6805\u69A8\u548B\u4E4D\u70B8\u8BC8\u6458\u658B\u5B85\u7A84\u503A\u5BE8\u77BB\u6BE1\u8A79\u7C98\u6CBE\u76CF\u65A9\u8F97\u5D2D\u5C55\u8638\u6808\u5360\u6218\u7AD9\u6E5B\u7EFD\u6A1F\u7AE0\u5F70\u6F33\u5F20\u638C\u6DA8\u6756\u4E08\u5E10\u8D26\u4ED7\u80C0\u7634\u969C\u62DB\u662D\u627E\u6CBC\u8D75\u7167\u7F69\u5146\u8087\u53EC\u906E\u6298\u54F2\u86F0\u8F99\u8005\u9517\u8517\u8FD9\u6D59\u73CD\u659F\u771F\u7504\u7827\u81FB\u8D1E\u9488\u4FA6\u6795\u75B9\u8BCA\u9707\u632F\u9547\u9635\u84B8\u6323\u7741\u5F81\u72F0\u4E89\u6014\u6574\u62EF\u6B63\u653F"],
      ["d640", "\u8AE4", 34, "\u8B08", 27],
      ["d680", "\u8B24\u8B25\u8B27", 30, "\u5E27\u75C7\u90D1\u8BC1\u829D\u679D\u652F\u5431\u8718\u77E5\u80A2\u8102\u6C41\u4E4B\u7EC7\u804C\u76F4\u690D\u6B96\u6267\u503C\u4F84\u5740\u6307\u6B62\u8DBE\u53EA\u65E8\u7EB8\u5FD7\u631A\u63B7\u81F3\u81F4\u7F6E\u5E1C\u5CD9\u5236\u667A\u79E9\u7A1A\u8D28\u7099\u75D4\u6EDE\u6CBB\u7A92\u4E2D\u76C5\u5FE0\u949F\u8877\u7EC8\u79CD\u80BF\u91CD\u4EF2\u4F17\u821F\u5468\u5DDE\u6D32\u8BCC\u7CA5\u8F74\u8098\u5E1A\u5492\u76B1\u5B99\u663C\u9AA4\u73E0\u682A\u86DB\u6731\u732A\u8BF8\u8BDB\u9010\u7AF9\u70DB\u716E\u62C4\u77A9\u5631\u4E3B\u8457\u67F1\u52A9\u86C0\u8D2E\u94F8\u7B51"],
      ["d740", "\u8B46", 31, "\u8B67", 4, "\u8B6D", 25],
      ["d780", "\u8B87", 24, "\u8BAC\u8BB1\u8BBB\u8BC7\u8BD0\u8BEA\u8C09\u8C1E\u4F4F\u6CE8\u795D\u9A7B\u6293\u722A\u62FD\u4E13\u7816\u8F6C\u64B0\u8D5A\u7BC6\u6869\u5E84\u88C5\u5986\u649E\u58EE\u72B6\u690E\u9525\u8FFD\u8D58\u5760\u7F00\u8C06\u51C6\u6349\u62D9\u5353\u684C\u7422\u8301\u914C\u5544\u7740\u707C\u6D4A\u5179\u54A8\u8D44\u59FF\u6ECB\u6DC4\u5B5C\u7D2B\u4ED4\u7C7D\u6ED3\u5B50\u81EA\u6E0D\u5B57\u9B03\u68D5\u8E2A\u5B97\u7EFC\u603B\u7EB5\u90B9\u8D70\u594F\u63CD\u79DF\u8DB3\u5352\u65CF\u7956\u8BC5\u963B\u7EC4\u94BB\u7E82\u5634\u9189\u6700\u7F6A\u5C0A\u9075\u6628\u5DE6\u4F50\u67DE\u505A\u4F5C\u5750\u5EA7"],
      ["d840", "\u8C38", 8, "\u8C42\u8C43\u8C44\u8C45\u8C48\u8C4A\u8C4B\u8C4D", 7, "\u8C56\u8C57\u8C58\u8C59\u8C5B", 5, "\u8C63", 6, "\u8C6C", 6, "\u8C74\u8C75\u8C76\u8C77\u8C7B", 6, "\u8C83\u8C84\u8C86\u8C87"],
      ["d880", "\u8C88\u8C8B\u8C8D", 6, "\u8C95\u8C96\u8C97\u8C99", 20, "\u4E8D\u4E0C\u5140\u4E10\u5EFF\u5345\u4E15\u4E98\u4E1E\u9B32\u5B6C\u5669\u4E28\u79BA\u4E3F\u5315\u4E47\u592D\u723B\u536E\u6C10\u56DF\u80E4\u9997\u6BD3\u777E\u9F17\u4E36\u4E9F\u9F10\u4E5C\u4E69\u4E93\u8288\u5B5B\u556C\u560F\u4EC4\u538D\u539D\u53A3\u53A5\u53AE\u9765\u8D5D\u531A\u53F5\u5326\u532E\u533E\u8D5C\u5366\u5363\u5202\u5208\u520E\u522D\u5233\u523F\u5240\u524C\u525E\u5261\u525C\u84AF\u527D\u5282\u5281\u5290\u5293\u5182\u7F54\u4EBB\u4EC3\u4EC9\u4EC2\u4EE8\u4EE1\u4EEB\u4EDE\u4F1B\u4EF3\u4F22\u4F64\u4EF5\u4F25\u4F27\u4F09\u4F2B\u4F5E\u4F67\u6538\u4F5A\u4F5D"],
      ["d940", "\u8CAE", 62],
      ["d980", "\u8CED", 32, "\u4F5F\u4F57\u4F32\u4F3D\u4F76\u4F74\u4F91\u4F89\u4F83\u4F8F\u4F7E\u4F7B\u4FAA\u4F7C\u4FAC\u4F94\u4FE6\u4FE8\u4FEA\u4FC5\u4FDA\u4FE3\u4FDC\u4FD1\u4FDF\u4FF8\u5029\u504C\u4FF3\u502C\u500F\u502E\u502D\u4FFE\u501C\u500C\u5025\u5028\u507E\u5043\u5055\u5048\u504E\u506C\u507B\u50A5\u50A7\u50A9\u50BA\u50D6\u5106\u50ED\u50EC\u50E6\u50EE\u5107\u510B\u4EDD\u6C3D\u4F58\u4F65\u4FCE\u9FA0\u6C46\u7C74\u516E\u5DFD\u9EC9\u9998\u5181\u5914\u52F9\u530D\u8A07\u5310\u51EB\u5919\u5155\u4EA0\u5156\u4EB3\u886E\u88A4\u4EB5\u8114\u88D2\u7980\u5B34\u8803\u7FB8\u51AB\u51B1\u51BD\u51BC"],
      ["da40", "\u8D0E", 14, "\u8D20\u8D51\u8D52\u8D57\u8D5F\u8D65\u8D68\u8D69\u8D6A\u8D6C\u8D6E\u8D6F\u8D71\u8D72\u8D78", 8, "\u8D82\u8D83\u8D86\u8D87\u8D88\u8D89\u8D8C", 4, "\u8D92\u8D93\u8D95", 9, "\u8DA0\u8DA1"],
      ["da80", "\u8DA2\u8DA4", 12, "\u8DB2\u8DB6\u8DB7\u8DB9\u8DBB\u8DBD\u8DC0\u8DC1\u8DC2\u8DC5\u8DC7\u8DC8\u8DC9\u8DCA\u8DCD\u8DD0\u8DD2\u8DD3\u8DD4\u51C7\u5196\u51A2\u51A5\u8BA0\u8BA6\u8BA7\u8BAA\u8BB4\u8BB5\u8BB7\u8BC2\u8BC3\u8BCB\u8BCF\u8BCE\u8BD2\u8BD3\u8BD4\u8BD6\u8BD8\u8BD9\u8BDC\u8BDF\u8BE0\u8BE4\u8BE8\u8BE9\u8BEE\u8BF0\u8BF3\u8BF6\u8BF9\u8BFC\u8BFF\u8C00\u8C02\u8C04\u8C07\u8C0C\u8C0F\u8C11\u8C12\u8C14\u8C15\u8C16\u8C19\u8C1B\u8C18\u8C1D\u8C1F\u8C20\u8C21\u8C25\u8C27\u8C2A\u8C2B\u8C2E\u8C2F\u8C32\u8C33\u8C35\u8C36\u5369\u537A\u961D\u9622\u9621\u9631\u962A\u963D\u963C\u9642\u9649\u9654\u965F\u9667\u966C\u9672\u9674\u9688\u968D\u9697\u96B0\u9097\u909B\u909D\u9099\u90AC\u90A1\u90B4\u90B3\u90B6\u90BA"],
      ["db40", "\u8DD5\u8DD8\u8DD9\u8DDC\u8DE0\u8DE1\u8DE2\u8DE5\u8DE6\u8DE7\u8DE9\u8DED\u8DEE\u8DF0\u8DF1\u8DF2\u8DF4\u8DF6\u8DFC\u8DFE", 6, "\u8E06\u8E07\u8E08\u8E0B\u8E0D\u8E0E\u8E10\u8E11\u8E12\u8E13\u8E15", 7, "\u8E20\u8E21\u8E24", 4, "\u8E2B\u8E2D\u8E30\u8E32\u8E33\u8E34\u8E36\u8E37\u8E38\u8E3B\u8E3C\u8E3E"],
      ["db80", "\u8E3F\u8E43\u8E45\u8E46\u8E4C", 4, "\u8E53", 5, "\u8E5A", 11, "\u8E67\u8E68\u8E6A\u8E6B\u8E6E\u8E71\u90B8\u90B0\u90CF\u90C5\u90BE\u90D0\u90C4\u90C7\u90D3\u90E6\u90E2\u90DC\u90D7\u90DB\u90EB\u90EF\u90FE\u9104\u9122\u911E\u9123\u9131\u912F\u9139\u9143\u9146\u520D\u5942\u52A2\u52AC\u52AD\u52BE\u54FF\u52D0\u52D6\u52F0\u53DF\u71EE\u77CD\u5EF4\u51F5\u51FC\u9B2F\u53B6\u5F01\u755A\u5DEF\u574C\u57A9\u57A1\u587E\u58BC\u58C5\u58D1\u5729\u572C\u572A\u5733\u5739\u572E\u572F\u575C\u573B\u5742\u5769\u5785\u576B\u5786\u577C\u577B\u5768\u576D\u5776\u5773\u57AD\u57A4\u578C\u57B2\u57CF\u57A7\u57B4\u5793\u57A0\u57D5\u57D8\u57DA\u57D9\u57D2\u57B8\u57F4\u57EF\u57F8\u57E4\u57DD"],
      ["dc40", "\u8E73\u8E75\u8E77", 4, "\u8E7D\u8E7E\u8E80\u8E82\u8E83\u8E84\u8E86\u8E88", 6, "\u8E91\u8E92\u8E93\u8E95", 6, "\u8E9D\u8E9F", 11, "\u8EAD\u8EAE\u8EB0\u8EB1\u8EB3", 6, "\u8EBB", 7],
      ["dc80", "\u8EC3", 10, "\u8ECF", 21, "\u580B\u580D\u57FD\u57ED\u5800\u581E\u5819\u5844\u5820\u5865\u586C\u5881\u5889\u589A\u5880\u99A8\u9F19\u61FF\u8279\u827D\u827F\u828F\u828A\u82A8\u8284\u828E\u8291\u8297\u8299\u82AB\u82B8\u82BE\u82B0\u82C8\u82CA\u82E3\u8298\u82B7\u82AE\u82CB\u82CC\u82C1\u82A9\u82B4\u82A1\u82AA\u829F\u82C4\u82CE\u82A4\u82E1\u8309\u82F7\u82E4\u830F\u8307\u82DC\u82F4\u82D2\u82D8\u830C\u82FB\u82D3\u8311\u831A\u8306\u8314\u8315\u82E0\u82D5\u831C\u8351\u835B\u835C\u8308\u8392\u833C\u8334\u8331\u839B\u835E\u832F\u834F\u8347\u8343\u835F\u8340\u8317\u8360\u832D\u833A\u8333\u8366\u8365"],
      ["dd40", "\u8EE5", 62],
      ["dd80", "\u8F24", 32, "\u8368\u831B\u8369\u836C\u836A\u836D\u836E\u83B0\u8378\u83B3\u83B4\u83A0\u83AA\u8393\u839C\u8385\u837C\u83B6\u83A9\u837D\u83B8\u837B\u8398\u839E\u83A8\u83BA\u83BC\u83C1\u8401\u83E5\u83D8\u5807\u8418\u840B\u83DD\u83FD\u83D6\u841C\u8438\u8411\u8406\u83D4\u83DF\u840F\u8403\u83F8\u83F9\u83EA\u83C5\u83C0\u8426\u83F0\u83E1\u845C\u8451\u845A\u8459\u8473\u8487\u8488\u847A\u8489\u8478\u843C\u8446\u8469\u8476\u848C\u848E\u8431\u846D\u84C1\u84CD\u84D0\u84E6\u84BD\u84D3\u84CA\u84BF\u84BA\u84E0\u84A1\u84B9\u84B4\u8497\u84E5\u84E3\u850C\u750D\u8538\u84F0\u8539\u851F\u853A"],
      ["de40", "\u8F45", 32, "\u8F6A\u8F80\u8F8C\u8F92\u8F9D\u8FA0\u8FA1\u8FA2\u8FA4\u8FA5\u8FA6\u8FA7\u8FAA\u8FAC\u8FAD\u8FAE\u8FAF\u8FB2\u8FB3\u8FB4\u8FB5\u8FB7\u8FB8\u8FBA\u8FBB\u8FBC\u8FBF\u8FC0\u8FC3\u8FC6"],
      ["de80", "\u8FC9", 4, "\u8FCF\u8FD2\u8FD6\u8FD7\u8FDA\u8FE0\u8FE1\u8FE3\u8FE7\u8FEC\u8FEF\u8FF1\u8FF2\u8FF4\u8FF5\u8FF6\u8FFA\u8FFB\u8FFC\u8FFE\u8FFF\u9007\u9008\u900C\u900E\u9013\u9015\u9018\u8556\u853B\u84FF\u84FC\u8559\u8548\u8568\u8564\u855E\u857A\u77A2\u8543\u8572\u857B\u85A4\u85A8\u8587\u858F\u8579\u85AE\u859C\u8585\u85B9\u85B7\u85B0\u85D3\u85C1\u85DC\u85FF\u8627\u8605\u8629\u8616\u863C\u5EFE\u5F08\u593C\u5941\u8037\u5955\u595A\u5958\u530F\u5C22\u5C25\u5C2C\u5C34\u624C\u626A\u629F\u62BB\u62CA\u62DA\u62D7\u62EE\u6322\u62F6\u6339\u634B\u6343\u63AD\u63F6\u6371\u637A\u638E\u63B4\u636D\u63AC\u638A\u6369\u63AE\u63BC\u63F2\u63F8\u63E0\u63FF\u63C4\u63DE\u63CE\u6452\u63C6\u63BE\u6445\u6441\u640B\u641B\u6420\u640C\u6426\u6421\u645E\u6484\u646D\u6496"],
      ["df40", "\u9019\u901C\u9023\u9024\u9025\u9027", 5, "\u9030", 4, "\u9037\u9039\u903A\u903D\u903F\u9040\u9043\u9045\u9046\u9048", 4, "\u904E\u9054\u9055\u9056\u9059\u905A\u905C", 5, "\u9064\u9066\u9067\u9069\u906A\u906B\u906C\u906F", 4, "\u9076", 6, "\u907E\u9081"],
      ["df80", "\u9084\u9085\u9086\u9087\u9089\u908A\u908C", 4, "\u9092\u9094\u9096\u9098\u909A\u909C\u909E\u909F\u90A0\u90A4\u90A5\u90A7\u90A8\u90A9\u90AB\u90AD\u90B2\u90B7\u90BC\u90BD\u90BF\u90C0\u647A\u64B7\u64B8\u6499\u64BA\u64C0\u64D0\u64D7\u64E4\u64E2\u6509\u6525\u652E\u5F0B\u5FD2\u7519\u5F11\u535F\u53F1\u53FD\u53E9\u53E8\u53FB\u5412\u5416\u5406\u544B\u5452\u5453\u5454\u5456\u5443\u5421\u5457\u5459\u5423\u5432\u5482\u5494\u5477\u5471\u5464\u549A\u549B\u5484\u5476\u5466\u549D\u54D0\u54AD\u54C2\u54B4\u54D2\u54A7\u54A6\u54D3\u54D4\u5472\u54A3\u54D5\u54BB\u54BF\u54CC\u54D9\u54DA\u54DC\u54A9\u54AA\u54A4\u54DD\u54CF\u54DE\u551B\u54E7\u5520\u54FD\u5514\u54F3\u5522\u5523\u550F\u5511\u5527\u552A\u5567\u558F\u55B5\u5549\u556D\u5541\u5555\u553F\u5550\u553C"],
      ["e040", "\u90C2\u90C3\u90C6\u90C8\u90C9\u90CB\u90CC\u90CD\u90D2\u90D4\u90D5\u90D6\u90D8\u90D9\u90DA\u90DE\u90DF\u90E0\u90E3\u90E4\u90E5\u90E9\u90EA\u90EC\u90EE\u90F0\u90F1\u90F2\u90F3\u90F5\u90F6\u90F7\u90F9\u90FA\u90FB\u90FC\u90FF\u9100\u9101\u9103\u9105", 19, "\u911A\u911B\u911C"],
      ["e080", "\u911D\u911F\u9120\u9121\u9124", 10, "\u9130\u9132", 6, "\u913A", 8, "\u9144\u5537\u5556\u5575\u5576\u5577\u5533\u5530\u555C\u558B\u55D2\u5583\u55B1\u55B9\u5588\u5581\u559F\u557E\u55D6\u5591\u557B\u55DF\u55BD\u55BE\u5594\u5599\u55EA\u55F7\u55C9\u561F\u55D1\u55EB\u55EC\u55D4\u55E6\u55DD\u55C4\u55EF\u55E5\u55F2\u55F3\u55CC\u55CD\u55E8\u55F5\u55E4\u8F94\u561E\u5608\u560C\u5601\u5624\u5623\u55FE\u5600\u5627\u562D\u5658\u5639\u5657\u562C\u564D\u5662\u5659\u565C\u564C\u5654\u5686\u5664\u5671\u566B\u567B\u567C\u5685\u5693\u56AF\u56D4\u56D7\u56DD\u56E1\u56F5\u56EB\u56F9\u56FF\u5704\u570A\u5709\u571C\u5E0F\u5E19\u5E14\u5E11\u5E31\u5E3B\u5E3C"],
      ["e140", "\u9145\u9147\u9148\u9151\u9153\u9154\u9155\u9156\u9158\u9159\u915B\u915C\u915F\u9160\u9166\u9167\u9168\u916B\u916D\u9173\u917A\u917B\u917C\u9180", 4, "\u9186\u9188\u918A\u918E\u918F\u9193", 6, "\u919C", 5, "\u91A4", 5, "\u91AB\u91AC\u91B0\u91B1\u91B2\u91B3\u91B6\u91B7\u91B8\u91B9\u91BB"],
      ["e180", "\u91BC", 10, "\u91C8\u91CB\u91D0\u91D2", 9, "\u91DD", 8, "\u5E37\u5E44\u5E54\u5E5B\u5E5E\u5E61\u5C8C\u5C7A\u5C8D\u5C90\u5C96\u5C88\u5C98\u5C99\u5C91\u5C9A\u5C9C\u5CB5\u5CA2\u5CBD\u5CAC\u5CAB\u5CB1\u5CA3\u5CC1\u5CB7\u5CC4\u5CD2\u5CE4\u5CCB\u5CE5\u5D02\u5D03\u5D27\u5D26\u5D2E\u5D24\u5D1E\u5D06\u5D1B\u5D58\u5D3E\u5D34\u5D3D\u5D6C\u5D5B\u5D6F\u5D5D\u5D6B\u5D4B\u5D4A\u5D69\u5D74\u5D82\u5D99\u5D9D\u8C73\u5DB7\u5DC5\u5F73\u5F77\u5F82\u5F87\u5F89\u5F8C\u5F95\u5F99\u5F9C\u5FA8\u5FAD\u5FB5\u5FBC\u8862\u5F61\u72AD\u72B0\u72B4\u72B7\u72B8\u72C3\u72C1\u72CE\u72CD\u72D2\u72E8\u72EF\u72E9\u72F2\u72F4\u72F7\u7301\u72F3\u7303\u72FA"],
      ["e240", "\u91E6", 62],
      ["e280", "\u9225", 32, "\u72FB\u7317\u7313\u7321\u730A\u731E\u731D\u7315\u7322\u7339\u7325\u732C\u7338\u7331\u7350\u734D\u7357\u7360\u736C\u736F\u737E\u821B\u5925\u98E7\u5924\u5902\u9963\u9967", 5, "\u9974\u9977\u997D\u9980\u9984\u9987\u998A\u998D\u9990\u9991\u9993\u9994\u9995\u5E80\u5E91\u5E8B\u5E96\u5EA5\u5EA0\u5EB9\u5EB5\u5EBE\u5EB3\u8D53\u5ED2\u5ED1\u5EDB\u5EE8\u5EEA\u81BA\u5FC4\u5FC9\u5FD6\u5FCF\u6003\u5FEE\u6004\u5FE1\u5FE4\u5FFE\u6005\u6006\u5FEA\u5FED\u5FF8\u6019\u6035\u6026\u601B\u600F\u600D\u6029\u602B\u600A\u603F\u6021\u6078\u6079\u607B\u607A\u6042"],
      ["e340", "\u9246", 45, "\u9275", 16],
      ["e380", "\u9286", 7, "\u928F", 24, "\u606A\u607D\u6096\u609A\u60AD\u609D\u6083\u6092\u608C\u609B\u60EC\u60BB\u60B1\u60DD\u60D8\u60C6\u60DA\u60B4\u6120\u6126\u6115\u6123\u60F4\u6100\u610E\u612B\u614A\u6175\u61AC\u6194\u61A7\u61B7\u61D4\u61F5\u5FDD\u96B3\u95E9\u95EB\u95F1\u95F3\u95F5\u95F6\u95FC\u95FE\u9603\u9604\u9606\u9608\u960A\u960B\u960C\u960D\u960F\u9612\u9615\u9616\u9617\u9619\u961A\u4E2C\u723F\u6215\u6C35\u6C54\u6C5C\u6C4A\u6CA3\u6C85\u6C90\u6C94\u6C8C\u6C68\u6C69\u6C74\u6C76\u6C86\u6CA9\u6CD0\u6CD4\u6CAD\u6CF7\u6CF8\u6CF1\u6CD7\u6CB2\u6CE0\u6CD6\u6CFA\u6CEB\u6CEE\u6CB1\u6CD3\u6CEF\u6CFE"],
      ["e440", "\u92A8", 5, "\u92AF", 24, "\u92C9", 31],
      ["e480", "\u92E9", 32, "\u6D39\u6D27\u6D0C\u6D43\u6D48\u6D07\u6D04\u6D19\u6D0E\u6D2B\u6D4D\u6D2E\u6D35\u6D1A\u6D4F\u6D52\u6D54\u6D33\u6D91\u6D6F\u6D9E\u6DA0\u6D5E\u6D93\u6D94\u6D5C\u6D60\u6D7C\u6D63\u6E1A\u6DC7\u6DC5\u6DDE\u6E0E\u6DBF\u6DE0\u6E11\u6DE6\u6DDD\u6DD9\u6E16\u6DAB\u6E0C\u6DAE\u6E2B\u6E6E\u6E4E\u6E6B\u6EB2\u6E5F\u6E86\u6E53\u6E54\u6E32\u6E25\u6E44\u6EDF\u6EB1\u6E98\u6EE0\u6F2D\u6EE2\u6EA5\u6EA7\u6EBD\u6EBB\u6EB7\u6ED7\u6EB4\u6ECF\u6E8F\u6EC2\u6E9F\u6F62\u6F46\u6F47\u6F24\u6F15\u6EF9\u6F2F\u6F36\u6F4B\u6F74\u6F2A\u6F09\u6F29\u6F89\u6F8D\u6F8C\u6F78\u6F72\u6F7C\u6F7A\u6FD1"],
      ["e540", "\u930A", 51, "\u933F", 10],
      ["e580", "\u934A", 31, "\u936B\u6FC9\u6FA7\u6FB9\u6FB6\u6FC2\u6FE1\u6FEE\u6FDE\u6FE0\u6FEF\u701A\u7023\u701B\u7039\u7035\u704F\u705E\u5B80\u5B84\u5B95\u5B93\u5BA5\u5BB8\u752F\u9A9E\u6434\u5BE4\u5BEE\u8930\u5BF0\u8E47\u8B07\u8FB6\u8FD3\u8FD5\u8FE5\u8FEE\u8FE4\u8FE9\u8FE6\u8FF3\u8FE8\u9005\u9004\u900B\u9026\u9011\u900D\u9016\u9021\u9035\u9036\u902D\u902F\u9044\u9051\u9052\u9050\u9068\u9058\u9062\u905B\u66B9\u9074\u907D\u9082\u9088\u9083\u908B\u5F50\u5F57\u5F56\u5F58\u5C3B\u54AB\u5C50\u5C59\u5B71\u5C63\u5C66\u7FBC\u5F2A\u5F29\u5F2D\u8274\u5F3C\u9B3B\u5C6E\u5981\u5983\u598D\u59A9\u59AA\u59A3"],
      ["e640", "\u936C", 34, "\u9390", 27],
      ["e680", "\u93AC", 29, "\u93CB\u93CC\u93CD\u5997\u59CA\u59AB\u599E\u59A4\u59D2\u59B2\u59AF\u59D7\u59BE\u5A05\u5A06\u59DD\u5A08\u59E3\u59D8\u59F9\u5A0C\u5A09\u5A32\u5A34\u5A11\u5A23\u5A13\u5A40\u5A67\u5A4A\u5A55\u5A3C\u5A62\u5A75\u80EC\u5AAA\u5A9B\u5A77\u5A7A\u5ABE\u5AEB\u5AB2\u5AD2\u5AD4\u5AB8\u5AE0\u5AE3\u5AF1\u5AD6\u5AE6\u5AD8\u5ADC\u5B09\u5B17\u5B16\u5B32\u5B37\u5B40\u5C15\u5C1C\u5B5A\u5B65\u5B73\u5B51\u5B53\u5B62\u9A75\u9A77\u9A78\u9A7A\u9A7F\u9A7D\u9A80\u9A81\u9A85\u9A88\u9A8A\u9A90\u9A92\u9A93\u9A96\u9A98\u9A9B\u9A9C\u9A9D\u9A9F\u9AA0\u9AA2\u9AA3\u9AA5\u9AA7\u7E9F\u7EA1\u7EA3\u7EA5\u7EA8\u7EA9"],
      ["e740", "\u93CE", 7, "\u93D7", 54],
      ["e780", "\u940E", 32, "\u7EAD\u7EB0\u7EBE\u7EC0\u7EC1\u7EC2\u7EC9\u7ECB\u7ECC\u7ED0\u7ED4\u7ED7\u7EDB\u7EE0\u7EE1\u7EE8\u7EEB\u7EEE\u7EEF\u7EF1\u7EF2\u7F0D\u7EF6\u7EFA\u7EFB\u7EFE\u7F01\u7F02\u7F03\u7F07\u7F08\u7F0B\u7F0C\u7F0F\u7F11\u7F12\u7F17\u7F19\u7F1C\u7F1B\u7F1F\u7F21", 6, "\u7F2A\u7F2B\u7F2C\u7F2D\u7F2F", 4, "\u7F35\u5E7A\u757F\u5DDB\u753E\u9095\u738E\u7391\u73AE\u73A2\u739F\u73CF\u73C2\u73D1\u73B7\u73B3\u73C0\u73C9\u73C8\u73E5\u73D9\u987C\u740A\u73E9\u73E7\u73DE\u73BA\u73F2\u740F\u742A\u745B\u7426\u7425\u7428\u7430\u742E\u742C"],
      ["e840", "\u942F", 14, "\u943F", 43, "\u946C\u946D\u946E\u946F"],
      ["e880", "\u9470", 20, "\u9491\u9496\u9498\u94C7\u94CF\u94D3\u94D4\u94DA\u94E6\u94FB\u951C\u9520\u741B\u741A\u7441\u745C\u7457\u7455\u7459\u7477\u746D\u747E\u749C\u748E\u7480\u7481\u7487\u748B\u749E\u74A8\u74A9\u7490\u74A7\u74D2\u74BA\u97EA\u97EB\u97EC\u674C\u6753\u675E\u6748\u6769\u67A5\u6787\u676A\u6773\u6798\u67A7\u6775\u67A8\u679E\u67AD\u678B\u6777\u677C\u67F0\u6809\u67D8\u680A\u67E9\u67B0\u680C\u67D9\u67B5\u67DA\u67B3\u67DD\u6800\u67C3\u67B8\u67E2\u680E\u67C1\u67FD\u6832\u6833\u6860\u6861\u684E\u6862\u6844\u6864\u6883\u681D\u6855\u6866\u6841\u6867\u6840\u683E\u684A\u6849\u6829\u68B5\u688F\u6874\u6877\u6893\u686B\u68C2\u696E\u68FC\u691F\u6920\u68F9"],
      ["e940", "\u9527\u9533\u953D\u9543\u9548\u954B\u9555\u955A\u9560\u956E\u9574\u9575\u9577", 7, "\u9580", 42],
      ["e980", "\u95AB", 32, "\u6924\u68F0\u690B\u6901\u6957\u68E3\u6910\u6971\u6939\u6960\u6942\u695D\u6984\u696B\u6980\u6998\u6978\u6934\u69CC\u6987\u6988\u69CE\u6989\u6966\u6963\u6979\u699B\u69A7\u69BB\u69AB\u69AD\u69D4\u69B1\u69C1\u69CA\u69DF\u6995\u69E0\u698D\u69FF\u6A2F\u69ED\u6A17\u6A18\u6A65\u69F2\u6A44\u6A3E\u6AA0\u6A50\u6A5B\u6A35\u6A8E\u6A79\u6A3D\u6A28\u6A58\u6A7C\u6A91\u6A90\u6AA9\u6A97\u6AAB\u7337\u7352\u6B81\u6B82\u6B87\u6B84\u6B92\u6B93\u6B8D\u6B9A\u6B9B\u6BA1\u6BAA\u8F6B\u8F6D\u8F71\u8F72\u8F73\u8F75\u8F76\u8F78\u8F77\u8F79\u8F7A\u8F7C\u8F7E\u8F81\u8F82\u8F84\u8F87\u8F8B"],
      ["ea40", "\u95CC", 27, "\u95EC\u95FF\u9607\u9613\u9618\u961B\u961E\u9620\u9623", 6, "\u962B\u962C\u962D\u962F\u9630\u9637\u9638\u9639\u963A\u963E\u9641\u9643\u964A\u964E\u964F\u9651\u9652\u9653\u9656\u9657"],
      ["ea80", "\u9658\u9659\u965A\u965C\u965D\u965E\u9660\u9663\u9665\u9666\u966B\u966D", 4, "\u9673\u9678", 12, "\u9687\u9689\u968A\u8F8D\u8F8E\u8F8F\u8F98\u8F9A\u8ECE\u620B\u6217\u621B\u621F\u6222\u6221\u6225\u6224\u622C\u81E7\u74EF\u74F4\u74FF\u750F\u7511\u7513\u6534\u65EE\u65EF\u65F0\u660A\u6619\u6772\u6603\u6615\u6600\u7085\u66F7\u661D\u6634\u6631\u6636\u6635\u8006\u665F\u6654\u6641\u664F\u6656\u6661\u6657\u6677\u6684\u668C\u66A7\u669D\u66BE\u66DB\u66DC\u66E6\u66E9\u8D32\u8D33\u8D36\u8D3B\u8D3D\u8D40\u8D45\u8D46\u8D48\u8D49\u8D47\u8D4D\u8D55\u8D59\u89C7\u89CA\u89CB\u89CC\u89CE\u89CF\u89D0\u89D1\u726E\u729F\u725D\u7266\u726F\u727E\u727F\u7284\u728B\u728D\u728F\u7292\u6308\u6332\u63B0"],
      ["eb40", "\u968C\u968E\u9691\u9692\u9693\u9695\u9696\u969A\u969B\u969D", 9, "\u96A8", 7, "\u96B1\u96B2\u96B4\u96B5\u96B7\u96B8\u96BA\u96BB\u96BF\u96C2\u96C3\u96C8\u96CA\u96CB\u96D0\u96D1\u96D3\u96D4\u96D6", 9, "\u96E1", 6, "\u96EB"],
      ["eb80", "\u96EC\u96ED\u96EE\u96F0\u96F1\u96F2\u96F4\u96F5\u96F8\u96FA\u96FB\u96FC\u96FD\u96FF\u9702\u9703\u9705\u970A\u970B\u970C\u9710\u9711\u9712\u9714\u9715\u9717", 4, "\u971D\u971F\u9720\u643F\u64D8\u8004\u6BEA\u6BF3\u6BFD\u6BF5\u6BF9\u6C05\u6C07\u6C06\u6C0D\u6C15\u6C18\u6C19\u6C1A\u6C21\u6C29\u6C24\u6C2A\u6C32\u6535\u6555\u656B\u724D\u7252\u7256\u7230\u8662\u5216\u809F\u809C\u8093\u80BC\u670A\u80BD\u80B1\u80AB\u80AD\u80B4\u80B7\u80E7\u80E8\u80E9\u80EA\u80DB\u80C2\u80C4\u80D9\u80CD\u80D7\u6710\u80DD\u80EB\u80F1\u80F4\u80ED\u810D\u810E\u80F2\u80FC\u6715\u8112\u8C5A\u8136\u811E\u812C\u8118\u8132\u8148\u814C\u8153\u8174\u8159\u815A\u8171\u8160\u8169\u817C\u817D\u816D\u8167\u584D\u5AB5\u8188\u8182\u8191\u6ED5\u81A3\u81AA\u81CC\u6726\u81CA\u81BB"],
      ["ec40", "\u9721", 8, "\u972B\u972C\u972E\u972F\u9731\u9733", 4, "\u973A\u973B\u973C\u973D\u973F", 18, "\u9754\u9755\u9757\u9758\u975A\u975C\u975D\u975F\u9763\u9764\u9766\u9767\u9768\u976A", 7],
      ["ec80", "\u9772\u9775\u9777", 4, "\u977D", 7, "\u9786", 4, "\u978C\u978E\u978F\u9790\u9793\u9795\u9796\u9797\u9799", 4, "\u81C1\u81A6\u6B24\u6B37\u6B39\u6B43\u6B46\u6B59\u98D1\u98D2\u98D3\u98D5\u98D9\u98DA\u6BB3\u5F40\u6BC2\u89F3\u6590\u9F51\u6593\u65BC\u65C6\u65C4\u65C3\u65CC\u65CE\u65D2\u65D6\u7080\u709C\u7096\u709D\u70BB\u70C0\u70B7\u70AB\u70B1\u70E8\u70CA\u7110\u7113\u7116\u712F\u7131\u7173\u715C\u7168\u7145\u7172\u714A\u7178\u717A\u7198\u71B3\u71B5\u71A8\u71A0\u71E0\u71D4\u71E7\u71F9\u721D\u7228\u706C\u7118\u7166\u71B9\u623E\u623D\u6243\u6248\u6249\u793B\u7940\u7946\u7949\u795B\u795C\u7953\u795A\u7962\u7957\u7960\u796F\u7967\u797A\u7985\u798A\u799A\u79A7\u79B3\u5FD1\u5FD0"],
      ["ed40", "\u979E\u979F\u97A1\u97A2\u97A4", 6, "\u97AC\u97AE\u97B0\u97B1\u97B3\u97B5", 46],
      ["ed80", "\u97E4\u97E5\u97E8\u97EE", 4, "\u97F4\u97F7", 23, "\u603C\u605D\u605A\u6067\u6041\u6059\u6063\u60AB\u6106\u610D\u615D\u61A9\u619D\u61CB\u61D1\u6206\u8080\u807F\u6C93\u6CF6\u6DFC\u77F6\u77F8\u7800\u7809\u7817\u7818\u7811\u65AB\u782D\u781C\u781D\u7839\u783A\u783B\u781F\u783C\u7825\u782C\u7823\u7829\u784E\u786D\u7856\u7857\u7826\u7850\u7847\u784C\u786A\u789B\u7893\u789A\u7887\u789C\u78A1\u78A3\u78B2\u78B9\u78A5\u78D4\u78D9\u78C9\u78EC\u78F2\u7905\u78F4\u7913\u7924\u791E\u7934\u9F9B\u9EF9\u9EFB\u9EFC\u76F1\u7704\u770D\u76F9\u7707\u7708\u771A\u7722\u7719\u772D\u7726\u7735\u7738\u7750\u7751\u7747\u7743\u775A\u7768"],
      ["ee40", "\u980F", 62],
      ["ee80", "\u984E", 32, "\u7762\u7765\u777F\u778D\u777D\u7780\u778C\u7791\u779F\u77A0\u77B0\u77B5\u77BD\u753A\u7540\u754E\u754B\u7548\u755B\u7572\u7579\u7583\u7F58\u7F61\u7F5F\u8A48\u7F68\u7F74\u7F71\u7F79\u7F81\u7F7E\u76CD\u76E5\u8832\u9485\u9486\u9487\u948B\u948A\u948C\u948D\u948F\u9490\u9494\u9497\u9495\u949A\u949B\u949C\u94A3\u94A4\u94AB\u94AA\u94AD\u94AC\u94AF\u94B0\u94B2\u94B4\u94B6", 4, "\u94BC\u94BD\u94BF\u94C4\u94C8", 6, "\u94D0\u94D1\u94D2\u94D5\u94D6\u94D7\u94D9\u94D8\u94DB\u94DE\u94DF\u94E0\u94E2\u94E4\u94E5\u94E7\u94E8\u94EA"],
      ["ef40", "\u986F", 5, "\u988B\u988E\u9892\u9895\u9899\u98A3\u98A8", 37, "\u98CF\u98D0\u98D4\u98D6\u98D7\u98DB\u98DC\u98DD\u98E0", 4],
      ["ef80", "\u98E5\u98E6\u98E9", 30, "\u94E9\u94EB\u94EE\u94EF\u94F3\u94F4\u94F5\u94F7\u94F9\u94FC\u94FD\u94FF\u9503\u9502\u9506\u9507\u9509\u950A\u950D\u950E\u950F\u9512", 4, "\u9518\u951B\u951D\u951E\u951F\u9522\u952A\u952B\u9529\u952C\u9531\u9532\u9534\u9536\u9537\u9538\u953C\u953E\u953F\u9542\u9535\u9544\u9545\u9546\u9549\u954C\u954E\u954F\u9552\u9553\u9554\u9556\u9557\u9558\u9559\u955B\u955E\u955F\u955D\u9561\u9562\u9564", 8, "\u956F\u9571\u9572\u9573\u953A\u77E7\u77EC\u96C9\u79D5\u79ED\u79E3\u79EB\u7A06\u5D47\u7A03\u7A02\u7A1E\u7A14"],
      ["f040", "\u9908", 4, "\u990E\u990F\u9911", 28, "\u992F", 26],
      ["f080", "\u994A", 9, "\u9956", 12, "\u9964\u9966\u9973\u9978\u9979\u997B\u997E\u9982\u9983\u9989\u7A39\u7A37\u7A51\u9ECF\u99A5\u7A70\u7688\u768E\u7693\u7699\u76A4\u74DE\u74E0\u752C\u9E20\u9E22\u9E28", 4, "\u9E32\u9E31\u9E36\u9E38\u9E37\u9E39\u9E3A\u9E3E\u9E41\u9E42\u9E44\u9E46\u9E47\u9E48\u9E49\u9E4B\u9E4C\u9E4E\u9E51\u9E55\u9E57\u9E5A\u9E5B\u9E5C\u9E5E\u9E63\u9E66", 6, "\u9E71\u9E6D\u9E73\u7592\u7594\u7596\u75A0\u759D\u75AC\u75A3\u75B3\u75B4\u75B8\u75C4\u75B1\u75B0\u75C3\u75C2\u75D6\u75CD\u75E3\u75E8\u75E6\u75E4\u75EB\u75E7\u7603\u75F1\u75FC\u75FF\u7610\u7600\u7605\u760C\u7617\u760A\u7625\u7618\u7615\u7619"],
      ["f140", "\u998C\u998E\u999A", 10, "\u99A6\u99A7\u99A9", 47],
      ["f180", "\u99D9", 32, "\u761B\u763C\u7622\u7620\u7640\u762D\u7630\u763F\u7635\u7643\u763E\u7633\u764D\u765E\u7654\u765C\u7656\u766B\u766F\u7FCA\u7AE6\u7A78\u7A79\u7A80\u7A86\u7A88\u7A95\u7AA6\u7AA0\u7AAC\u7AA8\u7AAD\u7AB3\u8864\u8869\u8872\u887D\u887F\u8882\u88A2\u88C6\u88B7\u88BC\u88C9\u88E2\u88CE\u88E3\u88E5\u88F1\u891A\u88FC\u88E8\u88FE\u88F0\u8921\u8919\u8913\u891B\u890A\u8934\u892B\u8936\u8941\u8966\u897B\u758B\u80E5\u76B2\u76B4\u77DC\u8012\u8014\u8016\u801C\u8020\u8022\u8025\u8026\u8027\u8029\u8028\u8031\u800B\u8035\u8043\u8046\u804D\u8052\u8069\u8071\u8983\u9878\u9880\u9883"],
      ["f240", "\u99FA", 62],
      ["f280", "\u9A39", 32, "\u9889\u988C\u988D\u988F\u9894\u989A\u989B\u989E\u989F\u98A1\u98A2\u98A5\u98A6\u864D\u8654\u866C\u866E\u867F\u867A\u867C\u867B\u86A8\u868D\u868B\u86AC\u869D\u86A7\u86A3\u86AA\u8693\u86A9\u86B6\u86C4\u86B5\u86CE\u86B0\u86BA\u86B1\u86AF\u86C9\u86CF\u86B4\u86E9\u86F1\u86F2\u86ED\u86F3\u86D0\u8713\u86DE\u86F4\u86DF\u86D8\u86D1\u8703\u8707\u86F8\u8708\u870A\u870D\u8709\u8723\u873B\u871E\u8725\u872E\u871A\u873E\u8748\u8734\u8731\u8729\u8737\u873F\u8782\u8722\u877D\u877E\u877B\u8760\u8770\u874C\u876E\u878B\u8753\u8763\u877C\u8764\u8759\u8765\u8793\u87AF\u87A8\u87D2"],
      ["f340", "\u9A5A", 17, "\u9A72\u9A83\u9A89\u9A8D\u9A8E\u9A94\u9A95\u9A99\u9AA6\u9AA9", 6, "\u9AB2\u9AB3\u9AB4\u9AB5\u9AB9\u9ABB\u9ABD\u9ABE\u9ABF\u9AC3\u9AC4\u9AC6", 4, "\u9ACD\u9ACE\u9ACF\u9AD0\u9AD2\u9AD4\u9AD5\u9AD6\u9AD7\u9AD9\u9ADA\u9ADB\u9ADC"],
      ["f380", "\u9ADD\u9ADE\u9AE0\u9AE2\u9AE3\u9AE4\u9AE5\u9AE7\u9AE8\u9AE9\u9AEA\u9AEC\u9AEE\u9AF0", 8, "\u9AFA\u9AFC", 6, "\u9B04\u9B05\u9B06\u87C6\u8788\u8785\u87AD\u8797\u8783\u87AB\u87E5\u87AC\u87B5\u87B3\u87CB\u87D3\u87BD\u87D1\u87C0\u87CA\u87DB\u87EA\u87E0\u87EE\u8816\u8813\u87FE\u880A\u881B\u8821\u8839\u883C\u7F36\u7F42\u7F44\u7F45\u8210\u7AFA\u7AFD\u7B08\u7B03\u7B04\u7B15\u7B0A\u7B2B\u7B0F\u7B47\u7B38\u7B2A\u7B19\u7B2E\u7B31\u7B20\u7B25\u7B24\u7B33\u7B3E\u7B1E\u7B58\u7B5A\u7B45\u7B75\u7B4C\u7B5D\u7B60\u7B6E\u7B7B\u7B62\u7B72\u7B71\u7B90\u7BA6\u7BA7\u7BB8\u7BAC\u7B9D\u7BA8\u7B85\u7BAA\u7B9C\u7BA2\u7BAB\u7BB4\u7BD1\u7BC1\u7BCC\u7BDD\u7BDA\u7BE5\u7BE6\u7BEA\u7C0C\u7BFE\u7BFC\u7C0F\u7C16\u7C0B"],
      ["f440", "\u9B07\u9B09", 5, "\u9B10\u9B11\u9B12\u9B14", 10, "\u9B20\u9B21\u9B22\u9B24", 10, "\u9B30\u9B31\u9B33", 7, "\u9B3D\u9B3E\u9B3F\u9B40\u9B46\u9B4A\u9B4B\u9B4C\u9B4E\u9B50\u9B52\u9B53\u9B55", 5],
      ["f480", "\u9B5B", 32, "\u7C1F\u7C2A\u7C26\u7C38\u7C41\u7C40\u81FE\u8201\u8202\u8204\u81EC\u8844\u8221\u8222\u8223\u822D\u822F\u8228\u822B\u8238\u823B\u8233\u8234\u823E\u8244\u8249\u824B\u824F\u825A\u825F\u8268\u887E\u8885\u8888\u88D8\u88DF\u895E\u7F9D\u7F9F\u7FA7\u7FAF\u7FB0\u7FB2\u7C7C\u6549\u7C91\u7C9D\u7C9C\u7C9E\u7CA2\u7CB2\u7CBC\u7CBD\u7CC1\u7CC7\u7CCC\u7CCD\u7CC8\u7CC5\u7CD7\u7CE8\u826E\u66A8\u7FBF\u7FCE\u7FD5\u7FE5\u7FE1\u7FE6\u7FE9\u7FEE\u7FF3\u7CF8\u7D77\u7DA6\u7DAE\u7E47\u7E9B\u9EB8\u9EB4\u8D73\u8D84\u8D94\u8D91\u8DB1\u8D67\u8D6D\u8C47\u8C49\u914A\u9150\u914E\u914F\u9164"],
      ["f540", "\u9B7C", 62],
      ["f580", "\u9BBB", 32, "\u9162\u9161\u9170\u9169\u916F\u917D\u917E\u9172\u9174\u9179\u918C\u9185\u9190\u918D\u9191\u91A2\u91A3\u91AA\u91AD\u91AE\u91AF\u91B5\u91B4\u91BA\u8C55\u9E7E\u8DB8\u8DEB\u8E05\u8E59\u8E69\u8DB5\u8DBF\u8DBC\u8DBA\u8DC4\u8DD6\u8DD7\u8DDA\u8DDE\u8DCE\u8DCF\u8DDB\u8DC6\u8DEC\u8DF7\u8DF8\u8DE3\u8DF9\u8DFB\u8DE4\u8E09\u8DFD\u8E14\u8E1D\u8E1F\u8E2C\u8E2E\u8E23\u8E2F\u8E3A\u8E40\u8E39\u8E35\u8E3D\u8E31\u8E49\u8E41\u8E42\u8E51\u8E52\u8E4A\u8E70\u8E76\u8E7C\u8E6F\u8E74\u8E85\u8E8F\u8E94\u8E90\u8E9C\u8E9E\u8C78\u8C82\u8C8A\u8C85\u8C98\u8C94\u659B\u89D6\u89DE\u89DA\u89DC"],
      ["f640", "\u9BDC", 62],
      ["f680", "\u9C1B", 32, "\u89E5\u89EB\u89EF\u8A3E\u8B26\u9753\u96E9\u96F3\u96EF\u9706\u9701\u9708\u970F\u970E\u972A\u972D\u9730\u973E\u9F80\u9F83\u9F85", 5, "\u9F8C\u9EFE\u9F0B\u9F0D\u96B9\u96BC\u96BD\u96CE\u96D2\u77BF\u96E0\u928E\u92AE\u92C8\u933E\u936A\u93CA\u938F\u943E\u946B\u9C7F\u9C82\u9C85\u9C86\u9C87\u9C88\u7A23\u9C8B\u9C8E\u9C90\u9C91\u9C92\u9C94\u9C95\u9C9A\u9C9B\u9C9E", 5, "\u9CA5", 4, "\u9CAB\u9CAD\u9CAE\u9CB0", 7, "\u9CBA\u9CBB\u9CBC\u9CBD\u9CC4\u9CC5\u9CC6\u9CC7\u9CCA\u9CCB"],
      ["f740", "\u9C3C", 62],
      ["f780", "\u9C7B\u9C7D\u9C7E\u9C80\u9C83\u9C84\u9C89\u9C8A\u9C8C\u9C8F\u9C93\u9C96\u9C97\u9C98\u9C99\u9C9D\u9CAA\u9CAC\u9CAF\u9CB9\u9CBE", 4, "\u9CC8\u9CC9\u9CD1\u9CD2\u9CDA\u9CDB\u9CE0\u9CE1\u9CCC", 4, "\u9CD3\u9CD4\u9CD5\u9CD7\u9CD8\u9CD9\u9CDC\u9CDD\u9CDF\u9CE2\u977C\u9785\u9791\u9792\u9794\u97AF\u97AB\u97A3\u97B2\u97B4\u9AB1\u9AB0\u9AB7\u9E58\u9AB6\u9ABA\u9ABC\u9AC1\u9AC0\u9AC5\u9AC2\u9ACB\u9ACC\u9AD1\u9B45\u9B43\u9B47\u9B49\u9B48\u9B4D\u9B51\u98E8\u990D\u992E\u9955\u9954\u9ADF\u9AE1\u9AE6\u9AEF\u9AEB\u9AFB\u9AED\u9AF9\u9B08\u9B0F\u9B13\u9B1F\u9B23\u9EBD\u9EBE\u7E3B\u9E82\u9E87\u9E88\u9E8B\u9E92\u93D6\u9E9D\u9E9F\u9EDB\u9EDC\u9EDD\u9EE0\u9EDF\u9EE2\u9EE9\u9EE7\u9EE5\u9EEA\u9EEF\u9F22\u9F2C\u9F2F\u9F39\u9F37\u9F3D\u9F3E\u9F44"],
      ["f840", "\u9CE3", 62],
      ["f880", "\u9D22", 32],
      ["f940", "\u9D43", 62],
      ["f980", "\u9D82", 32],
      ["fa40", "\u9DA3", 62],
      ["fa80", "\u9DE2", 32],
      ["fb40", "\u9E03", 27, "\u9E24\u9E27\u9E2E\u9E30\u9E34\u9E3B\u9E3C\u9E40\u9E4D\u9E50\u9E52\u9E53\u9E54\u9E56\u9E59\u9E5D\u9E5F\u9E60\u9E61\u9E62\u9E65\u9E6E\u9E6F\u9E72\u9E74", 9, "\u9E80"],
      ["fb80", "\u9E81\u9E83\u9E84\u9E85\u9E86\u9E89\u9E8A\u9E8C", 5, "\u9E94", 8, "\u9E9E\u9EA0", 5, "\u9EA7\u9EA8\u9EA9\u9EAA"],
      ["fc40", "\u9EAB", 8, "\u9EB5\u9EB6\u9EB7\u9EB9\u9EBA\u9EBC\u9EBF", 4, "\u9EC5\u9EC6\u9EC7\u9EC8\u9ECA\u9ECB\u9ECC\u9ED0\u9ED2\u9ED3\u9ED5\u9ED6\u9ED7\u9ED9\u9EDA\u9EDE\u9EE1\u9EE3\u9EE4\u9EE6\u9EE8\u9EEB\u9EEC\u9EED\u9EEE\u9EF0", 8, "\u9EFA\u9EFD\u9EFF", 6],
      ["fc80", "\u9F06", 4, "\u9F0C\u9F0F\u9F11\u9F12\u9F14\u9F15\u9F16\u9F18\u9F1A", 5, "\u9F21\u9F23", 8, "\u9F2D\u9F2E\u9F30\u9F31"],
      ["fd40", "\u9F32", 4, "\u9F38\u9F3A\u9F3C\u9F3F", 4, "\u9F45", 10, "\u9F52", 38],
      ["fd80", "\u9F79", 5, "\u9F81\u9F82\u9F8D", 11, "\u9F9C\u9F9D\u9F9E\u9FA1", 4, "\uF92C\uF979\uF995\uF9E7\uF9F1"],
      ["fe40", "\uFA0C\uFA0D\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA18\uFA1F\uFA20\uFA21\uFA23\uFA24\uFA27\uFA28\uFA29"]
    ];
  }
});

// ../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/tables/gbk-added.json
var require_gbk_added = __commonJS({
  "../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/tables/gbk-added.json"(exports, module) {
    module.exports = [
      ["a140", "\uE4C6", 62],
      ["a180", "\uE505", 32],
      ["a240", "\uE526", 62],
      ["a280", "\uE565", 32],
      ["a2ab", "\uE766", 5],
      ["a2e3", "\u20AC\uE76D"],
      ["a2ef", "\uE76E\uE76F"],
      ["a2fd", "\uE770\uE771"],
      ["a340", "\uE586", 62],
      ["a380", "\uE5C5", 31, "\u3000"],
      ["a440", "\uE5E6", 62],
      ["a480", "\uE625", 32],
      ["a4f4", "\uE772", 10],
      ["a540", "\uE646", 62],
      ["a580", "\uE685", 32],
      ["a5f7", "\uE77D", 7],
      ["a640", "\uE6A6", 62],
      ["a680", "\uE6E5", 32],
      ["a6b9", "\uE785", 7],
      ["a6d9", "\uE78D", 6],
      ["a6ec", "\uE794\uE795"],
      ["a6f3", "\uE796"],
      ["a6f6", "\uE797", 8],
      ["a740", "\uE706", 62],
      ["a780", "\uE745", 32],
      ["a7c2", "\uE7A0", 14],
      ["a7f2", "\uE7AF", 12],
      ["a896", "\uE7BC", 10],
      ["a8bc", "\uE7C7"],
      ["a8bf", "\u01F9"],
      ["a8c1", "\uE7C9\uE7CA\uE7CB\uE7CC"],
      ["a8ea", "\uE7CD", 20],
      ["a958", "\uE7E2"],
      ["a95b", "\uE7E3"],
      ["a95d", "\uE7E4\uE7E5\uE7E6"],
      ["a989", "\u303E\u2FF0", 11],
      ["a997", "\uE7F4", 12],
      ["a9f0", "\uE801", 14],
      ["aaa1", "\uE000", 93],
      ["aba1", "\uE05E", 93],
      ["aca1", "\uE0BC", 93],
      ["ada1", "\uE11A", 93],
      ["aea1", "\uE178", 93],
      ["afa1", "\uE1D6", 93],
      ["d7fa", "\uE810", 4],
      ["f8a1", "\uE234", 93],
      ["f9a1", "\uE292", 93],
      ["faa1", "\uE2F0", 93],
      ["fba1", "\uE34E", 93],
      ["fca1", "\uE3AC", 93],
      ["fda1", "\uE40A", 93],
      ["fe50", "\u2E81\uE816\uE817\uE818\u2E84\u3473\u3447\u2E88\u2E8B\uE81E\u359E\u361A\u360E\u2E8C\u2E97\u396E\u3918\uE826\u39CF\u39DF\u3A73\u39D0\uE82B\uE82C\u3B4E\u3C6E\u3CE0\u2EA7\uE831\uE832\u2EAA\u4056\u415F\u2EAE\u4337\u2EB3\u2EB6\u2EB7\uE83B\u43B1\u43AC\u2EBB\u43DD\u44D6\u4661\u464C\uE843"],
      ["fe80", "\u4723\u4729\u477C\u478D\u2ECA\u4947\u497A\u497D\u4982\u4983\u4985\u4986\u499F\u499B\u49B7\u49B6\uE854\uE855\u4CA3\u4C9F\u4CA0\u4CA1\u4C77\u4CA2\u4D13", 6, "\u4DAE\uE864\uE468", 93]
    ];
  }
});

// ../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json
var require_gb18030_ranges = __commonJS({
  "../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json"(exports, module) {
    module.exports = { uChars: [128, 165, 169, 178, 184, 216, 226, 235, 238, 244, 248, 251, 253, 258, 276, 284, 300, 325, 329, 334, 364, 463, 465, 467, 469, 471, 473, 475, 477, 506, 594, 610, 712, 716, 730, 930, 938, 962, 970, 1026, 1104, 1106, 8209, 8215, 8218, 8222, 8231, 8241, 8244, 8246, 8252, 8365, 8452, 8454, 8458, 8471, 8482, 8556, 8570, 8596, 8602, 8713, 8720, 8722, 8726, 8731, 8737, 8740, 8742, 8748, 8751, 8760, 8766, 8777, 8781, 8787, 8802, 8808, 8816, 8854, 8858, 8870, 8896, 8979, 9322, 9372, 9548, 9588, 9616, 9622, 9634, 9652, 9662, 9672, 9676, 9680, 9702, 9735, 9738, 9793, 9795, 11906, 11909, 11913, 11917, 11928, 11944, 11947, 11951, 11956, 11960, 11964, 11979, 12284, 12292, 12312, 12319, 12330, 12351, 12436, 12447, 12535, 12543, 12586, 12842, 12850, 12964, 13200, 13215, 13218, 13253, 13263, 13267, 13270, 13384, 13428, 13727, 13839, 13851, 14617, 14703, 14801, 14816, 14964, 15183, 15471, 15585, 16471, 16736, 17208, 17325, 17330, 17374, 17623, 17997, 18018, 18212, 18218, 18301, 18318, 18760, 18811, 18814, 18820, 18823, 18844, 18848, 18872, 19576, 19620, 19738, 19887, 40870, 59244, 59336, 59367, 59413, 59417, 59423, 59431, 59437, 59443, 59452, 59460, 59478, 59493, 63789, 63866, 63894, 63976, 63986, 64016, 64018, 64021, 64025, 64034, 64037, 64042, 65074, 65093, 65107, 65112, 65127, 65132, 65375, 65510, 65536], gbChars: [0, 36, 38, 45, 50, 81, 89, 95, 96, 100, 103, 104, 105, 109, 126, 133, 148, 172, 175, 179, 208, 306, 307, 308, 309, 310, 311, 312, 313, 341, 428, 443, 544, 545, 558, 741, 742, 749, 750, 805, 819, 820, 7922, 7924, 7925, 7927, 7934, 7943, 7944, 7945, 7950, 8062, 8148, 8149, 8152, 8164, 8174, 8236, 8240, 8262, 8264, 8374, 8380, 8381, 8384, 8388, 8390, 8392, 8393, 8394, 8396, 8401, 8406, 8416, 8419, 8424, 8437, 8439, 8445, 8482, 8485, 8496, 8521, 8603, 8936, 8946, 9046, 9050, 9063, 9066, 9076, 9092, 9100, 9108, 9111, 9113, 9131, 9162, 9164, 9218, 9219, 11329, 11331, 11334, 11336, 11346, 11361, 11363, 11366, 11370, 11372, 11375, 11389, 11682, 11686, 11687, 11692, 11694, 11714, 11716, 11723, 11725, 11730, 11736, 11982, 11989, 12102, 12336, 12348, 12350, 12384, 12393, 12395, 12397, 12510, 12553, 12851, 12962, 12973, 13738, 13823, 13919, 13933, 14080, 14298, 14585, 14698, 15583, 15847, 16318, 16434, 16438, 16481, 16729, 17102, 17122, 17315, 17320, 17402, 17418, 17859, 17909, 17911, 17915, 17916, 17936, 17939, 17961, 18664, 18703, 18814, 18962, 19043, 33469, 33470, 33471, 33484, 33485, 33490, 33497, 33501, 33505, 33513, 33520, 33536, 33550, 37845, 37921, 37948, 38029, 38038, 38064, 38065, 38066, 38069, 38075, 38076, 38078, 39108, 39109, 39113, 39114, 39115, 39116, 39265, 39394, 189e3] };
  }
});

// ../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/tables/cp949.json
var require_cp949 = __commonJS({
  "../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/tables/cp949.json"(exports, module) {
    module.exports = [
      ["0", "\0", 127],
      ["8141", "\uAC02\uAC03\uAC05\uAC06\uAC0B", 4, "\uAC18\uAC1E\uAC1F\uAC21\uAC22\uAC23\uAC25", 6, "\uAC2E\uAC32\uAC33\uAC34"],
      ["8161", "\uAC35\uAC36\uAC37\uAC3A\uAC3B\uAC3D\uAC3E\uAC3F\uAC41", 9, "\uAC4C\uAC4E", 5, "\uAC55"],
      ["8181", "\uAC56\uAC57\uAC59\uAC5A\uAC5B\uAC5D", 18, "\uAC72\uAC73\uAC75\uAC76\uAC79\uAC7B", 4, "\uAC82\uAC87\uAC88\uAC8D\uAC8E\uAC8F\uAC91\uAC92\uAC93\uAC95", 6, "\uAC9E\uACA2", 5, "\uACAB\uACAD\uACAE\uACB1", 6, "\uACBA\uACBE\uACBF\uACC0\uACC2\uACC3\uACC5\uACC6\uACC7\uACC9\uACCA\uACCB\uACCD", 7, "\uACD6\uACD8", 7, "\uACE2\uACE3\uACE5\uACE6\uACE9\uACEB\uACED\uACEE\uACF2\uACF4\uACF7", 4, "\uACFE\uACFF\uAD01\uAD02\uAD03\uAD05\uAD07", 4, "\uAD0E\uAD10\uAD12\uAD13"],
      ["8241", "\uAD14\uAD15\uAD16\uAD17\uAD19\uAD1A\uAD1B\uAD1D\uAD1E\uAD1F\uAD21", 7, "\uAD2A\uAD2B\uAD2E", 5],
      ["8261", "\uAD36\uAD37\uAD39\uAD3A\uAD3B\uAD3D", 6, "\uAD46\uAD48\uAD4A", 5, "\uAD51\uAD52\uAD53\uAD55\uAD56\uAD57"],
      ["8281", "\uAD59", 7, "\uAD62\uAD64", 7, "\uAD6E\uAD6F\uAD71\uAD72\uAD77\uAD78\uAD79\uAD7A\uAD7E\uAD80\uAD83", 4, "\uAD8A\uAD8B\uAD8D\uAD8E\uAD8F\uAD91", 10, "\uAD9E", 5, "\uADA5", 17, "\uADB8", 7, "\uADC2\uADC3\uADC5\uADC6\uADC7\uADC9", 6, "\uADD2\uADD4", 7, "\uADDD\uADDE\uADDF\uADE1\uADE2\uADE3\uADE5", 18],
      ["8341", "\uADFA\uADFB\uADFD\uADFE\uAE02", 5, "\uAE0A\uAE0C\uAE0E", 5, "\uAE15", 7],
      ["8361", "\uAE1D", 18, "\uAE32\uAE33\uAE35\uAE36\uAE39\uAE3B\uAE3C"],
      ["8381", "\uAE3D\uAE3E\uAE3F\uAE42\uAE44\uAE47\uAE48\uAE49\uAE4B\uAE4F\uAE51\uAE52\uAE53\uAE55\uAE57", 4, "\uAE5E\uAE62\uAE63\uAE64\uAE66\uAE67\uAE6A\uAE6B\uAE6D\uAE6E\uAE6F\uAE71", 6, "\uAE7A\uAE7E", 5, "\uAE86", 5, "\uAE8D", 46, "\uAEBF\uAEC1\uAEC2\uAEC3\uAEC5", 6, "\uAECE\uAED2", 5, "\uAEDA\uAEDB\uAEDD", 8],
      ["8441", "\uAEE6\uAEE7\uAEE9\uAEEA\uAEEC\uAEEE", 5, "\uAEF5\uAEF6\uAEF7\uAEF9\uAEFA\uAEFB\uAEFD", 8],
      ["8461", "\uAF06\uAF09\uAF0A\uAF0B\uAF0C\uAF0E\uAF0F\uAF11", 18],
      ["8481", "\uAF24", 7, "\uAF2E\uAF2F\uAF31\uAF33\uAF35", 6, "\uAF3E\uAF40\uAF44\uAF45\uAF46\uAF47\uAF4A", 5, "\uAF51", 10, "\uAF5E", 5, "\uAF66", 18, "\uAF7A", 5, "\uAF81\uAF82\uAF83\uAF85\uAF86\uAF87\uAF89", 6, "\uAF92\uAF93\uAF94\uAF96", 5, "\uAF9D", 26, "\uAFBA\uAFBB\uAFBD\uAFBE"],
      ["8541", "\uAFBF\uAFC1", 5, "\uAFCA\uAFCC\uAFCF", 4, "\uAFD5", 6, "\uAFDD", 4],
      ["8561", "\uAFE2", 5, "\uAFEA", 5, "\uAFF2\uAFF3\uAFF5\uAFF6\uAFF7\uAFF9", 6, "\uB002\uB003"],
      ["8581", "\uB005", 6, "\uB00D\uB00E\uB00F\uB011\uB012\uB013\uB015", 6, "\uB01E", 9, "\uB029", 26, "\uB046\uB047\uB049\uB04B\uB04D\uB04F\uB050\uB051\uB052\uB056\uB058\uB05A\uB05B\uB05C\uB05E", 29, "\uB07E\uB07F\uB081\uB082\uB083\uB085", 6, "\uB08E\uB090\uB092", 5, "\uB09B\uB09D\uB09E\uB0A3\uB0A4"],
      ["8641", "\uB0A5\uB0A6\uB0A7\uB0AA\uB0B0\uB0B2\uB0B6\uB0B7\uB0B9\uB0BA\uB0BB\uB0BD", 6, "\uB0C6\uB0CA", 5, "\uB0D2"],
      ["8661", "\uB0D3\uB0D5\uB0D6\uB0D7\uB0D9", 6, "\uB0E1\uB0E2\uB0E3\uB0E4\uB0E6", 10],
      ["8681", "\uB0F1", 22, "\uB10A\uB10D\uB10E\uB10F\uB111\uB114\uB115\uB116\uB117\uB11A\uB11E", 4, "\uB126\uB127\uB129\uB12A\uB12B\uB12D", 6, "\uB136\uB13A", 5, "\uB142\uB143\uB145\uB146\uB147\uB149", 6, "\uB152\uB153\uB156\uB157\uB159\uB15A\uB15B\uB15D\uB15E\uB15F\uB161", 22, "\uB17A\uB17B\uB17D\uB17E\uB17F\uB181\uB183", 4, "\uB18A\uB18C\uB18E\uB18F\uB190\uB191\uB195\uB196\uB197\uB199\uB19A\uB19B\uB19D"],
      ["8741", "\uB19E", 9, "\uB1A9", 15],
      ["8761", "\uB1B9", 18, "\uB1CD\uB1CE\uB1CF\uB1D1\uB1D2\uB1D3\uB1D5"],
      ["8781", "\uB1D6", 5, "\uB1DE\uB1E0", 7, "\uB1EA\uB1EB\uB1ED\uB1EE\uB1EF\uB1F1", 7, "\uB1FA\uB1FC\uB1FE", 5, "\uB206\uB207\uB209\uB20A\uB20D", 6, "\uB216\uB218\uB21A", 5, "\uB221", 18, "\uB235", 6, "\uB23D", 26, "\uB259\uB25A\uB25B\uB25D\uB25E\uB25F\uB261", 6, "\uB26A", 4],
      ["8841", "\uB26F", 4, "\uB276", 5, "\uB27D", 6, "\uB286\uB287\uB288\uB28A", 4],
      ["8861", "\uB28F\uB292\uB293\uB295\uB296\uB297\uB29B", 4, "\uB2A2\uB2A4\uB2A7\uB2A8\uB2A9\uB2AB\uB2AD\uB2AE\uB2AF\uB2B1\uB2B2\uB2B3\uB2B5\uB2B6\uB2B7"],
      ["8881", "\uB2B8", 15, "\uB2CA\uB2CB\uB2CD\uB2CE\uB2CF\uB2D1\uB2D3", 4, "\uB2DA\uB2DC\uB2DE\uB2DF\uB2E0\uB2E1\uB2E3\uB2E7\uB2E9\uB2EA\uB2F0\uB2F1\uB2F2\uB2F6\uB2FC\uB2FD\uB2FE\uB302\uB303\uB305\uB306\uB307\uB309", 6, "\uB312\uB316", 5, "\uB31D", 54, "\uB357\uB359\uB35A\uB35D\uB360\uB361\uB362\uB363"],
      ["8941", "\uB366\uB368\uB36A\uB36C\uB36D\uB36F\uB372\uB373\uB375\uB376\uB377\uB379", 6, "\uB382\uB386", 5, "\uB38D"],
      ["8961", "\uB38E\uB38F\uB391\uB392\uB393\uB395", 10, "\uB3A2", 5, "\uB3A9\uB3AA\uB3AB\uB3AD"],
      ["8981", "\uB3AE", 21, "\uB3C6\uB3C7\uB3C9\uB3CA\uB3CD\uB3CF\uB3D1\uB3D2\uB3D3\uB3D6\uB3D8\uB3DA\uB3DC\uB3DE\uB3DF\uB3E1\uB3E2\uB3E3\uB3E5\uB3E6\uB3E7\uB3E9", 18, "\uB3FD", 18, "\uB411", 6, "\uB419\uB41A\uB41B\uB41D\uB41E\uB41F\uB421", 6, "\uB42A\uB42C", 7, "\uB435", 15],
      ["8a41", "\uB445", 10, "\uB452\uB453\uB455\uB456\uB457\uB459", 6, "\uB462\uB464\uB466"],
      ["8a61", "\uB467", 4, "\uB46D", 18, "\uB481\uB482"],
      ["8a81", "\uB483", 4, "\uB489", 19, "\uB49E", 5, "\uB4A5\uB4A6\uB4A7\uB4A9\uB4AA\uB4AB\uB4AD", 7, "\uB4B6\uB4B8\uB4BA", 5, "\uB4C1\uB4C2\uB4C3\uB4C5\uB4C6\uB4C7\uB4C9", 6, "\uB4D1\uB4D2\uB4D3\uB4D4\uB4D6", 5, "\uB4DE\uB4DF\uB4E1\uB4E2\uB4E5\uB4E7", 4, "\uB4EE\uB4F0\uB4F2", 5, "\uB4F9", 26, "\uB516\uB517\uB519\uB51A\uB51D"],
      ["8b41", "\uB51E", 5, "\uB526\uB52B", 4, "\uB532\uB533\uB535\uB536\uB537\uB539", 6, "\uB542\uB546"],
      ["8b61", "\uB547\uB548\uB549\uB54A\uB54E\uB54F\uB551\uB552\uB553\uB555", 6, "\uB55E\uB562", 8],
      ["8b81", "\uB56B", 52, "\uB5A2\uB5A3\uB5A5\uB5A6\uB5A7\uB5A9\uB5AC\uB5AD\uB5AE\uB5AF\uB5B2\uB5B6", 4, "\uB5BE\uB5BF\uB5C1\uB5C2\uB5C3\uB5C5", 6, "\uB5CE\uB5D2", 5, "\uB5D9", 18, "\uB5ED", 18],
      ["8c41", "\uB600", 15, "\uB612\uB613\uB615\uB616\uB617\uB619", 4],
      ["8c61", "\uB61E", 6, "\uB626", 5, "\uB62D", 6, "\uB635", 5],
      ["8c81", "\uB63B", 12, "\uB649", 26, "\uB665\uB666\uB667\uB669", 50, "\uB69E\uB69F\uB6A1\uB6A2\uB6A3\uB6A5", 5, "\uB6AD\uB6AE\uB6AF\uB6B0\uB6B2", 16],
      ["8d41", "\uB6C3", 16, "\uB6D5", 8],
      ["8d61", "\uB6DE", 17, "\uB6F1\uB6F2\uB6F3\uB6F5\uB6F6\uB6F7\uB6F9\uB6FA"],
      ["8d81", "\uB6FB", 4, "\uB702\uB703\uB704\uB706", 33, "\uB72A\uB72B\uB72D\uB72E\uB731", 6, "\uB73A\uB73C", 7, "\uB745\uB746\uB747\uB749\uB74A\uB74B\uB74D", 6, "\uB756", 9, "\uB761\uB762\uB763\uB765\uB766\uB767\uB769", 6, "\uB772\uB774\uB776", 5, "\uB77E\uB77F\uB781\uB782\uB783\uB785", 6, "\uB78E\uB793\uB794\uB795\uB79A\uB79B\uB79D\uB79E"],
      ["8e41", "\uB79F\uB7A1", 6, "\uB7AA\uB7AE", 5, "\uB7B6\uB7B7\uB7B9", 8],
      ["8e61", "\uB7C2", 4, "\uB7C8\uB7CA", 19],
      ["8e81", "\uB7DE", 13, "\uB7EE\uB7EF\uB7F1\uB7F2\uB7F3\uB7F5", 6, "\uB7FE\uB802", 4, "\uB80A\uB80B\uB80D\uB80E\uB80F\uB811", 6, "\uB81A\uB81C\uB81E", 5, "\uB826\uB827\uB829\uB82A\uB82B\uB82D", 6, "\uB836\uB83A", 5, "\uB841\uB842\uB843\uB845", 11, "\uB852\uB854", 7, "\uB85E\uB85F\uB861\uB862\uB863\uB865", 6, "\uB86E\uB870\uB872", 5, "\uB879\uB87A\uB87B\uB87D", 7],
      ["8f41", "\uB885", 7, "\uB88E", 17],
      ["8f61", "\uB8A0", 7, "\uB8A9", 6, "\uB8B1\uB8B2\uB8B3\uB8B5\uB8B6\uB8B7\uB8B9", 4],
      ["8f81", "\uB8BE\uB8BF\uB8C2\uB8C4\uB8C6", 5, "\uB8CD\uB8CE\uB8CF\uB8D1\uB8D2\uB8D3\uB8D5", 7, "\uB8DE\uB8E0\uB8E2", 5, "\uB8EA\uB8EB\uB8ED\uB8EE\uB8EF\uB8F1", 6, "\uB8FA\uB8FC\uB8FE", 5, "\uB905", 18, "\uB919", 6, "\uB921", 26, "\uB93E\uB93F\uB941\uB942\uB943\uB945", 6, "\uB94D\uB94E\uB950\uB952", 5],
      ["9041", "\uB95A\uB95B\uB95D\uB95E\uB95F\uB961", 6, "\uB96A\uB96C\uB96E", 5, "\uB976\uB977\uB979\uB97A\uB97B\uB97D"],
      ["9061", "\uB97E", 5, "\uB986\uB988\uB98B\uB98C\uB98F", 15],
      ["9081", "\uB99F", 12, "\uB9AE\uB9AF\uB9B1\uB9B2\uB9B3\uB9B5", 6, "\uB9BE\uB9C0\uB9C2", 5, "\uB9CA\uB9CB\uB9CD\uB9D3", 4, "\uB9DA\uB9DC\uB9DF\uB9E0\uB9E2\uB9E6\uB9E7\uB9E9\uB9EA\uB9EB\uB9ED", 6, "\uB9F6\uB9FB", 4, "\uBA02", 5, "\uBA09", 11, "\uBA16", 33, "\uBA3A\uBA3B\uBA3D\uBA3E\uBA3F\uBA41\uBA43\uBA44\uBA45\uBA46"],
      ["9141", "\uBA47\uBA4A\uBA4C\uBA4F\uBA50\uBA51\uBA52\uBA56\uBA57\uBA59\uBA5A\uBA5B\uBA5D", 6, "\uBA66\uBA6A", 5],
      ["9161", "\uBA72\uBA73\uBA75\uBA76\uBA77\uBA79", 9, "\uBA86\uBA88\uBA89\uBA8A\uBA8B\uBA8D", 5],
      ["9181", "\uBA93", 20, "\uBAAA\uBAAD\uBAAE\uBAAF\uBAB1\uBAB3", 4, "\uBABA\uBABC\uBABE", 5, "\uBAC5\uBAC6\uBAC7\uBAC9", 14, "\uBADA", 33, "\uBAFD\uBAFE\uBAFF\uBB01\uBB02\uBB03\uBB05", 7, "\uBB0E\uBB10\uBB12", 5, "\uBB19\uBB1A\uBB1B\uBB1D\uBB1E\uBB1F\uBB21", 6],
      ["9241", "\uBB28\uBB2A\uBB2C", 7, "\uBB37\uBB39\uBB3A\uBB3F", 4, "\uBB46\uBB48\uBB4A\uBB4B\uBB4C\uBB4E\uBB51\uBB52"],
      ["9261", "\uBB53\uBB55\uBB56\uBB57\uBB59", 7, "\uBB62\uBB64", 7, "\uBB6D", 4],
      ["9281", "\uBB72", 21, "\uBB89\uBB8A\uBB8B\uBB8D\uBB8E\uBB8F\uBB91", 18, "\uBBA5\uBBA6\uBBA7\uBBA9\uBBAA\uBBAB\uBBAD", 6, "\uBBB5\uBBB6\uBBB8", 7, "\uBBC1\uBBC2\uBBC3\uBBC5\uBBC6\uBBC7\uBBC9", 6, "\uBBD1\uBBD2\uBBD4", 35, "\uBBFA\uBBFB\uBBFD\uBBFE\uBC01"],
      ["9341", "\uBC03", 4, "\uBC0A\uBC0E\uBC10\uBC12\uBC13\uBC19\uBC1A\uBC20\uBC21\uBC22\uBC23\uBC26\uBC28\uBC2A\uBC2B\uBC2C\uBC2E\uBC2F\uBC32\uBC33\uBC35"],
      ["9361", "\uBC36\uBC37\uBC39", 6, "\uBC42\uBC46\uBC47\uBC48\uBC4A\uBC4B\uBC4E\uBC4F\uBC51", 8],
      ["9381", "\uBC5A\uBC5B\uBC5C\uBC5E", 37, "\uBC86\uBC87\uBC89\uBC8A\uBC8D\uBC8F", 4, "\uBC96\uBC98\uBC9B", 4, "\uBCA2\uBCA3\uBCA5\uBCA6\uBCA9", 6, "\uBCB2\uBCB6", 5, "\uBCBE\uBCBF\uBCC1\uBCC2\uBCC3\uBCC5", 7, "\uBCCE\uBCD2\uBCD3\uBCD4\uBCD6\uBCD7\uBCD9\uBCDA\uBCDB\uBCDD", 22, "\uBCF7\uBCF9\uBCFA\uBCFB\uBCFD"],
      ["9441", "\uBCFE", 5, "\uBD06\uBD08\uBD0A", 5, "\uBD11\uBD12\uBD13\uBD15", 8],
      ["9461", "\uBD1E", 5, "\uBD25", 6, "\uBD2D", 12],
      ["9481", "\uBD3A", 5, "\uBD41", 6, "\uBD4A\uBD4B\uBD4D\uBD4E\uBD4F\uBD51", 6, "\uBD5A", 9, "\uBD65\uBD66\uBD67\uBD69", 22, "\uBD82\uBD83\uBD85\uBD86\uBD8B", 4, "\uBD92\uBD94\uBD96\uBD97\uBD98\uBD9B\uBD9D", 6, "\uBDA5", 10, "\uBDB1", 6, "\uBDB9", 24],
      ["9541", "\uBDD2\uBDD3\uBDD6\uBDD7\uBDD9\uBDDA\uBDDB\uBDDD", 11, "\uBDEA", 5, "\uBDF1"],
      ["9561", "\uBDF2\uBDF3\uBDF5\uBDF6\uBDF7\uBDF9", 6, "\uBE01\uBE02\uBE04\uBE06", 5, "\uBE0E\uBE0F\uBE11\uBE12\uBE13"],
      ["9581", "\uBE15", 6, "\uBE1E\uBE20", 35, "\uBE46\uBE47\uBE49\uBE4A\uBE4B\uBE4D\uBE4F", 4, "\uBE56\uBE58\uBE5C\uBE5D\uBE5E\uBE5F\uBE62\uBE63\uBE65\uBE66\uBE67\uBE69\uBE6B", 4, "\uBE72\uBE76", 4, "\uBE7E\uBE7F\uBE81\uBE82\uBE83\uBE85", 6, "\uBE8E\uBE92", 5, "\uBE9A", 13, "\uBEA9", 14],
      ["9641", "\uBEB8", 23, "\uBED2\uBED3"],
      ["9661", "\uBED5\uBED6\uBED9", 6, "\uBEE1\uBEE2\uBEE6", 5, "\uBEED", 8],
      ["9681", "\uBEF6", 10, "\uBF02", 5, "\uBF0A", 13, "\uBF1A\uBF1E", 33, "\uBF42\uBF43\uBF45\uBF46\uBF47\uBF49", 6, "\uBF52\uBF53\uBF54\uBF56", 44],
      ["9741", "\uBF83", 16, "\uBF95", 8],
      ["9761", "\uBF9E", 17, "\uBFB1", 7],
      ["9781", "\uBFB9", 11, "\uBFC6", 5, "\uBFCE\uBFCF\uBFD1\uBFD2\uBFD3\uBFD5", 6, "\uBFDD\uBFDE\uBFE0\uBFE2", 89, "\uC03D\uC03E\uC03F"],
      ["9841", "\uC040", 16, "\uC052", 5, "\uC059\uC05A\uC05B"],
      ["9861", "\uC05D\uC05E\uC05F\uC061", 6, "\uC06A", 15],
      ["9881", "\uC07A", 21, "\uC092\uC093\uC095\uC096\uC097\uC099", 6, "\uC0A2\uC0A4\uC0A6", 5, "\uC0AE\uC0B1\uC0B2\uC0B7", 4, "\uC0BE\uC0C2\uC0C3\uC0C4\uC0C6\uC0C7\uC0CA\uC0CB\uC0CD\uC0CE\uC0CF\uC0D1", 6, "\uC0DA\uC0DE", 5, "\uC0E6\uC0E7\uC0E9\uC0EA\uC0EB\uC0ED", 6, "\uC0F6\uC0F8\uC0FA", 5, "\uC101\uC102\uC103\uC105\uC106\uC107\uC109", 6, "\uC111\uC112\uC113\uC114\uC116", 5, "\uC121\uC122\uC125\uC128\uC129\uC12A\uC12B\uC12E"],
      ["9941", "\uC132\uC133\uC134\uC135\uC137\uC13A\uC13B\uC13D\uC13E\uC13F\uC141", 6, "\uC14A\uC14E", 5, "\uC156\uC157"],
      ["9961", "\uC159\uC15A\uC15B\uC15D", 6, "\uC166\uC16A", 5, "\uC171\uC172\uC173\uC175\uC176\uC177\uC179\uC17A\uC17B"],
      ["9981", "\uC17C", 8, "\uC186", 5, "\uC18F\uC191\uC192\uC193\uC195\uC197", 4, "\uC19E\uC1A0\uC1A2\uC1A3\uC1A4\uC1A6\uC1A7\uC1AA\uC1AB\uC1AD\uC1AE\uC1AF\uC1B1", 11, "\uC1BE", 5, "\uC1C5\uC1C6\uC1C7\uC1C9\uC1CA\uC1CB\uC1CD", 6, "\uC1D5\uC1D6\uC1D9", 6, "\uC1E1\uC1E2\uC1E3\uC1E5\uC1E6\uC1E7\uC1E9", 6, "\uC1F2\uC1F4", 7, "\uC1FE\uC1FF\uC201\uC202\uC203\uC205", 6, "\uC20E\uC210\uC212", 5, "\uC21A\uC21B\uC21D\uC21E\uC221\uC222\uC223"],
      ["9a41", "\uC224\uC225\uC226\uC227\uC22A\uC22C\uC22E\uC230\uC233\uC235", 16],
      ["9a61", "\uC246\uC247\uC249", 6, "\uC252\uC253\uC255\uC256\uC257\uC259", 6, "\uC261\uC262\uC263\uC264\uC266"],
      ["9a81", "\uC267", 4, "\uC26E\uC26F\uC271\uC272\uC273\uC275", 6, "\uC27E\uC280\uC282", 5, "\uC28A", 5, "\uC291", 6, "\uC299\uC29A\uC29C\uC29E", 5, "\uC2A6\uC2A7\uC2A9\uC2AA\uC2AB\uC2AE", 5, "\uC2B6\uC2B8\uC2BA", 33, "\uC2DE\uC2DF\uC2E1\uC2E2\uC2E5", 5, "\uC2EE\uC2F0\uC2F2\uC2F3\uC2F4\uC2F5\uC2F7\uC2FA\uC2FD\uC2FE\uC2FF\uC301", 6, "\uC30A\uC30B\uC30E\uC30F"],
      ["9b41", "\uC310\uC311\uC312\uC316\uC317\uC319\uC31A\uC31B\uC31D", 6, "\uC326\uC327\uC32A", 8],
      ["9b61", "\uC333", 17, "\uC346", 7],
      ["9b81", "\uC34E", 25, "\uC36A\uC36B\uC36D\uC36E\uC36F\uC371\uC373", 4, "\uC37A\uC37B\uC37E", 5, "\uC385\uC386\uC387\uC389\uC38A\uC38B\uC38D", 50, "\uC3C1", 22, "\uC3DA"],
      ["9c41", "\uC3DB\uC3DD\uC3DE\uC3E1\uC3E3", 4, "\uC3EA\uC3EB\uC3EC\uC3EE", 5, "\uC3F6\uC3F7\uC3F9", 5],
      ["9c61", "\uC3FF", 8, "\uC409", 6, "\uC411", 9],
      ["9c81", "\uC41B", 8, "\uC425", 6, "\uC42D\uC42E\uC42F\uC431\uC432\uC433\uC435", 6, "\uC43E", 9, "\uC449", 26, "\uC466\uC467\uC469\uC46A\uC46B\uC46D", 6, "\uC476\uC477\uC478\uC47A", 5, "\uC481", 18, "\uC495", 6, "\uC49D", 12],
      ["9d41", "\uC4AA", 13, "\uC4B9\uC4BA\uC4BB\uC4BD", 8],
      ["9d61", "\uC4C6", 25],
      ["9d81", "\uC4E0", 8, "\uC4EA", 5, "\uC4F2\uC4F3\uC4F5\uC4F6\uC4F7\uC4F9\uC4FB\uC4FC\uC4FD\uC4FE\uC502", 9, "\uC50D\uC50E\uC50F\uC511\uC512\uC513\uC515", 6, "\uC51D", 10, "\uC52A\uC52B\uC52D\uC52E\uC52F\uC531", 6, "\uC53A\uC53C\uC53E", 5, "\uC546\uC547\uC54B\uC54F\uC550\uC551\uC552\uC556\uC55A\uC55B\uC55C\uC55F\uC562\uC563\uC565\uC566\uC567\uC569", 6, "\uC572\uC576", 5, "\uC57E\uC57F\uC581\uC582\uC583\uC585\uC586\uC588\uC589\uC58A\uC58B\uC58E\uC590\uC592\uC593\uC594"],
      ["9e41", "\uC596\uC599\uC59A\uC59B\uC59D\uC59E\uC59F\uC5A1", 7, "\uC5AA", 9, "\uC5B6"],
      ["9e61", "\uC5B7\uC5BA\uC5BF", 4, "\uC5CB\uC5CD\uC5CF\uC5D2\uC5D3\uC5D5\uC5D6\uC5D7\uC5D9", 6, "\uC5E2\uC5E4\uC5E6\uC5E7"],
      ["9e81", "\uC5E8\uC5E9\uC5EA\uC5EB\uC5EF\uC5F1\uC5F2\uC5F3\uC5F5\uC5F8\uC5F9\uC5FA\uC5FB\uC602\uC603\uC604\uC609\uC60A\uC60B\uC60D\uC60E\uC60F\uC611", 6, "\uC61A\uC61D", 6, "\uC626\uC627\uC629\uC62A\uC62B\uC62F\uC631\uC632\uC636\uC638\uC63A\uC63C\uC63D\uC63E\uC63F\uC642\uC643\uC645\uC646\uC647\uC649", 6, "\uC652\uC656", 5, "\uC65E\uC65F\uC661", 10, "\uC66D\uC66E\uC670\uC672", 5, "\uC67A\uC67B\uC67D\uC67E\uC67F\uC681", 6, "\uC68A\uC68C\uC68E", 5, "\uC696\uC697\uC699\uC69A\uC69B\uC69D", 6, "\uC6A6"],
      ["9f41", "\uC6A8\uC6AA", 5, "\uC6B2\uC6B3\uC6B5\uC6B6\uC6B7\uC6BB", 4, "\uC6C2\uC6C4\uC6C6", 5, "\uC6CE"],
      ["9f61", "\uC6CF\uC6D1\uC6D2\uC6D3\uC6D5", 6, "\uC6DE\uC6DF\uC6E2", 5, "\uC6EA\uC6EB\uC6ED\uC6EE\uC6EF\uC6F1\uC6F2"],
      ["9f81", "\uC6F3", 4, "\uC6FA\uC6FB\uC6FC\uC6FE", 5, "\uC706\uC707\uC709\uC70A\uC70B\uC70D", 6, "\uC716\uC718\uC71A", 5, "\uC722\uC723\uC725\uC726\uC727\uC729", 6, "\uC732\uC734\uC736\uC738\uC739\uC73A\uC73B\uC73E\uC73F\uC741\uC742\uC743\uC745", 4, "\uC74B\uC74E\uC750\uC759\uC75A\uC75B\uC75D\uC75E\uC75F\uC761", 6, "\uC769\uC76A\uC76C", 7, "\uC776\uC777\uC779\uC77A\uC77B\uC77F\uC780\uC781\uC782\uC786\uC78B\uC78C\uC78D\uC78F\uC792\uC793\uC795\uC799\uC79B", 4, "\uC7A2\uC7A7", 4, "\uC7AE\uC7AF\uC7B1\uC7B2\uC7B3\uC7B5\uC7B6\uC7B7"],
      ["a041", "\uC7B8\uC7B9\uC7BA\uC7BB\uC7BE\uC7C2", 5, "\uC7CA\uC7CB\uC7CD\uC7CF\uC7D1", 6, "\uC7D9\uC7DA\uC7DB\uC7DC"],
      ["a061", "\uC7DE", 5, "\uC7E5\uC7E6\uC7E7\uC7E9\uC7EA\uC7EB\uC7ED", 13],
      ["a081", "\uC7FB", 4, "\uC802\uC803\uC805\uC806\uC807\uC809\uC80B", 4, "\uC812\uC814\uC817", 4, "\uC81E\uC81F\uC821\uC822\uC823\uC825", 6, "\uC82E\uC830\uC832", 5, "\uC839\uC83A\uC83B\uC83D\uC83E\uC83F\uC841", 6, "\uC84A\uC84B\uC84E", 5, "\uC855", 26, "\uC872\uC873\uC875\uC876\uC877\uC879\uC87B", 4, "\uC882\uC884\uC888\uC889\uC88A\uC88E", 5, "\uC895", 7, "\uC89E\uC8A0\uC8A2\uC8A3\uC8A4"],
      ["a141", "\uC8A5\uC8A6\uC8A7\uC8A9", 18, "\uC8BE\uC8BF\uC8C0\uC8C1"],
      ["a161", "\uC8C2\uC8C3\uC8C5\uC8C6\uC8C7\uC8C9\uC8CA\uC8CB\uC8CD", 6, "\uC8D6\uC8D8\uC8DA", 5, "\uC8E2\uC8E3\uC8E5"],
      ["a181", "\uC8E6", 14, "\uC8F6", 5, "\uC8FE\uC8FF\uC901\uC902\uC903\uC907", 4, "\uC90E\u3000\u3001\u3002\xB7\u2025\u2026\xA8\u3003\xAD\u2015\u2225\uFF3C\u223C\u2018\u2019\u201C\u201D\u3014\u3015\u3008", 9, "\xB1\xD7\xF7\u2260\u2264\u2265\u221E\u2234\xB0\u2032\u2033\u2103\u212B\uFFE0\uFFE1\uFFE5\u2642\u2640\u2220\u22A5\u2312\u2202\u2207\u2261\u2252\xA7\u203B\u2606\u2605\u25CB\u25CF\u25CE\u25C7\u25C6\u25A1\u25A0\u25B3\u25B2\u25BD\u25BC\u2192\u2190\u2191\u2193\u2194\u3013\u226A\u226B\u221A\u223D\u221D\u2235\u222B\u222C\u2208\u220B\u2286\u2287\u2282\u2283\u222A\u2229\u2227\u2228\uFFE2"],
      ["a241", "\uC910\uC912", 5, "\uC919", 18],
      ["a261", "\uC92D", 6, "\uC935", 18],
      ["a281", "\uC948", 7, "\uC952\uC953\uC955\uC956\uC957\uC959", 6, "\uC962\uC964", 7, "\uC96D\uC96E\uC96F\u21D2\u21D4\u2200\u2203\xB4\uFF5E\u02C7\u02D8\u02DD\u02DA\u02D9\xB8\u02DB\xA1\xBF\u02D0\u222E\u2211\u220F\xA4\u2109\u2030\u25C1\u25C0\u25B7\u25B6\u2664\u2660\u2661\u2665\u2667\u2663\u2299\u25C8\u25A3\u25D0\u25D1\u2592\u25A4\u25A5\u25A8\u25A7\u25A6\u25A9\u2668\u260F\u260E\u261C\u261E\xB6\u2020\u2021\u2195\u2197\u2199\u2196\u2198\u266D\u2669\u266A\u266C\u327F\u321C\u2116\u33C7\u2122\u33C2\u33D8\u2121\u20AC\xAE"],
      ["a341", "\uC971\uC972\uC973\uC975", 6, "\uC97D", 10, "\uC98A\uC98B\uC98D\uC98E\uC98F"],
      ["a361", "\uC991", 6, "\uC99A\uC99C\uC99E", 16],
      ["a381", "\uC9AF", 16, "\uC9C2\uC9C3\uC9C5\uC9C6\uC9C9\uC9CB", 4, "\uC9D2\uC9D4\uC9D7\uC9D8\uC9DB\uFF01", 58, "\uFFE6\uFF3D", 32, "\uFFE3"],
      ["a441", "\uC9DE\uC9DF\uC9E1\uC9E3\uC9E5\uC9E6\uC9E8\uC9E9\uC9EA\uC9EB\uC9EE\uC9F2", 5, "\uC9FA\uC9FB\uC9FD\uC9FE\uC9FF\uCA01\uCA02\uCA03\uCA04"],
      ["a461", "\uCA05\uCA06\uCA07\uCA0A\uCA0E", 5, "\uCA15\uCA16\uCA17\uCA19", 12],
      ["a481", "\uCA26\uCA27\uCA28\uCA2A", 28, "\u3131", 93],
      ["a541", "\uCA47", 4, "\uCA4E\uCA4F\uCA51\uCA52\uCA53\uCA55", 6, "\uCA5E\uCA62", 5, "\uCA69\uCA6A"],
      ["a561", "\uCA6B", 17, "\uCA7E", 5, "\uCA85\uCA86"],
      ["a581", "\uCA87", 16, "\uCA99", 14, "\u2170", 9],
      ["a5b0", "\u2160", 9],
      ["a5c1", "\u0391", 16, "\u03A3", 6],
      ["a5e1", "\u03B1", 16, "\u03C3", 6],
      ["a641", "\uCAA8", 19, "\uCABE\uCABF\uCAC1\uCAC2\uCAC3\uCAC5"],
      ["a661", "\uCAC6", 5, "\uCACE\uCAD0\uCAD2\uCAD4\uCAD5\uCAD6\uCAD7\uCADA", 5, "\uCAE1", 6],
      ["a681", "\uCAE8\uCAE9\uCAEA\uCAEB\uCAED", 6, "\uCAF5", 18, "\uCB09\uCB0A\u2500\u2502\u250C\u2510\u2518\u2514\u251C\u252C\u2524\u2534\u253C\u2501\u2503\u250F\u2513\u251B\u2517\u2523\u2533\u252B\u253B\u254B\u2520\u252F\u2528\u2537\u253F\u251D\u2530\u2525\u2538\u2542\u2512\u2511\u251A\u2519\u2516\u2515\u250E\u250D\u251E\u251F\u2521\u2522\u2526\u2527\u2529\u252A\u252D\u252E\u2531\u2532\u2535\u2536\u2539\u253A\u253D\u253E\u2540\u2541\u2543", 7],
      ["a741", "\uCB0B", 4, "\uCB11\uCB12\uCB13\uCB15\uCB16\uCB17\uCB19", 6, "\uCB22", 7],
      ["a761", "\uCB2A", 22, "\uCB42\uCB43\uCB44"],
      ["a781", "\uCB45\uCB46\uCB47\uCB4A\uCB4B\uCB4D\uCB4E\uCB4F\uCB51", 6, "\uCB5A\uCB5B\uCB5C\uCB5E", 5, "\uCB65", 7, "\u3395\u3396\u3397\u2113\u3398\u33C4\u33A3\u33A4\u33A5\u33A6\u3399", 9, "\u33CA\u338D\u338E\u338F\u33CF\u3388\u3389\u33C8\u33A7\u33A8\u33B0", 9, "\u3380", 4, "\u33BA", 5, "\u3390", 4, "\u2126\u33C0\u33C1\u338A\u338B\u338C\u33D6\u33C5\u33AD\u33AE\u33AF\u33DB\u33A9\u33AA\u33AB\u33AC\u33DD\u33D0\u33D3\u33C3\u33C9\u33DC\u33C6"],
      ["a841", "\uCB6D", 10, "\uCB7A", 14],
      ["a861", "\uCB89", 18, "\uCB9D", 6],
      ["a881", "\uCBA4", 19, "\uCBB9", 11, "\xC6\xD0\xAA\u0126"],
      ["a8a6", "\u0132"],
      ["a8a8", "\u013F\u0141\xD8\u0152\xBA\xDE\u0166\u014A"],
      ["a8b1", "\u3260", 27, "\u24D0", 25, "\u2460", 14, "\xBD\u2153\u2154\xBC\xBE\u215B\u215C\u215D\u215E"],
      ["a941", "\uCBC5", 14, "\uCBD5", 10],
      ["a961", "\uCBE0\uCBE1\uCBE2\uCBE3\uCBE5\uCBE6\uCBE8\uCBEA", 18],
      ["a981", "\uCBFD", 14, "\uCC0E\uCC0F\uCC11\uCC12\uCC13\uCC15", 6, "\uCC1E\uCC1F\uCC20\uCC23\uCC24\xE6\u0111\xF0\u0127\u0131\u0133\u0138\u0140\u0142\xF8\u0153\xDF\xFE\u0167\u014B\u0149\u3200", 27, "\u249C", 25, "\u2474", 14, "\xB9\xB2\xB3\u2074\u207F\u2081\u2082\u2083\u2084"],
      ["aa41", "\uCC25\uCC26\uCC2A\uCC2B\uCC2D\uCC2F\uCC31", 6, "\uCC3A\uCC3F", 4, "\uCC46\uCC47\uCC49\uCC4A\uCC4B\uCC4D\uCC4E"],
      ["aa61", "\uCC4F", 4, "\uCC56\uCC5A", 5, "\uCC61\uCC62\uCC63\uCC65\uCC67\uCC69", 6, "\uCC71\uCC72"],
      ["aa81", "\uCC73\uCC74\uCC76", 29, "\u3041", 82],
      ["ab41", "\uCC94\uCC95\uCC96\uCC97\uCC9A\uCC9B\uCC9D\uCC9E\uCC9F\uCCA1", 6, "\uCCAA\uCCAE", 5, "\uCCB6\uCCB7\uCCB9"],
      ["ab61", "\uCCBA\uCCBB\uCCBD", 6, "\uCCC6\uCCC8\uCCCA", 5, "\uCCD1\uCCD2\uCCD3\uCCD5", 5],
      ["ab81", "\uCCDB", 8, "\uCCE5", 6, "\uCCED\uCCEE\uCCEF\uCCF1", 12, "\u30A1", 85],
      ["ac41", "\uCCFE\uCCFF\uCD00\uCD02", 5, "\uCD0A\uCD0B\uCD0D\uCD0E\uCD0F\uCD11", 6, "\uCD1A\uCD1C\uCD1E\uCD1F\uCD20"],
      ["ac61", "\uCD21\uCD22\uCD23\uCD25\uCD26\uCD27\uCD29\uCD2A\uCD2B\uCD2D", 11, "\uCD3A", 4],
      ["ac81", "\uCD3F", 28, "\uCD5D\uCD5E\uCD5F\u0410", 5, "\u0401\u0416", 25],
      ["acd1", "\u0430", 5, "\u0451\u0436", 25],
      ["ad41", "\uCD61\uCD62\uCD63\uCD65", 6, "\uCD6E\uCD70\uCD72", 5, "\uCD79", 7],
      ["ad61", "\uCD81", 6, "\uCD89", 10, "\uCD96\uCD97\uCD99\uCD9A\uCD9B\uCD9D\uCD9E\uCD9F"],
      ["ad81", "\uCDA0\uCDA1\uCDA2\uCDA3\uCDA6\uCDA8\uCDAA", 5, "\uCDB1", 18, "\uCDC5"],
      ["ae41", "\uCDC6", 5, "\uCDCD\uCDCE\uCDCF\uCDD1", 16],
      ["ae61", "\uCDE2", 5, "\uCDE9\uCDEA\uCDEB\uCDED\uCDEE\uCDEF\uCDF1", 6, "\uCDFA\uCDFC\uCDFE", 4],
      ["ae81", "\uCE03\uCE05\uCE06\uCE07\uCE09\uCE0A\uCE0B\uCE0D", 6, "\uCE15\uCE16\uCE17\uCE18\uCE1A", 5, "\uCE22\uCE23\uCE25\uCE26\uCE27\uCE29\uCE2A\uCE2B"],
      ["af41", "\uCE2C\uCE2D\uCE2E\uCE2F\uCE32\uCE34\uCE36", 19],
      ["af61", "\uCE4A", 13, "\uCE5A\uCE5B\uCE5D\uCE5E\uCE62", 5, "\uCE6A\uCE6C"],
      ["af81", "\uCE6E", 5, "\uCE76\uCE77\uCE79\uCE7A\uCE7B\uCE7D", 6, "\uCE86\uCE88\uCE8A", 5, "\uCE92\uCE93\uCE95\uCE96\uCE97\uCE99"],
      ["b041", "\uCE9A", 5, "\uCEA2\uCEA6", 5, "\uCEAE", 12],
      ["b061", "\uCEBB", 5, "\uCEC2", 19],
      ["b081", "\uCED6", 13, "\uCEE6\uCEE7\uCEE9\uCEEA\uCEED", 6, "\uCEF6\uCEFA", 5, "\uAC00\uAC01\uAC04\uAC07\uAC08\uAC09\uAC0A\uAC10", 7, "\uAC19", 4, "\uAC20\uAC24\uAC2C\uAC2D\uAC2F\uAC30\uAC31\uAC38\uAC39\uAC3C\uAC40\uAC4B\uAC4D\uAC54\uAC58\uAC5C\uAC70\uAC71\uAC74\uAC77\uAC78\uAC7A\uAC80\uAC81\uAC83\uAC84\uAC85\uAC86\uAC89\uAC8A\uAC8B\uAC8C\uAC90\uAC94\uAC9C\uAC9D\uAC9F\uACA0\uACA1\uACA8\uACA9\uACAA\uACAC\uACAF\uACB0\uACB8\uACB9\uACBB\uACBC\uACBD\uACC1\uACC4\uACC8\uACCC\uACD5\uACD7\uACE0\uACE1\uACE4\uACE7\uACE8\uACEA\uACEC\uACEF\uACF0\uACF1\uACF3\uACF5\uACF6\uACFC\uACFD\uAD00\uAD04\uAD06"],
      ["b141", "\uCF02\uCF03\uCF05\uCF06\uCF07\uCF09", 6, "\uCF12\uCF14\uCF16", 5, "\uCF1D\uCF1E\uCF1F\uCF21\uCF22\uCF23"],
      ["b161", "\uCF25", 6, "\uCF2E\uCF32", 5, "\uCF39", 11],
      ["b181", "\uCF45", 14, "\uCF56\uCF57\uCF59\uCF5A\uCF5B\uCF5D", 6, "\uCF66\uCF68\uCF6A\uCF6B\uCF6C\uAD0C\uAD0D\uAD0F\uAD11\uAD18\uAD1C\uAD20\uAD29\uAD2C\uAD2D\uAD34\uAD35\uAD38\uAD3C\uAD44\uAD45\uAD47\uAD49\uAD50\uAD54\uAD58\uAD61\uAD63\uAD6C\uAD6D\uAD70\uAD73\uAD74\uAD75\uAD76\uAD7B\uAD7C\uAD7D\uAD7F\uAD81\uAD82\uAD88\uAD89\uAD8C\uAD90\uAD9C\uAD9D\uADA4\uADB7\uADC0\uADC1\uADC4\uADC8\uADD0\uADD1\uADD3\uADDC\uADE0\uADE4\uADF8\uADF9\uADFC\uADFF\uAE00\uAE01\uAE08\uAE09\uAE0B\uAE0D\uAE14\uAE30\uAE31\uAE34\uAE37\uAE38\uAE3A\uAE40\uAE41\uAE43\uAE45\uAE46\uAE4A\uAE4C\uAE4D\uAE4E\uAE50\uAE54\uAE56\uAE5C\uAE5D\uAE5F\uAE60\uAE61\uAE65\uAE68\uAE69\uAE6C\uAE70\uAE78"],
      ["b241", "\uCF6D\uCF6E\uCF6F\uCF72\uCF73\uCF75\uCF76\uCF77\uCF79", 6, "\uCF81\uCF82\uCF83\uCF84\uCF86", 5, "\uCF8D"],
      ["b261", "\uCF8E", 18, "\uCFA2", 5, "\uCFA9"],
      ["b281", "\uCFAA", 5, "\uCFB1", 18, "\uCFC5", 6, "\uAE79\uAE7B\uAE7C\uAE7D\uAE84\uAE85\uAE8C\uAEBC\uAEBD\uAEBE\uAEC0\uAEC4\uAECC\uAECD\uAECF\uAED0\uAED1\uAED8\uAED9\uAEDC\uAEE8\uAEEB\uAEED\uAEF4\uAEF8\uAEFC\uAF07\uAF08\uAF0D\uAF10\uAF2C\uAF2D\uAF30\uAF32\uAF34\uAF3C\uAF3D\uAF3F\uAF41\uAF42\uAF43\uAF48\uAF49\uAF50\uAF5C\uAF5D\uAF64\uAF65\uAF79\uAF80\uAF84\uAF88\uAF90\uAF91\uAF95\uAF9C\uAFB8\uAFB9\uAFBC\uAFC0\uAFC7\uAFC8\uAFC9\uAFCB\uAFCD\uAFCE\uAFD4\uAFDC\uAFE8\uAFE9\uAFF0\uAFF1\uAFF4\uAFF8\uB000\uB001\uB004\uB00C\uB010\uB014\uB01C\uB01D\uB028\uB044\uB045\uB048\uB04A\uB04C\uB04E\uB053\uB054\uB055\uB057\uB059"],
      ["b341", "\uCFCC", 19, "\uCFE2\uCFE3\uCFE5\uCFE6\uCFE7\uCFE9"],
      ["b361", "\uCFEA", 5, "\uCFF2\uCFF4\uCFF6", 5, "\uCFFD\uCFFE\uCFFF\uD001\uD002\uD003\uD005", 5],
      ["b381", "\uD00B", 5, "\uD012", 5, "\uD019", 19, "\uB05D\uB07C\uB07D\uB080\uB084\uB08C\uB08D\uB08F\uB091\uB098\uB099\uB09A\uB09C\uB09F\uB0A0\uB0A1\uB0A2\uB0A8\uB0A9\uB0AB", 4, "\uB0B1\uB0B3\uB0B4\uB0B5\uB0B8\uB0BC\uB0C4\uB0C5\uB0C7\uB0C8\uB0C9\uB0D0\uB0D1\uB0D4\uB0D8\uB0E0\uB0E5\uB108\uB109\uB10B\uB10C\uB110\uB112\uB113\uB118\uB119\uB11B\uB11C\uB11D\uB123\uB124\uB125\uB128\uB12C\uB134\uB135\uB137\uB138\uB139\uB140\uB141\uB144\uB148\uB150\uB151\uB154\uB155\uB158\uB15C\uB160\uB178\uB179\uB17C\uB180\uB182\uB188\uB189\uB18B\uB18D\uB192\uB193\uB194\uB198\uB19C\uB1A8\uB1CC\uB1D0\uB1D4\uB1DC\uB1DD"],
      ["b441", "\uD02E", 5, "\uD036\uD037\uD039\uD03A\uD03B\uD03D", 6, "\uD046\uD048\uD04A", 5],
      ["b461", "\uD051\uD052\uD053\uD055\uD056\uD057\uD059", 6, "\uD061", 10, "\uD06E\uD06F"],
      ["b481", "\uD071\uD072\uD073\uD075", 6, "\uD07E\uD07F\uD080\uD082", 18, "\uB1DF\uB1E8\uB1E9\uB1EC\uB1F0\uB1F9\uB1FB\uB1FD\uB204\uB205\uB208\uB20B\uB20C\uB214\uB215\uB217\uB219\uB220\uB234\uB23C\uB258\uB25C\uB260\uB268\uB269\uB274\uB275\uB27C\uB284\uB285\uB289\uB290\uB291\uB294\uB298\uB299\uB29A\uB2A0\uB2A1\uB2A3\uB2A5\uB2A6\uB2AA\uB2AC\uB2B0\uB2B4\uB2C8\uB2C9\uB2CC\uB2D0\uB2D2\uB2D8\uB2D9\uB2DB\uB2DD\uB2E2\uB2E4\uB2E5\uB2E6\uB2E8\uB2EB", 4, "\uB2F3\uB2F4\uB2F5\uB2F7", 4, "\uB2FF\uB300\uB301\uB304\uB308\uB310\uB311\uB313\uB314\uB315\uB31C\uB354\uB355\uB356\uB358\uB35B\uB35C\uB35E\uB35F\uB364\uB365"],
      ["b541", "\uD095", 14, "\uD0A6\uD0A7\uD0A9\uD0AA\uD0AB\uD0AD", 5],
      ["b561", "\uD0B3\uD0B6\uD0B8\uD0BA", 5, "\uD0C2\uD0C3\uD0C5\uD0C6\uD0C7\uD0CA", 5, "\uD0D2\uD0D6", 4],
      ["b581", "\uD0DB\uD0DE\uD0DF\uD0E1\uD0E2\uD0E3\uD0E5", 6, "\uD0EE\uD0F2", 5, "\uD0F9", 11, "\uB367\uB369\uB36B\uB36E\uB370\uB371\uB374\uB378\uB380\uB381\uB383\uB384\uB385\uB38C\uB390\uB394\uB3A0\uB3A1\uB3A8\uB3AC\uB3C4\uB3C5\uB3C8\uB3CB\uB3CC\uB3CE\uB3D0\uB3D4\uB3D5\uB3D7\uB3D9\uB3DB\uB3DD\uB3E0\uB3E4\uB3E8\uB3FC\uB410\uB418\uB41C\uB420\uB428\uB429\uB42B\uB434\uB450\uB451\uB454\uB458\uB460\uB461\uB463\uB465\uB46C\uB480\uB488\uB49D\uB4A4\uB4A8\uB4AC\uB4B5\uB4B7\uB4B9\uB4C0\uB4C4\uB4C8\uB4D0\uB4D5\uB4DC\uB4DD\uB4E0\uB4E3\uB4E4\uB4E6\uB4EC\uB4ED\uB4EF\uB4F1\uB4F8\uB514\uB515\uB518\uB51B\uB51C\uB524\uB525\uB527\uB528\uB529\uB52A\uB530\uB531\uB534\uB538"],
      ["b641", "\uD105", 7, "\uD10E", 17],
      ["b661", "\uD120", 15, "\uD132\uD133\uD135\uD136\uD137\uD139\uD13B\uD13C\uD13D\uD13E"],
      ["b681", "\uD13F\uD142\uD146", 5, "\uD14E\uD14F\uD151\uD152\uD153\uD155", 6, "\uD15E\uD160\uD162", 5, "\uD169\uD16A\uD16B\uD16D\uB540\uB541\uB543\uB544\uB545\uB54B\uB54C\uB54D\uB550\uB554\uB55C\uB55D\uB55F\uB560\uB561\uB5A0\uB5A1\uB5A4\uB5A8\uB5AA\uB5AB\uB5B0\uB5B1\uB5B3\uB5B4\uB5B5\uB5BB\uB5BC\uB5BD\uB5C0\uB5C4\uB5CC\uB5CD\uB5CF\uB5D0\uB5D1\uB5D8\uB5EC\uB610\uB611\uB614\uB618\uB625\uB62C\uB634\uB648\uB664\uB668\uB69C\uB69D\uB6A0\uB6A4\uB6AB\uB6AC\uB6B1\uB6D4\uB6F0\uB6F4\uB6F8\uB700\uB701\uB705\uB728\uB729\uB72C\uB72F\uB730\uB738\uB739\uB73B\uB744\uB748\uB74C\uB754\uB755\uB760\uB764\uB768\uB770\uB771\uB773\uB775\uB77C\uB77D\uB780\uB784\uB78C\uB78D\uB78F\uB790\uB791\uB792\uB796\uB797"],
      ["b741", "\uD16E", 13, "\uD17D", 6, "\uD185\uD186\uD187\uD189\uD18A"],
      ["b761", "\uD18B", 20, "\uD1A2\uD1A3\uD1A5\uD1A6\uD1A7"],
      ["b781", "\uD1A9", 6, "\uD1B2\uD1B4\uD1B6\uD1B7\uD1B8\uD1B9\uD1BB\uD1BD\uD1BE\uD1BF\uD1C1", 14, "\uB798\uB799\uB79C\uB7A0\uB7A8\uB7A9\uB7AB\uB7AC\uB7AD\uB7B4\uB7B5\uB7B8\uB7C7\uB7C9\uB7EC\uB7ED\uB7F0\uB7F4\uB7FC\uB7FD\uB7FF\uB800\uB801\uB807\uB808\uB809\uB80C\uB810\uB818\uB819\uB81B\uB81D\uB824\uB825\uB828\uB82C\uB834\uB835\uB837\uB838\uB839\uB840\uB844\uB851\uB853\uB85C\uB85D\uB860\uB864\uB86C\uB86D\uB86F\uB871\uB878\uB87C\uB88D\uB8A8\uB8B0\uB8B4\uB8B8\uB8C0\uB8C1\uB8C3\uB8C5\uB8CC\uB8D0\uB8D4\uB8DD\uB8DF\uB8E1\uB8E8\uB8E9\uB8EC\uB8F0\uB8F8\uB8F9\uB8FB\uB8FD\uB904\uB918\uB920\uB93C\uB93D\uB940\uB944\uB94C\uB94F\uB951\uB958\uB959\uB95C\uB960\uB968\uB969"],
      ["b841", "\uD1D0", 7, "\uD1D9", 17],
      ["b861", "\uD1EB", 8, "\uD1F5\uD1F6\uD1F7\uD1F9", 13],
      ["b881", "\uD208\uD20A", 5, "\uD211", 24, "\uB96B\uB96D\uB974\uB975\uB978\uB97C\uB984\uB985\uB987\uB989\uB98A\uB98D\uB98E\uB9AC\uB9AD\uB9B0\uB9B4\uB9BC\uB9BD\uB9BF\uB9C1\uB9C8\uB9C9\uB9CC\uB9CE", 4, "\uB9D8\uB9D9\uB9DB\uB9DD\uB9DE\uB9E1\uB9E3\uB9E4\uB9E5\uB9E8\uB9EC\uB9F4\uB9F5\uB9F7\uB9F8\uB9F9\uB9FA\uBA00\uBA01\uBA08\uBA15\uBA38\uBA39\uBA3C\uBA40\uBA42\uBA48\uBA49\uBA4B\uBA4D\uBA4E\uBA53\uBA54\uBA55\uBA58\uBA5C\uBA64\uBA65\uBA67\uBA68\uBA69\uBA70\uBA71\uBA74\uBA78\uBA83\uBA84\uBA85\uBA87\uBA8C\uBAA8\uBAA9\uBAAB\uBAAC\uBAB0\uBAB2\uBAB8\uBAB9\uBABB\uBABD\uBAC4\uBAC8\uBAD8\uBAD9\uBAFC"],
      ["b941", "\uD22A\uD22B\uD22E\uD22F\uD231\uD232\uD233\uD235", 6, "\uD23E\uD240\uD242", 5, "\uD249\uD24A\uD24B\uD24C"],
      ["b961", "\uD24D", 14, "\uD25D", 6, "\uD265\uD266\uD267\uD268"],
      ["b981", "\uD269", 22, "\uD282\uD283\uD285\uD286\uD287\uD289\uD28A\uD28B\uD28C\uBB00\uBB04\uBB0D\uBB0F\uBB11\uBB18\uBB1C\uBB20\uBB29\uBB2B\uBB34\uBB35\uBB36\uBB38\uBB3B\uBB3C\uBB3D\uBB3E\uBB44\uBB45\uBB47\uBB49\uBB4D\uBB4F\uBB50\uBB54\uBB58\uBB61\uBB63\uBB6C\uBB88\uBB8C\uBB90\uBBA4\uBBA8\uBBAC\uBBB4\uBBB7\uBBC0\uBBC4\uBBC8\uBBD0\uBBD3\uBBF8\uBBF9\uBBFC\uBBFF\uBC00\uBC02\uBC08\uBC09\uBC0B\uBC0C\uBC0D\uBC0F\uBC11\uBC14", 4, "\uBC1B", 4, "\uBC24\uBC25\uBC27\uBC29\uBC2D\uBC30\uBC31\uBC34\uBC38\uBC40\uBC41\uBC43\uBC44\uBC45\uBC49\uBC4C\uBC4D\uBC50\uBC5D\uBC84\uBC85\uBC88\uBC8B\uBC8C\uBC8E\uBC94\uBC95\uBC97"],
      ["ba41", "\uD28D\uD28E\uD28F\uD292\uD293\uD294\uD296", 5, "\uD29D\uD29E\uD29F\uD2A1\uD2A2\uD2A3\uD2A5", 6, "\uD2AD"],
      ["ba61", "\uD2AE\uD2AF\uD2B0\uD2B2", 5, "\uD2BA\uD2BB\uD2BD\uD2BE\uD2C1\uD2C3", 4, "\uD2CA\uD2CC", 5],
      ["ba81", "\uD2D2\uD2D3\uD2D5\uD2D6\uD2D7\uD2D9\uD2DA\uD2DB\uD2DD", 6, "\uD2E6", 9, "\uD2F2\uD2F3\uD2F5\uD2F6\uD2F7\uD2F9\uD2FA\uBC99\uBC9A\uBCA0\uBCA1\uBCA4\uBCA7\uBCA8\uBCB0\uBCB1\uBCB3\uBCB4\uBCB5\uBCBC\uBCBD\uBCC0\uBCC4\uBCCD\uBCCF\uBCD0\uBCD1\uBCD5\uBCD8\uBCDC\uBCF4\uBCF5\uBCF6\uBCF8\uBCFC\uBD04\uBD05\uBD07\uBD09\uBD10\uBD14\uBD24\uBD2C\uBD40\uBD48\uBD49\uBD4C\uBD50\uBD58\uBD59\uBD64\uBD68\uBD80\uBD81\uBD84\uBD87\uBD88\uBD89\uBD8A\uBD90\uBD91\uBD93\uBD95\uBD99\uBD9A\uBD9C\uBDA4\uBDB0\uBDB8\uBDD4\uBDD5\uBDD8\uBDDC\uBDE9\uBDF0\uBDF4\uBDF8\uBE00\uBE03\uBE05\uBE0C\uBE0D\uBE10\uBE14\uBE1C\uBE1D\uBE1F\uBE44\uBE45\uBE48\uBE4C\uBE4E\uBE54\uBE55\uBE57\uBE59\uBE5A\uBE5B\uBE60\uBE61\uBE64"],
      ["bb41", "\uD2FB", 4, "\uD302\uD304\uD306", 5, "\uD30F\uD311\uD312\uD313\uD315\uD317", 4, "\uD31E\uD322\uD323"],
      ["bb61", "\uD324\uD326\uD327\uD32A\uD32B\uD32D\uD32E\uD32F\uD331", 6, "\uD33A\uD33E", 5, "\uD346\uD347\uD348\uD349"],
      ["bb81", "\uD34A", 31, "\uBE68\uBE6A\uBE70\uBE71\uBE73\uBE74\uBE75\uBE7B\uBE7C\uBE7D\uBE80\uBE84\uBE8C\uBE8D\uBE8F\uBE90\uBE91\uBE98\uBE99\uBEA8\uBED0\uBED1\uBED4\uBED7\uBED8\uBEE0\uBEE3\uBEE4\uBEE5\uBEEC\uBF01\uBF08\uBF09\uBF18\uBF19\uBF1B\uBF1C\uBF1D\uBF40\uBF41\uBF44\uBF48\uBF50\uBF51\uBF55\uBF94\uBFB0\uBFC5\uBFCC\uBFCD\uBFD0\uBFD4\uBFDC\uBFDF\uBFE1\uC03C\uC051\uC058\uC05C\uC060\uC068\uC069\uC090\uC091\uC094\uC098\uC0A0\uC0A1\uC0A3\uC0A5\uC0AC\uC0AD\uC0AF\uC0B0\uC0B3\uC0B4\uC0B5\uC0B6\uC0BC\uC0BD\uC0BF\uC0C0\uC0C1\uC0C5\uC0C8\uC0C9\uC0CC\uC0D0\uC0D8\uC0D9\uC0DB\uC0DC\uC0DD\uC0E4"],
      ["bc41", "\uD36A", 17, "\uD37E\uD37F\uD381\uD382\uD383\uD385\uD386\uD387"],
      ["bc61", "\uD388\uD389\uD38A\uD38B\uD38E\uD392", 5, "\uD39A\uD39B\uD39D\uD39E\uD39F\uD3A1", 6, "\uD3AA\uD3AC\uD3AE"],
      ["bc81", "\uD3AF", 4, "\uD3B5\uD3B6\uD3B7\uD3B9\uD3BA\uD3BB\uD3BD", 6, "\uD3C6\uD3C7\uD3CA", 5, "\uD3D1", 5, "\uC0E5\uC0E8\uC0EC\uC0F4\uC0F5\uC0F7\uC0F9\uC100\uC104\uC108\uC110\uC115\uC11C", 4, "\uC123\uC124\uC126\uC127\uC12C\uC12D\uC12F\uC130\uC131\uC136\uC138\uC139\uC13C\uC140\uC148\uC149\uC14B\uC14C\uC14D\uC154\uC155\uC158\uC15C\uC164\uC165\uC167\uC168\uC169\uC170\uC174\uC178\uC185\uC18C\uC18D\uC18E\uC190\uC194\uC196\uC19C\uC19D\uC19F\uC1A1\uC1A5\uC1A8\uC1A9\uC1AC\uC1B0\uC1BD\uC1C4\uC1C8\uC1CC\uC1D4\uC1D7\uC1D8\uC1E0\uC1E4\uC1E8\uC1F0\uC1F1\uC1F3\uC1FC\uC1FD\uC200\uC204\uC20C\uC20D\uC20F\uC211\uC218\uC219\uC21C\uC21F\uC220\uC228\uC229\uC22B\uC22D"],
      ["bd41", "\uD3D7\uD3D9", 7, "\uD3E2\uD3E4", 7, "\uD3EE\uD3EF\uD3F1\uD3F2\uD3F3\uD3F5\uD3F6\uD3F7"],
      ["bd61", "\uD3F8\uD3F9\uD3FA\uD3FB\uD3FE\uD400\uD402", 5, "\uD409", 13],
      ["bd81", "\uD417", 5, "\uD41E", 25, "\uC22F\uC231\uC232\uC234\uC248\uC250\uC251\uC254\uC258\uC260\uC265\uC26C\uC26D\uC270\uC274\uC27C\uC27D\uC27F\uC281\uC288\uC289\uC290\uC298\uC29B\uC29D\uC2A4\uC2A5\uC2A8\uC2AC\uC2AD\uC2B4\uC2B5\uC2B7\uC2B9\uC2DC\uC2DD\uC2E0\uC2E3\uC2E4\uC2EB\uC2EC\uC2ED\uC2EF\uC2F1\uC2F6\uC2F8\uC2F9\uC2FB\uC2FC\uC300\uC308\uC309\uC30C\uC30D\uC313\uC314\uC315\uC318\uC31C\uC324\uC325\uC328\uC329\uC345\uC368\uC369\uC36C\uC370\uC372\uC378\uC379\uC37C\uC37D\uC384\uC388\uC38C\uC3C0\uC3D8\uC3D9\uC3DC\uC3DF\uC3E0\uC3E2\uC3E8\uC3E9\uC3ED\uC3F4\uC3F5\uC3F8\uC408\uC410\uC424\uC42C\uC430"],
      ["be41", "\uD438", 7, "\uD441\uD442\uD443\uD445", 14],
      ["be61", "\uD454", 7, "\uD45D\uD45E\uD45F\uD461\uD462\uD463\uD465", 7, "\uD46E\uD470\uD471\uD472"],
      ["be81", "\uD473", 4, "\uD47A\uD47B\uD47D\uD47E\uD481\uD483", 4, "\uD48A\uD48C\uD48E", 5, "\uD495", 8, "\uC434\uC43C\uC43D\uC448\uC464\uC465\uC468\uC46C\uC474\uC475\uC479\uC480\uC494\uC49C\uC4B8\uC4BC\uC4E9\uC4F0\uC4F1\uC4F4\uC4F8\uC4FA\uC4FF\uC500\uC501\uC50C\uC510\uC514\uC51C\uC528\uC529\uC52C\uC530\uC538\uC539\uC53B\uC53D\uC544\uC545\uC548\uC549\uC54A\uC54C\uC54D\uC54E\uC553\uC554\uC555\uC557\uC558\uC559\uC55D\uC55E\uC560\uC561\uC564\uC568\uC570\uC571\uC573\uC574\uC575\uC57C\uC57D\uC580\uC584\uC587\uC58C\uC58D\uC58F\uC591\uC595\uC597\uC598\uC59C\uC5A0\uC5A9\uC5B4\uC5B5\uC5B8\uC5B9\uC5BB\uC5BC\uC5BD\uC5BE\uC5C4", 6, "\uC5CC\uC5CE"],
      ["bf41", "\uD49E", 10, "\uD4AA", 14],
      ["bf61", "\uD4B9", 18, "\uD4CD\uD4CE\uD4CF\uD4D1\uD4D2\uD4D3\uD4D5"],
      ["bf81", "\uD4D6", 5, "\uD4DD\uD4DE\uD4E0", 7, "\uD4E9\uD4EA\uD4EB\uD4ED\uD4EE\uD4EF\uD4F1", 6, "\uD4F9\uD4FA\uD4FC\uC5D0\uC5D1\uC5D4\uC5D8\uC5E0\uC5E1\uC5E3\uC5E5\uC5EC\uC5ED\uC5EE\uC5F0\uC5F4\uC5F6\uC5F7\uC5FC", 5, "\uC605\uC606\uC607\uC608\uC60C\uC610\uC618\uC619\uC61B\uC61C\uC624\uC625\uC628\uC62C\uC62D\uC62E\uC630\uC633\uC634\uC635\uC637\uC639\uC63B\uC640\uC641\uC644\uC648\uC650\uC651\uC653\uC654\uC655\uC65C\uC65D\uC660\uC66C\uC66F\uC671\uC678\uC679\uC67C\uC680\uC688\uC689\uC68B\uC68D\uC694\uC695\uC698\uC69C\uC6A4\uC6A5\uC6A7\uC6A9\uC6B0\uC6B1\uC6B4\uC6B8\uC6B9\uC6BA\uC6C0\uC6C1\uC6C3\uC6C5\uC6CC\uC6CD\uC6D0\uC6D4\uC6DC\uC6DD\uC6E0\uC6E1\uC6E8"],
      ["c041", "\uD4FE", 5, "\uD505\uD506\uD507\uD509\uD50A\uD50B\uD50D", 6, "\uD516\uD518", 5],
      ["c061", "\uD51E", 25],
      ["c081", "\uD538\uD539\uD53A\uD53B\uD53E\uD53F\uD541\uD542\uD543\uD545", 6, "\uD54E\uD550\uD552", 5, "\uD55A\uD55B\uD55D\uD55E\uD55F\uD561\uD562\uD563\uC6E9\uC6EC\uC6F0\uC6F8\uC6F9\uC6FD\uC704\uC705\uC708\uC70C\uC714\uC715\uC717\uC719\uC720\uC721\uC724\uC728\uC730\uC731\uC733\uC735\uC737\uC73C\uC73D\uC740\uC744\uC74A\uC74C\uC74D\uC74F\uC751", 7, "\uC75C\uC760\uC768\uC76B\uC774\uC775\uC778\uC77C\uC77D\uC77E\uC783\uC784\uC785\uC787\uC788\uC789\uC78A\uC78E\uC790\uC791\uC794\uC796\uC797\uC798\uC79A\uC7A0\uC7A1\uC7A3\uC7A4\uC7A5\uC7A6\uC7AC\uC7AD\uC7B0\uC7B4\uC7BC\uC7BD\uC7BF\uC7C0\uC7C1\uC7C8\uC7C9\uC7CC\uC7CE\uC7D0\uC7D8\uC7DD\uC7E4\uC7E8\uC7EC\uC800\uC801\uC804\uC808\uC80A"],
      ["c141", "\uD564\uD566\uD567\uD56A\uD56C\uD56E", 5, "\uD576\uD577\uD579\uD57A\uD57B\uD57D", 6, "\uD586\uD58A\uD58B"],
      ["c161", "\uD58C\uD58D\uD58E\uD58F\uD591", 19, "\uD5A6\uD5A7"],
      ["c181", "\uD5A8", 31, "\uC810\uC811\uC813\uC815\uC816\uC81C\uC81D\uC820\uC824\uC82C\uC82D\uC82F\uC831\uC838\uC83C\uC840\uC848\uC849\uC84C\uC84D\uC854\uC870\uC871\uC874\uC878\uC87A\uC880\uC881\uC883\uC885\uC886\uC887\uC88B\uC88C\uC88D\uC894\uC89D\uC89F\uC8A1\uC8A8\uC8BC\uC8BD\uC8C4\uC8C8\uC8CC\uC8D4\uC8D5\uC8D7\uC8D9\uC8E0\uC8E1\uC8E4\uC8F5\uC8FC\uC8FD\uC900\uC904\uC905\uC906\uC90C\uC90D\uC90F\uC911\uC918\uC92C\uC934\uC950\uC951\uC954\uC958\uC960\uC961\uC963\uC96C\uC970\uC974\uC97C\uC988\uC989\uC98C\uC990\uC998\uC999\uC99B\uC99D\uC9C0\uC9C1\uC9C4\uC9C7\uC9C8\uC9CA\uC9D0\uC9D1\uC9D3"],
      ["c241", "\uD5CA\uD5CB\uD5CD\uD5CE\uD5CF\uD5D1\uD5D3", 4, "\uD5DA\uD5DC\uD5DE", 5, "\uD5E6\uD5E7\uD5E9\uD5EA\uD5EB\uD5ED\uD5EE"],
      ["c261", "\uD5EF", 4, "\uD5F6\uD5F8\uD5FA", 5, "\uD602\uD603\uD605\uD606\uD607\uD609", 6, "\uD612"],
      ["c281", "\uD616", 5, "\uD61D\uD61E\uD61F\uD621\uD622\uD623\uD625", 7, "\uD62E", 9, "\uD63A\uD63B\uC9D5\uC9D6\uC9D9\uC9DA\uC9DC\uC9DD\uC9E0\uC9E2\uC9E4\uC9E7\uC9EC\uC9ED\uC9EF\uC9F0\uC9F1\uC9F8\uC9F9\uC9FC\uCA00\uCA08\uCA09\uCA0B\uCA0C\uCA0D\uCA14\uCA18\uCA29\uCA4C\uCA4D\uCA50\uCA54\uCA5C\uCA5D\uCA5F\uCA60\uCA61\uCA68\uCA7D\uCA84\uCA98\uCABC\uCABD\uCAC0\uCAC4\uCACC\uCACD\uCACF\uCAD1\uCAD3\uCAD8\uCAD9\uCAE0\uCAEC\uCAF4\uCB08\uCB10\uCB14\uCB18\uCB20\uCB21\uCB41\uCB48\uCB49\uCB4C\uCB50\uCB58\uCB59\uCB5D\uCB64\uCB78\uCB79\uCB9C\uCBB8\uCBD4\uCBE4\uCBE7\uCBE9\uCC0C\uCC0D\uCC10\uCC14\uCC1C\uCC1D\uCC21\uCC22\uCC27\uCC28\uCC29\uCC2C\uCC2E\uCC30\uCC38\uCC39\uCC3B"],
      ["c341", "\uD63D\uD63E\uD63F\uD641\uD642\uD643\uD644\uD646\uD647\uD64A\uD64C\uD64E\uD64F\uD650\uD652\uD653\uD656\uD657\uD659\uD65A\uD65B\uD65D", 4],
      ["c361", "\uD662", 4, "\uD668\uD66A", 5, "\uD672\uD673\uD675", 11],
      ["c381", "\uD681\uD682\uD684\uD686", 5, "\uD68E\uD68F\uD691\uD692\uD693\uD695", 7, "\uD69E\uD6A0\uD6A2", 5, "\uD6A9\uD6AA\uCC3C\uCC3D\uCC3E\uCC44\uCC45\uCC48\uCC4C\uCC54\uCC55\uCC57\uCC58\uCC59\uCC60\uCC64\uCC66\uCC68\uCC70\uCC75\uCC98\uCC99\uCC9C\uCCA0\uCCA8\uCCA9\uCCAB\uCCAC\uCCAD\uCCB4\uCCB5\uCCB8\uCCBC\uCCC4\uCCC5\uCCC7\uCCC9\uCCD0\uCCD4\uCCE4\uCCEC\uCCF0\uCD01\uCD08\uCD09\uCD0C\uCD10\uCD18\uCD19\uCD1B\uCD1D\uCD24\uCD28\uCD2C\uCD39\uCD5C\uCD60\uCD64\uCD6C\uCD6D\uCD6F\uCD71\uCD78\uCD88\uCD94\uCD95\uCD98\uCD9C\uCDA4\uCDA5\uCDA7\uCDA9\uCDB0\uCDC4\uCDCC\uCDD0\uCDE8\uCDEC\uCDF0\uCDF8\uCDF9\uCDFB\uCDFD\uCE04\uCE08\uCE0C\uCE14\uCE19\uCE20\uCE21\uCE24\uCE28\uCE30\uCE31\uCE33\uCE35"],
      ["c441", "\uD6AB\uD6AD\uD6AE\uD6AF\uD6B1", 7, "\uD6BA\uD6BC", 7, "\uD6C6\uD6C7\uD6C9\uD6CA\uD6CB"],
      ["c461", "\uD6CD\uD6CE\uD6CF\uD6D0\uD6D2\uD6D3\uD6D5\uD6D6\uD6D8\uD6DA", 5, "\uD6E1\uD6E2\uD6E3\uD6E5\uD6E6\uD6E7\uD6E9", 4],
      ["c481", "\uD6EE\uD6EF\uD6F1\uD6F2\uD6F3\uD6F4\uD6F6", 5, "\uD6FE\uD6FF\uD701\uD702\uD703\uD705", 11, "\uD712\uD713\uD714\uCE58\uCE59\uCE5C\uCE5F\uCE60\uCE61\uCE68\uCE69\uCE6B\uCE6D\uCE74\uCE75\uCE78\uCE7C\uCE84\uCE85\uCE87\uCE89\uCE90\uCE91\uCE94\uCE98\uCEA0\uCEA1\uCEA3\uCEA4\uCEA5\uCEAC\uCEAD\uCEC1\uCEE4\uCEE5\uCEE8\uCEEB\uCEEC\uCEF4\uCEF5\uCEF7\uCEF8\uCEF9\uCF00\uCF01\uCF04\uCF08\uCF10\uCF11\uCF13\uCF15\uCF1C\uCF20\uCF24\uCF2C\uCF2D\uCF2F\uCF30\uCF31\uCF38\uCF54\uCF55\uCF58\uCF5C\uCF64\uCF65\uCF67\uCF69\uCF70\uCF71\uCF74\uCF78\uCF80\uCF85\uCF8C\uCFA1\uCFA8\uCFB0\uCFC4\uCFE0\uCFE1\uCFE4\uCFE8\uCFF0\uCFF1\uCFF3\uCFF5\uCFFC\uD000\uD004\uD011\uD018\uD02D\uD034\uD035\uD038\uD03C"],
      ["c541", "\uD715\uD716\uD717\uD71A\uD71B\uD71D\uD71E\uD71F\uD721", 6, "\uD72A\uD72C\uD72E", 5, "\uD736\uD737\uD739"],
      ["c561", "\uD73A\uD73B\uD73D", 6, "\uD745\uD746\uD748\uD74A", 5, "\uD752\uD753\uD755\uD75A", 4],
      ["c581", "\uD75F\uD762\uD764\uD766\uD767\uD768\uD76A\uD76B\uD76D\uD76E\uD76F\uD771\uD772\uD773\uD775", 6, "\uD77E\uD77F\uD780\uD782", 5, "\uD78A\uD78B\uD044\uD045\uD047\uD049\uD050\uD054\uD058\uD060\uD06C\uD06D\uD070\uD074\uD07C\uD07D\uD081\uD0A4\uD0A5\uD0A8\uD0AC\uD0B4\uD0B5\uD0B7\uD0B9\uD0C0\uD0C1\uD0C4\uD0C8\uD0C9\uD0D0\uD0D1\uD0D3\uD0D4\uD0D5\uD0DC\uD0DD\uD0E0\uD0E4\uD0EC\uD0ED\uD0EF\uD0F0\uD0F1\uD0F8\uD10D\uD130\uD131\uD134\uD138\uD13A\uD140\uD141\uD143\uD144\uD145\uD14C\uD14D\uD150\uD154\uD15C\uD15D\uD15F\uD161\uD168\uD16C\uD17C\uD184\uD188\uD1A0\uD1A1\uD1A4\uD1A8\uD1B0\uD1B1\uD1B3\uD1B5\uD1BA\uD1BC\uD1C0\uD1D8\uD1F4\uD1F8\uD207\uD209\uD210\uD22C\uD22D\uD230\uD234\uD23C\uD23D\uD23F\uD241\uD248\uD25C"],
      ["c641", "\uD78D\uD78E\uD78F\uD791", 6, "\uD79A\uD79C\uD79E", 5],
      ["c6a1", "\uD264\uD280\uD281\uD284\uD288\uD290\uD291\uD295\uD29C\uD2A0\uD2A4\uD2AC\uD2B1\uD2B8\uD2B9\uD2BC\uD2BF\uD2C0\uD2C2\uD2C8\uD2C9\uD2CB\uD2D4\uD2D8\uD2DC\uD2E4\uD2E5\uD2F0\uD2F1\uD2F4\uD2F8\uD300\uD301\uD303\uD305\uD30C\uD30D\uD30E\uD310\uD314\uD316\uD31C\uD31D\uD31F\uD320\uD321\uD325\uD328\uD329\uD32C\uD330\uD338\uD339\uD33B\uD33C\uD33D\uD344\uD345\uD37C\uD37D\uD380\uD384\uD38C\uD38D\uD38F\uD390\uD391\uD398\uD399\uD39C\uD3A0\uD3A8\uD3A9\uD3AB\uD3AD\uD3B4\uD3B8\uD3BC\uD3C4\uD3C5\uD3C8\uD3C9\uD3D0\uD3D8\uD3E1\uD3E3\uD3EC\uD3ED\uD3F0\uD3F4\uD3FC\uD3FD\uD3FF\uD401"],
      ["c7a1", "\uD408\uD41D\uD440\uD444\uD45C\uD460\uD464\uD46D\uD46F\uD478\uD479\uD47C\uD47F\uD480\uD482\uD488\uD489\uD48B\uD48D\uD494\uD4A9\uD4CC\uD4D0\uD4D4\uD4DC\uD4DF\uD4E8\uD4EC\uD4F0\uD4F8\uD4FB\uD4FD\uD504\uD508\uD50C\uD514\uD515\uD517\uD53C\uD53D\uD540\uD544\uD54C\uD54D\uD54F\uD551\uD558\uD559\uD55C\uD560\uD565\uD568\uD569\uD56B\uD56D\uD574\uD575\uD578\uD57C\uD584\uD585\uD587\uD588\uD589\uD590\uD5A5\uD5C8\uD5C9\uD5CC\uD5D0\uD5D2\uD5D8\uD5D9\uD5DB\uD5DD\uD5E4\uD5E5\uD5E8\uD5EC\uD5F4\uD5F5\uD5F7\uD5F9\uD600\uD601\uD604\uD608\uD610\uD611\uD613\uD614\uD615\uD61C\uD620"],
      ["c8a1", "\uD624\uD62D\uD638\uD639\uD63C\uD640\uD645\uD648\uD649\uD64B\uD64D\uD651\uD654\uD655\uD658\uD65C\uD667\uD669\uD670\uD671\uD674\uD683\uD685\uD68C\uD68D\uD690\uD694\uD69D\uD69F\uD6A1\uD6A8\uD6AC\uD6B0\uD6B9\uD6BB\uD6C4\uD6C5\uD6C8\uD6CC\uD6D1\uD6D4\uD6D7\uD6D9\uD6E0\uD6E4\uD6E8\uD6F0\uD6F5\uD6FC\uD6FD\uD700\uD704\uD711\uD718\uD719\uD71C\uD720\uD728\uD729\uD72B\uD72D\uD734\uD735\uD738\uD73C\uD744\uD747\uD749\uD750\uD751\uD754\uD756\uD757\uD758\uD759\uD760\uD761\uD763\uD765\uD769\uD76C\uD770\uD774\uD77C\uD77D\uD781\uD788\uD789\uD78C\uD790\uD798\uD799\uD79B\uD79D"],
      ["caa1", "\u4F3D\u4F73\u5047\u50F9\u52A0\u53EF\u5475\u54E5\u5609\u5AC1\u5BB6\u6687\u67B6\u67B7\u67EF\u6B4C\u73C2\u75C2\u7A3C\u82DB\u8304\u8857\u8888\u8A36\u8CC8\u8DCF\u8EFB\u8FE6\u99D5\u523B\u5374\u5404\u606A\u6164\u6BBC\u73CF\u811A\u89BA\u89D2\u95A3\u4F83\u520A\u58BE\u5978\u59E6\u5E72\u5E79\u61C7\u63C0\u6746\u67EC\u687F\u6F97\u764E\u770B\u78F5\u7A08\u7AFF\u7C21\u809D\u826E\u8271\u8AEB\u9593\u4E6B\u559D\u66F7\u6E34\u78A3\u7AED\u845B\u8910\u874E\u97A8\u52D8\u574E\u582A\u5D4C\u611F\u61BE\u6221\u6562\u67D1\u6A44\u6E1B\u7518\u75B3\u76E3\u77B0\u7D3A\u90AF\u9451\u9452\u9F95"],
      ["cba1", "\u5323\u5CAC\u7532\u80DB\u9240\u9598\u525B\u5808\u59DC\u5CA1\u5D17\u5EB7\u5F3A\u5F4A\u6177\u6C5F\u757A\u7586\u7CE0\u7D73\u7DB1\u7F8C\u8154\u8221\u8591\u8941\u8B1B\u92FC\u964D\u9C47\u4ECB\u4EF7\u500B\u51F1\u584F\u6137\u613E\u6168\u6539\u69EA\u6F11\u75A5\u7686\u76D6\u7B87\u82A5\u84CB\uF900\u93A7\u958B\u5580\u5BA2\u5751\uF901\u7CB3\u7FB9\u91B5\u5028\u53BB\u5C45\u5DE8\u62D2\u636E\u64DA\u64E7\u6E20\u70AC\u795B\u8DDD\u8E1E\uF902\u907D\u9245\u92F8\u4E7E\u4EF6\u5065\u5DFE\u5EFA\u6106\u6957\u8171\u8654\u8E47\u9375\u9A2B\u4E5E\u5091\u6770\u6840\u5109\u528D\u5292\u6AA2"],
      ["cca1", "\u77BC\u9210\u9ED4\u52AB\u602F\u8FF2\u5048\u61A9\u63ED\u64CA\u683C\u6A84\u6FC0\u8188\u89A1\u9694\u5805\u727D\u72AC\u7504\u7D79\u7E6D\u80A9\u898B\u8B74\u9063\u9D51\u6289\u6C7A\u6F54\u7D50\u7F3A\u8A23\u517C\u614A\u7B9D\u8B19\u9257\u938C\u4EAC\u4FD3\u501E\u50BE\u5106\u52C1\u52CD\u537F\u5770\u5883\u5E9A\u5F91\u6176\u61AC\u64CE\u656C\u666F\u66BB\u66F4\u6897\u6D87\u7085\u70F1\u749F\u74A5\u74CA\u75D9\u786C\u78EC\u7ADF\u7AF6\u7D45\u7D93\u8015\u803F\u811B\u8396\u8B66\u8F15\u9015\u93E1\u9803\u9838\u9A5A\u9BE8\u4FC2\u5553\u583A\u5951\u5B63\u5C46\u60B8\u6212\u6842\u68B0"],
      ["cda1", "\u68E8\u6EAA\u754C\u7678\u78CE\u7A3D\u7CFB\u7E6B\u7E7C\u8A08\u8AA1\u8C3F\u968E\u9DC4\u53E4\u53E9\u544A\u5471\u56FA\u59D1\u5B64\u5C3B\u5EAB\u62F7\u6537\u6545\u6572\u66A0\u67AF\u69C1\u6CBD\u75FC\u7690\u777E\u7A3F\u7F94\u8003\u80A1\u818F\u82E6\u82FD\u83F0\u85C1\u8831\u88B4\u8AA5\uF903\u8F9C\u932E\u96C7\u9867\u9AD8\u9F13\u54ED\u659B\u66F2\u688F\u7A40\u8C37\u9D60\u56F0\u5764\u5D11\u6606\u68B1\u68CD\u6EFE\u7428\u889E\u9BE4\u6C68\uF904\u9AA8\u4F9B\u516C\u5171\u529F\u5B54\u5DE5\u6050\u606D\u62F1\u63A7\u653B\u73D9\u7A7A\u86A3\u8CA2\u978F\u4E32\u5BE1\u6208\u679C\u74DC"],
      ["cea1", "\u79D1\u83D3\u8A87\u8AB2\u8DE8\u904E\u934B\u9846\u5ED3\u69E8\u85FF\u90ED\uF905\u51A0\u5B98\u5BEC\u6163\u68FA\u6B3E\u704C\u742F\u74D8\u7BA1\u7F50\u83C5\u89C0\u8CAB\u95DC\u9928\u522E\u605D\u62EC\u9002\u4F8A\u5149\u5321\u58D9\u5EE3\u66E0\u6D38\u709A\u72C2\u73D6\u7B50\u80F1\u945B\u5366\u639B\u7F6B\u4E56\u5080\u584A\u58DE\u602A\u6127\u62D0\u69D0\u9B41\u5B8F\u7D18\u80B1\u8F5F\u4EA4\u50D1\u54AC\u55AC\u5B0C\u5DA0\u5DE7\u652A\u654E\u6821\u6A4B\u72E1\u768E\u77EF\u7D5E\u7FF9\u81A0\u854E\u86DF\u8F03\u8F4E\u90CA\u9903\u9A55\u9BAB\u4E18\u4E45\u4E5D\u4EC7\u4FF1\u5177\u52FE"],
      ["cfa1", "\u5340\u53E3\u53E5\u548E\u5614\u5775\u57A2\u5BC7\u5D87\u5ED0\u61FC\u62D8\u6551\u67B8\u67E9\u69CB\u6B50\u6BC6\u6BEC\u6C42\u6E9D\u7078\u72D7\u7396\u7403\u77BF\u77E9\u7A76\u7D7F\u8009\u81FC\u8205\u820A\u82DF\u8862\u8B33\u8CFC\u8EC0\u9011\u90B1\u9264\u92B6\u99D2\u9A45\u9CE9\u9DD7\u9F9C\u570B\u5C40\u83CA\u97A0\u97AB\u9EB4\u541B\u7A98\u7FA4\u88D9\u8ECD\u90E1\u5800\u5C48\u6398\u7A9F\u5BAE\u5F13\u7A79\u7AAE\u828E\u8EAC\u5026\u5238\u52F8\u5377\u5708\u62F3\u6372\u6B0A\u6DC3\u7737\u53A5\u7357\u8568\u8E76\u95D5\u673A\u6AC3\u6F70\u8A6D\u8ECC\u994B\uF906\u6677\u6B78\u8CB4"],
      ["d0a1", "\u9B3C\uF907\u53EB\u572D\u594E\u63C6\u69FB\u73EA\u7845\u7ABA\u7AC5\u7CFE\u8475\u898F\u8D73\u9035\u95A8\u52FB\u5747\u7547\u7B60\u83CC\u921E\uF908\u6A58\u514B\u524B\u5287\u621F\u68D8\u6975\u9699\u50C5\u52A4\u52E4\u61C3\u65A4\u6839\u69FF\u747E\u7B4B\u82B9\u83EB\u89B2\u8B39\u8FD1\u9949\uF909\u4ECA\u5997\u64D2\u6611\u6A8E\u7434\u7981\u79BD\u82A9\u887E\u887F\u895F\uF90A\u9326\u4F0B\u53CA\u6025\u6271\u6C72\u7D1A\u7D66\u4E98\u5162\u77DC\u80AF\u4F01\u4F0E\u5176\u5180\u55DC\u5668\u573B\u57FA\u57FC\u5914\u5947\u5993\u5BC4\u5C90\u5D0E\u5DF1\u5E7E\u5FCC\u6280\u65D7\u65E3"],
      ["d1a1", "\u671E\u671F\u675E\u68CB\u68C4\u6A5F\u6B3A\u6C23\u6C7D\u6C82\u6DC7\u7398\u7426\u742A\u7482\u74A3\u7578\u757F\u7881\u78EF\u7941\u7947\u7948\u797A\u7B95\u7D00\u7DBA\u7F88\u8006\u802D\u808C\u8A18\u8B4F\u8C48\u8D77\u9321\u9324\u98E2\u9951\u9A0E\u9A0F\u9A65\u9E92\u7DCA\u4F76\u5409\u62EE\u6854\u91D1\u55AB\u513A\uF90B\uF90C\u5A1C\u61E6\uF90D\u62CF\u62FF\uF90E", 5, "\u90A3\uF914", 4, "\u8AFE\uF919\uF91A\uF91B\uF91C\u6696\uF91D\u7156\uF91E\uF91F\u96E3\uF920\u634F\u637A\u5357\uF921\u678F\u6960\u6E73\uF922\u7537\uF923\uF924\uF925"],
      ["d2a1", "\u7D0D\uF926\uF927\u8872\u56CA\u5A18\uF928", 4, "\u4E43\uF92D\u5167\u5948\u67F0\u8010\uF92E\u5973\u5E74\u649A\u79CA\u5FF5\u606C\u62C8\u637B\u5BE7\u5BD7\u52AA\uF92F\u5974\u5F29\u6012\uF930\uF931\uF932\u7459\uF933", 5, "\u99D1\uF939", 10, "\u6FC3\uF944\uF945\u81BF\u8FB2\u60F1\uF946\uF947\u8166\uF948\uF949\u5C3F\uF94A", 7, "\u5AE9\u8A25\u677B\u7D10\uF952", 5, "\u80FD\uF958\uF959\u5C3C\u6CE5\u533F\u6EBA\u591A\u8336"],
      ["d3a1", "\u4E39\u4EB6\u4F46\u55AE\u5718\u58C7\u5F56\u65B7\u65E6\u6A80\u6BB5\u6E4D\u77ED\u7AEF\u7C1E\u7DDE\u86CB\u8892\u9132\u935B\u64BB\u6FBE\u737A\u75B8\u9054\u5556\u574D\u61BA\u64D4\u66C7\u6DE1\u6E5B\u6F6D\u6FB9\u75F0\u8043\u81BD\u8541\u8983\u8AC7\u8B5A\u931F\u6C93\u7553\u7B54\u8E0F\u905D\u5510\u5802\u5858\u5E62\u6207\u649E\u68E0\u7576\u7CD6\u87B3\u9EE8\u4EE3\u5788\u576E\u5927\u5C0D\u5CB1\u5E36\u5F85\u6234\u64E1\u73B3\u81FA\u888B\u8CB8\u968A\u9EDB\u5B85\u5FB7\u60B3\u5012\u5200\u5230\u5716\u5835\u5857\u5C0E\u5C60\u5CF6\u5D8B\u5EA6\u5F92\u60BC\u6311\u6389\u6417\u6843"],
      ["d4a1", "\u68F9\u6AC2\u6DD8\u6E21\u6ED4\u6FE4\u71FE\u76DC\u7779\u79B1\u7A3B\u8404\u89A9\u8CED\u8DF3\u8E48\u9003\u9014\u9053\u90FD\u934D\u9676\u97DC\u6BD2\u7006\u7258\u72A2\u7368\u7763\u79BF\u7BE4\u7E9B\u8B80\u58A9\u60C7\u6566\u65FD\u66BE\u6C8C\u711E\u71C9\u8C5A\u9813\u4E6D\u7A81\u4EDD\u51AC\u51CD\u52D5\u540C\u61A7\u6771\u6850\u68DF\u6D1E\u6F7C\u75BC\u77B3\u7AE5\u80F4\u8463\u9285\u515C\u6597\u675C\u6793\u75D8\u7AC7\u8373\uF95A\u8C46\u9017\u982D\u5C6F\u81C0\u829A\u9041\u906F\u920D\u5F97\u5D9D\u6A59\u71C8\u767B\u7B49\u85E4\u8B04\u9127\u9A30\u5587\u61F6\uF95B\u7669\u7F85"],
      ["d5a1", "\u863F\u87BA\u88F8\u908F\uF95C\u6D1B\u70D9\u73DE\u7D61\u843D\uF95D\u916A\u99F1\uF95E\u4E82\u5375\u6B04\u6B12\u703E\u721B\u862D\u9E1E\u524C\u8FA3\u5D50\u64E5\u652C\u6B16\u6FEB\u7C43\u7E9C\u85CD\u8964\u89BD\u62C9\u81D8\u881F\u5ECA\u6717\u6D6A\u72FC\u7405\u746F\u8782\u90DE\u4F86\u5D0D\u5FA0\u840A\u51B7\u63A0\u7565\u4EAE\u5006\u5169\u51C9\u6881\u6A11\u7CAE\u7CB1\u7CE7\u826F\u8AD2\u8F1B\u91CF\u4FB6\u5137\u52F5\u5442\u5EEC\u616E\u623E\u65C5\u6ADA\u6FFE\u792A\u85DC\u8823\u95AD\u9A62\u9A6A\u9E97\u9ECE\u529B\u66C6\u6B77\u701D\u792B\u8F62\u9742\u6190\u6200\u6523\u6F23"],
      ["d6a1", "\u7149\u7489\u7DF4\u806F\u84EE\u8F26\u9023\u934A\u51BD\u5217\u52A3\u6D0C\u70C8\u88C2\u5EC9\u6582\u6BAE\u6FC2\u7C3E\u7375\u4EE4\u4F36\u56F9\uF95F\u5CBA\u5DBA\u601C\u73B2\u7B2D\u7F9A\u7FCE\u8046\u901E\u9234\u96F6\u9748\u9818\u9F61\u4F8B\u6FA7\u79AE\u91B4\u96B7\u52DE\uF960\u6488\u64C4\u6AD3\u6F5E\u7018\u7210\u76E7\u8001\u8606\u865C\u8DEF\u8F05\u9732\u9B6F\u9DFA\u9E75\u788C\u797F\u7DA0\u83C9\u9304\u9E7F\u9E93\u8AD6\u58DF\u5F04\u6727\u7027\u74CF\u7C60\u807E\u5121\u7028\u7262\u78CA\u8CC2\u8CDA\u8CF4\u96F7\u4E86\u50DA\u5BEE\u5ED6\u6599\u71CE\u7642\u77AD\u804A\u84FC"],
      ["d7a1", "\u907C\u9B27\u9F8D\u58D8\u5A41\u5C62\u6A13\u6DDA\u6F0F\u763B\u7D2F\u7E37\u851E\u8938\u93E4\u964B\u5289\u65D2\u67F3\u69B4\u6D41\u6E9C\u700F\u7409\u7460\u7559\u7624\u786B\u8B2C\u985E\u516D\u622E\u9678\u4F96\u502B\u5D19\u6DEA\u7DB8\u8F2A\u5F8B\u6144\u6817\uF961\u9686\u52D2\u808B\u51DC\u51CC\u695E\u7A1C\u7DBE\u83F1\u9675\u4FDA\u5229\u5398\u540F\u550E\u5C65\u60A7\u674E\u68A8\u6D6C\u7281\u72F8\u7406\u7483\uF962\u75E2\u7C6C\u7F79\u7FB8\u8389\u88CF\u88E1\u91CC\u91D0\u96E2\u9BC9\u541D\u6F7E\u71D0\u7498\u85FA\u8EAA\u96A3\u9C57\u9E9F\u6797\u6DCB\u7433\u81E8\u9716\u782C"],
      ["d8a1", "\u7ACB\u7B20\u7C92\u6469\u746A\u75F2\u78BC\u78E8\u99AC\u9B54\u9EBB\u5BDE\u5E55\u6F20\u819C\u83AB\u9088\u4E07\u534D\u5A29\u5DD2\u5F4E\u6162\u633D\u6669\u66FC\u6EFF\u6F2B\u7063\u779E\u842C\u8513\u883B\u8F13\u9945\u9C3B\u551C\u62B9\u672B\u6CAB\u8309\u896A\u977A\u4EA1\u5984\u5FD8\u5FD9\u671B\u7DB2\u7F54\u8292\u832B\u83BD\u8F1E\u9099\u57CB\u59B9\u5A92\u5BD0\u6627\u679A\u6885\u6BCF\u7164\u7F75\u8CB7\u8CE3\u9081\u9B45\u8108\u8C8A\u964C\u9A40\u9EA5\u5B5F\u6C13\u731B\u76F2\u76DF\u840C\u51AA\u8993\u514D\u5195\u52C9\u68C9\u6C94\u7704\u7720\u7DBF\u7DEC\u9762\u9EB5\u6EC5"],
      ["d9a1", "\u8511\u51A5\u540D\u547D\u660E\u669D\u6927\u6E9F\u76BF\u7791\u8317\u84C2\u879F\u9169\u9298\u9CF4\u8882\u4FAE\u5192\u52DF\u59C6\u5E3D\u6155\u6478\u6479\u66AE\u67D0\u6A21\u6BCD\u6BDB\u725F\u7261\u7441\u7738\u77DB\u8017\u82BC\u8305\u8B00\u8B28\u8C8C\u6728\u6C90\u7267\u76EE\u7766\u7A46\u9DA9\u6B7F\u6C92\u5922\u6726\u8499\u536F\u5893\u5999\u5EDF\u63CF\u6634\u6773\u6E3A\u732B\u7AD7\u82D7\u9328\u52D9\u5DEB\u61AE\u61CB\u620A\u62C7\u64AB\u65E0\u6959\u6B66\u6BCB\u7121\u73F7\u755D\u7E46\u821E\u8302\u856A\u8AA3\u8CBF\u9727\u9D61\u58A8\u9ED8\u5011\u520E\u543B\u554F\u6587"],
      ["daa1", "\u6C76\u7D0A\u7D0B\u805E\u868A\u9580\u96EF\u52FF\u6C95\u7269\u5473\u5A9A\u5C3E\u5D4B\u5F4C\u5FAE\u672A\u68B6\u6963\u6E3C\u6E44\u7709\u7C73\u7F8E\u8587\u8B0E\u8FF7\u9761\u9EF4\u5CB7\u60B6\u610D\u61AB\u654F\u65FB\u65FC\u6C11\u6CEF\u739F\u73C9\u7DE1\u9594\u5BC6\u871C\u8B10\u525D\u535A\u62CD\u640F\u64B2\u6734\u6A38\u6CCA\u73C0\u749E\u7B94\u7C95\u7E1B\u818A\u8236\u8584\u8FEB\u96F9\u99C1\u4F34\u534A\u53CD\u53DB\u62CC\u642C\u6500\u6591\u69C3\u6CEE\u6F58\u73ED\u7554\u7622\u76E4\u76FC\u78D0\u78FB\u792C\u7D46\u822C\u87E0\u8FD4\u9812\u98EF\u52C3\u62D4\u64A5\u6E24\u6F51"],
      ["dba1", "\u767C\u8DCB\u91B1\u9262\u9AEE\u9B43\u5023\u508D\u574A\u59A8\u5C28\u5E47\u5F77\u623F\u653E\u65B9\u65C1\u6609\u678B\u699C\u6EC2\u78C5\u7D21\u80AA\u8180\u822B\u82B3\u84A1\u868C\u8A2A\u8B17\u90A6\u9632\u9F90\u500D\u4FF3\uF963\u57F9\u5F98\u62DC\u6392\u676F\u6E43\u7119\u76C3\u80CC\u80DA\u88F4\u88F5\u8919\u8CE0\u8F29\u914D\u966A\u4F2F\u4F70\u5E1B\u67CF\u6822\u767D\u767E\u9B44\u5E61\u6A0A\u7169\u71D4\u756A\uF964\u7E41\u8543\u85E9\u98DC\u4F10\u7B4F\u7F70\u95A5\u51E1\u5E06\u68B5\u6C3E\u6C4E\u6CDB\u72AF\u7BC4\u8303\u6CD5\u743A\u50FB\u5288\u58C1\u64D8\u6A97\u74A7\u7656"],
      ["dca1", "\u78A7\u8617\u95E2\u9739\uF965\u535E\u5F01\u8B8A\u8FA8\u8FAF\u908A\u5225\u77A5\u9C49\u9F08\u4E19\u5002\u5175\u5C5B\u5E77\u661E\u663A\u67C4\u68C5\u70B3\u7501\u75C5\u79C9\u7ADD\u8F27\u9920\u9A08\u4FDD\u5821\u5831\u5BF6\u666E\u6B65\u6D11\u6E7A\u6F7D\u73E4\u752B\u83E9\u88DC\u8913\u8B5C\u8F14\u4F0F\u50D5\u5310\u535C\u5B93\u5FA9\u670D\u798F\u8179\u832F\u8514\u8907\u8986\u8F39\u8F3B\u99A5\u9C12\u672C\u4E76\u4FF8\u5949\u5C01\u5CEF\u5CF0\u6367\u68D2\u70FD\u71A2\u742B\u7E2B\u84EC\u8702\u9022\u92D2\u9CF3\u4E0D\u4ED8\u4FEF\u5085\u5256\u526F\u5426\u5490\u57E0\u592B\u5A66"],
      ["dda1", "\u5B5A\u5B75\u5BCC\u5E9C\uF966\u6276\u6577\u65A7\u6D6E\u6EA5\u7236\u7B26\u7C3F\u7F36\u8150\u8151\u819A\u8240\u8299\u83A9\u8A03\u8CA0\u8CE6\u8CFB\u8D74\u8DBA\u90E8\u91DC\u961C\u9644\u99D9\u9CE7\u5317\u5206\u5429\u5674\u58B3\u5954\u596E\u5FFF\u61A4\u626E\u6610\u6C7E\u711A\u76C6\u7C89\u7CDE\u7D1B\u82AC\u8CC1\u96F0\uF967\u4F5B\u5F17\u5F7F\u62C2\u5D29\u670B\u68DA\u787C\u7E43\u9D6C\u4E15\u5099\u5315\u532A\u5351\u5983\u5A62\u5E87\u60B2\u618A\u6249\u6279\u6590\u6787\u69A7\u6BD4\u6BD6\u6BD7\u6BD8\u6CB8\uF968\u7435\u75FA\u7812\u7891\u79D5\u79D8\u7C83\u7DCB\u7FE1\u80A5"],
      ["dea1", "\u813E\u81C2\u83F2\u871A\u88E8\u8AB9\u8B6C\u8CBB\u9119\u975E\u98DB\u9F3B\u56AC\u5B2A\u5F6C\u658C\u6AB3\u6BAF\u6D5C\u6FF1\u7015\u725D\u73AD\u8CA7\u8CD3\u983B\u6191\u6C37\u8058\u9A01\u4E4D\u4E8B\u4E9B\u4ED5\u4F3A\u4F3C\u4F7F\u4FDF\u50FF\u53F2\u53F8\u5506\u55E3\u56DB\u58EB\u5962\u5A11\u5BEB\u5BFA\u5C04\u5DF3\u5E2B\u5F99\u601D\u6368\u659C\u65AF\u67F6\u67FB\u68AD\u6B7B\u6C99\u6CD7\u6E23\u7009\u7345\u7802\u793E\u7940\u7960\u79C1\u7BE9\u7D17\u7D72\u8086\u820D\u838E\u84D1\u86C7\u88DF\u8A50\u8A5E\u8B1D\u8CDC\u8D66\u8FAD\u90AA\u98FC\u99DF\u9E9D\u524A\uF969\u6714\uF96A"],
      ["dfa1", "\u5098\u522A\u5C71\u6563\u6C55\u73CA\u7523\u759D\u7B97\u849C\u9178\u9730\u4E77\u6492\u6BBA\u715E\u85A9\u4E09\uF96B\u6749\u68EE\u6E17\u829F\u8518\u886B\u63F7\u6F81\u9212\u98AF\u4E0A\u50B7\u50CF\u511F\u5546\u55AA\u5617\u5B40\u5C19\u5CE0\u5E38\u5E8A\u5EA0\u5EC2\u60F3\u6851\u6A61\u6E58\u723D\u7240\u72C0\u76F8\u7965\u7BB1\u7FD4\u88F3\u89F4\u8A73\u8C61\u8CDE\u971C\u585E\u74BD\u8CFD\u55C7\uF96C\u7A61\u7D22\u8272\u7272\u751F\u7525\uF96D\u7B19\u5885\u58FB\u5DBC\u5E8F\u5EB6\u5F90\u6055\u6292\u637F\u654D\u6691\u66D9\u66F8\u6816\u68F2\u7280\u745E\u7B6E\u7D6E\u7DD6\u7F72"],
      ["e0a1", "\u80E5\u8212\u85AF\u897F\u8A93\u901D\u92E4\u9ECD\u9F20\u5915\u596D\u5E2D\u60DC\u6614\u6673\u6790\u6C50\u6DC5\u6F5F\u77F3\u78A9\u84C6\u91CB\u932B\u4ED9\u50CA\u5148\u5584\u5B0B\u5BA3\u6247\u657E\u65CB\u6E32\u717D\u7401\u7444\u7487\u74BF\u766C\u79AA\u7DDA\u7E55\u7FA8\u817A\u81B3\u8239\u861A\u87EC\u8A75\u8DE3\u9078\u9291\u9425\u994D\u9BAE\u5368\u5C51\u6954\u6CC4\u6D29\u6E2B\u820C\u859B\u893B\u8A2D\u8AAA\u96EA\u9F67\u5261\u66B9\u6BB2\u7E96\u87FE\u8D0D\u9583\u965D\u651D\u6D89\u71EE\uF96E\u57CE\u59D3\u5BAC\u6027\u60FA\u6210\u661F\u665F\u7329\u73F9\u76DB\u7701\u7B6C"],
      ["e1a1", "\u8056\u8072\u8165\u8AA0\u9192\u4E16\u52E2\u6B72\u6D17\u7A05\u7B39\u7D30\uF96F\u8CB0\u53EC\u562F\u5851\u5BB5\u5C0F\u5C11\u5DE2\u6240\u6383\u6414\u662D\u68B3\u6CBC\u6D88\u6EAF\u701F\u70A4\u71D2\u7526\u758F\u758E\u7619\u7B11\u7BE0\u7C2B\u7D20\u7D39\u852C\u856D\u8607\u8A34\u900D\u9061\u90B5\u92B7\u97F6\u9A37\u4FD7\u5C6C\u675F\u6D91\u7C9F\u7E8C\u8B16\u8D16\u901F\u5B6B\u5DFD\u640D\u84C0\u905C\u98E1\u7387\u5B8B\u609A\u677E\u6DDE\u8A1F\u8AA6\u9001\u980C\u5237\uF970\u7051\u788E\u9396\u8870\u91D7\u4FEE\u53D7\u55FD\u56DA\u5782\u58FD\u5AC2\u5B88\u5CAB\u5CC0\u5E25\u6101"],
      ["e2a1", "\u620D\u624B\u6388\u641C\u6536\u6578\u6A39\u6B8A\u6C34\u6D19\u6F31\u71E7\u72E9\u7378\u7407\u74B2\u7626\u7761\u79C0\u7A57\u7AEA\u7CB9\u7D8F\u7DAC\u7E61\u7F9E\u8129\u8331\u8490\u84DA\u85EA\u8896\u8AB0\u8B90\u8F38\u9042\u9083\u916C\u9296\u92B9\u968B\u96A7\u96A8\u96D6\u9700\u9808\u9996\u9AD3\u9B1A\u53D4\u587E\u5919\u5B70\u5BBF\u6DD1\u6F5A\u719F\u7421\u74B9\u8085\u83FD\u5DE1\u5F87\u5FAA\u6042\u65EC\u6812\u696F\u6A53\u6B89\u6D35\u6DF3\u73E3\u76FE\u77AC\u7B4D\u7D14\u8123\u821C\u8340\u84F4\u8563\u8A62\u8AC4\u9187\u931E\u9806\u99B4\u620C\u8853\u8FF0\u9265\u5D07\u5D27"],
      ["e3a1", "\u5D69\u745F\u819D\u8768\u6FD5\u62FE\u7FD2\u8936\u8972\u4E1E\u4E58\u50E7\u52DD\u5347\u627F\u6607\u7E69\u8805\u965E\u4F8D\u5319\u5636\u59CB\u5AA4\u5C38\u5C4E\u5C4D\u5E02\u5F11\u6043\u65BD\u662F\u6642\u67BE\u67F4\u731C\u77E2\u793A\u7FC5\u8494\u84CD\u8996\u8A66\u8A69\u8AE1\u8C55\u8C7A\u57F4\u5BD4\u5F0F\u606F\u62ED\u690D\u6B96\u6E5C\u7184\u7BD2\u8755\u8B58\u8EFE\u98DF\u98FE\u4F38\u4F81\u4FE1\u547B\u5A20\u5BB8\u613C\u65B0\u6668\u71FC\u7533\u795E\u7D33\u814E\u81E3\u8398\u85AA\u85CE\u8703\u8A0A\u8EAB\u8F9B\uF971\u8FC5\u5931\u5BA4\u5BE6\u6089\u5BE9\u5C0B\u5FC3\u6C81"],
      ["e4a1", "\uF972\u6DF1\u700B\u751A\u82AF\u8AF6\u4EC0\u5341\uF973\u96D9\u6C0F\u4E9E\u4FC4\u5152\u555E\u5A25\u5CE8\u6211\u7259\u82BD\u83AA\u86FE\u8859\u8A1D\u963F\u96C5\u9913\u9D09\u9D5D\u580A\u5CB3\u5DBD\u5E44\u60E1\u6115\u63E1\u6A02\u6E25\u9102\u9354\u984E\u9C10\u9F77\u5B89\u5CB8\u6309\u664F\u6848\u773C\u96C1\u978D\u9854\u9B9F\u65A1\u8B01\u8ECB\u95BC\u5535\u5CA9\u5DD6\u5EB5\u6697\u764C\u83F4\u95C7\u58D3\u62BC\u72CE\u9D28\u4EF0\u592E\u600F\u663B\u6B83\u79E7\u9D26\u5393\u54C0\u57C3\u5D16\u611B\u66D6\u6DAF\u788D\u827E\u9698\u9744\u5384\u627C\u6396\u6DB2\u7E0A\u814B\u984D"],
      ["e5a1", "\u6AFB\u7F4C\u9DAF\u9E1A\u4E5F\u503B\u51B6\u591C\u60F9\u63F6\u6930\u723A\u8036\uF974\u91CE\u5F31\uF975\uF976\u7D04\u82E5\u846F\u84BB\u85E5\u8E8D\uF977\u4F6F\uF978\uF979\u58E4\u5B43\u6059\u63DA\u6518\u656D\u6698\uF97A\u694A\u6A23\u6D0B\u7001\u716C\u75D2\u760D\u79B3\u7A70\uF97B\u7F8A\uF97C\u8944\uF97D\u8B93\u91C0\u967D\uF97E\u990A\u5704\u5FA1\u65BC\u6F01\u7600\u79A6\u8A9E\u99AD\u9B5A\u9F6C\u5104\u61B6\u6291\u6A8D\u81C6\u5043\u5830\u5F66\u7109\u8A00\u8AFA\u5B7C\u8616\u4FFA\u513C\u56B4\u5944\u63A9\u6DF9\u5DAA\u696D\u5186\u4E88\u4F59\uF97F\uF980\uF981\u5982\uF982"],
      ["e6a1", "\uF983\u6B5F\u6C5D\uF984\u74B5\u7916\uF985\u8207\u8245\u8339\u8F3F\u8F5D\uF986\u9918\uF987\uF988\uF989\u4EA6\uF98A\u57DF\u5F79\u6613\uF98B\uF98C\u75AB\u7E79\u8B6F\uF98D\u9006\u9A5B\u56A5\u5827\u59F8\u5A1F\u5BB4\uF98E\u5EF6\uF98F\uF990\u6350\u633B\uF991\u693D\u6C87\u6CBF\u6D8E\u6D93\u6DF5\u6F14\uF992\u70DF\u7136\u7159\uF993\u71C3\u71D5\uF994\u784F\u786F\uF995\u7B75\u7DE3\uF996\u7E2F\uF997\u884D\u8EDF\uF998\uF999\uF99A\u925B\uF99B\u9CF6\uF99C\uF99D\uF99E\u6085\u6D85\uF99F\u71B1\uF9A0\uF9A1\u95B1\u53AD\uF9A2\uF9A3\uF9A4\u67D3\uF9A5\u708E\u7130\u7430\u8276\u82D2"],
      ["e7a1", "\uF9A6\u95BB\u9AE5\u9E7D\u66C4\uF9A7\u71C1\u8449\uF9A8\uF9A9\u584B\uF9AA\uF9AB\u5DB8\u5F71\uF9AC\u6620\u668E\u6979\u69AE\u6C38\u6CF3\u6E36\u6F41\u6FDA\u701B\u702F\u7150\u71DF\u7370\uF9AD\u745B\uF9AE\u74D4\u76C8\u7A4E\u7E93\uF9AF\uF9B0\u82F1\u8A60\u8FCE\uF9B1\u9348\uF9B2\u9719\uF9B3\uF9B4\u4E42\u502A\uF9B5\u5208\u53E1\u66F3\u6C6D\u6FCA\u730A\u777F\u7A62\u82AE\u85DD\u8602\uF9B6\u88D4\u8A63\u8B7D\u8C6B\uF9B7\u92B3\uF9B8\u9713\u9810\u4E94\u4F0D\u4FC9\u50B2\u5348\u543E\u5433\u55DA\u5862\u58BA\u5967\u5A1B\u5BE4\u609F\uF9B9\u61CA\u6556\u65FF\u6664\u68A7\u6C5A\u6FB3"],
      ["e8a1", "\u70CF\u71AC\u7352\u7B7D\u8708\u8AA4\u9C32\u9F07\u5C4B\u6C83\u7344\u7389\u923A\u6EAB\u7465\u761F\u7A69\u7E15\u860A\u5140\u58C5\u64C1\u74EE\u7515\u7670\u7FC1\u9095\u96CD\u9954\u6E26\u74E6\u7AA9\u7AAA\u81E5\u86D9\u8778\u8A1B\u5A49\u5B8C\u5B9B\u68A1\u6900\u6D63\u73A9\u7413\u742C\u7897\u7DE9\u7FEB\u8118\u8155\u839E\u8C4C\u962E\u9811\u66F0\u5F80\u65FA\u6789\u6C6A\u738B\u502D\u5A03\u6B6A\u77EE\u5916\u5D6C\u5DCD\u7325\u754F\uF9BA\uF9BB\u50E5\u51F9\u582F\u592D\u5996\u59DA\u5BE5\uF9BC\uF9BD\u5DA2\u62D7\u6416\u6493\u64FE\uF9BE\u66DC\uF9BF\u6A48\uF9C0\u71FF\u7464\uF9C1"],
      ["e9a1", "\u7A88\u7AAF\u7E47\u7E5E\u8000\u8170\uF9C2\u87EF\u8981\u8B20\u9059\uF9C3\u9080\u9952\u617E\u6B32\u6D74\u7E1F\u8925\u8FB1\u4FD1\u50AD\u5197\u52C7\u57C7\u5889\u5BB9\u5EB8\u6142\u6995\u6D8C\u6E67\u6EB6\u7194\u7462\u7528\u752C\u8073\u8338\u84C9\u8E0A\u9394\u93DE\uF9C4\u4E8E\u4F51\u5076\u512A\u53C8\u53CB\u53F3\u5B87\u5BD3\u5C24\u611A\u6182\u65F4\u725B\u7397\u7440\u76C2\u7950\u7991\u79B9\u7D06\u7FBD\u828B\u85D5\u865E\u8FC2\u9047\u90F5\u91EA\u9685\u96E8\u96E9\u52D6\u5F67\u65ED\u6631\u682F\u715C\u7A36\u90C1\u980A\u4E91\uF9C5\u6A52\u6B9E\u6F90\u7189\u8018\u82B8\u8553"],
      ["eaa1", "\u904B\u9695\u96F2\u97FB\u851A\u9B31\u4E90\u718A\u96C4\u5143\u539F\u54E1\u5713\u5712\u57A3\u5A9B\u5AC4\u5BC3\u6028\u613F\u63F4\u6C85\u6D39\u6E72\u6E90\u7230\u733F\u7457\u82D1\u8881\u8F45\u9060\uF9C6\u9662\u9858\u9D1B\u6708\u8D8A\u925E\u4F4D\u5049\u50DE\u5371\u570D\u59D4\u5A01\u5C09\u6170\u6690\u6E2D\u7232\u744B\u7DEF\u80C3\u840E\u8466\u853F\u875F\u885B\u8918\u8B02\u9055\u97CB\u9B4F\u4E73\u4F91\u5112\u516A\uF9C7\u552F\u55A9\u5B7A\u5BA5\u5E7C\u5E7D\u5EBE\u60A0\u60DF\u6108\u6109\u63C4\u6538\u6709\uF9C8\u67D4\u67DA\uF9C9\u6961\u6962\u6CB9\u6D27\uF9CA\u6E38\uF9CB"],
      ["eba1", "\u6FE1\u7336\u7337\uF9CC\u745C\u7531\uF9CD\u7652\uF9CE\uF9CF\u7DAD\u81FE\u8438\u88D5\u8A98\u8ADB\u8AED\u8E30\u8E42\u904A\u903E\u907A\u9149\u91C9\u936E\uF9D0\uF9D1\u5809\uF9D2\u6BD3\u8089\u80B2\uF9D3\uF9D4\u5141\u596B\u5C39\uF9D5\uF9D6\u6F64\u73A7\u80E4\u8D07\uF9D7\u9217\u958F\uF9D8\uF9D9\uF9DA\uF9DB\u807F\u620E\u701C\u7D68\u878D\uF9DC\u57A0\u6069\u6147\u6BB7\u8ABE\u9280\u96B1\u4E59\u541F\u6DEB\u852D\u9670\u97F3\u98EE\u63D6\u6CE3\u9091\u51DD\u61C9\u81BA\u9DF9\u4F9D\u501A\u5100\u5B9C\u610F\u61FF\u64EC\u6905\u6BC5\u7591\u77E3\u7FA9\u8264\u858F\u87FB\u8863\u8ABC"],
      ["eca1", "\u8B70\u91AB\u4E8C\u4EE5\u4F0A\uF9DD\uF9DE\u5937\u59E8\uF9DF\u5DF2\u5F1B\u5F5B\u6021\uF9E0\uF9E1\uF9E2\uF9E3\u723E\u73E5\uF9E4\u7570\u75CD\uF9E5\u79FB\uF9E6\u800C\u8033\u8084\u82E1\u8351\uF9E7\uF9E8\u8CBD\u8CB3\u9087\uF9E9\uF9EA\u98F4\u990C\uF9EB\uF9EC\u7037\u76CA\u7FCA\u7FCC\u7FFC\u8B1A\u4EBA\u4EC1\u5203\u5370\uF9ED\u54BD\u56E0\u59FB\u5BC5\u5F15\u5FCD\u6E6E\uF9EE\uF9EF\u7D6A\u8335\uF9F0\u8693\u8A8D\uF9F1\u976D\u9777\uF9F2\uF9F3\u4E00\u4F5A\u4F7E\u58F9\u65E5\u6EA2\u9038\u93B0\u99B9\u4EFB\u58EC\u598A\u59D9\u6041\uF9F4\uF9F5\u7A14\uF9F6\u834F\u8CC3\u5165\u5344"],
      ["eda1", "\uF9F7\uF9F8\uF9F9\u4ECD\u5269\u5B55\u82BF\u4ED4\u523A\u54A8\u59C9\u59FF\u5B50\u5B57\u5B5C\u6063\u6148\u6ECB\u7099\u716E\u7386\u74F7\u75B5\u78C1\u7D2B\u8005\u81EA\u8328\u8517\u85C9\u8AEE\u8CC7\u96CC\u4F5C\u52FA\u56BC\u65AB\u6628\u707C\u70B8\u7235\u7DBD\u828D\u914C\u96C0\u9D72\u5B71\u68E7\u6B98\u6F7A\u76DE\u5C91\u66AB\u6F5B\u7BB4\u7C2A\u8836\u96DC\u4E08\u4ED7\u5320\u5834\u58BB\u58EF\u596C\u5C07\u5E33\u5E84\u5F35\u638C\u66B2\u6756\u6A1F\u6AA3\u6B0C\u6F3F\u7246\uF9FA\u7350\u748B\u7AE0\u7CA7\u8178\u81DF\u81E7\u838A\u846C\u8523\u8594\u85CF\u88DD\u8D13\u91AC\u9577"],
      ["eea1", "\u969C\u518D\u54C9\u5728\u5BB0\u624D\u6750\u683D\u6893\u6E3D\u6ED3\u707D\u7E21\u88C1\u8CA1\u8F09\u9F4B\u9F4E\u722D\u7B8F\u8ACD\u931A\u4F47\u4F4E\u5132\u5480\u59D0\u5E95\u62B5\u6775\u696E\u6A17\u6CAE\u6E1A\u72D9\u732A\u75BD\u7BB8\u7D35\u82E7\u83F9\u8457\u85F7\u8A5B\u8CAF\u8E87\u9019\u90B8\u96CE\u9F5F\u52E3\u540A\u5AE1\u5BC2\u6458\u6575\u6EF4\u72C4\uF9FB\u7684\u7A4D\u7B1B\u7C4D\u7E3E\u7FDF\u837B\u8B2B\u8CCA\u8D64\u8DE1\u8E5F\u8FEA\u8FF9\u9069\u93D1\u4F43\u4F7A\u50B3\u5168\u5178\u524D\u526A\u5861\u587C\u5960\u5C08\u5C55\u5EDB\u609B\u6230\u6813\u6BBF\u6C08\u6FB1"],
      ["efa1", "\u714E\u7420\u7530\u7538\u7551\u7672\u7B4C\u7B8B\u7BAD\u7BC6\u7E8F\u8A6E\u8F3E\u8F49\u923F\u9293\u9322\u942B\u96FB\u985A\u986B\u991E\u5207\u622A\u6298\u6D59\u7664\u7ACA\u7BC0\u7D76\u5360\u5CBE\u5E97\u6F38\u70B9\u7C98\u9711\u9B8E\u9EDE\u63A5\u647A\u8776\u4E01\u4E95\u4EAD\u505C\u5075\u5448\u59C3\u5B9A\u5E40\u5EAD\u5EF7\u5F81\u60C5\u633A\u653F\u6574\u65CC\u6676\u6678\u67FE\u6968\u6A89\u6B63\u6C40\u6DC0\u6DE8\u6E1F\u6E5E\u701E\u70A1\u738E\u73FD\u753A\u775B\u7887\u798E\u7A0B\u7A7D\u7CBE\u7D8E\u8247\u8A02\u8AEA\u8C9E\u912D\u914A\u91D8\u9266\u92CC\u9320\u9706\u9756"],
      ["f0a1", "\u975C\u9802\u9F0E\u5236\u5291\u557C\u5824\u5E1D\u5F1F\u608C\u63D0\u68AF\u6FDF\u796D\u7B2C\u81CD\u85BA\u88FD\u8AF8\u8E44\u918D\u9664\u969B\u973D\u984C\u9F4A\u4FCE\u5146\u51CB\u52A9\u5632\u5F14\u5F6B\u63AA\u64CD\u65E9\u6641\u66FA\u66F9\u671D\u689D\u68D7\u69FD\u6F15\u6F6E\u7167\u71E5\u722A\u74AA\u773A\u7956\u795A\u79DF\u7A20\u7A95\u7C97\u7CDF\u7D44\u7E70\u8087\u85FB\u86A4\u8A54\u8ABF\u8D99\u8E81\u9020\u906D\u91E3\u963B\u96D5\u9CE5\u65CF\u7C07\u8DB3\u93C3\u5B58\u5C0A\u5352\u62D9\u731D\u5027\u5B97\u5F9E\u60B0\u616B\u68D5\u6DD9\u742E\u7A2E\u7D42\u7D9C\u7E31\u816B"],
      ["f1a1", "\u8E2A\u8E35\u937E\u9418\u4F50\u5750\u5DE6\u5EA7\u632B\u7F6A\u4E3B\u4F4F\u4F8F\u505A\u59DD\u80C4\u546A\u5468\u55FE\u594F\u5B99\u5DDE\u5EDA\u665D\u6731\u67F1\u682A\u6CE8\u6D32\u6E4A\u6F8D\u70B7\u73E0\u7587\u7C4C\u7D02\u7D2C\u7DA2\u821F\u86DB\u8A3B\u8A85\u8D70\u8E8A\u8F33\u9031\u914E\u9152\u9444\u99D0\u7AF9\u7CA5\u4FCA\u5101\u51C6\u57C8\u5BEF\u5CFB\u6659\u6A3D\u6D5A\u6E96\u6FEC\u710C\u756F\u7AE3\u8822\u9021\u9075\u96CB\u99FF\u8301\u4E2D\u4EF2\u8846\u91CD\u537D\u6ADB\u696B\u6C41\u847A\u589E\u618E\u66FE\u62EF\u70DD\u7511\u75C7\u7E52\u84B8\u8B49\u8D08\u4E4B\u53EA"],
      ["f2a1", "\u54AB\u5730\u5740\u5FD7\u6301\u6307\u646F\u652F\u65E8\u667A\u679D\u67B3\u6B62\u6C60\u6C9A\u6F2C\u77E5\u7825\u7949\u7957\u7D19\u80A2\u8102\u81F3\u829D\u82B7\u8718\u8A8C\uF9FC\u8D04\u8DBE\u9072\u76F4\u7A19\u7A37\u7E54\u8077\u5507\u55D4\u5875\u632F\u6422\u6649\u664B\u686D\u699B\u6B84\u6D25\u6EB1\u73CD\u7468\u74A1\u755B\u75B9\u76E1\u771E\u778B\u79E6\u7E09\u7E1D\u81FB\u852F\u8897\u8A3A\u8CD1\u8EEB\u8FB0\u9032\u93AD\u9663\u9673\u9707\u4F84\u53F1\u59EA\u5AC9\u5E19\u684E\u74C6\u75BE\u79E9\u7A92\u81A3\u86ED\u8CEA\u8DCC\u8FED\u659F\u6715\uF9FD\u57F7\u6F57\u7DDD\u8F2F"],
      ["f3a1", "\u93F6\u96C6\u5FB5\u61F2\u6F84\u4E14\u4F98\u501F\u53C9\u55DF\u5D6F\u5DEE\u6B21\u6B64\u78CB\u7B9A\uF9FE\u8E49\u8ECA\u906E\u6349\u643E\u7740\u7A84\u932F\u947F\u9F6A\u64B0\u6FAF\u71E6\u74A8\u74DA\u7AC4\u7C12\u7E82\u7CB2\u7E98\u8B9A\u8D0A\u947D\u9910\u994C\u5239\u5BDF\u64E6\u672D\u7D2E\u50ED\u53C3\u5879\u6158\u6159\u61FA\u65AC\u7AD9\u8B92\u8B96\u5009\u5021\u5275\u5531\u5A3C\u5EE0\u5F70\u6134\u655E\u660C\u6636\u66A2\u69CD\u6EC4\u6F32\u7316\u7621\u7A93\u8139\u8259\u83D6\u84BC\u50B5\u57F0\u5BC0\u5BE8\u5F69\u63A1\u7826\u7DB5\u83DC\u8521\u91C7\u91F5\u518A\u67F5\u7B56"],
      ["f4a1", "\u8CAC\u51C4\u59BB\u60BD\u8655\u501C\uF9FF\u5254\u5C3A\u617D\u621A\u62D3\u64F2\u65A5\u6ECC\u7620\u810A\u8E60\u965F\u96BB\u4EDF\u5343\u5598\u5929\u5DDD\u64C5\u6CC9\u6DFA\u7394\u7A7F\u821B\u85A6\u8CE4\u8E10\u9077\u91E7\u95E1\u9621\u97C6\u51F8\u54F2\u5586\u5FB9\u64A4\u6F88\u7DB4\u8F1F\u8F4D\u9435\u50C9\u5C16\u6CBE\u6DFB\u751B\u77BB\u7C3D\u7C64\u8A79\u8AC2\u581E\u59BE\u5E16\u6377\u7252\u758A\u776B\u8ADC\u8CBC\u8F12\u5EF3\u6674\u6DF8\u807D\u83C1\u8ACB\u9751\u9BD6\uFA00\u5243\u66FF\u6D95\u6EEF\u7DE0\u8AE6\u902E\u905E\u9AD4\u521D\u527F\u54E8\u6194\u6284\u62DB\u68A2"],
      ["f5a1", "\u6912\u695A\u6A35\u7092\u7126\u785D\u7901\u790E\u79D2\u7A0D\u8096\u8278\u82D5\u8349\u8549\u8C82\u8D85\u9162\u918B\u91AE\u4FC3\u56D1\u71ED\u77D7\u8700\u89F8\u5BF8\u5FD6\u6751\u90A8\u53E2\u585A\u5BF5\u60A4\u6181\u6460\u7E3D\u8070\u8525\u9283\u64AE\u50AC\u5D14\u6700\u589C\u62BD\u63A8\u690E\u6978\u6A1E\u6E6B\u76BA\u79CB\u82BB\u8429\u8ACF\u8DA8\u8FFD\u9112\u914B\u919C\u9310\u9318\u939A\u96DB\u9A36\u9C0D\u4E11\u755C\u795D\u7AFA\u7B51\u7BC9\u7E2E\u84C4\u8E59\u8E74\u8EF8\u9010\u6625\u693F\u7443\u51FA\u672E\u9EDC\u5145\u5FE0\u6C96\u87F2\u885D\u8877\u60B4\u81B5\u8403"],
      ["f6a1", "\u8D05\u53D6\u5439\u5634\u5A36\u5C31\u708A\u7FE0\u805A\u8106\u81ED\u8DA3\u9189\u9A5F\u9DF2\u5074\u4EC4\u53A0\u60FB\u6E2C\u5C64\u4F88\u5024\u55E4\u5CD9\u5E5F\u6065\u6894\u6CBB\u6DC4\u71BE\u75D4\u75F4\u7661\u7A1A\u7A49\u7DC7\u7DFB\u7F6E\u81F4\u86A9\u8F1C\u96C9\u99B3\u9F52\u5247\u52C5\u98ED\u89AA\u4E03\u67D2\u6F06\u4FB5\u5BE2\u6795\u6C88\u6D78\u741B\u7827\u91DD\u937C\u87C4\u79E4\u7A31\u5FEB\u4ED6\u54A4\u553E\u58AE\u59A5\u60F0\u6253\u62D6\u6736\u6955\u8235\u9640\u99B1\u99DD\u502C\u5353\u5544\u577C\uFA01\u6258\uFA02\u64E2\u666B\u67DD\u6FC1\u6FEF\u7422\u7438\u8A17"],
      ["f7a1", "\u9438\u5451\u5606\u5766\u5F48\u619A\u6B4E\u7058\u70AD\u7DBB\u8A95\u596A\u812B\u63A2\u7708\u803D\u8CAA\u5854\u642D\u69BB\u5B95\u5E11\u6E6F\uFA03\u8569\u514C\u53F0\u592A\u6020\u614B\u6B86\u6C70\u6CF0\u7B1E\u80CE\u82D4\u8DC6\u90B0\u98B1\uFA04\u64C7\u6FA4\u6491\u6504\u514E\u5410\u571F\u8A0E\u615F\u6876\uFA05\u75DB\u7B52\u7D71\u901A\u5806\u69CC\u817F\u892A\u9000\u9839\u5078\u5957\u59AC\u6295\u900F\u9B2A\u615D\u7279\u95D6\u5761\u5A46\u5DF4\u628A\u64AD\u64FA\u6777\u6CE2\u6D3E\u722C\u7436\u7834\u7F77\u82AD\u8DDB\u9817\u5224\u5742\u677F\u7248\u74E3\u8CA9\u8FA6\u9211"],
      ["f8a1", "\u962A\u516B\u53ED\u634C\u4F69\u5504\u6096\u6557\u6C9B\u6D7F\u724C\u72FD\u7A17\u8987\u8C9D\u5F6D\u6F8E\u70F9\u81A8\u610E\u4FBF\u504F\u6241\u7247\u7BC7\u7DE8\u7FE9\u904D\u97AD\u9A19\u8CB6\u576A\u5E73\u67B0\u840D\u8A55\u5420\u5B16\u5E63\u5EE2\u5F0A\u6583\u80BA\u853D\u9589\u965B\u4F48\u5305\u530D\u530F\u5486\u54FA\u5703\u5E03\u6016\u629B\u62B1\u6355\uFA06\u6CE1\u6D66\u75B1\u7832\u80DE\u812F\u82DE\u8461\u84B2\u888D\u8912\u900B\u92EA\u98FD\u9B91\u5E45\u66B4\u66DD\u7011\u7206\uFA07\u4FF5\u527D\u5F6A\u6153\u6753\u6A19\u6F02\u74E2\u7968\u8868\u8C79\u98C7\u98C4\u9A43"],
      ["f9a1", "\u54C1\u7A1F\u6953\u8AF7\u8C4A\u98A8\u99AE\u5F7C\u62AB\u75B2\u76AE\u88AB\u907F\u9642\u5339\u5F3C\u5FC5\u6CCC\u73CC\u7562\u758B\u7B46\u82FE\u999D\u4E4F\u903C\u4E0B\u4F55\u53A6\u590F\u5EC8\u6630\u6CB3\u7455\u8377\u8766\u8CC0\u9050\u971E\u9C15\u58D1\u5B78\u8650\u8B14\u9DB4\u5BD2\u6068\u608D\u65F1\u6C57\u6F22\u6FA3\u701A\u7F55\u7FF0\u9591\u9592\u9650\u97D3\u5272\u8F44\u51FD\u542B\u54B8\u5563\u558A\u6ABB\u6DB5\u7DD8\u8266\u929C\u9677\u9E79\u5408\u54C8\u76D2\u86E4\u95A4\u95D4\u965C\u4EA2\u4F09\u59EE\u5AE6\u5DF7\u6052\u6297\u676D\u6841\u6C86\u6E2F\u7F38\u809B\u822A"],
      ["faa1", "\uFA08\uFA09\u9805\u4EA5\u5055\u54B3\u5793\u595A\u5B69\u5BB3\u61C8\u6977\u6D77\u7023\u87F9\u89E3\u8A72\u8AE7\u9082\u99ED\u9AB8\u52BE\u6838\u5016\u5E78\u674F\u8347\u884C\u4EAB\u5411\u56AE\u73E6\u9115\u97FF\u9909\u9957\u9999\u5653\u589F\u865B\u8A31\u61B2\u6AF6\u737B\u8ED2\u6B47\u96AA\u9A57\u5955\u7200\u8D6B\u9769\u4FD4\u5CF4\u5F26\u61F8\u665B\u6CEB\u70AB\u7384\u73B9\u73FE\u7729\u774D\u7D43\u7D62\u7E23\u8237\u8852\uFA0A\u8CE2\u9249\u986F\u5B51\u7A74\u8840\u9801\u5ACC\u4FE0\u5354\u593E\u5CFD\u633E\u6D79\u72F9\u8105\u8107\u83A2\u92CF\u9830\u4EA8\u5144\u5211\u578B"],
      ["fba1", "\u5F62\u6CC2\u6ECE\u7005\u7050\u70AF\u7192\u73E9\u7469\u834A\u87A2\u8861\u9008\u90A2\u93A3\u99A8\u516E\u5F57\u60E0\u6167\u66B3\u8559\u8E4A\u91AF\u978B\u4E4E\u4E92\u547C\u58D5\u58FA\u597D\u5CB5\u5F27\u6236\u6248\u660A\u6667\u6BEB\u6D69\u6DCF\u6E56\u6EF8\u6F94\u6FE0\u6FE9\u705D\u72D0\u7425\u745A\u74E0\u7693\u795C\u7CCA\u7E1E\u80E1\u82A6\u846B\u84BF\u864E\u865F\u8774\u8B77\u8C6A\u93AC\u9800\u9865\u60D1\u6216\u9177\u5A5A\u660F\u6DF7\u6E3E\u743F\u9B42\u5FFD\u60DA\u7B0F\u54C4\u5F18\u6C5E\u6CD3\u6D2A\u70D8\u7D05\u8679\u8A0C\u9D3B\u5316\u548C\u5B05\u6A3A\u706B\u7575"],
      ["fca1", "\u798D\u79BE\u82B1\u83EF\u8A71\u8B41\u8CA8\u9774\uFA0B\u64F4\u652B\u78BA\u78BB\u7A6B\u4E38\u559A\u5950\u5BA6\u5E7B\u60A3\u63DB\u6B61\u6665\u6853\u6E19\u7165\u74B0\u7D08\u9084\u9A69\u9C25\u6D3B\u6ED1\u733E\u8C41\u95CA\u51F0\u5E4C\u5FA8\u604D\u60F6\u6130\u614C\u6643\u6644\u69A5\u6CC1\u6E5F\u6EC9\u6F62\u714C\u749C\u7687\u7BC1\u7C27\u8352\u8757\u9051\u968D\u9EC3\u532F\u56DE\u5EFB\u5F8A\u6062\u6094\u61F7\u6666\u6703\u6A9C\u6DEE\u6FAE\u7070\u736A\u7E6A\u81BE\u8334\u86D4\u8AA8\u8CC4\u5283\u7372\u5B96\u6A6B\u9404\u54EE\u5686\u5B5D\u6548\u6585\u66C9\u689F\u6D8D\u6DC6"],
      ["fda1", "\u723B\u80B4\u9175\u9A4D\u4FAF\u5019\u539A\u540E\u543C\u5589\u55C5\u5E3F\u5F8C\u673D\u7166\u73DD\u9005\u52DB\u52F3\u5864\u58CE\u7104\u718F\u71FB\u85B0\u8A13\u6688\u85A8\u55A7\u6684\u714A\u8431\u5349\u5599\u6BC1\u5F59\u5FBD\u63EE\u6689\u7147\u8AF1\u8F1D\u9EBE\u4F11\u643A\u70CB\u7566\u8667\u6064\u8B4E\u9DF8\u5147\u51F6\u5308\u6D36\u80F8\u9ED1\u6615\u6B23\u7098\u75D5\u5403\u5C79\u7D07\u8A16\u6B20\u6B3D\u6B46\u5438\u6070\u6D3D\u7FD5\u8208\u50D6\u51DE\u559C\u566B\u56CD\u59EC\u5B09\u5E0C\u6199\u6198\u6231\u665E\u66E6\u7199\u71B9\u71BA\u72A7\u79A7\u7A00\u7FB2\u8A70"]
    ];
  }
});

// ../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/tables/cp950.json
var require_cp950 = __commonJS({
  "../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/tables/cp950.json"(exports, module) {
    module.exports = [
      ["0", "\0", 127],
      ["a140", "\u3000\uFF0C\u3001\u3002\uFF0E\u2027\uFF1B\uFF1A\uFF1F\uFF01\uFE30\u2026\u2025\uFE50\uFE51\uFE52\xB7\uFE54\uFE55\uFE56\uFE57\uFF5C\u2013\uFE31\u2014\uFE33\u2574\uFE34\uFE4F\uFF08\uFF09\uFE35\uFE36\uFF5B\uFF5D\uFE37\uFE38\u3014\u3015\uFE39\uFE3A\u3010\u3011\uFE3B\uFE3C\u300A\u300B\uFE3D\uFE3E\u3008\u3009\uFE3F\uFE40\u300C\u300D\uFE41\uFE42\u300E\u300F\uFE43\uFE44\uFE59\uFE5A"],
      ["a1a1", "\uFE5B\uFE5C\uFE5D\uFE5E\u2018\u2019\u201C\u201D\u301D\u301E\u2035\u2032\uFF03\uFF06\uFF0A\u203B\xA7\u3003\u25CB\u25CF\u25B3\u25B2\u25CE\u2606\u2605\u25C7\u25C6\u25A1\u25A0\u25BD\u25BC\u32A3\u2105\xAF\uFFE3\uFF3F\u02CD\uFE49\uFE4A\uFE4D\uFE4E\uFE4B\uFE4C\uFE5F\uFE60\uFE61\uFF0B\uFF0D\xD7\xF7\xB1\u221A\uFF1C\uFF1E\uFF1D\u2266\u2267\u2260\u221E\u2252\u2261\uFE62", 4, "\uFF5E\u2229\u222A\u22A5\u2220\u221F\u22BF\u33D2\u33D1\u222B\u222E\u2235\u2234\u2640\u2642\u2295\u2299\u2191\u2193\u2190\u2192\u2196\u2197\u2199\u2198\u2225\u2223\uFF0F"],
      ["a240", "\uFF3C\u2215\uFE68\uFF04\uFFE5\u3012\uFFE0\uFFE1\uFF05\uFF20\u2103\u2109\uFE69\uFE6A\uFE6B\u33D5\u339C\u339D\u339E\u33CE\u33A1\u338E\u338F\u33C4\xB0\u5159\u515B\u515E\u515D\u5161\u5163\u55E7\u74E9\u7CCE\u2581", 7, "\u258F\u258E\u258D\u258C\u258B\u258A\u2589\u253C\u2534\u252C\u2524\u251C\u2594\u2500\u2502\u2595\u250C\u2510\u2514\u2518\u256D"],
      ["a2a1", "\u256E\u2570\u256F\u2550\u255E\u256A\u2561\u25E2\u25E3\u25E5\u25E4\u2571\u2572\u2573\uFF10", 9, "\u2160", 9, "\u3021", 8, "\u5341\u5344\u5345\uFF21", 25, "\uFF41", 21],
      ["a340", "\uFF57\uFF58\uFF59\uFF5A\u0391", 16, "\u03A3", 6, "\u03B1", 16, "\u03C3", 6, "\u3105", 10],
      ["a3a1", "\u3110", 25, "\u02D9\u02C9\u02CA\u02C7\u02CB"],
      ["a3e1", "\u20AC"],
      ["a440", "\u4E00\u4E59\u4E01\u4E03\u4E43\u4E5D\u4E86\u4E8C\u4EBA\u513F\u5165\u516B\u51E0\u5200\u5201\u529B\u5315\u5341\u535C\u53C8\u4E09\u4E0B\u4E08\u4E0A\u4E2B\u4E38\u51E1\u4E45\u4E48\u4E5F\u4E5E\u4E8E\u4EA1\u5140\u5203\u52FA\u5343\u53C9\u53E3\u571F\u58EB\u5915\u5927\u5973\u5B50\u5B51\u5B53\u5BF8\u5C0F\u5C22\u5C38\u5C71\u5DDD\u5DE5\u5DF1\u5DF2\u5DF3\u5DFE\u5E72\u5EFE\u5F0B\u5F13\u624D"],
      ["a4a1", "\u4E11\u4E10\u4E0D\u4E2D\u4E30\u4E39\u4E4B\u5C39\u4E88\u4E91\u4E95\u4E92\u4E94\u4EA2\u4EC1\u4EC0\u4EC3\u4EC6\u4EC7\u4ECD\u4ECA\u4ECB\u4EC4\u5143\u5141\u5167\u516D\u516E\u516C\u5197\u51F6\u5206\u5207\u5208\u52FB\u52FE\u52FF\u5316\u5339\u5348\u5347\u5345\u535E\u5384\u53CB\u53CA\u53CD\u58EC\u5929\u592B\u592A\u592D\u5B54\u5C11\u5C24\u5C3A\u5C6F\u5DF4\u5E7B\u5EFF\u5F14\u5F15\u5FC3\u6208\u6236\u624B\u624E\u652F\u6587\u6597\u65A4\u65B9\u65E5\u66F0\u6708\u6728\u6B20\u6B62\u6B79\u6BCB\u6BD4\u6BDB\u6C0F\u6C34\u706B\u722A\u7236\u723B\u7247\u7259\u725B\u72AC\u738B\u4E19"],
      ["a540", "\u4E16\u4E15\u4E14\u4E18\u4E3B\u4E4D\u4E4F\u4E4E\u4EE5\u4ED8\u4ED4\u4ED5\u4ED6\u4ED7\u4EE3\u4EE4\u4ED9\u4EDE\u5145\u5144\u5189\u518A\u51AC\u51F9\u51FA\u51F8\u520A\u52A0\u529F\u5305\u5306\u5317\u531D\u4EDF\u534A\u5349\u5361\u5360\u536F\u536E\u53BB\u53EF\u53E4\u53F3\u53EC\u53EE\u53E9\u53E8\u53FC\u53F8\u53F5\u53EB\u53E6\u53EA\u53F2\u53F1\u53F0\u53E5\u53ED\u53FB\u56DB\u56DA\u5916"],
      ["a5a1", "\u592E\u5931\u5974\u5976\u5B55\u5B83\u5C3C\u5DE8\u5DE7\u5DE6\u5E02\u5E03\u5E73\u5E7C\u5F01\u5F18\u5F17\u5FC5\u620A\u6253\u6254\u6252\u6251\u65A5\u65E6\u672E\u672C\u672A\u672B\u672D\u6B63\u6BCD\u6C11\u6C10\u6C38\u6C41\u6C40\u6C3E\u72AF\u7384\u7389\u74DC\u74E6\u7518\u751F\u7528\u7529\u7530\u7531\u7532\u7533\u758B\u767D\u76AE\u76BF\u76EE\u77DB\u77E2\u77F3\u793A\u79BE\u7A74\u7ACB\u4E1E\u4E1F\u4E52\u4E53\u4E69\u4E99\u4EA4\u4EA6\u4EA5\u4EFF\u4F09\u4F19\u4F0A\u4F15\u4F0D\u4F10\u4F11\u4F0F\u4EF2\u4EF6\u4EFB\u4EF0\u4EF3\u4EFD\u4F01\u4F0B\u5149\u5147\u5146\u5148\u5168"],
      ["a640", "\u5171\u518D\u51B0\u5217\u5211\u5212\u520E\u5216\u52A3\u5308\u5321\u5320\u5370\u5371\u5409\u540F\u540C\u540A\u5410\u5401\u540B\u5404\u5411\u540D\u5408\u5403\u540E\u5406\u5412\u56E0\u56DE\u56DD\u5733\u5730\u5728\u572D\u572C\u572F\u5729\u5919\u591A\u5937\u5938\u5984\u5978\u5983\u597D\u5979\u5982\u5981\u5B57\u5B58\u5B87\u5B88\u5B85\u5B89\u5BFA\u5C16\u5C79\u5DDE\u5E06\u5E76\u5E74"],
      ["a6a1", "\u5F0F\u5F1B\u5FD9\u5FD6\u620E\u620C\u620D\u6210\u6263\u625B\u6258\u6536\u65E9\u65E8\u65EC\u65ED\u66F2\u66F3\u6709\u673D\u6734\u6731\u6735\u6B21\u6B64\u6B7B\u6C16\u6C5D\u6C57\u6C59\u6C5F\u6C60\u6C50\u6C55\u6C61\u6C5B\u6C4D\u6C4E\u7070\u725F\u725D\u767E\u7AF9\u7C73\u7CF8\u7F36\u7F8A\u7FBD\u8001\u8003\u800C\u8012\u8033\u807F\u8089\u808B\u808C\u81E3\u81EA\u81F3\u81FC\u820C\u821B\u821F\u826E\u8272\u827E\u866B\u8840\u884C\u8863\u897F\u9621\u4E32\u4EA8\u4F4D\u4F4F\u4F47\u4F57\u4F5E\u4F34\u4F5B\u4F55\u4F30\u4F50\u4F51\u4F3D\u4F3A\u4F38\u4F43\u4F54\u4F3C\u4F46\u4F63"],
      ["a740", "\u4F5C\u4F60\u4F2F\u4F4E\u4F36\u4F59\u4F5D\u4F48\u4F5A\u514C\u514B\u514D\u5175\u51B6\u51B7\u5225\u5224\u5229\u522A\u5228\u52AB\u52A9\u52AA\u52AC\u5323\u5373\u5375\u541D\u542D\u541E\u543E\u5426\u544E\u5427\u5446\u5443\u5433\u5448\u5442\u541B\u5429\u544A\u5439\u543B\u5438\u542E\u5435\u5436\u5420\u543C\u5440\u5431\u542B\u541F\u542C\u56EA\u56F0\u56E4\u56EB\u574A\u5751\u5740\u574D"],
      ["a7a1", "\u5747\u574E\u573E\u5750\u574F\u573B\u58EF\u593E\u599D\u5992\u59A8\u599E\u59A3\u5999\u5996\u598D\u59A4\u5993\u598A\u59A5\u5B5D\u5B5C\u5B5A\u5B5B\u5B8C\u5B8B\u5B8F\u5C2C\u5C40\u5C41\u5C3F\u5C3E\u5C90\u5C91\u5C94\u5C8C\u5DEB\u5E0C\u5E8F\u5E87\u5E8A\u5EF7\u5F04\u5F1F\u5F64\u5F62\u5F77\u5F79\u5FD8\u5FCC\u5FD7\u5FCD\u5FF1\u5FEB\u5FF8\u5FEA\u6212\u6211\u6284\u6297\u6296\u6280\u6276\u6289\u626D\u628A\u627C\u627E\u6279\u6273\u6292\u626F\u6298\u626E\u6295\u6293\u6291\u6286\u6539\u653B\u6538\u65F1\u66F4\u675F\u674E\u674F\u6750\u6751\u675C\u6756\u675E\u6749\u6746\u6760"],
      ["a840", "\u6753\u6757\u6B65\u6BCF\u6C42\u6C5E\u6C99\u6C81\u6C88\u6C89\u6C85\u6C9B\u6C6A\u6C7A\u6C90\u6C70\u6C8C\u6C68\u6C96\u6C92\u6C7D\u6C83\u6C72\u6C7E\u6C74\u6C86\u6C76\u6C8D\u6C94\u6C98\u6C82\u7076\u707C\u707D\u7078\u7262\u7261\u7260\u72C4\u72C2\u7396\u752C\u752B\u7537\u7538\u7682\u76EF\u77E3\u79C1\u79C0\u79BF\u7A76\u7CFB\u7F55\u8096\u8093\u809D\u8098\u809B\u809A\u80B2\u826F\u8292"],
      ["a8a1", "\u828B\u828D\u898B\u89D2\u8A00\u8C37\u8C46\u8C55\u8C9D\u8D64\u8D70\u8DB3\u8EAB\u8ECA\u8F9B\u8FB0\u8FC2\u8FC6\u8FC5\u8FC4\u5DE1\u9091\u90A2\u90AA\u90A6\u90A3\u9149\u91C6\u91CC\u9632\u962E\u9631\u962A\u962C\u4E26\u4E56\u4E73\u4E8B\u4E9B\u4E9E\u4EAB\u4EAC\u4F6F\u4F9D\u4F8D\u4F73\u4F7F\u4F6C\u4F9B\u4F8B\u4F86\u4F83\u4F70\u4F75\u4F88\u4F69\u4F7B\u4F96\u4F7E\u4F8F\u4F91\u4F7A\u5154\u5152\u5155\u5169\u5177\u5176\u5178\u51BD\u51FD\u523B\u5238\u5237\u523A\u5230\u522E\u5236\u5241\u52BE\u52BB\u5352\u5354\u5353\u5351\u5366\u5377\u5378\u5379\u53D6\u53D4\u53D7\u5473\u5475"],
      ["a940", "\u5496\u5478\u5495\u5480\u547B\u5477\u5484\u5492\u5486\u547C\u5490\u5471\u5476\u548C\u549A\u5462\u5468\u548B\u547D\u548E\u56FA\u5783\u5777\u576A\u5769\u5761\u5766\u5764\u577C\u591C\u5949\u5947\u5948\u5944\u5954\u59BE\u59BB\u59D4\u59B9\u59AE\u59D1\u59C6\u59D0\u59CD\u59CB\u59D3\u59CA\u59AF\u59B3\u59D2\u59C5\u5B5F\u5B64\u5B63\u5B97\u5B9A\u5B98\u5B9C\u5B99\u5B9B\u5C1A\u5C48\u5C45"],
      ["a9a1", "\u5C46\u5CB7\u5CA1\u5CB8\u5CA9\u5CAB\u5CB1\u5CB3\u5E18\u5E1A\u5E16\u5E15\u5E1B\u5E11\u5E78\u5E9A\u5E97\u5E9C\u5E95\u5E96\u5EF6\u5F26\u5F27\u5F29\u5F80\u5F81\u5F7F\u5F7C\u5FDD\u5FE0\u5FFD\u5FF5\u5FFF\u600F\u6014\u602F\u6035\u6016\u602A\u6015\u6021\u6027\u6029\u602B\u601B\u6216\u6215\u623F\u623E\u6240\u627F\u62C9\u62CC\u62C4\u62BF\u62C2\u62B9\u62D2\u62DB\u62AB\u62D3\u62D4\u62CB\u62C8\u62A8\u62BD\u62BC\u62D0\u62D9\u62C7\u62CD\u62B5\u62DA\u62B1\u62D8\u62D6\u62D7\u62C6\u62AC\u62CE\u653E\u65A7\u65BC\u65FA\u6614\u6613\u660C\u6606\u6602\u660E\u6600\u660F\u6615\u660A"],
      ["aa40", "\u6607\u670D\u670B\u676D\u678B\u6795\u6771\u679C\u6773\u6777\u6787\u679D\u6797\u676F\u6770\u677F\u6789\u677E\u6790\u6775\u679A\u6793\u677C\u676A\u6772\u6B23\u6B66\u6B67\u6B7F\u6C13\u6C1B\u6CE3\u6CE8\u6CF3\u6CB1\u6CCC\u6CE5\u6CB3\u6CBD\u6CBE\u6CBC\u6CE2\u6CAB\u6CD5\u6CD3\u6CB8\u6CC4\u6CB9\u6CC1\u6CAE\u6CD7\u6CC5\u6CF1\u6CBF\u6CBB\u6CE1\u6CDB\u6CCA\u6CAC\u6CEF\u6CDC\u6CD6\u6CE0"],
      ["aaa1", "\u7095\u708E\u7092\u708A\u7099\u722C\u722D\u7238\u7248\u7267\u7269\u72C0\u72CE\u72D9\u72D7\u72D0\u73A9\u73A8\u739F\u73AB\u73A5\u753D\u759D\u7599\u759A\u7684\u76C2\u76F2\u76F4\u77E5\u77FD\u793E\u7940\u7941\u79C9\u79C8\u7A7A\u7A79\u7AFA\u7CFE\u7F54\u7F8C\u7F8B\u8005\u80BA\u80A5\u80A2\u80B1\u80A1\u80AB\u80A9\u80B4\u80AA\u80AF\u81E5\u81FE\u820D\u82B3\u829D\u8299\u82AD\u82BD\u829F\u82B9\u82B1\u82AC\u82A5\u82AF\u82B8\u82A3\u82B0\u82BE\u82B7\u864E\u8671\u521D\u8868\u8ECB\u8FCE\u8FD4\u8FD1\u90B5\u90B8\u90B1\u90B6\u91C7\u91D1\u9577\u9580\u961C\u9640\u963F\u963B\u9644"],
      ["ab40", "\u9642\u96B9\u96E8\u9752\u975E\u4E9F\u4EAD\u4EAE\u4FE1\u4FB5\u4FAF\u4FBF\u4FE0\u4FD1\u4FCF\u4FDD\u4FC3\u4FB6\u4FD8\u4FDF\u4FCA\u4FD7\u4FAE\u4FD0\u4FC4\u4FC2\u4FDA\u4FCE\u4FDE\u4FB7\u5157\u5192\u5191\u51A0\u524E\u5243\u524A\u524D\u524C\u524B\u5247\u52C7\u52C9\u52C3\u52C1\u530D\u5357\u537B\u539A\u53DB\u54AC\u54C0\u54A8\u54CE\u54C9\u54B8\u54A6\u54B3\u54C7\u54C2\u54BD\u54AA\u54C1"],
      ["aba1", "\u54C4\u54C8\u54AF\u54AB\u54B1\u54BB\u54A9\u54A7\u54BF\u56FF\u5782\u578B\u57A0\u57A3\u57A2\u57CE\u57AE\u5793\u5955\u5951\u594F\u594E\u5950\u59DC\u59D8\u59FF\u59E3\u59E8\u5A03\u59E5\u59EA\u59DA\u59E6\u5A01\u59FB\u5B69\u5BA3\u5BA6\u5BA4\u5BA2\u5BA5\u5C01\u5C4E\u5C4F\u5C4D\u5C4B\u5CD9\u5CD2\u5DF7\u5E1D\u5E25\u5E1F\u5E7D\u5EA0\u5EA6\u5EFA\u5F08\u5F2D\u5F65\u5F88\u5F85\u5F8A\u5F8B\u5F87\u5F8C\u5F89\u6012\u601D\u6020\u6025\u600E\u6028\u604D\u6070\u6068\u6062\u6046\u6043\u606C\u606B\u606A\u6064\u6241\u62DC\u6316\u6309\u62FC\u62ED\u6301\u62EE\u62FD\u6307\u62F1\u62F7"],
      ["ac40", "\u62EF\u62EC\u62FE\u62F4\u6311\u6302\u653F\u6545\u65AB\u65BD\u65E2\u6625\u662D\u6620\u6627\u662F\u661F\u6628\u6631\u6624\u66F7\u67FF\u67D3\u67F1\u67D4\u67D0\u67EC\u67B6\u67AF\u67F5\u67E9\u67EF\u67C4\u67D1\u67B4\u67DA\u67E5\u67B8\u67CF\u67DE\u67F3\u67B0\u67D9\u67E2\u67DD\u67D2\u6B6A\u6B83\u6B86\u6BB5\u6BD2\u6BD7\u6C1F\u6CC9\u6D0B\u6D32\u6D2A\u6D41\u6D25\u6D0C\u6D31\u6D1E\u6D17"],
      ["aca1", "\u6D3B\u6D3D\u6D3E\u6D36\u6D1B\u6CF5\u6D39\u6D27\u6D38\u6D29\u6D2E\u6D35\u6D0E\u6D2B\u70AB\u70BA\u70B3\u70AC\u70AF\u70AD\u70B8\u70AE\u70A4\u7230\u7272\u726F\u7274\u72E9\u72E0\u72E1\u73B7\u73CA\u73BB\u73B2\u73CD\u73C0\u73B3\u751A\u752D\u754F\u754C\u754E\u754B\u75AB\u75A4\u75A5\u75A2\u75A3\u7678\u7686\u7687\u7688\u76C8\u76C6\u76C3\u76C5\u7701\u76F9\u76F8\u7709\u770B\u76FE\u76FC\u7707\u77DC\u7802\u7814\u780C\u780D\u7946\u7949\u7948\u7947\u79B9\u79BA\u79D1\u79D2\u79CB\u7A7F\u7A81\u7AFF\u7AFD\u7C7D\u7D02\u7D05\u7D00\u7D09\u7D07\u7D04\u7D06\u7F38\u7F8E\u7FBF\u8004"],
      ["ad40", "\u8010\u800D\u8011\u8036\u80D6\u80E5\u80DA\u80C3\u80C4\u80CC\u80E1\u80DB\u80CE\u80DE\u80E4\u80DD\u81F4\u8222\u82E7\u8303\u8305\u82E3\u82DB\u82E6\u8304\u82E5\u8302\u8309\u82D2\u82D7\u82F1\u8301\u82DC\u82D4\u82D1\u82DE\u82D3\u82DF\u82EF\u8306\u8650\u8679\u867B\u867A\u884D\u886B\u8981\u89D4\u8A08\u8A02\u8A03\u8C9E\u8CA0\u8D74\u8D73\u8DB4\u8ECD\u8ECC\u8FF0\u8FE6\u8FE2\u8FEA\u8FE5"],
      ["ada1", "\u8FED\u8FEB\u8FE4\u8FE8\u90CA\u90CE\u90C1\u90C3\u914B\u914A\u91CD\u9582\u9650\u964B\u964C\u964D\u9762\u9769\u97CB\u97ED\u97F3\u9801\u98A8\u98DB\u98DF\u9996\u9999\u4E58\u4EB3\u500C\u500D\u5023\u4FEF\u5026\u5025\u4FF8\u5029\u5016\u5006\u503C\u501F\u501A\u5012\u5011\u4FFA\u5000\u5014\u5028\u4FF1\u5021\u500B\u5019\u5018\u4FF3\u4FEE\u502D\u502A\u4FFE\u502B\u5009\u517C\u51A4\u51A5\u51A2\u51CD\u51CC\u51C6\u51CB\u5256\u525C\u5254\u525B\u525D\u532A\u537F\u539F\u539D\u53DF\u54E8\u5510\u5501\u5537\u54FC\u54E5\u54F2\u5506\u54FA\u5514\u54E9\u54ED\u54E1\u5509\u54EE\u54EA"],
      ["ae40", "\u54E6\u5527\u5507\u54FD\u550F\u5703\u5704\u57C2\u57D4\u57CB\u57C3\u5809\u590F\u5957\u5958\u595A\u5A11\u5A18\u5A1C\u5A1F\u5A1B\u5A13\u59EC\u5A20\u5A23\u5A29\u5A25\u5A0C\u5A09\u5B6B\u5C58\u5BB0\u5BB3\u5BB6\u5BB4\u5BAE\u5BB5\u5BB9\u5BB8\u5C04\u5C51\u5C55\u5C50\u5CED\u5CFD\u5CFB\u5CEA\u5CE8\u5CF0\u5CF6\u5D01\u5CF4\u5DEE\u5E2D\u5E2B\u5EAB\u5EAD\u5EA7\u5F31\u5F92\u5F91\u5F90\u6059"],
      ["aea1", "\u6063\u6065\u6050\u6055\u606D\u6069\u606F\u6084\u609F\u609A\u608D\u6094\u608C\u6085\u6096\u6247\u62F3\u6308\u62FF\u634E\u633E\u632F\u6355\u6342\u6346\u634F\u6349\u633A\u6350\u633D\u632A\u632B\u6328\u634D\u634C\u6548\u6549\u6599\u65C1\u65C5\u6642\u6649\u664F\u6643\u6652\u664C\u6645\u6641\u66F8\u6714\u6715\u6717\u6821\u6838\u6848\u6846\u6853\u6839\u6842\u6854\u6829\u68B3\u6817\u684C\u6851\u683D\u67F4\u6850\u6840\u683C\u6843\u682A\u6845\u6813\u6818\u6841\u6B8A\u6B89\u6BB7\u6C23\u6C27\u6C28\u6C26\u6C24\u6CF0\u6D6A\u6D95\u6D88\u6D87\u6D66\u6D78\u6D77\u6D59\u6D93"],
      ["af40", "\u6D6C\u6D89\u6D6E\u6D5A\u6D74\u6D69\u6D8C\u6D8A\u6D79\u6D85\u6D65\u6D94\u70CA\u70D8\u70E4\u70D9\u70C8\u70CF\u7239\u7279\u72FC\u72F9\u72FD\u72F8\u72F7\u7386\u73ED\u7409\u73EE\u73E0\u73EA\u73DE\u7554\u755D\u755C\u755A\u7559\u75BE\u75C5\u75C7\u75B2\u75B3\u75BD\u75BC\u75B9\u75C2\u75B8\u768B\u76B0\u76CA\u76CD\u76CE\u7729\u771F\u7720\u7728\u77E9\u7830\u7827\u7838\u781D\u7834\u7837"],
      ["afa1", "\u7825\u782D\u7820\u781F\u7832\u7955\u7950\u7960\u795F\u7956\u795E\u795D\u7957\u795A\u79E4\u79E3\u79E7\u79DF\u79E6\u79E9\u79D8\u7A84\u7A88\u7AD9\u7B06\u7B11\u7C89\u7D21\u7D17\u7D0B\u7D0A\u7D20\u7D22\u7D14\u7D10\u7D15\u7D1A\u7D1C\u7D0D\u7D19\u7D1B\u7F3A\u7F5F\u7F94\u7FC5\u7FC1\u8006\u8018\u8015\u8019\u8017\u803D\u803F\u80F1\u8102\u80F0\u8105\u80ED\u80F4\u8106\u80F8\u80F3\u8108\u80FD\u810A\u80FC\u80EF\u81ED\u81EC\u8200\u8210\u822A\u822B\u8228\u822C\u82BB\u832B\u8352\u8354\u834A\u8338\u8350\u8349\u8335\u8334\u834F\u8332\u8339\u8336\u8317\u8340\u8331\u8328\u8343"],
      ["b040", "\u8654\u868A\u86AA\u8693\u86A4\u86A9\u868C\u86A3\u869C\u8870\u8877\u8881\u8882\u887D\u8879\u8A18\u8A10\u8A0E\u8A0C\u8A15\u8A0A\u8A17\u8A13\u8A16\u8A0F\u8A11\u8C48\u8C7A\u8C79\u8CA1\u8CA2\u8D77\u8EAC\u8ED2\u8ED4\u8ECF\u8FB1\u9001\u9006\u8FF7\u9000\u8FFA\u8FF4\u9003\u8FFD\u9005\u8FF8\u9095\u90E1\u90DD\u90E2\u9152\u914D\u914C\u91D8\u91DD\u91D7\u91DC\u91D9\u9583\u9662\u9663\u9661"],
      ["b0a1", "\u965B\u965D\u9664\u9658\u965E\u96BB\u98E2\u99AC\u9AA8\u9AD8\u9B25\u9B32\u9B3C\u4E7E\u507A\u507D\u505C\u5047\u5043\u504C\u505A\u5049\u5065\u5076\u504E\u5055\u5075\u5074\u5077\u504F\u500F\u506F\u506D\u515C\u5195\u51F0\u526A\u526F\u52D2\u52D9\u52D8\u52D5\u5310\u530F\u5319\u533F\u5340\u533E\u53C3\u66FC\u5546\u556A\u5566\u5544\u555E\u5561\u5543\u554A\u5531\u5556\u554F\u5555\u552F\u5564\u5538\u552E\u555C\u552C\u5563\u5533\u5541\u5557\u5708\u570B\u5709\u57DF\u5805\u580A\u5806\u57E0\u57E4\u57FA\u5802\u5835\u57F7\u57F9\u5920\u5962\u5A36\u5A41\u5A49\u5A66\u5A6A\u5A40"],
      ["b140", "\u5A3C\u5A62\u5A5A\u5A46\u5A4A\u5B70\u5BC7\u5BC5\u5BC4\u5BC2\u5BBF\u5BC6\u5C09\u5C08\u5C07\u5C60\u5C5C\u5C5D\u5D07\u5D06\u5D0E\u5D1B\u5D16\u5D22\u5D11\u5D29\u5D14\u5D19\u5D24\u5D27\u5D17\u5DE2\u5E38\u5E36\u5E33\u5E37\u5EB7\u5EB8\u5EB6\u5EB5\u5EBE\u5F35\u5F37\u5F57\u5F6C\u5F69\u5F6B\u5F97\u5F99\u5F9E\u5F98\u5FA1\u5FA0\u5F9C\u607F\u60A3\u6089\u60A0\u60A8\u60CB\u60B4\u60E6\u60BD"],
      ["b1a1", "\u60C5\u60BB\u60B5\u60DC\u60BC\u60D8\u60D5\u60C6\u60DF\u60B8\u60DA\u60C7\u621A\u621B\u6248\u63A0\u63A7\u6372\u6396\u63A2\u63A5\u6377\u6367\u6398\u63AA\u6371\u63A9\u6389\u6383\u639B\u636B\u63A8\u6384\u6388\u6399\u63A1\u63AC\u6392\u638F\u6380\u637B\u6369\u6368\u637A\u655D\u6556\u6551\u6559\u6557\u555F\u654F\u6558\u6555\u6554\u659C\u659B\u65AC\u65CF\u65CB\u65CC\u65CE\u665D\u665A\u6664\u6668\u6666\u665E\u66F9\u52D7\u671B\u6881\u68AF\u68A2\u6893\u68B5\u687F\u6876\u68B1\u68A7\u6897\u68B0\u6883\u68C4\u68AD\u6886\u6885\u6894\u689D\u68A8\u689F\u68A1\u6882\u6B32\u6BBA"],
      ["b240", "\u6BEB\u6BEC\u6C2B\u6D8E\u6DBC\u6DF3\u6DD9\u6DB2\u6DE1\u6DCC\u6DE4\u6DFB\u6DFA\u6E05\u6DC7\u6DCB\u6DAF\u6DD1\u6DAE\u6DDE\u6DF9\u6DB8\u6DF7\u6DF5\u6DC5\u6DD2\u6E1A\u6DB5\u6DDA\u6DEB\u6DD8\u6DEA\u6DF1\u6DEE\u6DE8\u6DC6\u6DC4\u6DAA\u6DEC\u6DBF\u6DE6\u70F9\u7109\u710A\u70FD\u70EF\u723D\u727D\u7281\u731C\u731B\u7316\u7313\u7319\u7387\u7405\u740A\u7403\u7406\u73FE\u740D\u74E0\u74F6"],
      ["b2a1", "\u74F7\u751C\u7522\u7565\u7566\u7562\u7570\u758F\u75D4\u75D5\u75B5\u75CA\u75CD\u768E\u76D4\u76D2\u76DB\u7737\u773E\u773C\u7736\u7738\u773A\u786B\u7843\u784E\u7965\u7968\u796D\u79FB\u7A92\u7A95\u7B20\u7B28\u7B1B\u7B2C\u7B26\u7B19\u7B1E\u7B2E\u7C92\u7C97\u7C95\u7D46\u7D43\u7D71\u7D2E\u7D39\u7D3C\u7D40\u7D30\u7D33\u7D44\u7D2F\u7D42\u7D32\u7D31\u7F3D\u7F9E\u7F9A\u7FCC\u7FCE\u7FD2\u801C\u804A\u8046\u812F\u8116\u8123\u812B\u8129\u8130\u8124\u8202\u8235\u8237\u8236\u8239\u838E\u839E\u8398\u8378\u83A2\u8396\u83BD\u83AB\u8392\u838A\u8393\u8389\u83A0\u8377\u837B\u837C"],
      ["b340", "\u8386\u83A7\u8655\u5F6A\u86C7\u86C0\u86B6\u86C4\u86B5\u86C6\u86CB\u86B1\u86AF\u86C9\u8853\u889E\u8888\u88AB\u8892\u8896\u888D\u888B\u8993\u898F\u8A2A\u8A1D\u8A23\u8A25\u8A31\u8A2D\u8A1F\u8A1B\u8A22\u8C49\u8C5A\u8CA9\u8CAC\u8CAB\u8CA8\u8CAA\u8CA7\u8D67\u8D66\u8DBE\u8DBA\u8EDB\u8EDF\u9019\u900D\u901A\u9017\u9023\u901F\u901D\u9010\u9015\u901E\u9020\u900F\u9022\u9016\u901B\u9014"],
      ["b3a1", "\u90E8\u90ED\u90FD\u9157\u91CE\u91F5\u91E6\u91E3\u91E7\u91ED\u91E9\u9589\u966A\u9675\u9673\u9678\u9670\u9674\u9676\u9677\u966C\u96C0\u96EA\u96E9\u7AE0\u7ADF\u9802\u9803\u9B5A\u9CE5\u9E75\u9E7F\u9EA5\u9EBB\u50A2\u508D\u5085\u5099\u5091\u5080\u5096\u5098\u509A\u6700\u51F1\u5272\u5274\u5275\u5269\u52DE\u52DD\u52DB\u535A\u53A5\u557B\u5580\u55A7\u557C\u558A\u559D\u5598\u5582\u559C\u55AA\u5594\u5587\u558B\u5583\u55B3\u55AE\u559F\u553E\u55B2\u559A\u55BB\u55AC\u55B1\u557E\u5589\u55AB\u5599\u570D\u582F\u582A\u5834\u5824\u5830\u5831\u5821\u581D\u5820\u58F9\u58FA\u5960"],
      ["b440", "\u5A77\u5A9A\u5A7F\u5A92\u5A9B\u5AA7\u5B73\u5B71\u5BD2\u5BCC\u5BD3\u5BD0\u5C0A\u5C0B\u5C31\u5D4C\u5D50\u5D34\u5D47\u5DFD\u5E45\u5E3D\u5E40\u5E43\u5E7E\u5ECA\u5EC1\u5EC2\u5EC4\u5F3C\u5F6D\u5FA9\u5FAA\u5FA8\u60D1\u60E1\u60B2\u60B6\u60E0\u611C\u6123\u60FA\u6115\u60F0\u60FB\u60F4\u6168\u60F1\u610E\u60F6\u6109\u6100\u6112\u621F\u6249\u63A3\u638C\u63CF\u63C0\u63E9\u63C9\u63C6\u63CD"],
      ["b4a1", "\u63D2\u63E3\u63D0\u63E1\u63D6\u63ED\u63EE\u6376\u63F4\u63EA\u63DB\u6452\u63DA\u63F9\u655E\u6566\u6562\u6563\u6591\u6590\u65AF\u666E\u6670\u6674\u6676\u666F\u6691\u667A\u667E\u6677\u66FE\u66FF\u671F\u671D\u68FA\u68D5\u68E0\u68D8\u68D7\u6905\u68DF\u68F5\u68EE\u68E7\u68F9\u68D2\u68F2\u68E3\u68CB\u68CD\u690D\u6912\u690E\u68C9\u68DA\u696E\u68FB\u6B3E\u6B3A\u6B3D\u6B98\u6B96\u6BBC\u6BEF\u6C2E\u6C2F\u6C2C\u6E2F\u6E38\u6E54\u6E21\u6E32\u6E67\u6E4A\u6E20\u6E25\u6E23\u6E1B\u6E5B\u6E58\u6E24\u6E56\u6E6E\u6E2D\u6E26\u6E6F\u6E34\u6E4D\u6E3A\u6E2C\u6E43\u6E1D\u6E3E\u6ECB"],
      ["b540", "\u6E89\u6E19\u6E4E\u6E63\u6E44\u6E72\u6E69\u6E5F\u7119\u711A\u7126\u7130\u7121\u7136\u716E\u711C\u724C\u7284\u7280\u7336\u7325\u7334\u7329\u743A\u742A\u7433\u7422\u7425\u7435\u7436\u7434\u742F\u741B\u7426\u7428\u7525\u7526\u756B\u756A\u75E2\u75DB\u75E3\u75D9\u75D8\u75DE\u75E0\u767B\u767C\u7696\u7693\u76B4\u76DC\u774F\u77ED\u785D\u786C\u786F\u7A0D\u7A08\u7A0B\u7A05\u7A00\u7A98"],
      ["b5a1", "\u7A97\u7A96\u7AE5\u7AE3\u7B49\u7B56\u7B46\u7B50\u7B52\u7B54\u7B4D\u7B4B\u7B4F\u7B51\u7C9F\u7CA5\u7D5E\u7D50\u7D68\u7D55\u7D2B\u7D6E\u7D72\u7D61\u7D66\u7D62\u7D70\u7D73\u5584\u7FD4\u7FD5\u800B\u8052\u8085\u8155\u8154\u814B\u8151\u814E\u8139\u8146\u813E\u814C\u8153\u8174\u8212\u821C\u83E9\u8403\u83F8\u840D\u83E0\u83C5\u840B\u83C1\u83EF\u83F1\u83F4\u8457\u840A\u83F0\u840C\u83CC\u83FD\u83F2\u83CA\u8438\u840E\u8404\u83DC\u8407\u83D4\u83DF\u865B\u86DF\u86D9\u86ED\u86D4\u86DB\u86E4\u86D0\u86DE\u8857\u88C1\u88C2\u88B1\u8983\u8996\u8A3B\u8A60\u8A55\u8A5E\u8A3C\u8A41"],
      ["b640", "\u8A54\u8A5B\u8A50\u8A46\u8A34\u8A3A\u8A36\u8A56\u8C61\u8C82\u8CAF\u8CBC\u8CB3\u8CBD\u8CC1\u8CBB\u8CC0\u8CB4\u8CB7\u8CB6\u8CBF\u8CB8\u8D8A\u8D85\u8D81\u8DCE\u8DDD\u8DCB\u8DDA\u8DD1\u8DCC\u8DDB\u8DC6\u8EFB\u8EF8\u8EFC\u8F9C\u902E\u9035\u9031\u9038\u9032\u9036\u9102\u90F5\u9109\u90FE\u9163\u9165\u91CF\u9214\u9215\u9223\u9209\u921E\u920D\u9210\u9207\u9211\u9594\u958F\u958B\u9591"],
      ["b6a1", "\u9593\u9592\u958E\u968A\u968E\u968B\u967D\u9685\u9686\u968D\u9672\u9684\u96C1\u96C5\u96C4\u96C6\u96C7\u96EF\u96F2\u97CC\u9805\u9806\u9808\u98E7\u98EA\u98EF\u98E9\u98F2\u98ED\u99AE\u99AD\u9EC3\u9ECD\u9ED1\u4E82\u50AD\u50B5\u50B2\u50B3\u50C5\u50BE\u50AC\u50B7\u50BB\u50AF\u50C7\u527F\u5277\u527D\u52DF\u52E6\u52E4\u52E2\u52E3\u532F\u55DF\u55E8\u55D3\u55E6\u55CE\u55DC\u55C7\u55D1\u55E3\u55E4\u55EF\u55DA\u55E1\u55C5\u55C6\u55E5\u55C9\u5712\u5713\u585E\u5851\u5858\u5857\u585A\u5854\u586B\u584C\u586D\u584A\u5862\u5852\u584B\u5967\u5AC1\u5AC9\u5ACC\u5ABE\u5ABD\u5ABC"],
      ["b740", "\u5AB3\u5AC2\u5AB2\u5D69\u5D6F\u5E4C\u5E79\u5EC9\u5EC8\u5F12\u5F59\u5FAC\u5FAE\u611A\u610F\u6148\u611F\u60F3\u611B\u60F9\u6101\u6108\u614E\u614C\u6144\u614D\u613E\u6134\u6127\u610D\u6106\u6137\u6221\u6222\u6413\u643E\u641E\u642A\u642D\u643D\u642C\u640F\u641C\u6414\u640D\u6436\u6416\u6417\u6406\u656C\u659F\u65B0\u6697\u6689\u6687\u6688\u6696\u6684\u6698\u668D\u6703\u6994\u696D"],
      ["b7a1", "\u695A\u6977\u6960\u6954\u6975\u6930\u6982\u694A\u6968\u696B\u695E\u6953\u6979\u6986\u695D\u6963\u695B\u6B47\u6B72\u6BC0\u6BBF\u6BD3\u6BFD\u6EA2\u6EAF\u6ED3\u6EB6\u6EC2\u6E90\u6E9D\u6EC7\u6EC5\u6EA5\u6E98\u6EBC\u6EBA\u6EAB\u6ED1\u6E96\u6E9C\u6EC4\u6ED4\u6EAA\u6EA7\u6EB4\u714E\u7159\u7169\u7164\u7149\u7167\u715C\u716C\u7166\u714C\u7165\u715E\u7146\u7168\u7156\u723A\u7252\u7337\u7345\u733F\u733E\u746F\u745A\u7455\u745F\u745E\u7441\u743F\u7459\u745B\u745C\u7576\u7578\u7600\u75F0\u7601\u75F2\u75F1\u75FA\u75FF\u75F4\u75F3\u76DE\u76DF\u775B\u776B\u7766\u775E\u7763"],
      ["b840", "\u7779\u776A\u776C\u775C\u7765\u7768\u7762\u77EE\u788E\u78B0\u7897\u7898\u788C\u7889\u787C\u7891\u7893\u787F\u797A\u797F\u7981\u842C\u79BD\u7A1C\u7A1A\u7A20\u7A14\u7A1F\u7A1E\u7A9F\u7AA0\u7B77\u7BC0\u7B60\u7B6E\u7B67\u7CB1\u7CB3\u7CB5\u7D93\u7D79\u7D91\u7D81\u7D8F\u7D5B\u7F6E\u7F69\u7F6A\u7F72\u7FA9\u7FA8\u7FA4\u8056\u8058\u8086\u8084\u8171\u8170\u8178\u8165\u816E\u8173\u816B"],
      ["b8a1", "\u8179\u817A\u8166\u8205\u8247\u8482\u8477\u843D\u8431\u8475\u8466\u846B\u8449\u846C\u845B\u843C\u8435\u8461\u8463\u8469\u846D\u8446\u865E\u865C\u865F\u86F9\u8713\u8708\u8707\u8700\u86FE\u86FB\u8702\u8703\u8706\u870A\u8859\u88DF\u88D4\u88D9\u88DC\u88D8\u88DD\u88E1\u88CA\u88D5\u88D2\u899C\u89E3\u8A6B\u8A72\u8A73\u8A66\u8A69\u8A70\u8A87\u8A7C\u8A63\u8AA0\u8A71\u8A85\u8A6D\u8A62\u8A6E\u8A6C\u8A79\u8A7B\u8A3E\u8A68\u8C62\u8C8A\u8C89\u8CCA\u8CC7\u8CC8\u8CC4\u8CB2\u8CC3\u8CC2\u8CC5\u8DE1\u8DDF\u8DE8\u8DEF\u8DF3\u8DFA\u8DEA\u8DE4\u8DE6\u8EB2\u8F03\u8F09\u8EFE\u8F0A"],
      ["b940", "\u8F9F\u8FB2\u904B\u904A\u9053\u9042\u9054\u903C\u9055\u9050\u9047\u904F\u904E\u904D\u9051\u903E\u9041\u9112\u9117\u916C\u916A\u9169\u91C9\u9237\u9257\u9238\u923D\u9240\u923E\u925B\u924B\u9264\u9251\u9234\u9249\u924D\u9245\u9239\u923F\u925A\u9598\u9698\u9694\u9695\u96CD\u96CB\u96C9\u96CA\u96F7\u96FB\u96F9\u96F6\u9756\u9774\u9776\u9810\u9811\u9813\u980A\u9812\u980C\u98FC\u98F4"],
      ["b9a1", "\u98FD\u98FE\u99B3\u99B1\u99B4\u9AE1\u9CE9\u9E82\u9F0E\u9F13\u9F20\u50E7\u50EE\u50E5\u50D6\u50ED\u50DA\u50D5\u50CF\u50D1\u50F1\u50CE\u50E9\u5162\u51F3\u5283\u5282\u5331\u53AD\u55FE\u5600\u561B\u5617\u55FD\u5614\u5606\u5609\u560D\u560E\u55F7\u5616\u561F\u5608\u5610\u55F6\u5718\u5716\u5875\u587E\u5883\u5893\u588A\u5879\u5885\u587D\u58FD\u5925\u5922\u5924\u596A\u5969\u5AE1\u5AE6\u5AE9\u5AD7\u5AD6\u5AD8\u5AE3\u5B75\u5BDE\u5BE7\u5BE1\u5BE5\u5BE6\u5BE8\u5BE2\u5BE4\u5BDF\u5C0D\u5C62\u5D84\u5D87\u5E5B\u5E63\u5E55\u5E57\u5E54\u5ED3\u5ED6\u5F0A\u5F46\u5F70\u5FB9\u6147"],
      ["ba40", "\u613F\u614B\u6177\u6162\u6163\u615F\u615A\u6158\u6175\u622A\u6487\u6458\u6454\u64A4\u6478\u645F\u647A\u6451\u6467\u6434\u646D\u647B\u6572\u65A1\u65D7\u65D6\u66A2\u66A8\u669D\u699C\u69A8\u6995\u69C1\u69AE\u69D3\u69CB\u699B\u69B7\u69BB\u69AB\u69B4\u69D0\u69CD\u69AD\u69CC\u69A6\u69C3\u69A3\u6B49\u6B4C\u6C33\u6F33\u6F14\u6EFE\u6F13\u6EF4\u6F29\u6F3E\u6F20\u6F2C\u6F0F\u6F02\u6F22"],
      ["baa1", "\u6EFF\u6EEF\u6F06\u6F31\u6F38\u6F32\u6F23\u6F15\u6F2B\u6F2F\u6F88\u6F2A\u6EEC\u6F01\u6EF2\u6ECC\u6EF7\u7194\u7199\u717D\u718A\u7184\u7192\u723E\u7292\u7296\u7344\u7350\u7464\u7463\u746A\u7470\u746D\u7504\u7591\u7627\u760D\u760B\u7609\u7613\u76E1\u76E3\u7784\u777D\u777F\u7761\u78C1\u789F\u78A7\u78B3\u78A9\u78A3\u798E\u798F\u798D\u7A2E\u7A31\u7AAA\u7AA9\u7AED\u7AEF\u7BA1\u7B95\u7B8B\u7B75\u7B97\u7B9D\u7B94\u7B8F\u7BB8\u7B87\u7B84\u7CB9\u7CBD\u7CBE\u7DBB\u7DB0\u7D9C\u7DBD\u7DBE\u7DA0\u7DCA\u7DB4\u7DB2\u7DB1\u7DBA\u7DA2\u7DBF\u7DB5\u7DB8\u7DAD\u7DD2\u7DC7\u7DAC"],
      ["bb40", "\u7F70\u7FE0\u7FE1\u7FDF\u805E\u805A\u8087\u8150\u8180\u818F\u8188\u818A\u817F\u8182\u81E7\u81FA\u8207\u8214\u821E\u824B\u84C9\u84BF\u84C6\u84C4\u8499\u849E\u84B2\u849C\u84CB\u84B8\u84C0\u84D3\u8490\u84BC\u84D1\u84CA\u873F\u871C\u873B\u8722\u8725\u8734\u8718\u8755\u8737\u8729\u88F3\u8902\u88F4\u88F9\u88F8\u88FD\u88E8\u891A\u88EF\u8AA6\u8A8C\u8A9E\u8AA3\u8A8D\u8AA1\u8A93\u8AA4"],
      ["bba1", "\u8AAA\u8AA5\u8AA8\u8A98\u8A91\u8A9A\u8AA7\u8C6A\u8C8D\u8C8C\u8CD3\u8CD1\u8CD2\u8D6B\u8D99\u8D95\u8DFC\u8F14\u8F12\u8F15\u8F13\u8FA3\u9060\u9058\u905C\u9063\u9059\u905E\u9062\u905D\u905B\u9119\u9118\u911E\u9175\u9178\u9177\u9174\u9278\u9280\u9285\u9298\u9296\u927B\u9293\u929C\u92A8\u927C\u9291\u95A1\u95A8\u95A9\u95A3\u95A5\u95A4\u9699\u969C\u969B\u96CC\u96D2\u9700\u977C\u9785\u97F6\u9817\u9818\u98AF\u98B1\u9903\u9905\u990C\u9909\u99C1\u9AAF\u9AB0\u9AE6\u9B41\u9B42\u9CF4\u9CF6\u9CF3\u9EBC\u9F3B\u9F4A\u5104\u5100\u50FB\u50F5\u50F9\u5102\u5108\u5109\u5105\u51DC"],
      ["bc40", "\u5287\u5288\u5289\u528D\u528A\u52F0\u53B2\u562E\u563B\u5639\u5632\u563F\u5634\u5629\u5653\u564E\u5657\u5674\u5636\u562F\u5630\u5880\u589F\u589E\u58B3\u589C\u58AE\u58A9\u58A6\u596D\u5B09\u5AFB\u5B0B\u5AF5\u5B0C\u5B08\u5BEE\u5BEC\u5BE9\u5BEB\u5C64\u5C65\u5D9D\u5D94\u5E62\u5E5F\u5E61\u5EE2\u5EDA\u5EDF\u5EDD\u5EE3\u5EE0\u5F48\u5F71\u5FB7\u5FB5\u6176\u6167\u616E\u615D\u6155\u6182"],
      ["bca1", "\u617C\u6170\u616B\u617E\u61A7\u6190\u61AB\u618E\u61AC\u619A\u61A4\u6194\u61AE\u622E\u6469\u646F\u6479\u649E\u64B2\u6488\u6490\u64B0\u64A5\u6493\u6495\u64A9\u6492\u64AE\u64AD\u64AB\u649A\u64AC\u6499\u64A2\u64B3\u6575\u6577\u6578\u66AE\u66AB\u66B4\u66B1\u6A23\u6A1F\u69E8\u6A01\u6A1E\u6A19\u69FD\u6A21\u6A13\u6A0A\u69F3\u6A02\u6A05\u69ED\u6A11\u6B50\u6B4E\u6BA4\u6BC5\u6BC6\u6F3F\u6F7C\u6F84\u6F51\u6F66\u6F54\u6F86\u6F6D\u6F5B\u6F78\u6F6E\u6F8E\u6F7A\u6F70\u6F64\u6F97\u6F58\u6ED5\u6F6F\u6F60\u6F5F\u719F\u71AC\u71B1\u71A8\u7256\u729B\u734E\u7357\u7469\u748B\u7483"],
      ["bd40", "\u747E\u7480\u757F\u7620\u7629\u761F\u7624\u7626\u7621\u7622\u769A\u76BA\u76E4\u778E\u7787\u778C\u7791\u778B\u78CB\u78C5\u78BA\u78CA\u78BE\u78D5\u78BC\u78D0\u7A3F\u7A3C\u7A40\u7A3D\u7A37\u7A3B\u7AAF\u7AAE\u7BAD\u7BB1\u7BC4\u7BB4\u7BC6\u7BC7\u7BC1\u7BA0\u7BCC\u7CCA\u7DE0\u7DF4\u7DEF\u7DFB\u7DD8\u7DEC\u7DDD\u7DE8\u7DE3\u7DDA\u7DDE\u7DE9\u7D9E\u7DD9\u7DF2\u7DF9\u7F75\u7F77\u7FAF"],
      ["bda1", "\u7FE9\u8026\u819B\u819C\u819D\u81A0\u819A\u8198\u8517\u853D\u851A\u84EE\u852C\u852D\u8513\u8511\u8523\u8521\u8514\u84EC\u8525\u84FF\u8506\u8782\u8774\u8776\u8760\u8766\u8778\u8768\u8759\u8757\u874C\u8753\u885B\u885D\u8910\u8907\u8912\u8913\u8915\u890A\u8ABC\u8AD2\u8AC7\u8AC4\u8A95\u8ACB\u8AF8\u8AB2\u8AC9\u8AC2\u8ABF\u8AB0\u8AD6\u8ACD\u8AB6\u8AB9\u8ADB\u8C4C\u8C4E\u8C6C\u8CE0\u8CDE\u8CE6\u8CE4\u8CEC\u8CED\u8CE2\u8CE3\u8CDC\u8CEA\u8CE1\u8D6D\u8D9F\u8DA3\u8E2B\u8E10\u8E1D\u8E22\u8E0F\u8E29\u8E1F\u8E21\u8E1E\u8EBA\u8F1D\u8F1B\u8F1F\u8F29\u8F26\u8F2A\u8F1C\u8F1E"],
      ["be40", "\u8F25\u9069\u906E\u9068\u906D\u9077\u9130\u912D\u9127\u9131\u9187\u9189\u918B\u9183\u92C5\u92BB\u92B7\u92EA\u92AC\u92E4\u92C1\u92B3\u92BC\u92D2\u92C7\u92F0\u92B2\u95AD\u95B1\u9704\u9706\u9707\u9709\u9760\u978D\u978B\u978F\u9821\u982B\u981C\u98B3\u990A\u9913\u9912\u9918\u99DD\u99D0\u99DF\u99DB\u99D1\u99D5\u99D2\u99D9\u9AB7\u9AEE\u9AEF\u9B27\u9B45\u9B44\u9B77\u9B6F\u9D06\u9D09"],
      ["bea1", "\u9D03\u9EA9\u9EBE\u9ECE\u58A8\u9F52\u5112\u5118\u5114\u5110\u5115\u5180\u51AA\u51DD\u5291\u5293\u52F3\u5659\u566B\u5679\u5669\u5664\u5678\u566A\u5668\u5665\u5671\u566F\u566C\u5662\u5676\u58C1\u58BE\u58C7\u58C5\u596E\u5B1D\u5B34\u5B78\u5BF0\u5C0E\u5F4A\u61B2\u6191\u61A9\u618A\u61CD\u61B6\u61BE\u61CA\u61C8\u6230\u64C5\u64C1\u64CB\u64BB\u64BC\u64DA\u64C4\u64C7\u64C2\u64CD\u64BF\u64D2\u64D4\u64BE\u6574\u66C6\u66C9\u66B9\u66C4\u66C7\u66B8\u6A3D\u6A38\u6A3A\u6A59\u6A6B\u6A58\u6A39\u6A44\u6A62\u6A61\u6A4B\u6A47\u6A35\u6A5F\u6A48\u6B59\u6B77\u6C05\u6FC2\u6FB1\u6FA1"],
      ["bf40", "\u6FC3\u6FA4\u6FC1\u6FA7\u6FB3\u6FC0\u6FB9\u6FB6\u6FA6\u6FA0\u6FB4\u71BE\u71C9\u71D0\u71D2\u71C8\u71D5\u71B9\u71CE\u71D9\u71DC\u71C3\u71C4\u7368\u749C\u74A3\u7498\u749F\u749E\u74E2\u750C\u750D\u7634\u7638\u763A\u76E7\u76E5\u77A0\u779E\u779F\u77A5\u78E8\u78DA\u78EC\u78E7\u79A6\u7A4D\u7A4E\u7A46\u7A4C\u7A4B\u7ABA\u7BD9\u7C11\u7BC9\u7BE4\u7BDB\u7BE1\u7BE9\u7BE6\u7CD5\u7CD6\u7E0A"],
      ["bfa1", "\u7E11\u7E08\u7E1B\u7E23\u7E1E\u7E1D\u7E09\u7E10\u7F79\u7FB2\u7FF0\u7FF1\u7FEE\u8028\u81B3\u81A9\u81A8\u81FB\u8208\u8258\u8259\u854A\u8559\u8548\u8568\u8569\u8543\u8549\u856D\u856A\u855E\u8783\u879F\u879E\u87A2\u878D\u8861\u892A\u8932\u8925\u892B\u8921\u89AA\u89A6\u8AE6\u8AFA\u8AEB\u8AF1\u8B00\u8ADC\u8AE7\u8AEE\u8AFE\u8B01\u8B02\u8AF7\u8AED\u8AF3\u8AF6\u8AFC\u8C6B\u8C6D\u8C93\u8CF4\u8E44\u8E31\u8E34\u8E42\u8E39\u8E35\u8F3B\u8F2F\u8F38\u8F33\u8FA8\u8FA6\u9075\u9074\u9078\u9072\u907C\u907A\u9134\u9192\u9320\u9336\u92F8\u9333\u932F\u9322\u92FC\u932B\u9304\u931A"],
      ["c040", "\u9310\u9326\u9321\u9315\u932E\u9319\u95BB\u96A7\u96A8\u96AA\u96D5\u970E\u9711\u9716\u970D\u9713\u970F\u975B\u975C\u9766\u9798\u9830\u9838\u983B\u9837\u982D\u9839\u9824\u9910\u9928\u991E\u991B\u9921\u991A\u99ED\u99E2\u99F1\u9AB8\u9ABC\u9AFB\u9AED\u9B28\u9B91\u9D15\u9D23\u9D26\u9D28\u9D12\u9D1B\u9ED8\u9ED4\u9F8D\u9F9C\u512A\u511F\u5121\u5132\u52F5\u568E\u5680\u5690\u5685\u5687"],
      ["c0a1", "\u568F\u58D5\u58D3\u58D1\u58CE\u5B30\u5B2A\u5B24\u5B7A\u5C37\u5C68\u5DBC\u5DBA\u5DBD\u5DB8\u5E6B\u5F4C\u5FBD\u61C9\u61C2\u61C7\u61E6\u61CB\u6232\u6234\u64CE\u64CA\u64D8\u64E0\u64F0\u64E6\u64EC\u64F1\u64E2\u64ED\u6582\u6583\u66D9\u66D6\u6A80\u6A94\u6A84\u6AA2\u6A9C\u6ADB\u6AA3\u6A7E\u6A97\u6A90\u6AA0\u6B5C\u6BAE\u6BDA\u6C08\u6FD8\u6FF1\u6FDF\u6FE0\u6FDB\u6FE4\u6FEB\u6FEF\u6F80\u6FEC\u6FE1\u6FE9\u6FD5\u6FEE\u6FF0\u71E7\u71DF\u71EE\u71E6\u71E5\u71ED\u71EC\u71F4\u71E0\u7235\u7246\u7370\u7372\u74A9\u74B0\u74A6\u74A8\u7646\u7642\u764C\u76EA\u77B3\u77AA\u77B0\u77AC"],
      ["c140", "\u77A7\u77AD\u77EF\u78F7\u78FA\u78F4\u78EF\u7901\u79A7\u79AA\u7A57\u7ABF\u7C07\u7C0D\u7BFE\u7BF7\u7C0C\u7BE0\u7CE0\u7CDC\u7CDE\u7CE2\u7CDF\u7CD9\u7CDD\u7E2E\u7E3E\u7E46\u7E37\u7E32\u7E43\u7E2B\u7E3D\u7E31\u7E45\u7E41\u7E34\u7E39\u7E48\u7E35\u7E3F\u7E2F\u7F44\u7FF3\u7FFC\u8071\u8072\u8070\u806F\u8073\u81C6\u81C3\u81BA\u81C2\u81C0\u81BF\u81BD\u81C9\u81BE\u81E8\u8209\u8271\u85AA"],
      ["c1a1", "\u8584\u857E\u859C\u8591\u8594\u85AF\u859B\u8587\u85A8\u858A\u8667\u87C0\u87D1\u87B3\u87D2\u87C6\u87AB\u87BB\u87BA\u87C8\u87CB\u893B\u8936\u8944\u8938\u893D\u89AC\u8B0E\u8B17\u8B19\u8B1B\u8B0A\u8B20\u8B1D\u8B04\u8B10\u8C41\u8C3F\u8C73\u8CFA\u8CFD\u8CFC\u8CF8\u8CFB\u8DA8\u8E49\u8E4B\u8E48\u8E4A\u8F44\u8F3E\u8F42\u8F45\u8F3F\u907F\u907D\u9084\u9081\u9082\u9080\u9139\u91A3\u919E\u919C\u934D\u9382\u9328\u9375\u934A\u9365\u934B\u9318\u937E\u936C\u935B\u9370\u935A\u9354\u95CA\u95CB\u95CC\u95C8\u95C6\u96B1\u96B8\u96D6\u971C\u971E\u97A0\u97D3\u9846\u98B6\u9935\u9A01"],
      ["c240", "\u99FF\u9BAE\u9BAB\u9BAA\u9BAD\u9D3B\u9D3F\u9E8B\u9ECF\u9EDE\u9EDC\u9EDD\u9EDB\u9F3E\u9F4B\u53E2\u5695\u56AE\u58D9\u58D8\u5B38\u5F5D\u61E3\u6233\u64F4\u64F2\u64FE\u6506\u64FA\u64FB\u64F7\u65B7\u66DC\u6726\u6AB3\u6AAC\u6AC3\u6ABB\u6AB8\u6AC2\u6AAE\u6AAF\u6B5F\u6B78\u6BAF\u7009\u700B\u6FFE\u7006\u6FFA\u7011\u700F\u71FB\u71FC\u71FE\u71F8\u7377\u7375\u74A7\u74BF\u7515\u7656\u7658"],
      ["c2a1", "\u7652\u77BD\u77BF\u77BB\u77BC\u790E\u79AE\u7A61\u7A62\u7A60\u7AC4\u7AC5\u7C2B\u7C27\u7C2A\u7C1E\u7C23\u7C21\u7CE7\u7E54\u7E55\u7E5E\u7E5A\u7E61\u7E52\u7E59\u7F48\u7FF9\u7FFB\u8077\u8076\u81CD\u81CF\u820A\u85CF\u85A9\u85CD\u85D0\u85C9\u85B0\u85BA\u85B9\u85A6\u87EF\u87EC\u87F2\u87E0\u8986\u89B2\u89F4\u8B28\u8B39\u8B2C\u8B2B\u8C50\u8D05\u8E59\u8E63\u8E66\u8E64\u8E5F\u8E55\u8EC0\u8F49\u8F4D\u9087\u9083\u9088\u91AB\u91AC\u91D0\u9394\u938A\u9396\u93A2\u93B3\u93AE\u93AC\u93B0\u9398\u939A\u9397\u95D4\u95D6\u95D0\u95D5\u96E2\u96DC\u96D9\u96DB\u96DE\u9724\u97A3\u97A6"],
      ["c340", "\u97AD\u97F9\u984D\u984F\u984C\u984E\u9853\u98BA\u993E\u993F\u993D\u992E\u99A5\u9A0E\u9AC1\u9B03\u9B06\u9B4F\u9B4E\u9B4D\u9BCA\u9BC9\u9BFD\u9BC8\u9BC0\u9D51\u9D5D\u9D60\u9EE0\u9F15\u9F2C\u5133\u56A5\u58DE\u58DF\u58E2\u5BF5\u9F90\u5EEC\u61F2\u61F7\u61F6\u61F5\u6500\u650F\u66E0\u66DD\u6AE5\u6ADD\u6ADA\u6AD3\u701B\u701F\u7028\u701A\u701D\u7015\u7018\u7206\u720D\u7258\u72A2\u7378"],
      ["c3a1", "\u737A\u74BD\u74CA\u74E3\u7587\u7586\u765F\u7661\u77C7\u7919\u79B1\u7A6B\u7A69\u7C3E\u7C3F\u7C38\u7C3D\u7C37\u7C40\u7E6B\u7E6D\u7E79\u7E69\u7E6A\u7F85\u7E73\u7FB6\u7FB9\u7FB8\u81D8\u85E9\u85DD\u85EA\u85D5\u85E4\u85E5\u85F7\u87FB\u8805\u880D\u87F9\u87FE\u8960\u895F\u8956\u895E\u8B41\u8B5C\u8B58\u8B49\u8B5A\u8B4E\u8B4F\u8B46\u8B59\u8D08\u8D0A\u8E7C\u8E72\u8E87\u8E76\u8E6C\u8E7A\u8E74\u8F54\u8F4E\u8FAD\u908A\u908B\u91B1\u91AE\u93E1\u93D1\u93DF\u93C3\u93C8\u93DC\u93DD\u93D6\u93E2\u93CD\u93D8\u93E4\u93D7\u93E8\u95DC\u96B4\u96E3\u972A\u9727\u9761\u97DC\u97FB\u985E"],
      ["c440", "\u9858\u985B\u98BC\u9945\u9949\u9A16\u9A19\u9B0D\u9BE8\u9BE7\u9BD6\u9BDB\u9D89\u9D61\u9D72\u9D6A\u9D6C\u9E92\u9E97\u9E93\u9EB4\u52F8\u56A8\u56B7\u56B6\u56B4\u56BC\u58E4\u5B40\u5B43\u5B7D\u5BF6\u5DC9\u61F8\u61FA\u6518\u6514\u6519\u66E6\u6727\u6AEC\u703E\u7030\u7032\u7210\u737B\u74CF\u7662\u7665\u7926\u792A\u792C\u792B\u7AC7\u7AF6\u7C4C\u7C43\u7C4D\u7CEF\u7CF0\u8FAE\u7E7D\u7E7C"],
      ["c4a1", "\u7E82\u7F4C\u8000\u81DA\u8266\u85FB\u85F9\u8611\u85FA\u8606\u860B\u8607\u860A\u8814\u8815\u8964\u89BA\u89F8\u8B70\u8B6C\u8B66\u8B6F\u8B5F\u8B6B\u8D0F\u8D0D\u8E89\u8E81\u8E85\u8E82\u91B4\u91CB\u9418\u9403\u93FD\u95E1\u9730\u98C4\u9952\u9951\u99A8\u9A2B\u9A30\u9A37\u9A35\u9C13\u9C0D\u9E79\u9EB5\u9EE8\u9F2F\u9F5F\u9F63\u9F61\u5137\u5138\u56C1\u56C0\u56C2\u5914\u5C6C\u5DCD\u61FC\u61FE\u651D\u651C\u6595\u66E9\u6AFB\u6B04\u6AFA\u6BB2\u704C\u721B\u72A7\u74D6\u74D4\u7669\u77D3\u7C50\u7E8F\u7E8C\u7FBC\u8617\u862D\u861A\u8823\u8822\u8821\u881F\u896A\u896C\u89BD\u8B74"],
      ["c540", "\u8B77\u8B7D\u8D13\u8E8A\u8E8D\u8E8B\u8F5F\u8FAF\u91BA\u942E\u9433\u9435\u943A\u9438\u9432\u942B\u95E2\u9738\u9739\u9732\u97FF\u9867\u9865\u9957\u9A45\u9A43\u9A40\u9A3E\u9ACF\u9B54\u9B51\u9C2D\u9C25\u9DAF\u9DB4\u9DC2\u9DB8\u9E9D\u9EEF\u9F19\u9F5C\u9F66\u9F67\u513C\u513B\u56C8\u56CA\u56C9\u5B7F\u5DD4\u5DD2\u5F4E\u61FF\u6524\u6B0A\u6B61\u7051\u7058\u7380\u74E4\u758A\u766E\u766C"],
      ["c5a1", "\u79B3\u7C60\u7C5F\u807E\u807D\u81DF\u8972\u896F\u89FC\u8B80\u8D16\u8D17\u8E91\u8E93\u8F61\u9148\u9444\u9451\u9452\u973D\u973E\u97C3\u97C1\u986B\u9955\u9A55\u9A4D\u9AD2\u9B1A\u9C49\u9C31\u9C3E\u9C3B\u9DD3\u9DD7\u9F34\u9F6C\u9F6A\u9F94\u56CC\u5DD6\u6200\u6523\u652B\u652A\u66EC\u6B10\u74DA\u7ACA\u7C64\u7C63\u7C65\u7E93\u7E96\u7E94\u81E2\u8638\u863F\u8831\u8B8A\u9090\u908F\u9463\u9460\u9464\u9768\u986F\u995C\u9A5A\u9A5B\u9A57\u9AD3\u9AD4\u9AD1\u9C54\u9C57\u9C56\u9DE5\u9E9F\u9EF4\u56D1\u58E9\u652C\u705E\u7671\u7672\u77D7\u7F50\u7F88\u8836\u8839\u8862\u8B93\u8B92"],
      ["c640", "\u8B96\u8277\u8D1B\u91C0\u946A\u9742\u9748\u9744\u97C6\u9870\u9A5F\u9B22\u9B58\u9C5F\u9DF9\u9DFA\u9E7C\u9E7D\u9F07\u9F77\u9F72\u5EF3\u6B16\u7063\u7C6C\u7C6E\u883B\u89C0\u8EA1\u91C1\u9472\u9470\u9871\u995E\u9AD6\u9B23\u9ECC\u7064\u77DA\u8B9A\u9477\u97C9\u9A62\u9A65\u7E9C\u8B9C\u8EAA\u91C5\u947D\u947E\u947C\u9C77\u9C78\u9EF7\u8C54\u947F\u9E1A\u7228\u9A6A\u9B31\u9E1B\u9E1E\u7C72"],
      ["c940", "\u4E42\u4E5C\u51F5\u531A\u5382\u4E07\u4E0C\u4E47\u4E8D\u56D7\uFA0C\u5C6E\u5F73\u4E0F\u5187\u4E0E\u4E2E\u4E93\u4EC2\u4EC9\u4EC8\u5198\u52FC\u536C\u53B9\u5720\u5903\u592C\u5C10\u5DFF\u65E1\u6BB3\u6BCC\u6C14\u723F\u4E31\u4E3C\u4EE8\u4EDC\u4EE9\u4EE1\u4EDD\u4EDA\u520C\u531C\u534C\u5722\u5723\u5917\u592F\u5B81\u5B84\u5C12\u5C3B\u5C74\u5C73\u5E04\u5E80\u5E82\u5FC9\u6209\u6250\u6C15"],
      ["c9a1", "\u6C36\u6C43\u6C3F\u6C3B\u72AE\u72B0\u738A\u79B8\u808A\u961E\u4F0E\u4F18\u4F2C\u4EF5\u4F14\u4EF1\u4F00\u4EF7\u4F08\u4F1D\u4F02\u4F05\u4F22\u4F13\u4F04\u4EF4\u4F12\u51B1\u5213\u5209\u5210\u52A6\u5322\u531F\u534D\u538A\u5407\u56E1\u56DF\u572E\u572A\u5734\u593C\u5980\u597C\u5985\u597B\u597E\u5977\u597F\u5B56\u5C15\u5C25\u5C7C\u5C7A\u5C7B\u5C7E\u5DDF\u5E75\u5E84\u5F02\u5F1A\u5F74\u5FD5\u5FD4\u5FCF\u625C\u625E\u6264\u6261\u6266\u6262\u6259\u6260\u625A\u6265\u65EF\u65EE\u673E\u6739\u6738\u673B\u673A\u673F\u673C\u6733\u6C18\u6C46\u6C52\u6C5C\u6C4F\u6C4A\u6C54\u6C4B"],
      ["ca40", "\u6C4C\u7071\u725E\u72B4\u72B5\u738E\u752A\u767F\u7A75\u7F51\u8278\u827C\u8280\u827D\u827F\u864D\u897E\u9099\u9097\u9098\u909B\u9094\u9622\u9624\u9620\u9623\u4F56\u4F3B\u4F62\u4F49\u4F53\u4F64\u4F3E\u4F67\u4F52\u4F5F\u4F41\u4F58\u4F2D\u4F33\u4F3F\u4F61\u518F\u51B9\u521C\u521E\u5221\u52AD\u52AE\u5309\u5363\u5372\u538E\u538F\u5430\u5437\u542A\u5454\u5445\u5419\u541C\u5425\u5418"],
      ["caa1", "\u543D\u544F\u5441\u5428\u5424\u5447\u56EE\u56E7\u56E5\u5741\u5745\u574C\u5749\u574B\u5752\u5906\u5940\u59A6\u5998\u59A0\u5997\u598E\u59A2\u5990\u598F\u59A7\u59A1\u5B8E\u5B92\u5C28\u5C2A\u5C8D\u5C8F\u5C88\u5C8B\u5C89\u5C92\u5C8A\u5C86\u5C93\u5C95\u5DE0\u5E0A\u5E0E\u5E8B\u5E89\u5E8C\u5E88\u5E8D\u5F05\u5F1D\u5F78\u5F76\u5FD2\u5FD1\u5FD0\u5FED\u5FE8\u5FEE\u5FF3\u5FE1\u5FE4\u5FE3\u5FFA\u5FEF\u5FF7\u5FFB\u6000\u5FF4\u623A\u6283\u628C\u628E\u628F\u6294\u6287\u6271\u627B\u627A\u6270\u6281\u6288\u6277\u627D\u6272\u6274\u6537\u65F0\u65F4\u65F3\u65F2\u65F5\u6745\u6747"],
      ["cb40", "\u6759\u6755\u674C\u6748\u675D\u674D\u675A\u674B\u6BD0\u6C19\u6C1A\u6C78\u6C67\u6C6B\u6C84\u6C8B\u6C8F\u6C71\u6C6F\u6C69\u6C9A\u6C6D\u6C87\u6C95\u6C9C\u6C66\u6C73\u6C65\u6C7B\u6C8E\u7074\u707A\u7263\u72BF\u72BD\u72C3\u72C6\u72C1\u72BA\u72C5\u7395\u7397\u7393\u7394\u7392\u753A\u7539\u7594\u7595\u7681\u793D\u8034\u8095\u8099\u8090\u8092\u809C\u8290\u828F\u8285\u828E\u8291\u8293"],
      ["cba1", "\u828A\u8283\u8284\u8C78\u8FC9\u8FBF\u909F\u90A1\u90A5\u909E\u90A7\u90A0\u9630\u9628\u962F\u962D\u4E33\u4F98\u4F7C\u4F85\u4F7D\u4F80\u4F87\u4F76\u4F74\u4F89\u4F84\u4F77\u4F4C\u4F97\u4F6A\u4F9A\u4F79\u4F81\u4F78\u4F90\u4F9C\u4F94\u4F9E\u4F92\u4F82\u4F95\u4F6B\u4F6E\u519E\u51BC\u51BE\u5235\u5232\u5233\u5246\u5231\u52BC\u530A\u530B\u533C\u5392\u5394\u5487\u547F\u5481\u5491\u5482\u5488\u546B\u547A\u547E\u5465\u546C\u5474\u5466\u548D\u546F\u5461\u5460\u5498\u5463\u5467\u5464\u56F7\u56F9\u576F\u5772\u576D\u576B\u5771\u5770\u5776\u5780\u5775\u577B\u5773\u5774\u5762"],
      ["cc40", "\u5768\u577D\u590C\u5945\u59B5\u59BA\u59CF\u59CE\u59B2\u59CC\u59C1\u59B6\u59BC\u59C3\u59D6\u59B1\u59BD\u59C0\u59C8\u59B4\u59C7\u5B62\u5B65\u5B93\u5B95\u5C44\u5C47\u5CAE\u5CA4\u5CA0\u5CB5\u5CAF\u5CA8\u5CAC\u5C9F\u5CA3\u5CAD\u5CA2\u5CAA\u5CA7\u5C9D\u5CA5\u5CB6\u5CB0\u5CA6\u5E17\u5E14\u5E19\u5F28\u5F22\u5F23\u5F24\u5F54\u5F82\u5F7E\u5F7D\u5FDE\u5FE5\u602D\u6026\u6019\u6032\u600B"],
      ["cca1", "\u6034\u600A\u6017\u6033\u601A\u601E\u602C\u6022\u600D\u6010\u602E\u6013\u6011\u600C\u6009\u601C\u6214\u623D\u62AD\u62B4\u62D1\u62BE\u62AA\u62B6\u62CA\u62AE\u62B3\u62AF\u62BB\u62A9\u62B0\u62B8\u653D\u65A8\u65BB\u6609\u65FC\u6604\u6612\u6608\u65FB\u6603\u660B\u660D\u6605\u65FD\u6611\u6610\u66F6\u670A\u6785\u676C\u678E\u6792\u6776\u677B\u6798\u6786\u6784\u6774\u678D\u678C\u677A\u679F\u6791\u6799\u6783\u677D\u6781\u6778\u6779\u6794\u6B25\u6B80\u6B7E\u6BDE\u6C1D\u6C93\u6CEC\u6CEB\u6CEE\u6CD9\u6CB6\u6CD4\u6CAD\u6CE7\u6CB7\u6CD0\u6CC2\u6CBA\u6CC3\u6CC6\u6CED\u6CF2"],
      ["cd40", "\u6CD2\u6CDD\u6CB4\u6C8A\u6C9D\u6C80\u6CDE\u6CC0\u6D30\u6CCD\u6CC7\u6CB0\u6CF9\u6CCF\u6CE9\u6CD1\u7094\u7098\u7085\u7093\u7086\u7084\u7091\u7096\u7082\u709A\u7083\u726A\u72D6\u72CB\u72D8\u72C9\u72DC\u72D2\u72D4\u72DA\u72CC\u72D1\u73A4\u73A1\u73AD\u73A6\u73A2\u73A0\u73AC\u739D\u74DD\u74E8\u753F\u7540\u753E\u758C\u7598\u76AF\u76F3\u76F1\u76F0\u76F5\u77F8\u77FC\u77F9\u77FB\u77FA"],
      ["cda1", "\u77F7\u7942\u793F\u79C5\u7A78\u7A7B\u7AFB\u7C75\u7CFD\u8035\u808F\u80AE\u80A3\u80B8\u80B5\u80AD\u8220\u82A0\u82C0\u82AB\u829A\u8298\u829B\u82B5\u82A7\u82AE\u82BC\u829E\u82BA\u82B4\u82A8\u82A1\u82A9\u82C2\u82A4\u82C3\u82B6\u82A2\u8670\u866F\u866D\u866E\u8C56\u8FD2\u8FCB\u8FD3\u8FCD\u8FD6\u8FD5\u8FD7\u90B2\u90B4\u90AF\u90B3\u90B0\u9639\u963D\u963C\u963A\u9643\u4FCD\u4FC5\u4FD3\u4FB2\u4FC9\u4FCB\u4FC1\u4FD4\u4FDC\u4FD9\u4FBB\u4FB3\u4FDB\u4FC7\u4FD6\u4FBA\u4FC0\u4FB9\u4FEC\u5244\u5249\u52C0\u52C2\u533D\u537C\u5397\u5396\u5399\u5398\u54BA\u54A1\u54AD\u54A5\u54CF"],
      ["ce40", "\u54C3\u830D\u54B7\u54AE\u54D6\u54B6\u54C5\u54C6\u54A0\u5470\u54BC\u54A2\u54BE\u5472\u54DE\u54B0\u57B5\u579E\u579F\u57A4\u578C\u5797\u579D\u579B\u5794\u5798\u578F\u5799\u57A5\u579A\u5795\u58F4\u590D\u5953\u59E1\u59DE\u59EE\u5A00\u59F1\u59DD\u59FA\u59FD\u59FC\u59F6\u59E4\u59F2\u59F7\u59DB\u59E9\u59F3\u59F5\u59E0\u59FE\u59F4\u59ED\u5BA8\u5C4C\u5CD0\u5CD8\u5CCC\u5CD7\u5CCB\u5CDB"],
      ["cea1", "\u5CDE\u5CDA\u5CC9\u5CC7\u5CCA\u5CD6\u5CD3\u5CD4\u5CCF\u5CC8\u5CC6\u5CCE\u5CDF\u5CF8\u5DF9\u5E21\u5E22\u5E23\u5E20\u5E24\u5EB0\u5EA4\u5EA2\u5E9B\u5EA3\u5EA5\u5F07\u5F2E\u5F56\u5F86\u6037\u6039\u6054\u6072\u605E\u6045\u6053\u6047\u6049\u605B\u604C\u6040\u6042\u605F\u6024\u6044\u6058\u6066\u606E\u6242\u6243\u62CF\u630D\u630B\u62F5\u630E\u6303\u62EB\u62F9\u630F\u630C\u62F8\u62F6\u6300\u6313\u6314\u62FA\u6315\u62FB\u62F0\u6541\u6543\u65AA\u65BF\u6636\u6621\u6632\u6635\u661C\u6626\u6622\u6633\u662B\u663A\u661D\u6634\u6639\u662E\u670F\u6710\u67C1\u67F2\u67C8\u67BA"],
      ["cf40", "\u67DC\u67BB\u67F8\u67D8\u67C0\u67B7\u67C5\u67EB\u67E4\u67DF\u67B5\u67CD\u67B3\u67F7\u67F6\u67EE\u67E3\u67C2\u67B9\u67CE\u67E7\u67F0\u67B2\u67FC\u67C6\u67ED\u67CC\u67AE\u67E6\u67DB\u67FA\u67C9\u67CA\u67C3\u67EA\u67CB\u6B28\u6B82\u6B84\u6BB6\u6BD6\u6BD8\u6BE0\u6C20\u6C21\u6D28\u6D34\u6D2D\u6D1F\u6D3C\u6D3F\u6D12\u6D0A\u6CDA\u6D33\u6D04\u6D19\u6D3A\u6D1A\u6D11\u6D00\u6D1D\u6D42"],
      ["cfa1", "\u6D01\u6D18\u6D37\u6D03\u6D0F\u6D40\u6D07\u6D20\u6D2C\u6D08\u6D22\u6D09\u6D10\u70B7\u709F\u70BE\u70B1\u70B0\u70A1\u70B4\u70B5\u70A9\u7241\u7249\u724A\u726C\u7270\u7273\u726E\u72CA\u72E4\u72E8\u72EB\u72DF\u72EA\u72E6\u72E3\u7385\u73CC\u73C2\u73C8\u73C5\u73B9\u73B6\u73B5\u73B4\u73EB\u73BF\u73C7\u73BE\u73C3\u73C6\u73B8\u73CB\u74EC\u74EE\u752E\u7547\u7548\u75A7\u75AA\u7679\u76C4\u7708\u7703\u7704\u7705\u770A\u76F7\u76FB\u76FA\u77E7\u77E8\u7806\u7811\u7812\u7805\u7810\u780F\u780E\u7809\u7803\u7813\u794A\u794C\u794B\u7945\u7944\u79D5\u79CD\u79CF\u79D6\u79CE\u7A80"],
      ["d040", "\u7A7E\u7AD1\u7B00\u7B01\u7C7A\u7C78\u7C79\u7C7F\u7C80\u7C81\u7D03\u7D08\u7D01\u7F58\u7F91\u7F8D\u7FBE\u8007\u800E\u800F\u8014\u8037\u80D8\u80C7\u80E0\u80D1\u80C8\u80C2\u80D0\u80C5\u80E3\u80D9\u80DC\u80CA\u80D5\u80C9\u80CF\u80D7\u80E6\u80CD\u81FF\u8221\u8294\u82D9\u82FE\u82F9\u8307\u82E8\u8300\u82D5\u833A\u82EB\u82D6\u82F4\u82EC\u82E1\u82F2\u82F5\u830C\u82FB\u82F6\u82F0\u82EA"],
      ["d0a1", "\u82E4\u82E0\u82FA\u82F3\u82ED\u8677\u8674\u867C\u8673\u8841\u884E\u8867\u886A\u8869\u89D3\u8A04\u8A07\u8D72\u8FE3\u8FE1\u8FEE\u8FE0\u90F1\u90BD\u90BF\u90D5\u90C5\u90BE\u90C7\u90CB\u90C8\u91D4\u91D3\u9654\u964F\u9651\u9653\u964A\u964E\u501E\u5005\u5007\u5013\u5022\u5030\u501B\u4FF5\u4FF4\u5033\u5037\u502C\u4FF6\u4FF7\u5017\u501C\u5020\u5027\u5035\u502F\u5031\u500E\u515A\u5194\u5193\u51CA\u51C4\u51C5\u51C8\u51CE\u5261\u525A\u5252\u525E\u525F\u5255\u5262\u52CD\u530E\u539E\u5526\u54E2\u5517\u5512\u54E7\u54F3\u54E4\u551A\u54FF\u5504\u5508\u54EB\u5511\u5505\u54F1"],
      ["d140", "\u550A\u54FB\u54F7\u54F8\u54E0\u550E\u5503\u550B\u5701\u5702\u57CC\u5832\u57D5\u57D2\u57BA\u57C6\u57BD\u57BC\u57B8\u57B6\u57BF\u57C7\u57D0\u57B9\u57C1\u590E\u594A\u5A19\u5A16\u5A2D\u5A2E\u5A15\u5A0F\u5A17\u5A0A\u5A1E\u5A33\u5B6C\u5BA7\u5BAD\u5BAC\u5C03\u5C56\u5C54\u5CEC\u5CFF\u5CEE\u5CF1\u5CF7\u5D00\u5CF9\u5E29\u5E28\u5EA8\u5EAE\u5EAA\u5EAC\u5F33\u5F30\u5F67\u605D\u605A\u6067"],
      ["d1a1", "\u6041\u60A2\u6088\u6080\u6092\u6081\u609D\u6083\u6095\u609B\u6097\u6087\u609C\u608E\u6219\u6246\u62F2\u6310\u6356\u632C\u6344\u6345\u6336\u6343\u63E4\u6339\u634B\u634A\u633C\u6329\u6341\u6334\u6358\u6354\u6359\u632D\u6347\u6333\u635A\u6351\u6338\u6357\u6340\u6348\u654A\u6546\u65C6\u65C3\u65C4\u65C2\u664A\u665F\u6647\u6651\u6712\u6713\u681F\u681A\u6849\u6832\u6833\u683B\u684B\u684F\u6816\u6831\u681C\u6835\u682B\u682D\u682F\u684E\u6844\u6834\u681D\u6812\u6814\u6826\u6828\u682E\u684D\u683A\u6825\u6820\u6B2C\u6B2F\u6B2D\u6B31\u6B34\u6B6D\u8082\u6B88\u6BE6\u6BE4"],
      ["d240", "\u6BE8\u6BE3\u6BE2\u6BE7\u6C25\u6D7A\u6D63\u6D64\u6D76\u6D0D\u6D61\u6D92\u6D58\u6D62\u6D6D\u6D6F\u6D91\u6D8D\u6DEF\u6D7F\u6D86\u6D5E\u6D67\u6D60\u6D97\u6D70\u6D7C\u6D5F\u6D82\u6D98\u6D2F\u6D68\u6D8B\u6D7E\u6D80\u6D84\u6D16\u6D83\u6D7B\u6D7D\u6D75\u6D90\u70DC\u70D3\u70D1\u70DD\u70CB\u7F39\u70E2\u70D7\u70D2\u70DE\u70E0\u70D4\u70CD\u70C5\u70C6\u70C7\u70DA\u70CE\u70E1\u7242\u7278"],
      ["d2a1", "\u7277\u7276\u7300\u72FA\u72F4\u72FE\u72F6\u72F3\u72FB\u7301\u73D3\u73D9\u73E5\u73D6\u73BC\u73E7\u73E3\u73E9\u73DC\u73D2\u73DB\u73D4\u73DD\u73DA\u73D7\u73D8\u73E8\u74DE\u74DF\u74F4\u74F5\u7521\u755B\u755F\u75B0\u75C1\u75BB\u75C4\u75C0\u75BF\u75B6\u75BA\u768A\u76C9\u771D\u771B\u7710\u7713\u7712\u7723\u7711\u7715\u7719\u771A\u7722\u7727\u7823\u782C\u7822\u7835\u782F\u7828\u782E\u782B\u7821\u7829\u7833\u782A\u7831\u7954\u795B\u794F\u795C\u7953\u7952\u7951\u79EB\u79EC\u79E0\u79EE\u79ED\u79EA\u79DC\u79DE\u79DD\u7A86\u7A89\u7A85\u7A8B\u7A8C\u7A8A\u7A87\u7AD8\u7B10"],
      ["d340", "\u7B04\u7B13\u7B05\u7B0F\u7B08\u7B0A\u7B0E\u7B09\u7B12\u7C84\u7C91\u7C8A\u7C8C\u7C88\u7C8D\u7C85\u7D1E\u7D1D\u7D11\u7D0E\u7D18\u7D16\u7D13\u7D1F\u7D12\u7D0F\u7D0C\u7F5C\u7F61\u7F5E\u7F60\u7F5D\u7F5B\u7F96\u7F92\u7FC3\u7FC2\u7FC0\u8016\u803E\u8039\u80FA\u80F2\u80F9\u80F5\u8101\u80FB\u8100\u8201\u822F\u8225\u8333\u832D\u8344\u8319\u8351\u8325\u8356\u833F\u8341\u8326\u831C\u8322"],
      ["d3a1", "\u8342\u834E\u831B\u832A\u8308\u833C\u834D\u8316\u8324\u8320\u8337\u832F\u8329\u8347\u8345\u834C\u8353\u831E\u832C\u834B\u8327\u8348\u8653\u8652\u86A2\u86A8\u8696\u868D\u8691\u869E\u8687\u8697\u8686\u868B\u869A\u8685\u86A5\u8699\u86A1\u86A7\u8695\u8698\u868E\u869D\u8690\u8694\u8843\u8844\u886D\u8875\u8876\u8872\u8880\u8871\u887F\u886F\u8883\u887E\u8874\u887C\u8A12\u8C47\u8C57\u8C7B\u8CA4\u8CA3\u8D76\u8D78\u8DB5\u8DB7\u8DB6\u8ED1\u8ED3\u8FFE\u8FF5\u9002\u8FFF\u8FFB\u9004\u8FFC\u8FF6\u90D6\u90E0\u90D9\u90DA\u90E3\u90DF\u90E5\u90D8\u90DB\u90D7\u90DC\u90E4\u9150"],
      ["d440", "\u914E\u914F\u91D5\u91E2\u91DA\u965C\u965F\u96BC\u98E3\u9ADF\u9B2F\u4E7F\u5070\u506A\u5061\u505E\u5060\u5053\u504B\u505D\u5072\u5048\u504D\u5041\u505B\u504A\u5062\u5015\u5045\u505F\u5069\u506B\u5063\u5064\u5046\u5040\u506E\u5073\u5057\u5051\u51D0\u526B\u526D\u526C\u526E\u52D6\u52D3\u532D\u539C\u5575\u5576\u553C\u554D\u5550\u5534\u552A\u5551\u5562\u5536\u5535\u5530\u5552\u5545"],
      ["d4a1", "\u550C\u5532\u5565\u554E\u5539\u5548\u552D\u553B\u5540\u554B\u570A\u5707\u57FB\u5814\u57E2\u57F6\u57DC\u57F4\u5800\u57ED\u57FD\u5808\u57F8\u580B\u57F3\u57CF\u5807\u57EE\u57E3\u57F2\u57E5\u57EC\u57E1\u580E\u57FC\u5810\u57E7\u5801\u580C\u57F1\u57E9\u57F0\u580D\u5804\u595C\u5A60\u5A58\u5A55\u5A67\u5A5E\u5A38\u5A35\u5A6D\u5A50\u5A5F\u5A65\u5A6C\u5A53\u5A64\u5A57\u5A43\u5A5D\u5A52\u5A44\u5A5B\u5A48\u5A8E\u5A3E\u5A4D\u5A39\u5A4C\u5A70\u5A69\u5A47\u5A51\u5A56\u5A42\u5A5C\u5B72\u5B6E\u5BC1\u5BC0\u5C59\u5D1E\u5D0B\u5D1D\u5D1A\u5D20\u5D0C\u5D28\u5D0D\u5D26\u5D25\u5D0F"],
      ["d540", "\u5D30\u5D12\u5D23\u5D1F\u5D2E\u5E3E\u5E34\u5EB1\u5EB4\u5EB9\u5EB2\u5EB3\u5F36\u5F38\u5F9B\u5F96\u5F9F\u608A\u6090\u6086\u60BE\u60B0\u60BA\u60D3\u60D4\u60CF\u60E4\u60D9\u60DD\u60C8\u60B1\u60DB\u60B7\u60CA\u60BF\u60C3\u60CD\u60C0\u6332\u6365\u638A\u6382\u637D\u63BD\u639E\u63AD\u639D\u6397\u63AB\u638E\u636F\u6387\u6390\u636E\u63AF\u6375\u639C\u636D\u63AE\u637C\u63A4\u633B\u639F"],
      ["d5a1", "\u6378\u6385\u6381\u6391\u638D\u6370\u6553\u65CD\u6665\u6661\u665B\u6659\u665C\u6662\u6718\u6879\u6887\u6890\u689C\u686D\u686E\u68AE\u68AB\u6956\u686F\u68A3\u68AC\u68A9\u6875\u6874\u68B2\u688F\u6877\u6892\u687C\u686B\u6872\u68AA\u6880\u6871\u687E\u689B\u6896\u688B\u68A0\u6889\u68A4\u6878\u687B\u6891\u688C\u688A\u687D\u6B36\u6B33\u6B37\u6B38\u6B91\u6B8F\u6B8D\u6B8E\u6B8C\u6C2A\u6DC0\u6DAB\u6DB4\u6DB3\u6E74\u6DAC\u6DE9\u6DE2\u6DB7\u6DF6\u6DD4\u6E00\u6DC8\u6DE0\u6DDF\u6DD6\u6DBE\u6DE5\u6DDC\u6DDD\u6DDB\u6DF4\u6DCA\u6DBD\u6DED\u6DF0\u6DBA\u6DD5\u6DC2\u6DCF\u6DC9"],
      ["d640", "\u6DD0\u6DF2\u6DD3\u6DFD\u6DD7\u6DCD\u6DE3\u6DBB\u70FA\u710D\u70F7\u7117\u70F4\u710C\u70F0\u7104\u70F3\u7110\u70FC\u70FF\u7106\u7113\u7100\u70F8\u70F6\u710B\u7102\u710E\u727E\u727B\u727C\u727F\u731D\u7317\u7307\u7311\u7318\u730A\u7308\u72FF\u730F\u731E\u7388\u73F6\u73F8\u73F5\u7404\u7401\u73FD\u7407\u7400\u73FA\u73FC\u73FF\u740C\u740B\u73F4\u7408\u7564\u7563\u75CE\u75D2\u75CF"],
      ["d6a1", "\u75CB\u75CC\u75D1\u75D0\u768F\u7689\u76D3\u7739\u772F\u772D\u7731\u7732\u7734\u7733\u773D\u7725\u773B\u7735\u7848\u7852\u7849\u784D\u784A\u784C\u7826\u7845\u7850\u7964\u7967\u7969\u796A\u7963\u796B\u7961\u79BB\u79FA\u79F8\u79F6\u79F7\u7A8F\u7A94\u7A90\u7B35\u7B47\u7B34\u7B25\u7B30\u7B22\u7B24\u7B33\u7B18\u7B2A\u7B1D\u7B31\u7B2B\u7B2D\u7B2F\u7B32\u7B38\u7B1A\u7B23\u7C94\u7C98\u7C96\u7CA3\u7D35\u7D3D\u7D38\u7D36\u7D3A\u7D45\u7D2C\u7D29\u7D41\u7D47\u7D3E\u7D3F\u7D4A\u7D3B\u7D28\u7F63\u7F95\u7F9C\u7F9D\u7F9B\u7FCA\u7FCB\u7FCD\u7FD0\u7FD1\u7FC7\u7FCF\u7FC9\u801F"],
      ["d740", "\u801E\u801B\u8047\u8043\u8048\u8118\u8125\u8119\u811B\u812D\u811F\u812C\u811E\u8121\u8115\u8127\u811D\u8122\u8211\u8238\u8233\u823A\u8234\u8232\u8274\u8390\u83A3\u83A8\u838D\u837A\u8373\u83A4\u8374\u838F\u8381\u8395\u8399\u8375\u8394\u83A9\u837D\u8383\u838C\u839D\u839B\u83AA\u838B\u837E\u83A5\u83AF\u8388\u8397\u83B0\u837F\u83A6\u8387\u83AE\u8376\u839A\u8659\u8656\u86BF\u86B7"],
      ["d7a1", "\u86C2\u86C1\u86C5\u86BA\u86B0\u86C8\u86B9\u86B3\u86B8\u86CC\u86B4\u86BB\u86BC\u86C3\u86BD\u86BE\u8852\u8889\u8895\u88A8\u88A2\u88AA\u889A\u8891\u88A1\u889F\u8898\u88A7\u8899\u889B\u8897\u88A4\u88AC\u888C\u8893\u888E\u8982\u89D6\u89D9\u89D5\u8A30\u8A27\u8A2C\u8A1E\u8C39\u8C3B\u8C5C\u8C5D\u8C7D\u8CA5\u8D7D\u8D7B\u8D79\u8DBC\u8DC2\u8DB9\u8DBF\u8DC1\u8ED8\u8EDE\u8EDD\u8EDC\u8ED7\u8EE0\u8EE1\u9024\u900B\u9011\u901C\u900C\u9021\u90EF\u90EA\u90F0\u90F4\u90F2\u90F3\u90D4\u90EB\u90EC\u90E9\u9156\u9158\u915A\u9153\u9155\u91EC\u91F4\u91F1\u91F3\u91F8\u91E4\u91F9\u91EA"],
      ["d840", "\u91EB\u91F7\u91E8\u91EE\u957A\u9586\u9588\u967C\u966D\u966B\u9671\u966F\u96BF\u976A\u9804\u98E5\u9997\u509B\u5095\u5094\u509E\u508B\u50A3\u5083\u508C\u508E\u509D\u5068\u509C\u5092\u5082\u5087\u515F\u51D4\u5312\u5311\u53A4\u53A7\u5591\u55A8\u55A5\u55AD\u5577\u5645\u55A2\u5593\u5588\u558F\u55B5\u5581\u55A3\u5592\u55A4\u557D\u558C\u55A6\u557F\u5595\u55A1\u558E\u570C\u5829\u5837"],
      ["d8a1", "\u5819\u581E\u5827\u5823\u5828\u57F5\u5848\u5825\u581C\u581B\u5833\u583F\u5836\u582E\u5839\u5838\u582D\u582C\u583B\u5961\u5AAF\u5A94\u5A9F\u5A7A\u5AA2\u5A9E\u5A78\u5AA6\u5A7C\u5AA5\u5AAC\u5A95\u5AAE\u5A37\u5A84\u5A8A\u5A97\u5A83\u5A8B\u5AA9\u5A7B\u5A7D\u5A8C\u5A9C\u5A8F\u5A93\u5A9D\u5BEA\u5BCD\u5BCB\u5BD4\u5BD1\u5BCA\u5BCE\u5C0C\u5C30\u5D37\u5D43\u5D6B\u5D41\u5D4B\u5D3F\u5D35\u5D51\u5D4E\u5D55\u5D33\u5D3A\u5D52\u5D3D\u5D31\u5D59\u5D42\u5D39\u5D49\u5D38\u5D3C\u5D32\u5D36\u5D40\u5D45\u5E44\u5E41\u5F58\u5FA6\u5FA5\u5FAB\u60C9\u60B9\u60CC\u60E2\u60CE\u60C4\u6114"],
      ["d940", "\u60F2\u610A\u6116\u6105\u60F5\u6113\u60F8\u60FC\u60FE\u60C1\u6103\u6118\u611D\u6110\u60FF\u6104\u610B\u624A\u6394\u63B1\u63B0\u63CE\u63E5\u63E8\u63EF\u63C3\u649D\u63F3\u63CA\u63E0\u63F6\u63D5\u63F2\u63F5\u6461\u63DF\u63BE\u63DD\u63DC\u63C4\u63D8\u63D3\u63C2\u63C7\u63CC\u63CB\u63C8\u63F0\u63D7\u63D9\u6532\u6567\u656A\u6564\u655C\u6568\u6565\u658C\u659D\u659E\u65AE\u65D0\u65D2"],
      ["d9a1", "\u667C\u666C\u667B\u6680\u6671\u6679\u666A\u6672\u6701\u690C\u68D3\u6904\u68DC\u692A\u68EC\u68EA\u68F1\u690F\u68D6\u68F7\u68EB\u68E4\u68F6\u6913\u6910\u68F3\u68E1\u6907\u68CC\u6908\u6970\u68B4\u6911\u68EF\u68C6\u6914\u68F8\u68D0\u68FD\u68FC\u68E8\u690B\u690A\u6917\u68CE\u68C8\u68DD\u68DE\u68E6\u68F4\u68D1\u6906\u68D4\u68E9\u6915\u6925\u68C7\u6B39\u6B3B\u6B3F\u6B3C\u6B94\u6B97\u6B99\u6B95\u6BBD\u6BF0\u6BF2\u6BF3\u6C30\u6DFC\u6E46\u6E47\u6E1F\u6E49\u6E88\u6E3C\u6E3D\u6E45\u6E62\u6E2B\u6E3F\u6E41\u6E5D\u6E73\u6E1C\u6E33\u6E4B\u6E40\u6E51\u6E3B\u6E03\u6E2E\u6E5E"],
      ["da40", "\u6E68\u6E5C\u6E61\u6E31\u6E28\u6E60\u6E71\u6E6B\u6E39\u6E22\u6E30\u6E53\u6E65\u6E27\u6E78\u6E64\u6E77\u6E55\u6E79\u6E52\u6E66\u6E35\u6E36\u6E5A\u7120\u711E\u712F\u70FB\u712E\u7131\u7123\u7125\u7122\u7132\u711F\u7128\u713A\u711B\u724B\u725A\u7288\u7289\u7286\u7285\u728B\u7312\u730B\u7330\u7322\u7331\u7333\u7327\u7332\u732D\u7326\u7323\u7335\u730C\u742E\u742C\u7430\u742B\u7416"],
      ["daa1", "\u741A\u7421\u742D\u7431\u7424\u7423\u741D\u7429\u7420\u7432\u74FB\u752F\u756F\u756C\u75E7\u75DA\u75E1\u75E6\u75DD\u75DF\u75E4\u75D7\u7695\u7692\u76DA\u7746\u7747\u7744\u774D\u7745\u774A\u774E\u774B\u774C\u77DE\u77EC\u7860\u7864\u7865\u785C\u786D\u7871\u786A\u786E\u7870\u7869\u7868\u785E\u7862\u7974\u7973\u7972\u7970\u7A02\u7A0A\u7A03\u7A0C\u7A04\u7A99\u7AE6\u7AE4\u7B4A\u7B3B\u7B44\u7B48\u7B4C\u7B4E\u7B40\u7B58\u7B45\u7CA2\u7C9E\u7CA8\u7CA1\u7D58\u7D6F\u7D63\u7D53\u7D56\u7D67\u7D6A\u7D4F\u7D6D\u7D5C\u7D6B\u7D52\u7D54\u7D69\u7D51\u7D5F\u7D4E\u7F3E\u7F3F\u7F65"],
      ["db40", "\u7F66\u7FA2\u7FA0\u7FA1\u7FD7\u8051\u804F\u8050\u80FE\u80D4\u8143\u814A\u8152\u814F\u8147\u813D\u814D\u813A\u81E6\u81EE\u81F7\u81F8\u81F9\u8204\u823C\u823D\u823F\u8275\u833B\u83CF\u83F9\u8423\u83C0\u83E8\u8412\u83E7\u83E4\u83FC\u83F6\u8410\u83C6\u83C8\u83EB\u83E3\u83BF\u8401\u83DD\u83E5\u83D8\u83FF\u83E1\u83CB\u83CE\u83D6\u83F5\u83C9\u8409\u840F\u83DE\u8411\u8406\u83C2\u83F3"],
      ["dba1", "\u83D5\u83FA\u83C7\u83D1\u83EA\u8413\u83C3\u83EC\u83EE\u83C4\u83FB\u83D7\u83E2\u841B\u83DB\u83FE\u86D8\u86E2\u86E6\u86D3\u86E3\u86DA\u86EA\u86DD\u86EB\u86DC\u86EC\u86E9\u86D7\u86E8\u86D1\u8848\u8856\u8855\u88BA\u88D7\u88B9\u88B8\u88C0\u88BE\u88B6\u88BC\u88B7\u88BD\u88B2\u8901\u88C9\u8995\u8998\u8997\u89DD\u89DA\u89DB\u8A4E\u8A4D\u8A39\u8A59\u8A40\u8A57\u8A58\u8A44\u8A45\u8A52\u8A48\u8A51\u8A4A\u8A4C\u8A4F\u8C5F\u8C81\u8C80\u8CBA\u8CBE\u8CB0\u8CB9\u8CB5\u8D84\u8D80\u8D89\u8DD8\u8DD3\u8DCD\u8DC7\u8DD6\u8DDC\u8DCF\u8DD5\u8DD9\u8DC8\u8DD7\u8DC5\u8EEF\u8EF7\u8EFA"],
      ["dc40", "\u8EF9\u8EE6\u8EEE\u8EE5\u8EF5\u8EE7\u8EE8\u8EF6\u8EEB\u8EF1\u8EEC\u8EF4\u8EE9\u902D\u9034\u902F\u9106\u912C\u9104\u90FF\u90FC\u9108\u90F9\u90FB\u9101\u9100\u9107\u9105\u9103\u9161\u9164\u915F\u9162\u9160\u9201\u920A\u9225\u9203\u921A\u9226\u920F\u920C\u9200\u9212\u91FF\u91FD\u9206\u9204\u9227\u9202\u921C\u9224\u9219\u9217\u9205\u9216\u957B\u958D\u958C\u9590\u9687\u967E\u9688"],
      ["dca1", "\u9689\u9683\u9680\u96C2\u96C8\u96C3\u96F1\u96F0\u976C\u9770\u976E\u9807\u98A9\u98EB\u9CE6\u9EF9\u4E83\u4E84\u4EB6\u50BD\u50BF\u50C6\u50AE\u50C4\u50CA\u50B4\u50C8\u50C2\u50B0\u50C1\u50BA\u50B1\u50CB\u50C9\u50B6\u50B8\u51D7\u527A\u5278\u527B\u527C\u55C3\u55DB\u55CC\u55D0\u55CB\u55CA\u55DD\u55C0\u55D4\u55C4\u55E9\u55BF\u55D2\u558D\u55CF\u55D5\u55E2\u55D6\u55C8\u55F2\u55CD\u55D9\u55C2\u5714\u5853\u5868\u5864\u584F\u584D\u5849\u586F\u5855\u584E\u585D\u5859\u5865\u585B\u583D\u5863\u5871\u58FC\u5AC7\u5AC4\u5ACB\u5ABA\u5AB8\u5AB1\u5AB5\u5AB0\u5ABF\u5AC8\u5ABB\u5AC6"],
      ["dd40", "\u5AB7\u5AC0\u5ACA\u5AB4\u5AB6\u5ACD\u5AB9\u5A90\u5BD6\u5BD8\u5BD9\u5C1F\u5C33\u5D71\u5D63\u5D4A\u5D65\u5D72\u5D6C\u5D5E\u5D68\u5D67\u5D62\u5DF0\u5E4F\u5E4E\u5E4A\u5E4D\u5E4B\u5EC5\u5ECC\u5EC6\u5ECB\u5EC7\u5F40\u5FAF\u5FAD\u60F7\u6149\u614A\u612B\u6145\u6136\u6132\u612E\u6146\u612F\u614F\u6129\u6140\u6220\u9168\u6223\u6225\u6224\u63C5\u63F1\u63EB\u6410\u6412\u6409\u6420\u6424"],
      ["dda1", "\u6433\u6443\u641F\u6415\u6418\u6439\u6437\u6422\u6423\u640C\u6426\u6430\u6428\u6441\u6435\u642F\u640A\u641A\u6440\u6425\u6427\u640B\u63E7\u641B\u642E\u6421\u640E\u656F\u6592\u65D3\u6686\u668C\u6695\u6690\u668B\u668A\u6699\u6694\u6678\u6720\u6966\u695F\u6938\u694E\u6962\u6971\u693F\u6945\u696A\u6939\u6942\u6957\u6959\u697A\u6948\u6949\u6935\u696C\u6933\u693D\u6965\u68F0\u6978\u6934\u6969\u6940\u696F\u6944\u6976\u6958\u6941\u6974\u694C\u693B\u694B\u6937\u695C\u694F\u6951\u6932\u6952\u692F\u697B\u693C\u6B46\u6B45\u6B43\u6B42\u6B48\u6B41\u6B9B\uFA0D\u6BFB\u6BFC"],
      ["de40", "\u6BF9\u6BF7\u6BF8\u6E9B\u6ED6\u6EC8\u6E8F\u6EC0\u6E9F\u6E93\u6E94\u6EA0\u6EB1\u6EB9\u6EC6\u6ED2\u6EBD\u6EC1\u6E9E\u6EC9\u6EB7\u6EB0\u6ECD\u6EA6\u6ECF\u6EB2\u6EBE\u6EC3\u6EDC\u6ED8\u6E99\u6E92\u6E8E\u6E8D\u6EA4\u6EA1\u6EBF\u6EB3\u6ED0\u6ECA\u6E97\u6EAE\u6EA3\u7147\u7154\u7152\u7163\u7160\u7141\u715D\u7162\u7172\u7178\u716A\u7161\u7142\u7158\u7143\u714B\u7170\u715F\u7150\u7153"],
      ["dea1", "\u7144\u714D\u715A\u724F\u728D\u728C\u7291\u7290\u728E\u733C\u7342\u733B\u733A\u7340\u734A\u7349\u7444\u744A\u744B\u7452\u7451\u7457\u7440\u744F\u7450\u744E\u7442\u7446\u744D\u7454\u74E1\u74FF\u74FE\u74FD\u751D\u7579\u7577\u6983\u75EF\u760F\u7603\u75F7\u75FE\u75FC\u75F9\u75F8\u7610\u75FB\u75F6\u75ED\u75F5\u75FD\u7699\u76B5\u76DD\u7755\u775F\u7760\u7752\u7756\u775A\u7769\u7767\u7754\u7759\u776D\u77E0\u7887\u789A\u7894\u788F\u7884\u7895\u7885\u7886\u78A1\u7883\u7879\u7899\u7880\u7896\u787B\u797C\u7982\u797D\u7979\u7A11\u7A18\u7A19\u7A12\u7A17\u7A15\u7A22\u7A13"],
      ["df40", "\u7A1B\u7A10\u7AA3\u7AA2\u7A9E\u7AEB\u7B66\u7B64\u7B6D\u7B74\u7B69\u7B72\u7B65\u7B73\u7B71\u7B70\u7B61\u7B78\u7B76\u7B63\u7CB2\u7CB4\u7CAF\u7D88\u7D86\u7D80\u7D8D\u7D7F\u7D85\u7D7A\u7D8E\u7D7B\u7D83\u7D7C\u7D8C\u7D94\u7D84\u7D7D\u7D92\u7F6D\u7F6B\u7F67\u7F68\u7F6C\u7FA6\u7FA5\u7FA7\u7FDB\u7FDC\u8021\u8164\u8160\u8177\u815C\u8169\u815B\u8162\u8172\u6721\u815E\u8176\u8167\u816F"],
      ["dfa1", "\u8144\u8161\u821D\u8249\u8244\u8240\u8242\u8245\u84F1\u843F\u8456\u8476\u8479\u848F\u848D\u8465\u8451\u8440\u8486\u8467\u8430\u844D\u847D\u845A\u8459\u8474\u8473\u845D\u8507\u845E\u8437\u843A\u8434\u847A\u8443\u8478\u8432\u8445\u8429\u83D9\u844B\u842F\u8442\u842D\u845F\u8470\u8439\u844E\u844C\u8452\u846F\u84C5\u848E\u843B\u8447\u8436\u8433\u8468\u847E\u8444\u842B\u8460\u8454\u846E\u8450\u870B\u8704\u86F7\u870C\u86FA\u86D6\u86F5\u874D\u86F8\u870E\u8709\u8701\u86F6\u870D\u8705\u88D6\u88CB\u88CD\u88CE\u88DE\u88DB\u88DA\u88CC\u88D0\u8985\u899B\u89DF\u89E5\u89E4"],
      ["e040", "\u89E1\u89E0\u89E2\u89DC\u89E6\u8A76\u8A86\u8A7F\u8A61\u8A3F\u8A77\u8A82\u8A84\u8A75\u8A83\u8A81\u8A74\u8A7A\u8C3C\u8C4B\u8C4A\u8C65\u8C64\u8C66\u8C86\u8C84\u8C85\u8CCC\u8D68\u8D69\u8D91\u8D8C\u8D8E\u8D8F\u8D8D\u8D93\u8D94\u8D90\u8D92\u8DF0\u8DE0\u8DEC\u8DF1\u8DEE\u8DD0\u8DE9\u8DE3\u8DE2\u8DE7\u8DF2\u8DEB\u8DF4\u8F06\u8EFF\u8F01\u8F00\u8F05\u8F07\u8F08\u8F02\u8F0B\u9052\u903F"],
      ["e0a1", "\u9044\u9049\u903D\u9110\u910D\u910F\u9111\u9116\u9114\u910B\u910E\u916E\u916F\u9248\u9252\u9230\u923A\u9266\u9233\u9265\u925E\u9283\u922E\u924A\u9246\u926D\u926C\u924F\u9260\u9267\u926F\u9236\u9261\u9270\u9231\u9254\u9263\u9250\u9272\u924E\u9253\u924C\u9256\u9232\u959F\u959C\u959E\u959B\u9692\u9693\u9691\u9697\u96CE\u96FA\u96FD\u96F8\u96F5\u9773\u9777\u9778\u9772\u980F\u980D\u980E\u98AC\u98F6\u98F9\u99AF\u99B2\u99B0\u99B5\u9AAD\u9AAB\u9B5B\u9CEA\u9CED\u9CE7\u9E80\u9EFD\u50E6\u50D4\u50D7\u50E8\u50F3\u50DB\u50EA\u50DD\u50E4\u50D3\u50EC\u50F0\u50EF\u50E3\u50E0"],
      ["e140", "\u51D8\u5280\u5281\u52E9\u52EB\u5330\u53AC\u5627\u5615\u560C\u5612\u55FC\u560F\u561C\u5601\u5613\u5602\u55FA\u561D\u5604\u55FF\u55F9\u5889\u587C\u5890\u5898\u5886\u5881\u587F\u5874\u588B\u587A\u5887\u5891\u588E\u5876\u5882\u5888\u587B\u5894\u588F\u58FE\u596B\u5ADC\u5AEE\u5AE5\u5AD5\u5AEA\u5ADA\u5AED\u5AEB\u5AF3\u5AE2\u5AE0\u5ADB\u5AEC\u5ADE\u5ADD\u5AD9\u5AE8\u5ADF\u5B77\u5BE0"],
      ["e1a1", "\u5BE3\u5C63\u5D82\u5D80\u5D7D\u5D86\u5D7A\u5D81\u5D77\u5D8A\u5D89\u5D88\u5D7E\u5D7C\u5D8D\u5D79\u5D7F\u5E58\u5E59\u5E53\u5ED8\u5ED1\u5ED7\u5ECE\u5EDC\u5ED5\u5ED9\u5ED2\u5ED4\u5F44\u5F43\u5F6F\u5FB6\u612C\u6128\u6141\u615E\u6171\u6173\u6152\u6153\u6172\u616C\u6180\u6174\u6154\u617A\u615B\u6165\u613B\u616A\u6161\u6156\u6229\u6227\u622B\u642B\u644D\u645B\u645D\u6474\u6476\u6472\u6473\u647D\u6475\u6466\u64A6\u644E\u6482\u645E\u645C\u644B\u6453\u6460\u6450\u647F\u643F\u646C\u646B\u6459\u6465\u6477\u6573\u65A0\u66A1\u66A0\u669F\u6705\u6704\u6722\u69B1\u69B6\u69C9"],
      ["e240", "\u69A0\u69CE\u6996\u69B0\u69AC\u69BC\u6991\u6999\u698E\u69A7\u698D\u69A9\u69BE\u69AF\u69BF\u69C4\u69BD\u69A4\u69D4\u69B9\u69CA\u699A\u69CF\u69B3\u6993\u69AA\u69A1\u699E\u69D9\u6997\u6990\u69C2\u69B5\u69A5\u69C6\u6B4A\u6B4D\u6B4B\u6B9E\u6B9F\u6BA0\u6BC3\u6BC4\u6BFE\u6ECE\u6EF5\u6EF1\u6F03\u6F25\u6EF8\u6F37\u6EFB\u6F2E\u6F09\u6F4E\u6F19\u6F1A\u6F27\u6F18\u6F3B\u6F12\u6EED\u6F0A"],
      ["e2a1", "\u6F36\u6F73\u6EF9\u6EEE\u6F2D\u6F40\u6F30\u6F3C\u6F35\u6EEB\u6F07\u6F0E\u6F43\u6F05\u6EFD\u6EF6\u6F39\u6F1C\u6EFC\u6F3A\u6F1F\u6F0D\u6F1E\u6F08\u6F21\u7187\u7190\u7189\u7180\u7185\u7182\u718F\u717B\u7186\u7181\u7197\u7244\u7253\u7297\u7295\u7293\u7343\u734D\u7351\u734C\u7462\u7473\u7471\u7475\u7472\u7467\u746E\u7500\u7502\u7503\u757D\u7590\u7616\u7608\u760C\u7615\u7611\u760A\u7614\u76B8\u7781\u777C\u7785\u7782\u776E\u7780\u776F\u777E\u7783\u78B2\u78AA\u78B4\u78AD\u78A8\u787E\u78AB\u789E\u78A5\u78A0\u78AC\u78A2\u78A4\u7998\u798A\u798B\u7996\u7995\u7994\u7993"],
      ["e340", "\u7997\u7988\u7992\u7990\u7A2B\u7A4A\u7A30\u7A2F\u7A28\u7A26\u7AA8\u7AAB\u7AAC\u7AEE\u7B88\u7B9C\u7B8A\u7B91\u7B90\u7B96\u7B8D\u7B8C\u7B9B\u7B8E\u7B85\u7B98\u5284\u7B99\u7BA4\u7B82\u7CBB\u7CBF\u7CBC\u7CBA\u7DA7\u7DB7\u7DC2\u7DA3\u7DAA\u7DC1\u7DC0\u7DC5\u7D9D\u7DCE\u7DC4\u7DC6\u7DCB\u7DCC\u7DAF\u7DB9\u7D96\u7DBC\u7D9F\u7DA6\u7DAE\u7DA9\u7DA1\u7DC9\u7F73\u7FE2\u7FE3\u7FE5\u7FDE"],
      ["e3a1", "\u8024\u805D\u805C\u8189\u8186\u8183\u8187\u818D\u818C\u818B\u8215\u8497\u84A4\u84A1\u849F\u84BA\u84CE\u84C2\u84AC\u84AE\u84AB\u84B9\u84B4\u84C1\u84CD\u84AA\u849A\u84B1\u84D0\u849D\u84A7\u84BB\u84A2\u8494\u84C7\u84CC\u849B\u84A9\u84AF\u84A8\u84D6\u8498\u84B6\u84CF\u84A0\u84D7\u84D4\u84D2\u84DB\u84B0\u8491\u8661\u8733\u8723\u8728\u876B\u8740\u872E\u871E\u8721\u8719\u871B\u8743\u872C\u8741\u873E\u8746\u8720\u8732\u872A\u872D\u873C\u8712\u873A\u8731\u8735\u8742\u8726\u8727\u8738\u8724\u871A\u8730\u8711\u88F7\u88E7\u88F1\u88F2\u88FA\u88FE\u88EE\u88FC\u88F6\u88FB"],
      ["e440", "\u88F0\u88EC\u88EB\u899D\u89A1\u899F\u899E\u89E9\u89EB\u89E8\u8AAB\u8A99\u8A8B\u8A92\u8A8F\u8A96\u8C3D\u8C68\u8C69\u8CD5\u8CCF\u8CD7\u8D96\u8E09\u8E02\u8DFF\u8E0D\u8DFD\u8E0A\u8E03\u8E07\u8E06\u8E05\u8DFE\u8E00\u8E04\u8F10\u8F11\u8F0E\u8F0D\u9123\u911C\u9120\u9122\u911F\u911D\u911A\u9124\u9121\u911B\u917A\u9172\u9179\u9173\u92A5\u92A4\u9276\u929B\u927A\u92A0\u9294\u92AA\u928D"],
      ["e4a1", "\u92A6\u929A\u92AB\u9279\u9297\u927F\u92A3\u92EE\u928E\u9282\u9295\u92A2\u927D\u9288\u92A1\u928A\u9286\u928C\u9299\u92A7\u927E\u9287\u92A9\u929D\u928B\u922D\u969E\u96A1\u96FF\u9758\u977D\u977A\u977E\u9783\u9780\u9782\u977B\u9784\u9781\u977F\u97CE\u97CD\u9816\u98AD\u98AE\u9902\u9900\u9907\u999D\u999C\u99C3\u99B9\u99BB\u99BA\u99C2\u99BD\u99C7\u9AB1\u9AE3\u9AE7\u9B3E\u9B3F\u9B60\u9B61\u9B5F\u9CF1\u9CF2\u9CF5\u9EA7\u50FF\u5103\u5130\u50F8\u5106\u5107\u50F6\u50FE\u510B\u510C\u50FD\u510A\u528B\u528C\u52F1\u52EF\u5648\u5642\u564C\u5635\u5641\u564A\u5649\u5646\u5658"],
      ["e540", "\u565A\u5640\u5633\u563D\u562C\u563E\u5638\u562A\u563A\u571A\u58AB\u589D\u58B1\u58A0\u58A3\u58AF\u58AC\u58A5\u58A1\u58FF\u5AFF\u5AF4\u5AFD\u5AF7\u5AF6\u5B03\u5AF8\u5B02\u5AF9\u5B01\u5B07\u5B05\u5B0F\u5C67\u5D99\u5D97\u5D9F\u5D92\u5DA2\u5D93\u5D95\u5DA0\u5D9C\u5DA1\u5D9A\u5D9E\u5E69\u5E5D\u5E60\u5E5C\u7DF3\u5EDB\u5EDE\u5EE1\u5F49\u5FB2\u618B\u6183\u6179\u61B1\u61B0\u61A2\u6189"],
      ["e5a1", "\u619B\u6193\u61AF\u61AD\u619F\u6192\u61AA\u61A1\u618D\u6166\u61B3\u622D\u646E\u6470\u6496\u64A0\u6485\u6497\u649C\u648F\u648B\u648A\u648C\u64A3\u649F\u6468\u64B1\u6498\u6576\u657A\u6579\u657B\u65B2\u65B3\u66B5\u66B0\u66A9\u66B2\u66B7\u66AA\u66AF\u6A00\u6A06\u6A17\u69E5\u69F8\u6A15\u69F1\u69E4\u6A20\u69FF\u69EC\u69E2\u6A1B\u6A1D\u69FE\u6A27\u69F2\u69EE\u6A14\u69F7\u69E7\u6A40\u6A08\u69E6\u69FB\u6A0D\u69FC\u69EB\u6A09\u6A04\u6A18\u6A25\u6A0F\u69F6\u6A26\u6A07\u69F4\u6A16\u6B51\u6BA5\u6BA3\u6BA2\u6BA6\u6C01\u6C00\u6BFF\u6C02\u6F41\u6F26\u6F7E\u6F87\u6FC6\u6F92"],
      ["e640", "\u6F8D\u6F89\u6F8C\u6F62\u6F4F\u6F85\u6F5A\u6F96\u6F76\u6F6C\u6F82\u6F55\u6F72\u6F52\u6F50\u6F57\u6F94\u6F93\u6F5D\u6F00\u6F61\u6F6B\u6F7D\u6F67\u6F90\u6F53\u6F8B\u6F69\u6F7F\u6F95\u6F63\u6F77\u6F6A\u6F7B\u71B2\u71AF\u719B\u71B0\u71A0\u719A\u71A9\u71B5\u719D\u71A5\u719E\u71A4\u71A1\u71AA\u719C\u71A7\u71B3\u7298\u729A\u7358\u7352\u735E\u735F\u7360\u735D\u735B\u7361\u735A\u7359"],
      ["e6a1", "\u7362\u7487\u7489\u748A\u7486\u7481\u747D\u7485\u7488\u747C\u7479\u7508\u7507\u757E\u7625\u761E\u7619\u761D\u761C\u7623\u761A\u7628\u761B\u769C\u769D\u769E\u769B\u778D\u778F\u7789\u7788\u78CD\u78BB\u78CF\u78CC\u78D1\u78CE\u78D4\u78C8\u78C3\u78C4\u78C9\u799A\u79A1\u79A0\u799C\u79A2\u799B\u6B76\u7A39\u7AB2\u7AB4\u7AB3\u7BB7\u7BCB\u7BBE\u7BAC\u7BCE\u7BAF\u7BB9\u7BCA\u7BB5\u7CC5\u7CC8\u7CCC\u7CCB\u7DF7\u7DDB\u7DEA\u7DE7\u7DD7\u7DE1\u7E03\u7DFA\u7DE6\u7DF6\u7DF1\u7DF0\u7DEE\u7DDF\u7F76\u7FAC\u7FB0\u7FAD\u7FED\u7FEB\u7FEA\u7FEC\u7FE6\u7FE8\u8064\u8067\u81A3\u819F"],
      ["e740", "\u819E\u8195\u81A2\u8199\u8197\u8216\u824F\u8253\u8252\u8250\u824E\u8251\u8524\u853B\u850F\u8500\u8529\u850E\u8509\u850D\u851F\u850A\u8527\u851C\u84FB\u852B\u84FA\u8508\u850C\u84F4\u852A\u84F2\u8515\u84F7\u84EB\u84F3\u84FC\u8512\u84EA\u84E9\u8516\u84FE\u8528\u851D\u852E\u8502\u84FD\u851E\u84F6\u8531\u8526\u84E7\u84E8\u84F0\u84EF\u84F9\u8518\u8520\u8530\u850B\u8519\u852F\u8662"],
      ["e7a1", "\u8756\u8763\u8764\u8777\u87E1\u8773\u8758\u8754\u875B\u8752\u8761\u875A\u8751\u875E\u876D\u876A\u8750\u874E\u875F\u875D\u876F\u876C\u877A\u876E\u875C\u8765\u874F\u877B\u8775\u8762\u8767\u8769\u885A\u8905\u890C\u8914\u890B\u8917\u8918\u8919\u8906\u8916\u8911\u890E\u8909\u89A2\u89A4\u89A3\u89ED\u89F0\u89EC\u8ACF\u8AC6\u8AB8\u8AD3\u8AD1\u8AD4\u8AD5\u8ABB\u8AD7\u8ABE\u8AC0\u8AC5\u8AD8\u8AC3\u8ABA\u8ABD\u8AD9\u8C3E\u8C4D\u8C8F\u8CE5\u8CDF\u8CD9\u8CE8\u8CDA\u8CDD\u8CE7\u8DA0\u8D9C\u8DA1\u8D9B\u8E20\u8E23\u8E25\u8E24\u8E2E\u8E15\u8E1B\u8E16\u8E11\u8E19\u8E26\u8E27"],
      ["e840", "\u8E14\u8E12\u8E18\u8E13\u8E1C\u8E17\u8E1A\u8F2C\u8F24\u8F18\u8F1A\u8F20\u8F23\u8F16\u8F17\u9073\u9070\u906F\u9067\u906B\u912F\u912B\u9129\u912A\u9132\u9126\u912E\u9185\u9186\u918A\u9181\u9182\u9184\u9180\u92D0\u92C3\u92C4\u92C0\u92D9\u92B6\u92CF\u92F1\u92DF\u92D8\u92E9\u92D7\u92DD\u92CC\u92EF\u92C2\u92E8\u92CA\u92C8\u92CE\u92E6\u92CD\u92D5\u92C9\u92E0\u92DE\u92E7\u92D1\u92D3"],
      ["e8a1", "\u92B5\u92E1\u92C6\u92B4\u957C\u95AC\u95AB\u95AE\u95B0\u96A4\u96A2\u96D3\u9705\u9708\u9702\u975A\u978A\u978E\u9788\u97D0\u97CF\u981E\u981D\u9826\u9829\u9828\u9820\u981B\u9827\u98B2\u9908\u98FA\u9911\u9914\u9916\u9917\u9915\u99DC\u99CD\u99CF\u99D3\u99D4\u99CE\u99C9\u99D6\u99D8\u99CB\u99D7\u99CC\u9AB3\u9AEC\u9AEB\u9AF3\u9AF2\u9AF1\u9B46\u9B43\u9B67\u9B74\u9B71\u9B66\u9B76\u9B75\u9B70\u9B68\u9B64\u9B6C\u9CFC\u9CFA\u9CFD\u9CFF\u9CF7\u9D07\u9D00\u9CF9\u9CFB\u9D08\u9D05\u9D04\u9E83\u9ED3\u9F0F\u9F10\u511C\u5113\u5117\u511A\u5111\u51DE\u5334\u53E1\u5670\u5660\u566E"],
      ["e940", "\u5673\u5666\u5663\u566D\u5672\u565E\u5677\u571C\u571B\u58C8\u58BD\u58C9\u58BF\u58BA\u58C2\u58BC\u58C6\u5B17\u5B19\u5B1B\u5B21\u5B14\u5B13\u5B10\u5B16\u5B28\u5B1A\u5B20\u5B1E\u5BEF\u5DAC\u5DB1\u5DA9\u5DA7\u5DB5\u5DB0\u5DAE\u5DAA\u5DA8\u5DB2\u5DAD\u5DAF\u5DB4\u5E67\u5E68\u5E66\u5E6F\u5EE9\u5EE7\u5EE6\u5EE8\u5EE5\u5F4B\u5FBC\u619D\u61A8\u6196\u61C5\u61B4\u61C6\u61C1\u61CC\u61BA"],
      ["e9a1", "\u61BF\u61B8\u618C\u64D7\u64D6\u64D0\u64CF\u64C9\u64BD\u6489\u64C3\u64DB\u64F3\u64D9\u6533\u657F\u657C\u65A2\u66C8\u66BE\u66C0\u66CA\u66CB\u66CF\u66BD\u66BB\u66BA\u66CC\u6723\u6A34\u6A66\u6A49\u6A67\u6A32\u6A68\u6A3E\u6A5D\u6A6D\u6A76\u6A5B\u6A51\u6A28\u6A5A\u6A3B\u6A3F\u6A41\u6A6A\u6A64\u6A50\u6A4F\u6A54\u6A6F\u6A69\u6A60\u6A3C\u6A5E\u6A56\u6A55\u6A4D\u6A4E\u6A46\u6B55\u6B54\u6B56\u6BA7\u6BAA\u6BAB\u6BC8\u6BC7\u6C04\u6C03\u6C06\u6FAD\u6FCB\u6FA3\u6FC7\u6FBC\u6FCE\u6FC8\u6F5E\u6FC4\u6FBD\u6F9E\u6FCA\u6FA8\u7004\u6FA5\u6FAE\u6FBA\u6FAC\u6FAA\u6FCF\u6FBF\u6FB8"],
      ["ea40", "\u6FA2\u6FC9\u6FAB\u6FCD\u6FAF\u6FB2\u6FB0\u71C5\u71C2\u71BF\u71B8\u71D6\u71C0\u71C1\u71CB\u71D4\u71CA\u71C7\u71CF\u71BD\u71D8\u71BC\u71C6\u71DA\u71DB\u729D\u729E\u7369\u7366\u7367\u736C\u7365\u736B\u736A\u747F\u749A\u74A0\u7494\u7492\u7495\u74A1\u750B\u7580\u762F\u762D\u7631\u763D\u7633\u763C\u7635\u7632\u7630\u76BB\u76E6\u779A\u779D\u77A1\u779C\u779B\u77A2\u77A3\u7795\u7799"],
      ["eaa1", "\u7797\u78DD\u78E9\u78E5\u78EA\u78DE\u78E3\u78DB\u78E1\u78E2\u78ED\u78DF\u78E0\u79A4\u7A44\u7A48\u7A47\u7AB6\u7AB8\u7AB5\u7AB1\u7AB7\u7BDE\u7BE3\u7BE7\u7BDD\u7BD5\u7BE5\u7BDA\u7BE8\u7BF9\u7BD4\u7BEA\u7BE2\u7BDC\u7BEB\u7BD8\u7BDF\u7CD2\u7CD4\u7CD7\u7CD0\u7CD1\u7E12\u7E21\u7E17\u7E0C\u7E1F\u7E20\u7E13\u7E0E\u7E1C\u7E15\u7E1A\u7E22\u7E0B\u7E0F\u7E16\u7E0D\u7E14\u7E25\u7E24\u7F43\u7F7B\u7F7C\u7F7A\u7FB1\u7FEF\u802A\u8029\u806C\u81B1\u81A6\u81AE\u81B9\u81B5\u81AB\u81B0\u81AC\u81B4\u81B2\u81B7\u81A7\u81F2\u8255\u8256\u8257\u8556\u8545\u856B\u854D\u8553\u8561\u8558"],
      ["eb40", "\u8540\u8546\u8564\u8541\u8562\u8544\u8551\u8547\u8563\u853E\u855B\u8571\u854E\u856E\u8575\u8555\u8567\u8560\u858C\u8566\u855D\u8554\u8565\u856C\u8663\u8665\u8664\u879B\u878F\u8797\u8793\u8792\u8788\u8781\u8796\u8798\u8779\u8787\u87A3\u8785\u8790\u8791\u879D\u8784\u8794\u879C\u879A\u8789\u891E\u8926\u8930\u892D\u892E\u8927\u8931\u8922\u8929\u8923\u892F\u892C\u891F\u89F1\u8AE0"],
      ["eba1", "\u8AE2\u8AF2\u8AF4\u8AF5\u8ADD\u8B14\u8AE4\u8ADF\u8AF0\u8AC8\u8ADE\u8AE1\u8AE8\u8AFF\u8AEF\u8AFB\u8C91\u8C92\u8C90\u8CF5\u8CEE\u8CF1\u8CF0\u8CF3\u8D6C\u8D6E\u8DA5\u8DA7\u8E33\u8E3E\u8E38\u8E40\u8E45\u8E36\u8E3C\u8E3D\u8E41\u8E30\u8E3F\u8EBD\u8F36\u8F2E\u8F35\u8F32\u8F39\u8F37\u8F34\u9076\u9079\u907B\u9086\u90FA\u9133\u9135\u9136\u9193\u9190\u9191\u918D\u918F\u9327\u931E\u9308\u931F\u9306\u930F\u937A\u9338\u933C\u931B\u9323\u9312\u9301\u9346\u932D\u930E\u930D\u92CB\u931D\u92FA\u9325\u9313\u92F9\u92F7\u9334\u9302\u9324\u92FF\u9329\u9339\u9335\u932A\u9314\u930C"],
      ["ec40", "\u930B\u92FE\u9309\u9300\u92FB\u9316\u95BC\u95CD\u95BE\u95B9\u95BA\u95B6\u95BF\u95B5\u95BD\u96A9\u96D4\u970B\u9712\u9710\u9799\u9797\u9794\u97F0\u97F8\u9835\u982F\u9832\u9924\u991F\u9927\u9929\u999E\u99EE\u99EC\u99E5\u99E4\u99F0\u99E3\u99EA\u99E9\u99E7\u9AB9\u9ABF\u9AB4\u9ABB\u9AF6\u9AFA\u9AF9\u9AF7\u9B33\u9B80\u9B85\u9B87\u9B7C\u9B7E\u9B7B\u9B82\u9B93\u9B92\u9B90\u9B7A\u9B95"],
      ["eca1", "\u9B7D\u9B88\u9D25\u9D17\u9D20\u9D1E\u9D14\u9D29\u9D1D\u9D18\u9D22\u9D10\u9D19\u9D1F\u9E88\u9E86\u9E87\u9EAE\u9EAD\u9ED5\u9ED6\u9EFA\u9F12\u9F3D\u5126\u5125\u5122\u5124\u5120\u5129\u52F4\u5693\u568C\u568D\u5686\u5684\u5683\u567E\u5682\u567F\u5681\u58D6\u58D4\u58CF\u58D2\u5B2D\u5B25\u5B32\u5B23\u5B2C\u5B27\u5B26\u5B2F\u5B2E\u5B7B\u5BF1\u5BF2\u5DB7\u5E6C\u5E6A\u5FBE\u5FBB\u61C3\u61B5\u61BC\u61E7\u61E0\u61E5\u61E4\u61E8\u61DE\u64EF\u64E9\u64E3\u64EB\u64E4\u64E8\u6581\u6580\u65B6\u65DA\u66D2\u6A8D\u6A96\u6A81\u6AA5\u6A89\u6A9F\u6A9B\u6AA1\u6A9E\u6A87\u6A93\u6A8E"],
      ["ed40", "\u6A95\u6A83\u6AA8\u6AA4\u6A91\u6A7F\u6AA6\u6A9A\u6A85\u6A8C\u6A92\u6B5B\u6BAD\u6C09\u6FCC\u6FA9\u6FF4\u6FD4\u6FE3\u6FDC\u6FED\u6FE7\u6FE6\u6FDE\u6FF2\u6FDD\u6FE2\u6FE8\u71E1\u71F1\u71E8\u71F2\u71E4\u71F0\u71E2\u7373\u736E\u736F\u7497\u74B2\u74AB\u7490\u74AA\u74AD\u74B1\u74A5\u74AF\u7510\u7511\u7512\u750F\u7584\u7643\u7648\u7649\u7647\u76A4\u76E9\u77B5\u77AB\u77B2\u77B7\u77B6"],
      ["eda1", "\u77B4\u77B1\u77A8\u77F0\u78F3\u78FD\u7902\u78FB\u78FC\u78F2\u7905\u78F9\u78FE\u7904\u79AB\u79A8\u7A5C\u7A5B\u7A56\u7A58\u7A54\u7A5A\u7ABE\u7AC0\u7AC1\u7C05\u7C0F\u7BF2\u7C00\u7BFF\u7BFB\u7C0E\u7BF4\u7C0B\u7BF3\u7C02\u7C09\u7C03\u7C01\u7BF8\u7BFD\u7C06\u7BF0\u7BF1\u7C10\u7C0A\u7CE8\u7E2D\u7E3C\u7E42\u7E33\u9848\u7E38\u7E2A\u7E49\u7E40\u7E47\u7E29\u7E4C\u7E30\u7E3B\u7E36\u7E44\u7E3A\u7F45\u7F7F\u7F7E\u7F7D\u7FF4\u7FF2\u802C\u81BB\u81C4\u81CC\u81CA\u81C5\u81C7\u81BC\u81E9\u825B\u825A\u825C\u8583\u8580\u858F\u85A7\u8595\u85A0\u858B\u85A3\u857B\u85A4\u859A\u859E"],
      ["ee40", "\u8577\u857C\u8589\u85A1\u857A\u8578\u8557\u858E\u8596\u8586\u858D\u8599\u859D\u8581\u85A2\u8582\u8588\u8585\u8579\u8576\u8598\u8590\u859F\u8668\u87BE\u87AA\u87AD\u87C5\u87B0\u87AC\u87B9\u87B5\u87BC\u87AE\u87C9\u87C3\u87C2\u87CC\u87B7\u87AF\u87C4\u87CA\u87B4\u87B6\u87BF\u87B8\u87BD\u87DE\u87B2\u8935\u8933\u893C\u893E\u8941\u8952\u8937\u8942\u89AD\u89AF\u89AE\u89F2\u89F3\u8B1E"],
      ["eea1", "\u8B18\u8B16\u8B11\u8B05\u8B0B\u8B22\u8B0F\u8B12\u8B15\u8B07\u8B0D\u8B08\u8B06\u8B1C\u8B13\u8B1A\u8C4F\u8C70\u8C72\u8C71\u8C6F\u8C95\u8C94\u8CF9\u8D6F\u8E4E\u8E4D\u8E53\u8E50\u8E4C\u8E47\u8F43\u8F40\u9085\u907E\u9138\u919A\u91A2\u919B\u9199\u919F\u91A1\u919D\u91A0\u93A1\u9383\u93AF\u9364\u9356\u9347\u937C\u9358\u935C\u9376\u9349\u9350\u9351\u9360\u936D\u938F\u934C\u936A\u9379\u9357\u9355\u9352\u934F\u9371\u9377\u937B\u9361\u935E\u9363\u9367\u9380\u934E\u9359\u95C7\u95C0\u95C9\u95C3\u95C5\u95B7\u96AE\u96B0\u96AC\u9720\u971F\u9718\u971D\u9719\u979A\u97A1\u979C"],
      ["ef40", "\u979E\u979D\u97D5\u97D4\u97F1\u9841\u9844\u984A\u9849\u9845\u9843\u9925\u992B\u992C\u992A\u9933\u9932\u992F\u992D\u9931\u9930\u9998\u99A3\u99A1\u9A02\u99FA\u99F4\u99F7\u99F9\u99F8\u99F6\u99FB\u99FD\u99FE\u99FC\u9A03\u9ABE\u9AFE\u9AFD\u9B01\u9AFC\u9B48\u9B9A\u9BA8\u9B9E\u9B9B\u9BA6\u9BA1\u9BA5\u9BA4\u9B86\u9BA2\u9BA0\u9BAF\u9D33\u9D41\u9D67\u9D36\u9D2E\u9D2F\u9D31\u9D38\u9D30"],
      ["efa1", "\u9D45\u9D42\u9D43\u9D3E\u9D37\u9D40\u9D3D\u7FF5\u9D2D\u9E8A\u9E89\u9E8D\u9EB0\u9EC8\u9EDA\u9EFB\u9EFF\u9F24\u9F23\u9F22\u9F54\u9FA0\u5131\u512D\u512E\u5698\u569C\u5697\u569A\u569D\u5699\u5970\u5B3C\u5C69\u5C6A\u5DC0\u5E6D\u5E6E\u61D8\u61DF\u61ED\u61EE\u61F1\u61EA\u61F0\u61EB\u61D6\u61E9\u64FF\u6504\u64FD\u64F8\u6501\u6503\u64FC\u6594\u65DB\u66DA\u66DB\u66D8\u6AC5\u6AB9\u6ABD\u6AE1\u6AC6\u6ABA\u6AB6\u6AB7\u6AC7\u6AB4\u6AAD\u6B5E\u6BC9\u6C0B\u7007\u700C\u700D\u7001\u7005\u7014\u700E\u6FFF\u7000\u6FFB\u7026\u6FFC\u6FF7\u700A\u7201\u71FF\u71F9\u7203\u71FD\u7376"],
      ["f040", "\u74B8\u74C0\u74B5\u74C1\u74BE\u74B6\u74BB\u74C2\u7514\u7513\u765C\u7664\u7659\u7650\u7653\u7657\u765A\u76A6\u76BD\u76EC\u77C2\u77BA\u78FF\u790C\u7913\u7914\u7909\u7910\u7912\u7911\u79AD\u79AC\u7A5F\u7C1C\u7C29\u7C19\u7C20\u7C1F\u7C2D\u7C1D\u7C26\u7C28\u7C22\u7C25\u7C30\u7E5C\u7E50\u7E56\u7E63\u7E58\u7E62\u7E5F\u7E51\u7E60\u7E57\u7E53\u7FB5\u7FB3\u7FF7\u7FF8\u8075\u81D1\u81D2"],
      ["f0a1", "\u81D0\u825F\u825E\u85B4\u85C6\u85C0\u85C3\u85C2\u85B3\u85B5\u85BD\u85C7\u85C4\u85BF\u85CB\u85CE\u85C8\u85C5\u85B1\u85B6\u85D2\u8624\u85B8\u85B7\u85BE\u8669\u87E7\u87E6\u87E2\u87DB\u87EB\u87EA\u87E5\u87DF\u87F3\u87E4\u87D4\u87DC\u87D3\u87ED\u87D8\u87E3\u87A4\u87D7\u87D9\u8801\u87F4\u87E8\u87DD\u8953\u894B\u894F\u894C\u8946\u8950\u8951\u8949\u8B2A\u8B27\u8B23\u8B33\u8B30\u8B35\u8B47\u8B2F\u8B3C\u8B3E\u8B31\u8B25\u8B37\u8B26\u8B36\u8B2E\u8B24\u8B3B\u8B3D\u8B3A\u8C42\u8C75\u8C99\u8C98\u8C97\u8CFE\u8D04\u8D02\u8D00\u8E5C\u8E62\u8E60\u8E57\u8E56\u8E5E\u8E65\u8E67"],
      ["f140", "\u8E5B\u8E5A\u8E61\u8E5D\u8E69\u8E54\u8F46\u8F47\u8F48\u8F4B\u9128\u913A\u913B\u913E\u91A8\u91A5\u91A7\u91AF\u91AA\u93B5\u938C\u9392\u93B7\u939B\u939D\u9389\u93A7\u938E\u93AA\u939E\u93A6\u9395\u9388\u9399\u939F\u938D\u93B1\u9391\u93B2\u93A4\u93A8\u93B4\u93A3\u93A5\u95D2\u95D3\u95D1\u96B3\u96D7\u96DA\u5DC2\u96DF\u96D8\u96DD\u9723\u9722\u9725\u97AC\u97AE\u97A8\u97AB\u97A4\u97AA"],
      ["f1a1", "\u97A2\u97A5\u97D7\u97D9\u97D6\u97D8\u97FA\u9850\u9851\u9852\u98B8\u9941\u993C\u993A\u9A0F\u9A0B\u9A09\u9A0D\u9A04\u9A11\u9A0A\u9A05\u9A07\u9A06\u9AC0\u9ADC\u9B08\u9B04\u9B05\u9B29\u9B35\u9B4A\u9B4C\u9B4B\u9BC7\u9BC6\u9BC3\u9BBF\u9BC1\u9BB5\u9BB8\u9BD3\u9BB6\u9BC4\u9BB9\u9BBD\u9D5C\u9D53\u9D4F\u9D4A\u9D5B\u9D4B\u9D59\u9D56\u9D4C\u9D57\u9D52\u9D54\u9D5F\u9D58\u9D5A\u9E8E\u9E8C\u9EDF\u9F01\u9F00\u9F16\u9F25\u9F2B\u9F2A\u9F29\u9F28\u9F4C\u9F55\u5134\u5135\u5296\u52F7\u53B4\u56AB\u56AD\u56A6\u56A7\u56AA\u56AC\u58DA\u58DD\u58DB\u5912\u5B3D\u5B3E\u5B3F\u5DC3\u5E70"],
      ["f240", "\u5FBF\u61FB\u6507\u6510\u650D\u6509\u650C\u650E\u6584\u65DE\u65DD\u66DE\u6AE7\u6AE0\u6ACC\u6AD1\u6AD9\u6ACB\u6ADF\u6ADC\u6AD0\u6AEB\u6ACF\u6ACD\u6ADE\u6B60\u6BB0\u6C0C\u7019\u7027\u7020\u7016\u702B\u7021\u7022\u7023\u7029\u7017\u7024\u701C\u702A\u720C\u720A\u7207\u7202\u7205\u72A5\u72A6\u72A4\u72A3\u72A1\u74CB\u74C5\u74B7\u74C3\u7516\u7660\u77C9\u77CA\u77C4\u77F1\u791D\u791B"],
      ["f2a1", "\u7921\u791C\u7917\u791E\u79B0\u7A67\u7A68\u7C33\u7C3C\u7C39\u7C2C\u7C3B\u7CEC\u7CEA\u7E76\u7E75\u7E78\u7E70\u7E77\u7E6F\u7E7A\u7E72\u7E74\u7E68\u7F4B\u7F4A\u7F83\u7F86\u7FB7\u7FFD\u7FFE\u8078\u81D7\u81D5\u8264\u8261\u8263\u85EB\u85F1\u85ED\u85D9\u85E1\u85E8\u85DA\u85D7\u85EC\u85F2\u85F8\u85D8\u85DF\u85E3\u85DC\u85D1\u85F0\u85E6\u85EF\u85DE\u85E2\u8800\u87FA\u8803\u87F6\u87F7\u8809\u880C\u880B\u8806\u87FC\u8808\u87FF\u880A\u8802\u8962\u895A\u895B\u8957\u8961\u895C\u8958\u895D\u8959\u8988\u89B7\u89B6\u89F6\u8B50\u8B48\u8B4A\u8B40\u8B53\u8B56\u8B54\u8B4B\u8B55"],
      ["f340", "\u8B51\u8B42\u8B52\u8B57\u8C43\u8C77\u8C76\u8C9A\u8D06\u8D07\u8D09\u8DAC\u8DAA\u8DAD\u8DAB\u8E6D\u8E78\u8E73\u8E6A\u8E6F\u8E7B\u8EC2\u8F52\u8F51\u8F4F\u8F50\u8F53\u8FB4\u9140\u913F\u91B0\u91AD\u93DE\u93C7\u93CF\u93C2\u93DA\u93D0\u93F9\u93EC\u93CC\u93D9\u93A9\u93E6\u93CA\u93D4\u93EE\u93E3\u93D5\u93C4\u93CE\u93C0\u93D2\u93E7\u957D\u95DA\u95DB\u96E1\u9729\u972B\u972C\u9728\u9726"],
      ["f3a1", "\u97B3\u97B7\u97B6\u97DD\u97DE\u97DF\u985C\u9859\u985D\u9857\u98BF\u98BD\u98BB\u98BE\u9948\u9947\u9943\u99A6\u99A7\u9A1A\u9A15\u9A25\u9A1D\u9A24\u9A1B\u9A22\u9A20\u9A27\u9A23\u9A1E\u9A1C\u9A14\u9AC2\u9B0B\u9B0A\u9B0E\u9B0C\u9B37\u9BEA\u9BEB\u9BE0\u9BDE\u9BE4\u9BE6\u9BE2\u9BF0\u9BD4\u9BD7\u9BEC\u9BDC\u9BD9\u9BE5\u9BD5\u9BE1\u9BDA\u9D77\u9D81\u9D8A\u9D84\u9D88\u9D71\u9D80\u9D78\u9D86\u9D8B\u9D8C\u9D7D\u9D6B\u9D74\u9D75\u9D70\u9D69\u9D85\u9D73\u9D7B\u9D82\u9D6F\u9D79\u9D7F\u9D87\u9D68\u9E94\u9E91\u9EC0\u9EFC\u9F2D\u9F40\u9F41\u9F4D\u9F56\u9F57\u9F58\u5337\u56B2"],
      ["f440", "\u56B5\u56B3\u58E3\u5B45\u5DC6\u5DC7\u5EEE\u5EEF\u5FC0\u5FC1\u61F9\u6517\u6516\u6515\u6513\u65DF\u66E8\u66E3\u66E4\u6AF3\u6AF0\u6AEA\u6AE8\u6AF9\u6AF1\u6AEE\u6AEF\u703C\u7035\u702F\u7037\u7034\u7031\u7042\u7038\u703F\u703A\u7039\u7040\u703B\u7033\u7041\u7213\u7214\u72A8\u737D\u737C\u74BA\u76AB\u76AA\u76BE\u76ED\u77CC\u77CE\u77CF\u77CD\u77F2\u7925\u7923\u7927\u7928\u7924\u7929"],
      ["f4a1", "\u79B2\u7A6E\u7A6C\u7A6D\u7AF7\u7C49\u7C48\u7C4A\u7C47\u7C45\u7CEE\u7E7B\u7E7E\u7E81\u7E80\u7FBA\u7FFF\u8079\u81DB\u81D9\u820B\u8268\u8269\u8622\u85FF\u8601\u85FE\u861B\u8600\u85F6\u8604\u8609\u8605\u860C\u85FD\u8819\u8810\u8811\u8817\u8813\u8816\u8963\u8966\u89B9\u89F7\u8B60\u8B6A\u8B5D\u8B68\u8B63\u8B65\u8B67\u8B6D\u8DAE\u8E86\u8E88\u8E84\u8F59\u8F56\u8F57\u8F55\u8F58\u8F5A\u908D\u9143\u9141\u91B7\u91B5\u91B2\u91B3\u940B\u9413\u93FB\u9420\u940F\u9414\u93FE\u9415\u9410\u9428\u9419\u940D\u93F5\u9400\u93F7\u9407\u940E\u9416\u9412\u93FA\u9409\u93F8\u940A\u93FF"],
      ["f540", "\u93FC\u940C\u93F6\u9411\u9406\u95DE\u95E0\u95DF\u972E\u972F\u97B9\u97BB\u97FD\u97FE\u9860\u9862\u9863\u985F\u98C1\u98C2\u9950\u994E\u9959\u994C\u994B\u9953\u9A32\u9A34\u9A31\u9A2C\u9A2A\u9A36\u9A29\u9A2E\u9A38\u9A2D\u9AC7\u9ACA\u9AC6\u9B10\u9B12\u9B11\u9C0B\u9C08\u9BF7\u9C05\u9C12\u9BF8\u9C40\u9C07\u9C0E\u9C06\u9C17\u9C14\u9C09\u9D9F\u9D99\u9DA4\u9D9D\u9D92\u9D98\u9D90\u9D9B"],
      ["f5a1", "\u9DA0\u9D94\u9D9C\u9DAA\u9D97\u9DA1\u9D9A\u9DA2\u9DA8\u9D9E\u9DA3\u9DBF\u9DA9\u9D96\u9DA6\u9DA7\u9E99\u9E9B\u9E9A\u9EE5\u9EE4\u9EE7\u9EE6\u9F30\u9F2E\u9F5B\u9F60\u9F5E\u9F5D\u9F59\u9F91\u513A\u5139\u5298\u5297\u56C3\u56BD\u56BE\u5B48\u5B47\u5DCB\u5DCF\u5EF1\u61FD\u651B\u6B02\u6AFC\u6B03\u6AF8\u6B00\u7043\u7044\u704A\u7048\u7049\u7045\u7046\u721D\u721A\u7219\u737E\u7517\u766A\u77D0\u792D\u7931\u792F\u7C54\u7C53\u7CF2\u7E8A\u7E87\u7E88\u7E8B\u7E86\u7E8D\u7F4D\u7FBB\u8030\u81DD\u8618\u862A\u8626\u861F\u8623\u861C\u8619\u8627\u862E\u8621\u8620\u8629\u861E\u8625"],
      ["f640", "\u8829\u881D\u881B\u8820\u8824\u881C\u882B\u884A\u896D\u8969\u896E\u896B\u89FA\u8B79\u8B78\u8B45\u8B7A\u8B7B\u8D10\u8D14\u8DAF\u8E8E\u8E8C\u8F5E\u8F5B\u8F5D\u9146\u9144\u9145\u91B9\u943F\u943B\u9436\u9429\u943D\u943C\u9430\u9439\u942A\u9437\u942C\u9440\u9431\u95E5\u95E4\u95E3\u9735\u973A\u97BF\u97E1\u9864\u98C9\u98C6\u98C0\u9958\u9956\u9A39\u9A3D\u9A46\u9A44\u9A42\u9A41\u9A3A"],
      ["f6a1", "\u9A3F\u9ACD\u9B15\u9B17\u9B18\u9B16\u9B3A\u9B52\u9C2B\u9C1D\u9C1C\u9C2C\u9C23\u9C28\u9C29\u9C24\u9C21\u9DB7\u9DB6\u9DBC\u9DC1\u9DC7\u9DCA\u9DCF\u9DBE\u9DC5\u9DC3\u9DBB\u9DB5\u9DCE\u9DB9\u9DBA\u9DAC\u9DC8\u9DB1\u9DAD\u9DCC\u9DB3\u9DCD\u9DB2\u9E7A\u9E9C\u9EEB\u9EEE\u9EED\u9F1B\u9F18\u9F1A\u9F31\u9F4E\u9F65\u9F64\u9F92\u4EB9\u56C6\u56C5\u56CB\u5971\u5B4B\u5B4C\u5DD5\u5DD1\u5EF2\u6521\u6520\u6526\u6522\u6B0B\u6B08\u6B09\u6C0D\u7055\u7056\u7057\u7052\u721E\u721F\u72A9\u737F\u74D8\u74D5\u74D9\u74D7\u766D\u76AD\u7935\u79B4\u7A70\u7A71\u7C57\u7C5C\u7C59\u7C5B\u7C5A"],
      ["f740", "\u7CF4\u7CF1\u7E91\u7F4F\u7F87\u81DE\u826B\u8634\u8635\u8633\u862C\u8632\u8636\u882C\u8828\u8826\u882A\u8825\u8971\u89BF\u89BE\u89FB\u8B7E\u8B84\u8B82\u8B86\u8B85\u8B7F\u8D15\u8E95\u8E94\u8E9A\u8E92\u8E90\u8E96\u8E97\u8F60\u8F62\u9147\u944C\u9450\u944A\u944B\u944F\u9447\u9445\u9448\u9449\u9446\u973F\u97E3\u986A\u9869\u98CB\u9954\u995B\u9A4E\u9A53\u9A54\u9A4C\u9A4F\u9A48\u9A4A"],
      ["f7a1", "\u9A49\u9A52\u9A50\u9AD0\u9B19\u9B2B\u9B3B\u9B56\u9B55\u9C46\u9C48\u9C3F\u9C44\u9C39\u9C33\u9C41\u9C3C\u9C37\u9C34\u9C32\u9C3D\u9C36\u9DDB\u9DD2\u9DDE\u9DDA\u9DCB\u9DD0\u9DDC\u9DD1\u9DDF\u9DE9\u9DD9\u9DD8\u9DD6\u9DF5\u9DD5\u9DDD\u9EB6\u9EF0\u9F35\u9F33\u9F32\u9F42\u9F6B\u9F95\u9FA2\u513D\u5299\u58E8\u58E7\u5972\u5B4D\u5DD8\u882F\u5F4F\u6201\u6203\u6204\u6529\u6525\u6596\u66EB\u6B11\u6B12\u6B0F\u6BCA\u705B\u705A\u7222\u7382\u7381\u7383\u7670\u77D4\u7C67\u7C66\u7E95\u826C\u863A\u8640\u8639\u863C\u8631\u863B\u863E\u8830\u8832\u882E\u8833\u8976\u8974\u8973\u89FE"],
      ["f840", "\u8B8C\u8B8E\u8B8B\u8B88\u8C45\u8D19\u8E98\u8F64\u8F63\u91BC\u9462\u9455\u945D\u9457\u945E\u97C4\u97C5\u9800\u9A56\u9A59\u9B1E\u9B1F\u9B20\u9C52\u9C58\u9C50\u9C4A\u9C4D\u9C4B\u9C55\u9C59\u9C4C\u9C4E\u9DFB\u9DF7\u9DEF\u9DE3\u9DEB\u9DF8\u9DE4\u9DF6\u9DE1\u9DEE\u9DE6\u9DF2\u9DF0\u9DE2\u9DEC\u9DF4\u9DF3\u9DE8\u9DED\u9EC2\u9ED0\u9EF2\u9EF3\u9F06\u9F1C\u9F38\u9F37\u9F36\u9F43\u9F4F"],
      ["f8a1", "\u9F71\u9F70\u9F6E\u9F6F\u56D3\u56CD\u5B4E\u5C6D\u652D\u66ED\u66EE\u6B13\u705F\u7061\u705D\u7060\u7223\u74DB\u74E5\u77D5\u7938\u79B7\u79B6\u7C6A\u7E97\u7F89\u826D\u8643\u8838\u8837\u8835\u884B\u8B94\u8B95\u8E9E\u8E9F\u8EA0\u8E9D\u91BE\u91BD\u91C2\u946B\u9468\u9469\u96E5\u9746\u9743\u9747\u97C7\u97E5\u9A5E\u9AD5\u9B59\u9C63\u9C67\u9C66\u9C62\u9C5E\u9C60\u9E02\u9DFE\u9E07\u9E03\u9E06\u9E05\u9E00\u9E01\u9E09\u9DFF\u9DFD\u9E04\u9EA0\u9F1E\u9F46\u9F74\u9F75\u9F76\u56D4\u652E\u65B8\u6B18\u6B19\u6B17\u6B1A\u7062\u7226\u72AA\u77D8\u77D9\u7939\u7C69\u7C6B\u7CF6\u7E9A"],
      ["f940", "\u7E98\u7E9B\u7E99\u81E0\u81E1\u8646\u8647\u8648\u8979\u897A\u897C\u897B\u89FF\u8B98\u8B99\u8EA5\u8EA4\u8EA3\u946E\u946D\u946F\u9471\u9473\u9749\u9872\u995F\u9C68\u9C6E\u9C6D\u9E0B\u9E0D\u9E10\u9E0F\u9E12\u9E11\u9EA1\u9EF5\u9F09\u9F47\u9F78\u9F7B\u9F7A\u9F79\u571E\u7066\u7C6F\u883C\u8DB2\u8EA6\u91C3\u9474\u9478\u9476\u9475\u9A60\u9C74\u9C73\u9C71\u9C75\u9E14\u9E13\u9EF6\u9F0A"],
      ["f9a1", "\u9FA4\u7068\u7065\u7CF7\u866A\u883E\u883D\u883F\u8B9E\u8C9C\u8EA9\u8EC9\u974B\u9873\u9874\u98CC\u9961\u99AB\u9A64\u9A66\u9A67\u9B24\u9E15\u9E17\u9F48\u6207\u6B1E\u7227\u864C\u8EA8\u9482\u9480\u9481\u9A69\u9A68\u9B2E\u9E19\u7229\u864B\u8B9F\u9483\u9C79\u9EB7\u7675\u9A6B\u9C7A\u9E1D\u7069\u706A\u9EA4\u9F7E\u9F49\u9F98\u7881\u92B9\u88CF\u58BB\u6052\u7CA7\u5AFA\u2554\u2566\u2557\u2560\u256C\u2563\u255A\u2569\u255D\u2552\u2564\u2555\u255E\u256A\u2561\u2558\u2567\u255B\u2553\u2565\u2556\u255F\u256B\u2562\u2559\u2568\u255C\u2551\u2550\u256D\u256E\u2570\u256F\u2593"]
    ];
  }
});

// ../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/tables/big5-added.json
var require_big5_added = __commonJS({
  "../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/tables/big5-added.json"(exports, module) {
    module.exports = [
      ["8740", "\u43F0\u4C32\u4603\u45A6\u4578\u{27267}\u4D77\u45B3\u{27CB1}\u4CE2\u{27CC5}\u3B95\u4736\u4744\u4C47\u4C40\u{242BF}\u{23617}\u{27352}\u{26E8B}\u{270D2}\u4C57\u{2A351}\u474F\u45DA\u4C85\u{27C6C}\u4D07\u4AA4\u46A1\u{26B23}\u7225\u{25A54}\u{21A63}\u{23E06}\u{23F61}\u664D\u56FB"],
      ["8767", "\u7D95\u591D\u{28BB9}\u3DF4\u9734\u{27BEF}\u5BDB\u{21D5E}\u5AA4\u3625\u{29EB0}\u5AD1\u5BB7\u5CFC\u676E\u8593\u{29945}\u7461\u749D\u3875\u{21D53}\u{2369E}\u{26021}\u3EEC"],
      ["87a1", "\u{258DE}\u3AF5\u7AFC\u9F97\u{24161}\u{2890D}\u{231EA}\u{20A8A}\u{2325E}\u430A\u8484\u9F96\u942F\u4930\u8613\u5896\u974A\u9218\u79D0\u7A32\u6660\u6A29\u889D\u744C\u7BC5\u6782\u7A2C\u524F\u9046\u34E6\u73C4\u{25DB9}\u74C6\u9FC7\u57B3\u492F\u544C\u4131\u{2368E}\u5818\u7A72\u{27B65}\u8B8F\u46AE\u{26E88}\u4181\u{25D99}\u7BAE\u{224BC}\u9FC8\u{224C1}\u{224C9}\u{224CC}\u9FC9\u8504\u{235BB}\u40B4\u9FCA\u44E1\u{2ADFF}\u62C1\u706E\u9FCB"],
      ["8840", "\u31C0", 4, "\u{2010C}\u31C5\u{200D1}\u{200CD}\u31C6\u31C7\u{200CB}\u{21FE8}\u31C8\u{200CA}\u31C9\u31CA\u31CB\u31CC\u{2010E}\u31CD\u31CE\u0100\xC1\u01CD\xC0\u0112\xC9\u011A\xC8\u014C\xD3\u01D1\xD2\u0FFF\xCA\u0304\u1EBE\u0FFF\xCA\u030C\u1EC0\xCA\u0101\xE1\u01CE\xE0\u0251\u0113\xE9\u011B\xE8\u012B\xED\u01D0\xEC\u014D\xF3\u01D2\xF2\u016B\xFA\u01D4\xF9\u01D6\u01D8\u01DA"],
      ["88a1", "\u01DC\xFC\u0FFF\xEA\u0304\u1EBF\u0FFF\xEA\u030C\u1EC1\xEA\u0261\u23DA\u23DB"],
      ["8940", "\u{2A3A9}\u{21145}"],
      ["8943", "\u650A"],
      ["8946", "\u4E3D\u6EDD\u9D4E\u91DF"],
      ["894c", "\u{27735}\u6491\u4F1A\u4F28\u4FA8\u5156\u5174\u519C\u51E4\u52A1\u52A8\u533B\u534E\u53D1\u53D8\u56E2\u58F0\u5904\u5907\u5932\u5934\u5B66\u5B9E\u5B9F\u5C9A\u5E86\u603B\u6589\u67FE\u6804\u6865\u6D4E\u70BC\u7535\u7EA4\u7EAC\u7EBA\u7EC7\u7ECF\u7EDF\u7F06\u7F37\u827A\u82CF\u836F\u89C6\u8BBE\u8BE2\u8F66\u8F67\u8F6E"],
      ["89a1", "\u7411\u7CFC\u7DCD\u6946\u7AC9\u5227"],
      ["89ab", "\u918C\u78B8\u915E\u80BC"],
      ["89b0", "\u8D0B\u80F6\u{209E7}"],
      ["89b5", "\u809F\u9EC7\u4CCD\u9DC9\u9E0C\u4C3E\u{29DF6}\u{2700E}\u9E0A\u{2A133}\u35C1"],
      ["89c1", "\u6E9A\u823E\u7519"],
      ["89c5", "\u4911\u9A6C\u9A8F\u9F99\u7987\u{2846C}\u{21DCA}\u{205D0}\u{22AE6}\u4E24\u4E81\u4E80\u4E87\u4EBF\u4EEB\u4F37\u344C\u4FBD\u3E48\u5003\u5088\u347D\u3493\u34A5\u5186\u5905\u51DB\u51FC\u5205\u4E89\u5279\u5290\u5327\u35C7\u53A9\u3551\u53B0\u3553\u53C2\u5423\u356D\u3572\u3681\u5493\u54A3\u54B4\u54B9\u54D0\u54EF\u5518\u5523\u5528\u3598\u553F\u35A5\u35BF\u55D7\u35C5"],
      ["8a40", "\u{27D84}\u5525"],
      ["8a43", "\u{20C42}\u{20D15}\u{2512B}\u5590\u{22CC6}\u39EC\u{20341}\u8E46\u{24DB8}\u{294E5}\u4053\u{280BE}\u777A\u{22C38}\u3A34\u47D5\u{2815D}\u{269F2}\u{24DEA}\u64DD\u{20D7C}\u{20FB4}\u{20CD5}\u{210F4}\u648D\u8E7E\u{20E96}\u{20C0B}\u{20F64}\u{22CA9}\u{28256}\u{244D3}"],
      ["8a64", "\u{20D46}\u{29A4D}\u{280E9}\u47F4\u{24EA7}\u{22CC2}\u9AB2\u3A67\u{295F4}\u3FED\u3506\u{252C7}\u{297D4}\u{278C8}\u{22D44}\u9D6E\u9815"],
      ["8a76", "\u43D9\u{260A5}\u64B4\u54E3\u{22D4C}\u{22BCA}\u{21077}\u39FB\u{2106F}"],
      ["8aa1", "\u{266DA}\u{26716}\u{279A0}\u64EA\u{25052}\u{20C43}\u8E68\u{221A1}\u{28B4C}\u{20731}"],
      ["8aac", "\u480B\u{201A9}\u3FFA\u5873\u{22D8D}"],
      ["8ab2", "\u{245C8}\u{204FC}\u{26097}\u{20F4C}\u{20D96}\u5579\u40BB\u43BA"],
      ["8abb", "\u4AB4\u{22A66}\u{2109D}\u81AA\u98F5\u{20D9C}\u6379\u39FE\u{22775}\u8DC0\u56A1\u647C\u3E43"],
      ["8ac9", "\u{2A601}\u{20E09}\u{22ACF}\u{22CC9}"],
      ["8ace", "\u{210C8}\u{239C2}\u3992\u3A06\u{2829B}\u3578\u{25E49}\u{220C7}\u5652\u{20F31}\u{22CB2}\u{29720}\u34BC\u6C3D\u{24E3B}"],
      ["8adf", "\u{27574}\u{22E8B}\u{22208}\u{2A65B}\u{28CCD}\u{20E7A}\u{20C34}\u{2681C}\u7F93\u{210CF}\u{22803}\u{22939}\u35FB\u{251E3}\u{20E8C}\u{20F8D}\u{20EAA}\u3F93\u{20F30}\u{20D47}\u{2114F}\u{20E4C}"],
      ["8af6", "\u{20EAB}\u{20BA9}\u{20D48}\u{210C0}\u{2113D}\u3FF9\u{22696}\u6432\u{20FAD}"],
      ["8b40", "\u{233F4}\u{27639}\u{22BCE}\u{20D7E}\u{20D7F}\u{22C51}\u{22C55}\u3A18\u{20E98}\u{210C7}\u{20F2E}\u{2A632}\u{26B50}\u{28CD2}\u{28D99}\u{28CCA}\u95AA\u54CC\u82C4\u55B9"],
      ["8b55", "\u{29EC3}\u9C26\u9AB6\u{2775E}\u{22DEE}\u7140\u816D\u80EC\u5C1C\u{26572}\u8134\u3797\u535F\u{280BD}\u91B6\u{20EFA}\u{20E0F}\u{20E77}\u{20EFB}\u35DD\u{24DEB}\u3609\u{20CD6}\u56AF\u{227B5}\u{210C9}\u{20E10}\u{20E78}\u{21078}\u{21148}\u{28207}\u{21455}\u{20E79}\u{24E50}\u{22DA4}\u5A54\u{2101D}\u{2101E}\u{210F5}\u{210F6}\u579C\u{20E11}"],
      ["8ba1", "\u{27694}\u{282CD}\u{20FB5}\u{20E7B}\u{2517E}\u3703\u{20FB6}\u{21180}\u{252D8}\u{2A2BD}\u{249DA}\u{2183A}\u{24177}\u{2827C}\u5899\u5268\u361A\u{2573D}\u7BB2\u5B68\u4800\u4B2C\u9F27\u49E7\u9C1F\u9B8D\u{25B74}\u{2313D}\u55FB\u35F2\u5689\u4E28\u5902\u{21BC1}\u{2F878}\u9751\u{20086}\u4E5B\u4EBB\u353E\u5C23\u5F51\u5FC4\u38FA\u624C\u6535\u6B7A\u6C35\u6C3A\u706C\u722B\u4E2C\u72AD\u{248E9}\u7F52\u793B\u7CF9\u7F53\u{2626A}\u34C1"],
      ["8bde", "\u{2634B}\u8002\u8080\u{26612}\u{26951}\u535D\u8864\u89C1\u{278B2}\u8BA0\u8D1D\u9485\u9578\u957F\u95E8\u{28E0F}\u97E6\u9875\u98CE\u98DE\u9963\u{29810}\u9C7C\u9E1F\u9EC4\u6B6F\uF907\u4E37\u{20087}\u961D\u6237\u94A2"],
      ["8c40", "\u503B\u6DFE\u{29C73}\u9FA6\u3DC9\u888F\u{2414E}\u7077\u5CF5\u4B20\u{251CD}\u3559\u{25D30}\u6122\u{28A32}\u8FA7\u91F6\u7191\u6719\u73BA\u{23281}\u{2A107}\u3C8B\u{21980}\u4B10\u78E4\u7402\u51AE\u{2870F}\u4009\u6A63\u{2A2BA}\u4223\u860F\u{20A6F}\u7A2A\u{29947}\u{28AEA}\u9755\u704D\u5324\u{2207E}\u93F4\u76D9\u{289E3}\u9FA7\u77DD\u4EA3\u4FF0\u50BC\u4E2F\u4F17\u9FA8\u5434\u7D8B\u5892\u58D0\u{21DB6}\u5E92\u5E99\u5FC2\u{22712}\u658B"],
      ["8ca1", "\u{233F9}\u6919\u6A43\u{23C63}\u6CFF"],
      ["8ca7", "\u7200\u{24505}\u738C\u3EDB\u{24A13}\u5B15\u74B9\u8B83\u{25CA4}\u{25695}\u7A93\u7BEC\u7CC3\u7E6C\u82F8\u8597\u9FA9\u8890\u9FAA\u8EB9\u9FAB\u8FCF\u855F\u99E0\u9221\u9FAC\u{28DB9}\u{2143F}\u4071\u42A2\u5A1A"],
      ["8cc9", "\u9868\u676B\u4276\u573D"],
      ["8cce", "\u85D6\u{2497B}\u82BF\u{2710D}\u4C81\u{26D74}\u5D7B\u{26B15}\u{26FBE}\u9FAD\u9FAE\u5B96\u9FAF\u66E7\u7E5B\u6E57\u79CA\u3D88\u44C3\u{23256}\u{22796}\u439A\u4536"],
      ["8ce6", "\u5CD5\u{23B1A}\u8AF9\u5C78\u3D12\u{23551}\u5D78\u9FB2\u7157\u4558\u{240EC}\u{21E23}\u4C77\u3978\u344A\u{201A4}\u{26C41}\u8ACC\u4FB4\u{20239}\u59BF\u816C\u9856\u{298FA}\u5F3B"],
      ["8d40", "\u{20B9F}"],
      ["8d42", "\u{221C1}\u{2896D}\u4102\u46BB\u{29079}\u3F07\u9FB3\u{2A1B5}\u40F8\u37D6\u46F7\u{26C46}\u417C\u{286B2}\u{273FF}\u456D\u38D4\u{2549A}\u4561\u451B\u4D89\u4C7B\u4D76\u45EA\u3FC8\u{24B0F}\u3661\u44DE\u44BD\u41ED\u5D3E\u5D48\u5D56\u3DFC\u380F\u5DA4\u5DB9\u3820\u3838\u5E42\u5EBD\u5F25\u5F83\u3908\u3914\u393F\u394D\u60D7\u613D\u5CE5\u3989\u61B7\u61B9\u61CF\u39B8\u622C\u6290\u62E5\u6318\u39F8\u56B1"],
      ["8da1", "\u3A03\u63E2\u63FB\u6407\u645A\u3A4B\u64C0\u5D15\u5621\u9F9F\u3A97\u6586\u3ABD\u65FF\u6653\u3AF2\u6692\u3B22\u6716\u3B42\u67A4\u6800\u3B58\u684A\u6884\u3B72\u3B71\u3B7B\u6909\u6943\u725C\u6964\u699F\u6985\u3BBC\u69D6\u3BDD\u6A65\u6A74\u6A71\u6A82\u3BEC\u6A99\u3BF2\u6AAB\u6AB5\u6AD4\u6AF6\u6B81\u6BC1\u6BEA\u6C75\u6CAA\u3CCB\u6D02\u6D06\u6D26\u6D81\u3CEF\u6DA4\u6DB1\u6E15\u6E18\u6E29\u6E86\u{289C0}\u6EBB\u6EE2\u6EDA\u9F7F\u6EE8\u6EE9\u6F24\u6F34\u3D46\u{23F41}\u6F81\u6FBE\u3D6A\u3D75\u71B7\u5C99\u3D8A\u702C\u3D91\u7050\u7054\u706F\u707F\u7089\u{20325}\u43C1\u35F1\u{20ED8}"],
      ["8e40", "\u{23ED7}\u57BE\u{26ED3}\u713E\u{257E0}\u364E\u69A2\u{28BE9}\u5B74\u7A49\u{258E1}\u{294D9}\u7A65\u7A7D\u{259AC}\u7ABB\u7AB0\u7AC2\u7AC3\u71D1\u{2648D}\u41CA\u7ADA\u7ADD\u7AEA\u41EF\u54B2\u{25C01}\u7B0B\u7B55\u7B29\u{2530E}\u{25CFE}\u7BA2\u7B6F\u839C\u{25BB4}\u{26C7F}\u7BD0\u8421\u7B92\u7BB8\u{25D20}\u3DAD\u{25C65}\u8492\u7BFA\u7C06\u7C35\u{25CC1}\u7C44\u7C83\u{24882}\u7CA6\u667D\u{24578}\u7CC9\u7CC7\u7CE6\u7C74\u7CF3\u7CF5\u7CCE"],
      ["8ea1", "\u7E67\u451D\u{26E44}\u7D5D\u{26ED6}\u748D\u7D89\u7DAB\u7135\u7DB3\u7DD2\u{24057}\u{26029}\u7DE4\u3D13\u7DF5\u{217F9}\u7DE5\u{2836D}\u7E1D\u{26121}\u{2615A}\u7E6E\u7E92\u432B\u946C\u7E27\u7F40\u7F41\u7F47\u7936\u{262D0}\u99E1\u7F97\u{26351}\u7FA3\u{21661}\u{20068}\u455C\u{23766}\u4503\u{2833A}\u7FFA\u{26489}\u8005\u8008\u801D\u8028\u802F\u{2A087}\u{26CC3}\u803B\u803C\u8061\u{22714}\u4989\u{26626}\u{23DE3}\u{266E8}\u6725\u80A7\u{28A48}\u8107\u811A\u58B0\u{226F6}\u6C7F\u{26498}\u{24FB8}\u64E7\u{2148A}\u8218\u{2185E}\u6A53\u{24A65}\u{24A95}\u447A\u8229\u{20B0D}\u{26A52}\u{23D7E}\u4FF9\u{214FD}\u84E2\u8362\u{26B0A}\u{249A7}\u{23530}\u{21773}\u{23DF8}\u82AA\u691B\u{2F994}\u41DB"],
      ["8f40", "\u854B\u82D0\u831A\u{20E16}\u{217B4}\u36C1\u{2317D}\u{2355A}\u827B\u82E2\u8318\u{23E8B}\u{26DA3}\u{26B05}\u{26B97}\u{235CE}\u3DBF\u831D\u55EC\u8385\u450B\u{26DA5}\u83AC\u83C1\u83D3\u347E\u{26ED4}\u6A57\u855A\u3496\u{26E42}\u{22EEF}\u8458\u{25BE4}\u8471\u3DD3\u44E4\u6AA7\u844A\u{23CB5}\u7958\u84A8\u{26B96}\u{26E77}\u{26E43}\u84DE\u840F\u8391\u44A0\u8493\u84E4\u{25C91}\u4240\u{25CC0}\u4543\u8534\u5AF2\u{26E99}\u4527\u8573\u4516\u67BF\u8616"],
      ["8fa1", "\u{28625}\u{2863B}\u85C1\u{27088}\u8602\u{21582}\u{270CD}\u{2F9B2}\u456A\u8628\u3648\u{218A2}\u53F7\u{2739A}\u867E\u8771\u{2A0F8}\u87EE\u{22C27}\u87B1\u87DA\u880F\u5661\u866C\u6856\u460F\u8845\u8846\u{275E0}\u{23DB9}\u{275E4}\u885E\u889C\u465B\u88B4\u88B5\u63C1\u88C5\u7777\u{2770F}\u8987\u898A\u89A6\u89A9\u89A7\u89BC\u{28A25}\u89E7\u{27924}\u{27ABD}\u8A9C\u7793\u91FE\u8A90\u{27A59}\u7AE9\u{27B3A}\u{23F8F}\u4713\u{27B38}\u717C\u8B0C\u8B1F\u{25430}\u{25565}\u8B3F\u8B4C\u8B4D\u8AA9\u{24A7A}\u8B90\u8B9B\u8AAF\u{216DF}\u4615\u884F\u8C9B\u{27D54}\u{27D8F}\u{2F9D4}\u3725\u{27D53}\u8CD6\u{27D98}\u{27DBD}\u8D12\u8D03\u{21910}\u8CDB\u705C\u8D11\u{24CC9}\u3ED0\u8D77"],
      ["9040", "\u8DA9\u{28002}\u{21014}\u{2498A}\u3B7C\u{281BC}\u{2710C}\u7AE7\u8EAD\u8EB6\u8EC3\u92D4\u8F19\u8F2D\u{28365}\u{28412}\u8FA5\u9303\u{2A29F}\u{20A50}\u8FB3\u492A\u{289DE}\u{2853D}\u{23DBB}\u5EF8\u{23262}\u8FF9\u{2A014}\u{286BC}\u{28501}\u{22325}\u3980\u{26ED7}\u9037\u{2853C}\u{27ABE}\u9061\u{2856C}\u{2860B}\u90A8\u{28713}\u90C4\u{286E6}\u90AE\u90FD\u9167\u3AF0\u91A9\u91C4\u7CAC\u{28933}\u{21E89}\u920E\u6C9F\u9241\u9262\u{255B9}\u92B9\u{28AC6}\u{23C9B}\u{28B0C}\u{255DB}"],
      ["90a1", "\u{20D31}\u932C\u936B\u{28AE1}\u{28BEB}\u708F\u5AC3\u{28AE2}\u{28AE5}\u4965\u9244\u{28BEC}\u{28C39}\u{28BFF}\u9373\u945B\u8EBC\u9585\u95A6\u9426\u95A0\u6FF6\u42B9\u{2267A}\u{286D8}\u{2127C}\u{23E2E}\u49DF\u6C1C\u967B\u9696\u416C\u96A3\u{26ED5}\u61DA\u96B6\u78F5\u{28AE0}\u96BD\u53CC\u49A1\u{26CB8}\u{20274}\u{26410}\u{290AF}\u{290E5}\u{24AD1}\u{21915}\u{2330A}\u9731\u8642\u9736\u4A0F\u453D\u4585\u{24AE9}\u7075\u5B41\u971B\u975C\u{291D5}\u9757\u5B4A\u{291EB}\u975F\u9425\u50D0\u{230B7}\u{230BC}\u9789\u979F\u97B1\u97BE\u97C0\u97D2\u97E0\u{2546C}\u97EE\u741C\u{29433}\u97FF\u97F5\u{2941D}\u{2797A}\u4AD1\u9834\u9833\u984B\u9866\u3B0E\u{27175}\u3D51\u{20630}\u{2415C}"],
      ["9140", "\u{25706}\u98CA\u98B7\u98C8\u98C7\u4AFF\u{26D27}\u{216D3}\u55B0\u98E1\u98E6\u98EC\u9378\u9939\u{24A29}\u4B72\u{29857}\u{29905}\u99F5\u9A0C\u9A3B\u9A10\u9A58\u{25725}\u36C4\u{290B1}\u{29BD5}\u9AE0\u9AE2\u{29B05}\u9AF4\u4C0E\u9B14\u9B2D\u{28600}\u5034\u9B34\u{269A8}\u38C3\u{2307D}\u9B50\u9B40\u{29D3E}\u5A45\u{21863}\u9B8E\u{2424B}\u9C02\u9BFF\u9C0C\u{29E68}\u9DD4\u{29FB7}\u{2A192}\u{2A1AB}\u{2A0E1}\u{2A123}\u{2A1DF}\u9D7E\u9D83\u{2A134}\u9E0E\u6888"],
      ["91a1", "\u9DC4\u{2215B}\u{2A193}\u{2A220}\u{2193B}\u{2A233}\u9D39\u{2A0B9}\u{2A2B4}\u9E90\u9E95\u9E9E\u9EA2\u4D34\u9EAA\u9EAF\u{24364}\u9EC1\u3B60\u39E5\u3D1D\u4F32\u37BE\u{28C2B}\u9F02\u9F08\u4B96\u9424\u{26DA2}\u9F17\u9F16\u9F39\u569F\u568A\u9F45\u99B8\u{2908B}\u97F2\u847F\u9F62\u9F69\u7ADC\u9F8E\u7216\u4BBE\u{24975}\u{249BB}\u7177\u{249F8}\u{24348}\u{24A51}\u739E\u{28BDA}\u{218FA}\u799F\u{2897E}\u{28E36}\u9369\u93F3\u{28A44}\u92EC\u9381\u93CB\u{2896C}\u{244B9}\u7217\u3EEB\u7772\u7A43\u70D0\u{24473}\u{243F8}\u717E\u{217EF}\u70A3\u{218BE}\u{23599}\u3EC7\u{21885}\u{2542F}\u{217F8}\u3722\u{216FB}\u{21839}\u36E1\u{21774}\u{218D1}\u{25F4B}\u3723\u{216C0}\u575B\u{24A25}\u{213FE}\u{212A8}"],
      ["9240", "\u{213C6}\u{214B6}\u8503\u{236A6}\u8503\u8455\u{24994}\u{27165}\u{23E31}\u{2555C}\u{23EFB}\u{27052}\u44F4\u{236EE}\u{2999D}\u{26F26}\u67F9\u3733\u3C15\u3DE7\u586C\u{21922}\u6810\u4057\u{2373F}\u{240E1}\u{2408B}\u{2410F}\u{26C21}\u54CB\u569E\u{266B1}\u5692\u{20FDF}\u{20BA8}\u{20E0D}\u93C6\u{28B13}\u939C\u4EF8\u512B\u3819\u{24436}\u4EBC\u{20465}\u{2037F}\u4F4B\u4F8A\u{25651}\u5A68\u{201AB}\u{203CB}\u3999\u{2030A}\u{20414}\u3435\u4F29\u{202C0}\u{28EB3}\u{20275}\u8ADA\u{2020C}\u4E98"],
      ["92a1", "\u50CD\u510D\u4FA2\u4F03\u{24A0E}\u{23E8A}\u4F42\u502E\u506C\u5081\u4FCC\u4FE5\u5058\u50FC\u5159\u515B\u515D\u515E\u6E76\u{23595}\u{23E39}\u{23EBF}\u6D72\u{21884}\u{23E89}\u51A8\u51C3\u{205E0}\u44DD\u{204A3}\u{20492}\u{20491}\u8D7A\u{28A9C}\u{2070E}\u5259\u52A4\u{20873}\u52E1\u936E\u467A\u718C\u{2438C}\u{20C20}\u{249AC}\u{210E4}\u69D1\u{20E1D}\u7479\u3EDE\u7499\u7414\u7456\u7398\u4B8E\u{24ABC}\u{2408D}\u53D0\u3584\u720F\u{240C9}\u55B4\u{20345}\u54CD\u{20BC6}\u571D\u925D\u96F4\u9366\u57DD\u578D\u577F\u363E\u58CB\u5A99\u{28A46}\u{216FA}\u{2176F}\u{21710}\u5A2C\u59B8\u928F\u5A7E\u5ACF\u5A12\u{25946}\u{219F3}\u{21861}\u{24295}\u36F5\u6D05\u7443\u5A21\u{25E83}"],
      ["9340", "\u5A81\u{28BD7}\u{20413}\u93E0\u748C\u{21303}\u7105\u4972\u9408\u{289FB}\u93BD\u37A0\u5C1E\u5C9E\u5E5E\u5E48\u{21996}\u{2197C}\u{23AEE}\u5ECD\u5B4F\u{21903}\u{21904}\u3701\u{218A0}\u36DD\u{216FE}\u36D3\u812A\u{28A47}\u{21DBA}\u{23472}\u{289A8}\u5F0C\u5F0E\u{21927}\u{217AB}\u5A6B\u{2173B}\u5B44\u8614\u{275FD}\u8860\u607E\u{22860}\u{2262B}\u5FDB\u3EB8\u{225AF}\u{225BE}\u{29088}\u{26F73}\u61C0\u{2003E}\u{20046}\u{2261B}\u6199\u6198\u6075\u{22C9B}\u{22D07}\u{246D4}\u{2914D}"],
      ["93a1", "\u6471\u{24665}\u{22B6A}\u3A29\u{22B22}\u{23450}\u{298EA}\u{22E78}\u6337\u{2A45B}\u64B6\u6331\u63D1\u{249E3}\u{22D67}\u62A4\u{22CA1}\u643B\u656B\u6972\u3BF4\u{2308E}\u{232AD}\u{24989}\u{232AB}\u550D\u{232E0}\u{218D9}\u{2943F}\u66CE\u{23289}\u{231B3}\u3AE0\u4190\u{25584}\u{28B22}\u{2558F}\u{216FC}\u{2555B}\u{25425}\u78EE\u{23103}\u{2182A}\u{23234}\u3464\u{2320F}\u{23182}\u{242C9}\u668E\u{26D24}\u666B\u4B93\u6630\u{27870}\u{21DEB}\u6663\u{232D2}\u{232E1}\u661E\u{25872}\u38D1\u{2383A}\u{237BC}\u3B99\u{237A2}\u{233FE}\u74D0\u3B96\u678F\u{2462A}\u68B6\u681E\u3BC4\u6ABE\u3863\u{237D5}\u{24487}\u6A33\u6A52\u6AC9\u6B05\u{21912}\u6511\u6898\u6A4C\u3BD7\u6A7A\u6B57\u{23FC0}\u{23C9A}\u93A0\u92F2\u{28BEA}\u{28ACB}"],
      ["9440", "\u9289\u{2801E}\u{289DC}\u9467\u6DA5\u6F0B\u{249EC}\u6D67\u{23F7F}\u3D8F\u6E04\u{2403C}\u5A3D\u6E0A\u5847\u6D24\u7842\u713B\u{2431A}\u{24276}\u70F1\u7250\u7287\u7294\u{2478F}\u{24725}\u5179\u{24AA4}\u{205EB}\u747A\u{23EF8}\u{2365F}\u{24A4A}\u{24917}\u{25FE1}\u3F06\u3EB1\u{24ADF}\u{28C23}\u{23F35}\u60A7\u3EF3\u74CC\u743C\u9387\u7437\u449F\u{26DEA}\u4551\u7583\u3F63\u{24CD9}\u{24D06}\u3F58\u7555\u7673\u{2A5C6}\u3B19\u7468\u{28ACC}\u{249AB}\u{2498E}\u3AFB"],
      ["94a1", "\u3DCD\u{24A4E}\u3EFF\u{249C5}\u{248F3}\u91FA\u5732\u9342\u{28AE3}\u{21864}\u50DF\u{25221}\u{251E7}\u7778\u{23232}\u770E\u770F\u777B\u{24697}\u{23781}\u3A5E\u{248F0}\u7438\u749B\u3EBF\u{24ABA}\u{24AC7}\u40C8\u{24A96}\u{261AE}\u9307\u{25581}\u781E\u788D\u7888\u78D2\u73D0\u7959\u{27741}\u{256E3}\u410E\u799B\u8496\u79A5\u6A2D\u{23EFA}\u7A3A\u79F4\u416E\u{216E6}\u4132\u9235\u79F1\u{20D4C}\u{2498C}\u{20299}\u{23DBA}\u{2176E}\u3597\u556B\u3570\u36AA\u{201D4}\u{20C0D}\u7AE2\u5A59\u{226F5}\u{25AAF}\u{25A9C}\u5A0D\u{2025B}\u78F0\u5A2A\u{25BC6}\u7AFE\u41F9\u7C5D\u7C6D\u4211\u{25BB3}\u{25EBC}\u{25EA6}\u7CCD\u{249F9}\u{217B0}\u7C8E\u7C7C\u7CAE\u6AB2\u7DDC\u7E07\u7DD3\u7F4E\u{26261}"],
      ["9540", "\u{2615C}\u{27B48}\u7D97\u{25E82}\u426A\u{26B75}\u{20916}\u67D6\u{2004E}\u{235CF}\u57C4\u{26412}\u{263F8}\u{24962}\u7FDD\u7B27\u{2082C}\u{25AE9}\u{25D43}\u7B0C\u{25E0E}\u99E6\u8645\u9A63\u6A1C\u{2343F}\u39E2\u{249F7}\u{265AD}\u9A1F\u{265A0}\u8480\u{27127}\u{26CD1}\u44EA\u8137\u4402\u80C6\u8109\u8142\u{267B4}\u98C3\u{26A42}\u8262\u8265\u{26A51}\u8453\u{26DA7}\u8610\u{2721B}\u5A86\u417F\u{21840}\u5B2B\u{218A1}\u5AE4\u{218D8}\u86A0\u{2F9BC}\u{23D8F}\u882D\u{27422}\u5A02"],
      ["95a1", "\u886E\u4F45\u8887\u88BF\u88E6\u8965\u894D\u{25683}\u8954\u{27785}\u{27784}\u{28BF5}\u{28BD9}\u{28B9C}\u{289F9}\u3EAD\u84A3\u46F5\u46CF\u37F2\u8A3D\u8A1C\u{29448}\u5F4D\u922B\u{24284}\u65D4\u7129\u70C4\u{21845}\u9D6D\u8C9F\u8CE9\u{27DDC}\u599A\u77C3\u59F0\u436E\u36D4\u8E2A\u8EA7\u{24C09}\u8F30\u8F4A\u42F4\u6C58\u6FBB\u{22321}\u489B\u6F79\u6E8B\u{217DA}\u9BE9\u36B5\u{2492F}\u90BB\u9097\u5571\u4906\u91BB\u9404\u{28A4B}\u4062\u{28AFC}\u9427\u{28C1D}\u{28C3B}\u84E5\u8A2B\u9599\u95A7\u9597\u9596\u{28D34}\u7445\u3EC2\u{248FF}\u{24A42}\u{243EA}\u3EE7\u{23225}\u968F\u{28EE7}\u{28E66}\u{28E65}\u3ECC\u{249ED}\u{24A78}\u{23FEE}\u7412\u746B\u3EFC\u9741\u{290B0}"],
      ["9640", "\u6847\u4A1D\u{29093}\u{257DF}\u975D\u9368\u{28989}\u{28C26}\u{28B2F}\u{263BE}\u92BA\u5B11\u8B69\u493C\u73F9\u{2421B}\u979B\u9771\u9938\u{20F26}\u5DC1\u{28BC5}\u{24AB2}\u981F\u{294DA}\u92F6\u{295D7}\u91E5\u44C0\u{28B50}\u{24A67}\u{28B64}\u98DC\u{28A45}\u3F00\u922A\u4925\u8414\u993B\u994D\u{27B06}\u3DFD\u999B\u4B6F\u99AA\u9A5C\u{28B65}\u{258C8}\u6A8F\u9A21\u5AFE\u9A2F\u{298F1}\u4B90\u{29948}\u99BC\u4BBD\u4B97\u937D\u5872\u{21302}\u5822\u{249B8}"],
      ["96a1", "\u{214E8}\u7844\u{2271F}\u{23DB8}\u68C5\u3D7D\u9458\u3927\u6150\u{22781}\u{2296B}\u6107\u9C4F\u9C53\u9C7B\u9C35\u9C10\u9B7F\u9BCF\u{29E2D}\u9B9F\u{2A1F5}\u{2A0FE}\u9D21\u4CAE\u{24104}\u9E18\u4CB0\u9D0C\u{2A1B4}\u{2A0ED}\u{2A0F3}\u{2992F}\u9DA5\u84BD\u{26E12}\u{26FDF}\u{26B82}\u85FC\u4533\u{26DA4}\u{26E84}\u{26DF0}\u8420\u85EE\u{26E00}\u{237D7}\u{26064}\u79E2\u{2359C}\u{23640}\u492D\u{249DE}\u3D62\u93DB\u92BE\u9348\u{202BF}\u78B9\u9277\u944D\u4FE4\u3440\u9064\u{2555D}\u783D\u7854\u78B6\u784B\u{21757}\u{231C9}\u{24941}\u369A\u4F72\u6FDA\u6FD9\u701E\u701E\u5414\u{241B5}\u57BB\u58F3\u578A\u9D16\u57D7\u7134\u34AF\u{241AC}\u71EB\u{26C40}\u{24F97}\u5B28\u{217B5}\u{28A49}"],
      ["9740", "\u610C\u5ACE\u5A0B\u42BC\u{24488}\u372C\u4B7B\u{289FC}\u93BB\u93B8\u{218D6}\u{20F1D}\u8472\u{26CC0}\u{21413}\u{242FA}\u{22C26}\u{243C1}\u5994\u{23DB7}\u{26741}\u7DA8\u{2615B}\u{260A4}\u{249B9}\u{2498B}\u{289FA}\u92E5\u73E2\u3EE9\u74B4\u{28B63}\u{2189F}\u3EE1\u{24AB3}\u6AD8\u73F3\u73FB\u3ED6\u{24A3E}\u{24A94}\u{217D9}\u{24A66}\u{203A7}\u{21424}\u{249E5}\u7448\u{24916}\u70A5\u{24976}\u9284\u73E6\u935F\u{204FE}\u9331\u{28ACE}\u{28A16}\u9386\u{28BE7}\u{255D5}\u4935\u{28A82}\u716B"],
      ["97a1", "\u{24943}\u{20CFF}\u56A4\u{2061A}\u{20BEB}\u{20CB8}\u5502\u79C4\u{217FA}\u7DFE\u{216C2}\u{24A50}\u{21852}\u452E\u9401\u370A\u{28AC0}\u{249AD}\u59B0\u{218BF}\u{21883}\u{27484}\u5AA1\u36E2\u{23D5B}\u36B0\u925F\u5A79\u{28A81}\u{21862}\u9374\u3CCD\u{20AB4}\u4A96\u398A\u50F4\u3D69\u3D4C\u{2139C}\u7175\u42FB\u{28218}\u6E0F\u{290E4}\u44EB\u6D57\u{27E4F}\u7067\u6CAF\u3CD6\u{23FED}\u{23E2D}\u6E02\u6F0C\u3D6F\u{203F5}\u7551\u36BC\u34C8\u4680\u3EDA\u4871\u59C4\u926E\u493E\u8F41\u{28C1C}\u{26BC0}\u5812\u57C8\u36D6\u{21452}\u70FE\u{24362}\u{24A71}\u{22FE3}\u{212B0}\u{223BD}\u68B9\u6967\u{21398}\u{234E5}\u{27BF4}\u{236DF}\u{28A83}\u{237D6}\u{233FA}\u{24C9F}\u6A1A\u{236AD}\u{26CB7}\u843E\u44DF\u44CE"],
      ["9840", "\u{26D26}\u{26D51}\u{26C82}\u{26FDE}\u6F17\u{27109}\u833D\u{2173A}\u83ED\u{26C80}\u{27053}\u{217DB}\u5989\u5A82\u{217B3}\u5A61\u5A71\u{21905}\u{241FC}\u372D\u59EF\u{2173C}\u36C7\u718E\u9390\u669A\u{242A5}\u5A6E\u5A2B\u{24293}\u6A2B\u{23EF9}\u{27736}\u{2445B}\u{242CA}\u711D\u{24259}\u{289E1}\u4FB0\u{26D28}\u5CC2\u{244CE}\u{27E4D}\u{243BD}\u6A0C\u{24256}\u{21304}\u70A6\u7133\u{243E9}\u3DA5\u6CDF\u{2F825}\u{24A4F}\u7E65\u59EB\u5D2F\u3DF3\u5F5C\u{24A5D}\u{217DF}\u7DA4\u8426"],
      ["98a1", "\u5485\u{23AFA}\u{23300}\u{20214}\u577E\u{208D5}\u{20619}\u3FE5\u{21F9E}\u{2A2B6}\u7003\u{2915B}\u5D70\u738F\u7CD3\u{28A59}\u{29420}\u4FC8\u7FE7\u72CD\u7310\u{27AF4}\u7338\u7339\u{256F6}\u7341\u7348\u3EA9\u{27B18}\u906C\u71F5\u{248F2}\u73E1\u81F6\u3ECA\u770C\u3ED1\u6CA2\u56FD\u7419\u741E\u741F\u3EE2\u3EF0\u3EF4\u3EFA\u74D3\u3F0E\u3F53\u7542\u756D\u7572\u758D\u3F7C\u75C8\u75DC\u3FC0\u764D\u3FD7\u7674\u3FDC\u767A\u{24F5C}\u7188\u5623\u8980\u5869\u401D\u7743\u4039\u6761\u4045\u35DB\u7798\u406A\u406F\u5C5E\u77BE\u77CB\u58F2\u7818\u70B9\u781C\u40A8\u7839\u7847\u7851\u7866\u8448\u{25535}\u7933\u6803\u7932\u4103"],
      ["9940", "\u4109\u7991\u7999\u8FBB\u7A06\u8FBC\u4167\u7A91\u41B2\u7ABC\u8279\u41C4\u7ACF\u7ADB\u41CF\u4E21\u7B62\u7B6C\u7B7B\u7C12\u7C1B\u4260\u427A\u7C7B\u7C9C\u428C\u7CB8\u4294\u7CED\u8F93\u70C0\u{20CCF}\u7DCF\u7DD4\u7DD0\u7DFD\u7FAE\u7FB4\u729F\u4397\u8020\u8025\u7B39\u802E\u8031\u8054\u3DCC\u57B4\u70A0\u80B7\u80E9\u43ED\u810C\u732A\u810E\u8112\u7560\u8114\u4401\u3B39\u8156\u8159\u815A"],
      ["99a1", "\u4413\u583A\u817C\u8184\u4425\u8193\u442D\u81A5\u57EF\u81C1\u81E4\u8254\u448F\u82A6\u8276\u82CA\u82D8\u82FF\u44B0\u8357\u9669\u698A\u8405\u70F5\u8464\u60E3\u8488\u4504\u84BE\u84E1\u84F8\u8510\u8538\u8552\u453B\u856F\u8570\u85E0\u4577\u8672\u8692\u86B2\u86EF\u9645\u878B\u4606\u4617\u88AE\u88FF\u8924\u8947\u8991\u{27967}\u8A29\u8A38\u8A94\u8AB4\u8C51\u8CD4\u8CF2\u8D1C\u4798\u585F\u8DC3\u47ED\u4EEE\u8E3A\u55D8\u5754\u8E71\u55F5\u8EB0\u4837\u8ECE\u8EE2\u8EE4\u8EED\u8EF2\u8FB7\u8FC1\u8FCA\u8FCC\u9033\u99C4\u48AD\u98E0\u9213\u491E\u9228\u9258\u926B\u92B1\u92AE\u92BF"],
      ["9a40", "\u92E3\u92EB\u92F3\u92F4\u92FD\u9343\u9384\u93AD\u4945\u4951\u9EBF\u9417\u5301\u941D\u942D\u943E\u496A\u9454\u9479\u952D\u95A2\u49A7\u95F4\u9633\u49E5\u67A0\u4A24\u9740\u4A35\u97B2\u97C2\u5654\u4AE4\u60E8\u98B9\u4B19\u98F1\u5844\u990E\u9919\u51B4\u991C\u9937\u9942\u995D\u9962\u4B70\u99C5\u4B9D\u9A3C\u9B0F\u7A83\u9B69\u9B81\u9BDD\u9BF1\u9BF4\u4C6D\u9C20\u376F\u{21BC2}\u9D49\u9C3A"],
      ["9aa1", "\u9EFE\u5650\u9D93\u9DBD\u9DC0\u9DFC\u94F6\u8FB6\u9E7B\u9EAC\u9EB1\u9EBD\u9EC6\u94DC\u9EE2\u9EF1\u9EF8\u7AC8\u9F44\u{20094}\u{202B7}\u{203A0}\u691A\u94C3\u59AC\u{204D7}\u5840\u94C1\u37B9\u{205D5}\u{20615}\u{20676}\u{216BA}\u5757\u7173\u{20AC2}\u{20ACD}\u{20BBF}\u546A\u{2F83B}\u{20BCB}\u549E\u{20BFB}\u{20C3B}\u{20C53}\u{20C65}\u{20C7C}\u60E7\u{20C8D}\u567A\u{20CB5}\u{20CDD}\u{20CED}\u{20D6F}\u{20DB2}\u{20DC8}\u6955\u9C2F\u87A5\u{20E04}\u{20E0E}\u{20ED7}\u{20F90}\u{20F2D}\u{20E73}\u5C20\u{20FBC}\u5E0B\u{2105C}\u{2104F}\u{21076}\u671E\u{2107B}\u{21088}\u{21096}\u3647\u{210BF}\u{210D3}\u{2112F}\u{2113B}\u5364\u84AD\u{212E3}\u{21375}\u{21336}\u8B81\u{21577}\u{21619}\u{217C3}\u{217C7}\u4E78\u70BB\u{2182D}\u{2196A}"],
      ["9b40", "\u{21A2D}\u{21A45}\u{21C2A}\u{21C70}\u{21CAC}\u{21EC8}\u62C3\u{21ED5}\u{21F15}\u7198\u6855\u{22045}\u69E9\u36C8\u{2227C}\u{223D7}\u{223FA}\u{2272A}\u{22871}\u{2294F}\u82FD\u{22967}\u{22993}\u{22AD5}\u89A5\u{22AE8}\u8FA0\u{22B0E}\u97B8\u{22B3F}\u9847\u9ABD\u{22C4C}"],
      ["9b62", "\u{22C88}\u{22CB7}\u{25BE8}\u{22D08}\u{22D12}\u{22DB7}\u{22D95}\u{22E42}\u{22F74}\u{22FCC}\u{23033}\u{23066}\u{2331F}\u{233DE}\u5FB1\u6648\u66BF\u{27A79}\u{23567}\u{235F3}\u7201\u{249BA}\u77D7\u{2361A}\u{23716}\u7E87\u{20346}\u58B5\u670E"],
      ["9ba1", "\u6918\u{23AA7}\u{27657}\u{25FE2}\u{23E11}\u{23EB9}\u{275FE}\u{2209A}\u48D0\u4AB8\u{24119}\u{28A9A}\u{242EE}\u{2430D}\u{2403B}\u{24334}\u{24396}\u{24A45}\u{205CA}\u51D2\u{20611}\u599F\u{21EA8}\u3BBE\u{23CFF}\u{24404}\u{244D6}\u5788\u{24674}\u399B\u{2472F}\u{285E8}\u{299C9}\u3762\u{221C3}\u8B5E\u{28B4E}\u99D6\u{24812}\u{248FB}\u{24A15}\u7209\u{24AC0}\u{20C78}\u5965\u{24EA5}\u{24F86}\u{20779}\u8EDA\u{2502C}\u528F\u573F\u7171\u{25299}\u{25419}\u{23F4A}\u{24AA7}\u55BC\u{25446}\u{2546E}\u{26B52}\u91D4\u3473\u{2553F}\u{27632}\u{2555E}\u4718\u{25562}\u{25566}\u{257C7}\u{2493F}\u{2585D}\u5066\u34FB\u{233CC}\u60DE\u{25903}\u477C\u{28948}\u{25AAE}\u{25B89}\u{25C06}\u{21D90}\u57A1\u7151\u6FB6\u{26102}\u{27C12}\u9056\u{261B2}\u{24F9A}\u8B62\u{26402}\u{2644A}"],
      ["9c40", "\u5D5B\u{26BF7}\u8F36\u{26484}\u{2191C}\u8AEA\u{249F6}\u{26488}\u{23FEF}\u{26512}\u4BC0\u{265BF}\u{266B5}\u{2271B}\u9465\u{257E1}\u6195\u5A27\u{2F8CD}\u4FBB\u56B9\u{24521}\u{266FC}\u4E6A\u{24934}\u9656\u6D8F\u{26CBD}\u3618\u8977\u{26799}\u{2686E}\u{26411}\u{2685E}\u71DF\u{268C7}\u7B42\u{290C0}\u{20A11}\u{26926}\u9104\u{26939}\u7A45\u9DF0\u{269FA}\u9A26\u{26A2D}\u365F\u{26469}\u{20021}\u7983\u{26A34}\u{26B5B}\u5D2C\u{23519}\u83CF\u{26B9D}\u46D0\u{26CA4}\u753B\u8865\u{26DAE}\u58B6"],
      ["9ca1", "\u371C\u{2258D}\u{2704B}\u{271CD}\u3C54\u{27280}\u{27285}\u9281\u{2217A}\u{2728B}\u9330\u{272E6}\u{249D0}\u6C39\u949F\u{27450}\u{20EF8}\u8827\u88F5\u{22926}\u{28473}\u{217B1}\u6EB8\u{24A2A}\u{21820}\u39A4\u36B9\u5C10\u79E3\u453F\u66B6\u{29CAD}\u{298A4}\u8943\u{277CC}\u{27858}\u56D6\u40DF\u{2160A}\u39A1\u{2372F}\u{280E8}\u{213C5}\u71AD\u8366\u{279DD}\u{291A8}\u5A67\u4CB7\u{270AF}\u{289AB}\u{279FD}\u{27A0A}\u{27B0B}\u{27D66}\u{2417A}\u7B43\u797E\u{28009}\u6FB5\u{2A2DF}\u6A03\u{28318}\u53A2\u{26E07}\u93BF\u6836\u975D\u{2816F}\u{28023}\u{269B5}\u{213ED}\u{2322F}\u{28048}\u5D85\u{28C30}\u{28083}\u5715\u9823\u{28949}\u5DAB\u{24988}\u65BE\u69D5\u53D2\u{24AA5}\u{23F81}\u3C11\u6736\u{28090}\u{280F4}\u{2812E}\u{21FA1}\u{2814F}"],
      ["9d40", "\u{28189}\u{281AF}\u{2821A}\u{28306}\u{2832F}\u{2838A}\u35CA\u{28468}\u{286AA}\u48FA\u63E6\u{28956}\u7808\u9255\u{289B8}\u43F2\u{289E7}\u43DF\u{289E8}\u{28B46}\u{28BD4}\u59F8\u{28C09}\u8F0B\u{28FC5}\u{290EC}\u7B51\u{29110}\u{2913C}\u3DF7\u{2915E}\u{24ACA}\u8FD0\u728F\u568B\u{294E7}\u{295E9}\u{295B0}\u{295B8}\u{29732}\u{298D1}\u{29949}\u{2996A}\u{299C3}\u{29A28}\u{29B0E}\u{29D5A}\u{29D9B}\u7E9F\u{29EF8}\u{29F23}\u4CA4\u9547\u{2A293}\u71A2\u{2A2FF}\u4D91\u9012\u{2A5CB}\u4D9C\u{20C9C}\u8FBE\u55C1"],
      ["9da1", "\u8FBA\u{224B0}\u8FB9\u{24A93}\u4509\u7E7F\u6F56\u6AB1\u4EEA\u34E4\u{28B2C}\u{2789D}\u373A\u8E80\u{217F5}\u{28024}\u{28B6C}\u{28B99}\u{27A3E}\u{266AF}\u3DEB\u{27655}\u{23CB7}\u{25635}\u{25956}\u4E9A\u{25E81}\u{26258}\u56BF\u{20E6D}\u8E0E\u5B6D\u{23E88}\u{24C9E}\u63DE\u62D0\u{217F6}\u{2187B}\u6530\u562D\u{25C4A}\u541A\u{25311}\u3DC6\u{29D98}\u4C7D\u5622\u561E\u7F49\u{25ED8}\u5975\u{23D40}\u8770\u4E1C\u{20FEA}\u{20D49}\u{236BA}\u8117\u9D5E\u8D18\u763B\u9C45\u764E\u77B9\u9345\u5432\u8148\u82F7\u5625\u8132\u8418\u80BD\u55EA\u7962\u5643\u5416\u{20E9D}\u35CE\u5605\u55F1\u66F1\u{282E2}\u362D\u7534\u55F0\u55BA\u5497\u5572\u{20C41}\u{20C96}\u5ED0\u{25148}\u{20E76}\u{22C62}"],
      ["9e40", "\u{20EA2}\u9EAB\u7D5A\u55DE\u{21075}\u629D\u976D\u5494\u8CCD\u71F6\u9176\u63FC\u63B9\u63FE\u5569\u{22B43}\u9C72\u{22EB3}\u519A\u34DF\u{20DA7}\u51A7\u544D\u551E\u5513\u7666\u8E2D\u{2688A}\u75B1\u80B6\u8804\u8786\u88C7\u81B6\u841C\u{210C1}\u44EC\u7304\u{24706}\u5B90\u830B\u{26893}\u567B\u{226F4}\u{27D2F}\u{241A3}\u{27D73}\u{26ED0}\u{272B6}\u9170\u{211D9}\u9208\u{23CFC}\u{2A6A9}\u{20EAC}\u{20EF9}\u7266\u{21CA2}\u474E\u{24FC2}\u{27FF9}\u{20FEB}\u40FA"],
      ["9ea1", "\u9C5D\u651F\u{22DA0}\u48F3\u{247E0}\u{29D7C}\u{20FEC}\u{20E0A}\u6062\u{275A3}\u{20FED}"],
      ["9ead", "\u{26048}\u{21187}\u71A3\u7E8E\u9D50\u4E1A\u4E04\u3577\u5B0D\u6CB2\u5367\u36AC\u39DC\u537D\u36A5\u{24618}\u589A\u{24B6E}\u822D\u544B\u57AA\u{25A95}\u{20979}"],
      ["9ec5", "\u3A52\u{22465}\u7374\u{29EAC}\u4D09\u9BED\u{23CFE}\u{29F30}\u4C5B\u{24FA9}\u{2959E}\u{29FDE}\u845C\u{23DB6}\u{272B2}\u{267B3}\u{23720}\u632E\u7D25\u{23EF7}\u{23E2C}\u3A2A\u9008\u52CC\u3E74\u367A\u45E9\u{2048E}\u7640\u5AF0\u{20EB6}\u787A\u{27F2E}\u58A7\u40BF\u567C\u9B8B\u5D74\u7654\u{2A434}\u9E85\u4CE1\u75F9\u37FB\u6119\u{230DA}\u{243F2}"],
      ["9ef5", "\u565D\u{212A9}\u57A7\u{24963}\u{29E06}\u5234\u{270AE}\u35AD\u6C4A\u9D7C"],
      ["9f40", "\u7C56\u9B39\u57DE\u{2176C}\u5C53\u64D3\u{294D0}\u{26335}\u{27164}\u86AD\u{20D28}\u{26D22}\u{24AE2}\u{20D71}"],
      ["9f4f", "\u51FE\u{21F0F}\u5D8E\u9703\u{21DD1}\u9E81\u904C\u7B1F\u9B02\u5CD1\u7BA3\u6268\u6335\u9AFF\u7BCF\u9B2A\u7C7E\u9B2E\u7C42\u7C86\u9C15\u7BFC\u9B09\u9F17\u9C1B\u{2493E}\u9F5A\u5573\u5BC3\u4FFD\u9E98\u4FF2\u5260\u3E06\u52D1\u5767\u5056\u59B7\u5E12\u97C8\u9DAB\u8F5C\u5469\u97B4\u9940\u97BA\u532C\u6130"],
      ["9fa1", "\u692C\u53DA\u9C0A\u9D02\u4C3B\u9641\u6980\u50A6\u7546\u{2176D}\u99DA\u5273"],
      ["9fae", "\u9159\u9681\u915C"],
      ["9fb2", "\u9151\u{28E97}\u637F\u{26D23}\u6ACA\u5611\u918E\u757A\u6285\u{203FC}\u734F\u7C70\u{25C21}\u{23CFD}"],
      ["9fc1", "\u{24919}\u76D6\u9B9D\u4E2A\u{20CD4}\u83BE\u8842"],
      ["9fc9", "\u5C4A\u69C0\u50ED\u577A\u521F\u5DF5\u4ECE\u6C31\u{201F2}\u4F39\u549C\u54DA\u529A\u8D82\u35FE\u5F0C\u35F3"],
      ["9fdb", "\u6B52\u917C\u9FA5\u9B97\u982E\u98B4\u9ABA\u9EA8\u9E84\u717A\u7B14"],
      ["9fe7", "\u6BFA\u8818\u7F78"],
      ["9feb", "\u5620\u{2A64A}\u8E77\u9F53"],
      ["9ff0", "\u8DD4\u8E4F\u9E1C\u8E01\u6282\u{2837D}\u8E28\u8E75\u7AD3\u{24A77}\u7A3E\u78D8\u6CEA\u8A67\u7607"],
      ["a040", "\u{28A5A}\u9F26\u6CCE\u87D6\u75C3\u{2A2B2}\u7853\u{2F840}\u8D0C\u72E2\u7371\u8B2D\u7302\u74F1\u8CEB\u{24ABB}\u862F\u5FBA\u88A0\u44B7"],
      ["a055", "\u{2183B}\u{26E05}"],
      ["a058", "\u8A7E\u{2251B}"],
      ["a05b", "\u60FD\u7667\u9AD7\u9D44\u936E\u9B8F\u87F5"],
      ["a063", "\u880F\u8CF7\u732C\u9721\u9BB0\u35D6\u72B2\u4C07\u7C51\u994A\u{26159}\u6159\u4C04\u9E96\u617D"],
      ["a073", "\u575F\u616F\u62A6\u6239\u62CE\u3A5C\u61E2\u53AA\u{233F5}\u6364\u6802\u35D2"],
      ["a0a1", "\u5D57\u{28BC2}\u8FDA\u{28E39}"],
      ["a0a6", "\u50D9\u{21D46}\u7906\u5332\u9638\u{20F3B}\u4065"],
      ["a0ae", "\u77FE"],
      ["a0b0", "\u7CC2\u{25F1A}\u7CDA\u7A2D\u8066\u8063\u7D4D\u7505\u74F2\u8994\u821A\u670C\u8062\u{27486}\u805B\u74F0\u8103\u7724\u8989\u{267CC}\u7553\u{26ED1}\u87A9\u87CE\u81C8\u878C\u8A49\u8CAD\u8B43\u772B\u74F8\u84DA\u3635\u69B2\u8DA6"],
      ["a0d4", "\u89A9\u7468\u6DB9\u87C1\u{24011}\u74E7\u3DDB\u7176\u60A4\u619C\u3CD1\u7162\u6077"],
      ["a0e2", "\u7F71\u{28B2D}\u7250\u60E9\u4B7E\u5220\u3C18\u{23CC7}\u{25ED7}\u{27656}\u{25531}\u{21944}\u{212FE}\u{29903}\u{26DDC}\u{270AD}\u5CC1\u{261AD}\u{28A0F}\u{23677}\u{200EE}\u{26846}\u{24F0E}\u4562\u5B1F\u{2634C}\u9F50\u9EA6\u{2626B}"],
      ["a3c0", "\u2400", 31, "\u2421"],
      ["c6a1", "\u2460", 9, "\u2474", 9, "\u2170", 9, "\u4E36\u4E3F\u4E85\u4EA0\u5182\u5196\u51AB\u52F9\u5338\u5369\u53B6\u590A\u5B80\u5DDB\u2F33\u5E7F\u5EF4\u5F50\u5F61\u6534\u65E0\u7592\u7676\u8FB5\u96B6\xA8\u02C6\u30FD\u30FE\u309D\u309E\u3003\u4EDD\u3005\u3006\u3007\u30FC\uFF3B\uFF3D\u273D\u3041", 23],
      ["c740", "\u3059", 58, "\u30A1\u30A2\u30A3\u30A4"],
      ["c7a1", "\u30A5", 81, "\u0410", 5, "\u0401\u0416", 4],
      ["c840", "\u041B", 26, "\u0451\u0436", 25, "\u21E7\u21B8\u21B9\u31CF\u{200CC}\u4E5A\u{2008A}\u5202\u4491"],
      ["c8a1", "\u9FB0\u5188\u9FB1\u{27607}"],
      ["c8cd", "\uFFE2\uFFE4\uFF07\uFF02\u3231\u2116\u2121\u309B\u309C\u2E80\u2E84\u2E86\u2E87\u2E88\u2E8A\u2E8C\u2E8D\u2E95\u2E9C\u2E9D\u2EA5\u2EA7\u2EAA\u2EAC\u2EAE\u2EB6\u2EBC\u2EBE\u2EC6\u2ECA\u2ECC\u2ECD\u2ECF\u2ED6\u2ED7\u2EDE\u2EE3"],
      ["c8f5", "\u0283\u0250\u025B\u0254\u0275\u0153\xF8\u014B\u028A\u026A"],
      ["f9fe", "\uFFED"],
      ["fa40", "\u{20547}\u92DB\u{205DF}\u{23FC5}\u854C\u42B5\u73EF\u51B5\u3649\u{24942}\u{289E4}\u9344\u{219DB}\u82EE\u{23CC8}\u783C\u6744\u62DF\u{24933}\u{289AA}\u{202A0}\u{26BB3}\u{21305}\u4FAB\u{224ED}\u5008\u{26D29}\u{27A84}\u{23600}\u{24AB1}\u{22513}\u5029\u{2037E}\u5FA4\u{20380}\u{20347}\u6EDB\u{2041F}\u507D\u5101\u347A\u510E\u986C\u3743\u8416\u{249A4}\u{20487}\u5160\u{233B4}\u516A\u{20BFF}\u{220FC}\u{202E5}\u{22530}\u{2058E}\u{23233}\u{21983}\u5B82\u877D\u{205B3}\u{23C99}\u51B2\u51B8"],
      ["faa1", "\u9D34\u51C9\u51CF\u51D1\u3CDC\u51D3\u{24AA6}\u51B3\u51E2\u5342\u51ED\u83CD\u693E\u{2372D}\u5F7B\u520B\u5226\u523C\u52B5\u5257\u5294\u52B9\u52C5\u7C15\u8542\u52E0\u860D\u{26B13}\u5305\u{28ADE}\u5549\u6ED9\u{23F80}\u{20954}\u{23FEC}\u5333\u5344\u{20BE2}\u6CCB\u{21726}\u681B\u73D5\u604A\u3EAA\u38CC\u{216E8}\u71DD\u44A2\u536D\u5374\u{286AB}\u537E\u537F\u{21596}\u{21613}\u77E6\u5393\u{28A9B}\u53A0\u53AB\u53AE\u73A7\u{25772}\u3F59\u739C\u53C1\u53C5\u6C49\u4E49\u57FE\u53D9\u3AAB\u{20B8F}\u53E0\u{23FEB}\u{22DA3}\u53F6\u{20C77}\u5413\u7079\u552B\u6657\u6D5B\u546D\u{26B53}\u{20D74}\u555D\u548F\u54A4\u47A6\u{2170D}\u{20EDD}\u3DB4\u{20D4D}"],
      ["fb40", "\u{289BC}\u{22698}\u5547\u4CED\u542F\u7417\u5586\u55A9\u5605\u{218D7}\u{2403A}\u4552\u{24435}\u66B3\u{210B4}\u5637\u66CD\u{2328A}\u66A4\u66AD\u564D\u564F\u78F1\u56F1\u9787\u53FE\u5700\u56EF\u56ED\u{28B66}\u3623\u{2124F}\u5746\u{241A5}\u6C6E\u708B\u5742\u36B1\u{26C7E}\u57E6\u{21416}\u5803\u{21454}\u{24363}\u5826\u{24BF5}\u585C\u58AA\u3561\u58E0\u58DC\u{2123C}\u58FB\u5BFF\u5743\u{2A150}\u{24278}\u93D3\u35A1\u591F\u68A6\u36C3\u6E59"],
      ["fba1", "\u{2163E}\u5A24\u5553\u{21692}\u8505\u59C9\u{20D4E}\u{26C81}\u{26D2A}\u{217DC}\u59D9\u{217FB}\u{217B2}\u{26DA6}\u6D71\u{21828}\u{216D5}\u59F9\u{26E45}\u5AAB\u5A63\u36E6\u{249A9}\u5A77\u3708\u5A96\u7465\u5AD3\u{26FA1}\u{22554}\u3D85\u{21911}\u3732\u{216B8}\u5E83\u52D0\u5B76\u6588\u5B7C\u{27A0E}\u4004\u485D\u{20204}\u5BD5\u6160\u{21A34}\u{259CC}\u{205A5}\u5BF3\u5B9D\u4D10\u5C05\u{21B44}\u5C13\u73CE\u5C14\u{21CA5}\u{26B28}\u5C49\u48DD\u5C85\u5CE9\u5CEF\u5D8B\u{21DF9}\u{21E37}\u5D10\u5D18\u5D46\u{21EA4}\u5CBA\u5DD7\u82FC\u382D\u{24901}\u{22049}\u{22173}\u8287\u3836\u3BC2\u5E2E\u6A8A\u5E75\u5E7A\u{244BC}\u{20CD3}\u53A6\u4EB7\u5ED0\u53A8\u{21771}\u5E09\u5EF4\u{28482}"],
      ["fc40", "\u5EF9\u5EFB\u38A0\u5EFC\u683E\u941B\u5F0D\u{201C1}\u{2F894}\u3ADE\u48AE\u{2133A}\u5F3A\u{26888}\u{223D0}\u5F58\u{22471}\u5F63\u97BD\u{26E6E}\u5F72\u9340\u{28A36}\u5FA7\u5DB6\u3D5F\u{25250}\u{21F6A}\u{270F8}\u{22668}\u91D6\u{2029E}\u{28A29}\u6031\u6685\u{21877}\u3963\u3DC7\u3639\u5790\u{227B4}\u7971\u3E40\u609E\u60A4\u60B3\u{24982}\u{2498F}\u{27A53}\u74A4\u50E1\u5AA0\u6164\u8424\u6142\u{2F8A6}\u{26ED2}\u6181\u51F4\u{20656}\u6187\u5BAA\u{23FB7}"],
      ["fca1", "\u{2285F}\u61D3\u{28B9D}\u{2995D}\u61D0\u3932\u{22980}\u{228C1}\u6023\u615C\u651E\u638B\u{20118}\u62C5\u{21770}\u62D5\u{22E0D}\u636C\u{249DF}\u3A17\u6438\u63F8\u{2138E}\u{217FC}\u6490\u6F8A\u{22E36}\u9814\u{2408C}\u{2571D}\u64E1\u64E5\u947B\u3A66\u643A\u3A57\u654D\u6F16\u{24A28}\u{24A23}\u6585\u656D\u655F\u{2307E}\u65B5\u{24940}\u4B37\u65D1\u40D8\u{21829}\u65E0\u65E3\u5FDF\u{23400}\u6618\u{231F7}\u{231F8}\u6644\u{231A4}\u{231A5}\u664B\u{20E75}\u6667\u{251E6}\u6673\u6674\u{21E3D}\u{23231}\u{285F4}\u{231C8}\u{25313}\u77C5\u{228F7}\u99A4\u6702\u{2439C}\u{24A21}\u3B2B\u69FA\u{237C2}\u675E\u6767\u6762\u{241CD}\u{290ED}\u67D7\u44E9\u6822\u6E50\u923C\u6801\u{233E6}\u{26DA0}\u685D"],
      ["fd40", "\u{2346F}\u69E1\u6A0B\u{28ADF}\u6973\u68C3\u{235CD}\u6901\u6900\u3D32\u3A01\u{2363C}\u3B80\u67AC\u6961\u{28A4A}\u42FC\u6936\u6998\u3BA1\u{203C9}\u8363\u5090\u69F9\u{23659}\u{2212A}\u6A45\u{23703}\u6A9D\u3BF3\u67B1\u6AC8\u{2919C}\u3C0D\u6B1D\u{20923}\u60DE\u6B35\u6B74\u{227CD}\u6EB5\u{23ADB}\u{203B5}\u{21958}\u3740\u5421\u{23B5A}\u6BE1\u{23EFC}\u6BDC\u6C37\u{2248B}\u{248F1}\u{26B51}\u6C5A\u8226\u6C79\u{23DBC}\u44C5\u{23DBD}\u{241A4}\u{2490C}\u{24900}"],
      ["fda1", "\u{23CC9}\u36E5\u3CEB\u{20D32}\u9B83\u{231F9}\u{22491}\u7F8F\u6837\u{26D25}\u{26DA1}\u{26DEB}\u6D96\u6D5C\u6E7C\u6F04\u{2497F}\u{24085}\u{26E72}\u8533\u{26F74}\u51C7\u6C9C\u6E1D\u842E\u{28B21}\u6E2F\u{23E2F}\u7453\u{23F82}\u79CC\u6E4F\u5A91\u{2304B}\u6FF8\u370D\u6F9D\u{23E30}\u6EFA\u{21497}\u{2403D}\u4555\u93F0\u6F44\u6F5C\u3D4E\u6F74\u{29170}\u3D3B\u6F9F\u{24144}\u6FD3\u{24091}\u{24155}\u{24039}\u{23FF0}\u{23FB4}\u{2413F}\u51DF\u{24156}\u{24157}\u{24140}\u{261DD}\u704B\u707E\u70A7\u7081\u70CC\u70D5\u70D6\u70DF\u4104\u3DE8\u71B4\u7196\u{24277}\u712B\u7145\u5A88\u714A\u716E\u5C9C\u{24365}\u714F\u9362\u{242C1}\u712C\u{2445A}\u{24A27}\u{24A22}\u71BA\u{28BE8}\u70BD\u720E"],
      ["fe40", "\u9442\u7215\u5911\u9443\u7224\u9341\u{25605}\u722E\u7240\u{24974}\u68BD\u7255\u7257\u3E55\u{23044}\u680D\u6F3D\u7282\u732A\u732B\u{24823}\u{2882B}\u48ED\u{28804}\u7328\u732E\u73CF\u73AA\u{20C3A}\u{26A2E}\u73C9\u7449\u{241E2}\u{216E7}\u{24A24}\u6623\u36C5\u{249B7}\u{2498D}\u{249FB}\u73F7\u7415\u6903\u{24A26}\u7439\u{205C3}\u3ED7\u745C\u{228AD}\u7460\u{28EB2}\u7447\u73E4\u7476\u83B9\u746C\u3730\u7474\u93F1\u6A2C\u7482\u4953\u{24A8C}"],
      ["fea1", "\u{2415F}\u{24A79}\u{28B8F}\u5B46\u{28C03}\u{2189E}\u74C8\u{21988}\u750E\u74E9\u751E\u{28ED9}\u{21A4B}\u5BD7\u{28EAC}\u9385\u754D\u754A\u7567\u756E\u{24F82}\u3F04\u{24D13}\u758E\u745D\u759E\u75B4\u7602\u762C\u7651\u764F\u766F\u7676\u{263F5}\u7690\u81EF\u37F8\u{26911}\u{2690E}\u76A1\u76A5\u76B7\u76CC\u{26F9F}\u8462\u{2509D}\u{2517D}\u{21E1C}\u771E\u7726\u7740\u64AF\u{25220}\u7758\u{232AC}\u77AF\u{28964}\u{28968}\u{216C1}\u77F4\u7809\u{21376}\u{24A12}\u68CA\u78AF\u78C7\u78D3\u96A5\u792E\u{255E0}\u78D7\u7934\u78B1\u{2760C}\u8FB8\u8884\u{28B2B}\u{26083}\u{2261C}\u7986\u8900\u6902\u7980\u{25857}\u799D\u{27B39}\u793C\u79A9\u6E2A\u{27126}\u3EA8\u79C6\u{2910D}\u79D4"]
    ];
  }
});

// ../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/dbcs-data.js
var require_dbcs_data = __commonJS({
  "../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/dbcs-data.js"(exports, module) {
    "use strict";
    module.exports = {
      // == Japanese/ShiftJIS ====================================================
      // All japanese encodings are based on JIS X set of standards:
      // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF.
      // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. 
      //              Has several variations in 1978, 1983, 1990 and 1997.
      // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead.
      // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233.
      //              2 planes, first is superset of 0208, second - revised 0212.
      //              Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx)
      // Byte encodings are:
      //  * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte
      //               encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC.
      //               Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI.
      //  * EUC-JP:    Up to 3 bytes per character. Used mostly on *nixes.
      //               0x00-0x7F       - lower part of 0201
      //               0x8E, 0xA1-0xDF - upper part of 0201
      //               (0xA1-0xFE)x2   - 0208 plane (94x94).
      //               0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94).
      //  * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon.
      //               Used as-is in ISO2022 family.
      //  * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, 
      //                0201-1976 Roman, 0208-1978, 0208-1983.
      //  * ISO2022-JP-1: Adds esc seq for 0212-1990.
      //  * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7.
      //  * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2.
      //  * ISO2022-JP-2004: Adds 0213-2004 Plane 1.
      //
      // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes.
      //
      // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html
      "shiftjis": {
        type: "_dbcs",
        table: function() {
          return require_shiftjis();
        },
        encodeAdd: { "\xA5": 92, "\u203E": 126 },
        encodeSkipVals: [{ from: 60736, to: 63808 }]
      },
      "csshiftjis": "shiftjis",
      "mskanji": "shiftjis",
      "sjis": "shiftjis",
      "windows31j": "shiftjis",
      "ms31j": "shiftjis",
      "xsjis": "shiftjis",
      "windows932": "shiftjis",
      "ms932": "shiftjis",
      "932": "shiftjis",
      "cp932": "shiftjis",
      "eucjp": {
        type: "_dbcs",
        table: function() {
          return require_eucjp();
        },
        encodeAdd: { "\xA5": 92, "\u203E": 126 }
      },
      // TODO: KDDI extension to Shift_JIS
      // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes.
      // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars.
      // == Chinese/GBK ==========================================================
      // http://en.wikipedia.org/wiki/GBK
      // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder
      // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936
      "gb2312": "cp936",
      "gb231280": "cp936",
      "gb23121980": "cp936",
      "csgb2312": "cp936",
      "csiso58gb231280": "cp936",
      "euccn": "cp936",
      // Microsoft's CP936 is a subset and approximation of GBK.
      "windows936": "cp936",
      "ms936": "cp936",
      "936": "cp936",
      "cp936": {
        type: "_dbcs",
        table: function() {
          return require_cp936();
        }
      },
      // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other.
      "gbk": {
        type: "_dbcs",
        table: function() {
          return require_cp936().concat(require_gbk_added());
        }
      },
      "xgbk": "gbk",
      "isoir58": "gbk",
      // GB18030 is an algorithmic extension of GBK.
      // Main source: https://www.w3.org/TR/encoding/#gbk-encoder
      // http://icu-project.org/docs/papers/gb18030.html
      // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml
      // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0
      "gb18030": {
        type: "_dbcs",
        table: function() {
          return require_cp936().concat(require_gbk_added());
        },
        gb18030: function() {
          return require_gb18030_ranges();
        },
        encodeSkipVals: [128],
        encodeAdd: { "\u20AC": 41699 }
      },
      "chinese": "gb18030",
      // == Korean ===============================================================
      // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same.
      "windows949": "cp949",
      "ms949": "cp949",
      "949": "cp949",
      "cp949": {
        type: "_dbcs",
        table: function() {
          return require_cp949();
        }
      },
      "cseuckr": "cp949",
      "csksc56011987": "cp949",
      "euckr": "cp949",
      "isoir149": "cp949",
      "korean": "cp949",
      "ksc56011987": "cp949",
      "ksc56011989": "cp949",
      "ksc5601": "cp949",
      // == Big5/Taiwan/Hong Kong ================================================
      // There are lots of tables for Big5 and cp950. Please see the following links for history:
      // http://moztw.org/docs/big5/  http://www.haible.de/bruno/charsets/conversion-tables/Big5.html
      // Variations, in roughly number of defined chars:
      //  * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT
      //  * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/
      //  * Big5-2003 (Taiwan standard) almost superset of cp950.
      //  * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers.
      //  * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. 
      //    many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years.
      //    Plus, it has 4 combining sequences.
      //    Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299
      //    because big5-hkscs is the only encoding to include astral characters in non-algorithmic way.
      //    Implementations are not consistent within browsers; sometimes labeled as just big5.
      //    MS Internet Explorer switches from big5 to big5-hkscs when a patch applied.
      //    Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31
      //    In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s.
      //    Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt
      //                   http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt
      // 
      // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder
      // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong.
      "windows950": "cp950",
      "ms950": "cp950",
      "950": "cp950",
      "cp950": {
        type: "_dbcs",
        table: function() {
          return require_cp950();
        }
      },
      // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus.
      "big5": "big5hkscs",
      "big5hkscs": {
        type: "_dbcs",
        table: function() {
          return require_cp950().concat(require_big5_added());
        },
        encodeSkipVals: [41676]
      },
      "cnbig5": "big5hkscs",
      "csbig5": "big5hkscs",
      "xxbig5": "big5hkscs"
    };
  }
});

// ../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/index.js
var require_encodings = __commonJS({
  "../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/encodings/index.js"(exports, module) {
    "use strict";
    var modules = [
      require_internal(),
      require_utf16(),
      require_utf7(),
      require_sbcs_codec(),
      require_sbcs_data(),
      require_sbcs_data_generated(),
      require_dbcs_codec(),
      require_dbcs_data()
    ];
    for (i = 0; i < modules.length; i++) {
      module = modules[i];
      for (enc in module)
        if (Object.prototype.hasOwnProperty.call(module, enc))
          exports[enc] = module[enc];
    }
    var module;
    var enc;
    var i;
  }
});

// ../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/lib/streams.js
var require_streams = __commonJS({
  "../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/lib/streams.js"(exports, module) {
    "use strict";
    var Buffer3 = __require("buffer").Buffer;
    var Transform = __require("stream").Transform;
    module.exports = function(iconv) {
      iconv.encodeStream = function encodeStream(encoding, options) {
        return new IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options);
      };
      iconv.decodeStream = function decodeStream(encoding, options) {
        return new IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options);
      };
      iconv.supportsStreams = true;
      iconv.IconvLiteEncoderStream = IconvLiteEncoderStream;
      iconv.IconvLiteDecoderStream = IconvLiteDecoderStream;
      iconv._collect = IconvLiteDecoderStream.prototype.collect;
    };
    function IconvLiteEncoderStream(conv, options) {
      this.conv = conv;
      options = options || {};
      options.decodeStrings = false;
      Transform.call(this, options);
    }
    IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, {
      constructor: { value: IconvLiteEncoderStream }
    });
    IconvLiteEncoderStream.prototype._transform = function(chunk2, encoding, done) {
      if (typeof chunk2 != "string")
        return done(new Error("Iconv encoding stream needs strings as its input."));
      try {
        var res = this.conv.write(chunk2);
        if (res && res.length) this.push(res);
        done();
      } catch (e) {
        done(e);
      }
    };
    IconvLiteEncoderStream.prototype._flush = function(done) {
      try {
        var res = this.conv.end();
        if (res && res.length) this.push(res);
        done();
      } catch (e) {
        done(e);
      }
    };
    IconvLiteEncoderStream.prototype.collect = function(cb) {
      var chunks = [];
      this.on("error", cb);
      this.on("data", function(chunk2) {
        chunks.push(chunk2);
      });
      this.on("end", function() {
        cb(null, Buffer3.concat(chunks));
      });
      return this;
    };
    function IconvLiteDecoderStream(conv, options) {
      this.conv = conv;
      options = options || {};
      options.encoding = this.encoding = "utf8";
      Transform.call(this, options);
    }
    IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, {
      constructor: { value: IconvLiteDecoderStream }
    });
    IconvLiteDecoderStream.prototype._transform = function(chunk2, encoding, done) {
      if (!Buffer3.isBuffer(chunk2))
        return done(new Error("Iconv decoding stream needs buffers as its input."));
      try {
        var res = this.conv.write(chunk2);
        if (res && res.length) this.push(res, this.encoding);
        done();
      } catch (e) {
        done(e);
      }
    };
    IconvLiteDecoderStream.prototype._flush = function(done) {
      try {
        var res = this.conv.end();
        if (res && res.length) this.push(res, this.encoding);
        done();
      } catch (e) {
        done(e);
      }
    };
    IconvLiteDecoderStream.prototype.collect = function(cb) {
      var res = "";
      this.on("error", cb);
      this.on("data", function(chunk2) {
        res += chunk2;
      });
      this.on("end", function() {
        cb(null, res);
      });
      return this;
    };
  }
});

// ../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/lib/extend-node.js
var require_extend_node = __commonJS({
  "../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/lib/extend-node.js"(exports, module) {
    "use strict";
    var Buffer3 = __require("buffer").Buffer;
    module.exports = function(iconv) {
      var original = void 0;
      iconv.supportsNodeEncodingsExtension = !(Buffer3.from || new Buffer3(0) instanceof Uint8Array);
      iconv.extendNodeEncodings = function extendNodeEncodings() {
        if (original) return;
        original = {};
        if (!iconv.supportsNodeEncodingsExtension) {
          console.error("ACTION NEEDED: require('iconv-lite').extendNodeEncodings() is not supported in your version of Node");
          console.error("See more info at https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility");
          return;
        }
        var nodeNativeEncodings = {
          "hex": true,
          "utf8": true,
          "utf-8": true,
          "ascii": true,
          "binary": true,
          "base64": true,
          "ucs2": true,
          "ucs-2": true,
          "utf16le": true,
          "utf-16le": true
        };
        Buffer3.isNativeEncoding = function(enc) {
          return enc && nodeNativeEncodings[enc.toLowerCase()];
        };
        var SlowBuffer = __require("buffer").SlowBuffer;
        original.SlowBufferToString = SlowBuffer.prototype.toString;
        SlowBuffer.prototype.toString = function(encoding, start, end) {
          encoding = String(encoding || "utf8").toLowerCase();
          if (Buffer3.isNativeEncoding(encoding))
            return original.SlowBufferToString.call(this, encoding, start, end);
          if (typeof start == "undefined") start = 0;
          if (typeof end == "undefined") end = this.length;
          return iconv.decode(this.slice(start, end), encoding);
        };
        original.SlowBufferWrite = SlowBuffer.prototype.write;
        SlowBuffer.prototype.write = function(string4, offset, length, encoding) {
          if (isFinite(offset)) {
            if (!isFinite(length)) {
              encoding = length;
              length = void 0;
            }
          } else {
            var swap = encoding;
            encoding = offset;
            offset = length;
            length = swap;
          }
          offset = +offset || 0;
          var remaining = this.length - offset;
          if (!length) {
            length = remaining;
          } else {
            length = +length;
            if (length > remaining) {
              length = remaining;
            }
          }
          encoding = String(encoding || "utf8").toLowerCase();
          if (Buffer3.isNativeEncoding(encoding))
            return original.SlowBufferWrite.call(this, string4, offset, length, encoding);
          if (string4.length > 0 && (length < 0 || offset < 0))
            throw new RangeError("attempt to write beyond buffer bounds");
          var buf = iconv.encode(string4, encoding);
          if (buf.length < length) length = buf.length;
          buf.copy(this, offset, 0, length);
          return length;
        };
        original.BufferIsEncoding = Buffer3.isEncoding;
        Buffer3.isEncoding = function(encoding) {
          return Buffer3.isNativeEncoding(encoding) || iconv.encodingExists(encoding);
        };
        original.BufferByteLength = Buffer3.byteLength;
        Buffer3.byteLength = SlowBuffer.byteLength = function(str, encoding) {
          encoding = String(encoding || "utf8").toLowerCase();
          if (Buffer3.isNativeEncoding(encoding))
            return original.BufferByteLength.call(this, str, encoding);
          return iconv.encode(str, encoding).length;
        };
        original.BufferToString = Buffer3.prototype.toString;
        Buffer3.prototype.toString = function(encoding, start, end) {
          encoding = String(encoding || "utf8").toLowerCase();
          if (Buffer3.isNativeEncoding(encoding))
            return original.BufferToString.call(this, encoding, start, end);
          if (typeof start == "undefined") start = 0;
          if (typeof end == "undefined") end = this.length;
          return iconv.decode(this.slice(start, end), encoding);
        };
        original.BufferWrite = Buffer3.prototype.write;
        Buffer3.prototype.write = function(string4, offset, length, encoding) {
          var _offset = offset, _length2 = length, _encoding = encoding;
          if (isFinite(offset)) {
            if (!isFinite(length)) {
              encoding = length;
              length = void 0;
            }
          } else {
            var swap = encoding;
            encoding = offset;
            offset = length;
            length = swap;
          }
          encoding = String(encoding || "utf8").toLowerCase();
          if (Buffer3.isNativeEncoding(encoding))
            return original.BufferWrite.call(this, string4, _offset, _length2, _encoding);
          offset = +offset || 0;
          var remaining = this.length - offset;
          if (!length) {
            length = remaining;
          } else {
            length = +length;
            if (length > remaining) {
              length = remaining;
            }
          }
          if (string4.length > 0 && (length < 0 || offset < 0))
            throw new RangeError("attempt to write beyond buffer bounds");
          var buf = iconv.encode(string4, encoding);
          if (buf.length < length) length = buf.length;
          buf.copy(this, offset, 0, length);
          return length;
        };
        if (iconv.supportsStreams) {
          var Readable = __require("stream").Readable;
          original.ReadableSetEncoding = Readable.prototype.setEncoding;
          Readable.prototype.setEncoding = function setEncoding(enc, options) {
            this._readableState.decoder = iconv.getDecoder(enc, options);
            this._readableState.encoding = enc;
          };
          Readable.prototype.collect = iconv._collect;
        }
      };
      iconv.undoExtendNodeEncodings = function undoExtendNodeEncodings() {
        if (!iconv.supportsNodeEncodingsExtension)
          return;
        if (!original)
          throw new Error("require('iconv-lite').undoExtendNodeEncodings(): Nothing to undo; extendNodeEncodings() is not called.");
        delete Buffer3.isNativeEncoding;
        var SlowBuffer = __require("buffer").SlowBuffer;
        SlowBuffer.prototype.toString = original.SlowBufferToString;
        SlowBuffer.prototype.write = original.SlowBufferWrite;
        Buffer3.isEncoding = original.BufferIsEncoding;
        Buffer3.byteLength = original.BufferByteLength;
        Buffer3.prototype.toString = original.BufferToString;
        Buffer3.prototype.write = original.BufferWrite;
        if (iconv.supportsStreams) {
          var Readable = __require("stream").Readable;
          Readable.prototype.setEncoding = original.ReadableSetEncoding;
          delete Readable.prototype.collect;
        }
        original = void 0;
      };
    };
  }
});

// ../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/lib/index.js
var require_lib = __commonJS({
  "../../node_modules/.pnpm/iconv-lite@0.4.24/node_modules/iconv-lite/lib/index.js"(exports, module) {
    "use strict";
    var Buffer3 = require_safer().Buffer;
    var bomHandling = require_bom_handling();
    var iconv = module.exports;
    iconv.encodings = null;
    iconv.defaultCharUnicode = "\uFFFD";
    iconv.defaultCharSingleByte = "?";
    iconv.encode = function encode(str, encoding, options) {
      str = "" + (str || "");
      var encoder = iconv.getEncoder(encoding, options);
      var res = encoder.write(str);
      var trail = encoder.end();
      return trail && trail.length > 0 ? Buffer3.concat([res, trail]) : res;
    };
    iconv.decode = function decode(buf, encoding, options) {
      if (typeof buf === "string") {
        if (!iconv.skipDecodeWarning) {
          console.error("Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding");
          iconv.skipDecodeWarning = true;
        }
        buf = Buffer3.from("" + (buf || ""), "binary");
      }
      var decoder = iconv.getDecoder(encoding, options);
      var res = decoder.write(buf);
      var trail = decoder.end();
      return trail ? res + trail : res;
    };
    iconv.encodingExists = function encodingExists(enc) {
      try {
        iconv.getCodec(enc);
        return true;
      } catch (e) {
        return false;
      }
    };
    iconv.toEncoding = iconv.encode;
    iconv.fromEncoding = iconv.decode;
    iconv._codecDataCache = {};
    iconv.getCodec = function getCodec(encoding) {
      if (!iconv.encodings)
        iconv.encodings = require_encodings();
      var enc = iconv._canonicalizeEncoding(encoding);
      var codecOptions = {};
      while (true) {
        var codec = iconv._codecDataCache[enc];
        if (codec)
          return codec;
        var codecDef = iconv.encodings[enc];
        switch (typeof codecDef) {
          case "string":
            enc = codecDef;
            break;
          case "object":
            for (var key in codecDef)
              codecOptions[key] = codecDef[key];
            if (!codecOptions.encodingName)
              codecOptions.encodingName = enc;
            enc = codecDef.type;
            break;
          case "function":
            if (!codecOptions.encodingName)
              codecOptions.encodingName = enc;
            codec = new codecDef(codecOptions, iconv);
            iconv._codecDataCache[codecOptions.encodingName] = codec;
            return codec;
          default:
            throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '" + enc + "')");
        }
      }
    };
    iconv._canonicalizeEncoding = function(encoding) {
      return ("" + encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, "");
    };
    iconv.getEncoder = function getEncoder(encoding, options) {
      var codec = iconv.getCodec(encoding), encoder = new codec.encoder(options, codec);
      if (codec.bomAware && options && options.addBOM)
        encoder = new bomHandling.PrependBOM(encoder, options);
      return encoder;
    };
    iconv.getDecoder = function getDecoder(encoding, options) {
      var codec = iconv.getCodec(encoding), decoder = new codec.decoder(options, codec);
      if (codec.bomAware && !(options && options.stripBOM === false))
        decoder = new bomHandling.StripBOM(decoder, options);
      return decoder;
    };
    var nodeVer = typeof process !== "undefined" && process.versions && process.versions.node;
    if (nodeVer) {
      nodeVerArr = nodeVer.split(".").map(Number);
      if (nodeVerArr[0] > 0 || nodeVerArr[1] >= 10) {
        require_streams()(iconv);
      }
      require_extend_node()(iconv);
    }
    var nodeVerArr;
    if (false) {
      console.error("iconv-lite warning: javascript files use encoding different from utf-8. See https://github.com/ashtuchkin/iconv-lite/wiki/Javascript-source-file-encodings for more info.");
    }
  }
});

// ../../node_modules/.pnpm/unpipe@1.0.0/node_modules/unpipe/index.js
var require_unpipe = __commonJS({
  "../../node_modules/.pnpm/unpipe@1.0.0/node_modules/unpipe/index.js"(exports, module) {
    "use strict";
    module.exports = unpipe;
    function hasPipeDataListeners(stream) {
      var listeners = stream.listeners("data");
      for (var i = 0; i < listeners.length; i++) {
        if (listeners[i].name === "ondata") {
          return true;
        }
      }
      return false;
    }
    function unpipe(stream) {
      if (!stream) {
        throw new TypeError("argument stream is required");
      }
      if (typeof stream.unpipe === "function") {
        stream.unpipe();
        return;
      }
      if (!hasPipeDataListeners(stream)) {
        return;
      }
      var listener;
      var listeners = stream.listeners("close");
      for (var i = 0; i < listeners.length; i++) {
        listener = listeners[i];
        if (listener.name !== "cleanup" && listener.name !== "onclose") {
          continue;
        }
        listener.call(stream);
      }
    }
  }
});

// ../../node_modules/.pnpm/raw-body@2.5.2/node_modules/raw-body/index.js
var require_raw_body = __commonJS({
  "../../node_modules/.pnpm/raw-body@2.5.2/node_modules/raw-body/index.js"(exports, module) {
    "use strict";
    var asyncHooks = tryRequireAsyncHooks();
    var bytes = require_bytes();
    var createError = require_http_errors();
    var iconv = require_lib();
    var unpipe = require_unpipe();
    module.exports = getRawBody;
    var ICONV_ENCODING_MESSAGE_REGEXP = /^Encoding not recognized: /;
    function getDecoder(encoding) {
      if (!encoding) return null;
      try {
        return iconv.getDecoder(encoding);
      } catch (e) {
        if (!ICONV_ENCODING_MESSAGE_REGEXP.test(e.message)) throw e;
        throw createError(415, "specified encoding unsupported", {
          encoding,
          type: "encoding.unsupported"
        });
      }
    }
    function getRawBody(stream, options, callback) {
      var done = callback;
      var opts = options || {};
      if (stream === void 0) {
        throw new TypeError("argument stream is required");
      } else if (typeof stream !== "object" || stream === null || typeof stream.on !== "function") {
        throw new TypeError("argument stream must be a stream");
      }
      if (options === true || typeof options === "string") {
        opts = {
          encoding: options
        };
      }
      if (typeof options === "function") {
        done = options;
        opts = {};
      }
      if (done !== void 0 && typeof done !== "function") {
        throw new TypeError("argument callback must be a function");
      }
      if (!done && !global.Promise) {
        throw new TypeError("argument callback is required");
      }
      var encoding = opts.encoding !== true ? opts.encoding : "utf-8";
      var limit = bytes.parse(opts.limit);
      var length = opts.length != null && !isNaN(opts.length) ? parseInt(opts.length, 10) : null;
      if (done) {
        return readStream(stream, encoding, length, limit, wrap(done));
      }
      return new Promise(function executor(resolve, reject) {
        readStream(stream, encoding, length, limit, function onRead(err, buf) {
          if (err) return reject(err);
          resolve(buf);
        });
      });
    }
    function halt(stream) {
      unpipe(stream);
      if (typeof stream.pause === "function") {
        stream.pause();
      }
    }
    function readStream(stream, encoding, length, limit, callback) {
      var complete = false;
      var sync = true;
      if (limit !== null && length !== null && length > limit) {
        return done(createError(413, "request entity too large", {
          expected: length,
          length,
          limit,
          type: "entity.too.large"
        }));
      }
      var state = stream._readableState;
      if (stream._decoder || state && (state.encoding || state.decoder)) {
        return done(createError(500, "stream encoding should not be set", {
          type: "stream.encoding.set"
        }));
      }
      if (typeof stream.readable !== "undefined" && !stream.readable) {
        return done(createError(500, "stream is not readable", {
          type: "stream.not.readable"
        }));
      }
      var received = 0;
      var decoder;
      try {
        decoder = getDecoder(encoding);
      } catch (err) {
        return done(err);
      }
      var buffer = decoder ? "" : [];
      stream.on("aborted", onAborted);
      stream.on("close", cleanup);
      stream.on("data", onData);
      stream.on("end", onEnd);
      stream.on("error", onEnd);
      sync = false;
      function done() {
        var args = new Array(arguments.length);
        for (var i = 0; i < args.length; i++) {
          args[i] = arguments[i];
        }
        complete = true;
        if (sync) {
          process.nextTick(invokeCallback);
        } else {
          invokeCallback();
        }
        function invokeCallback() {
          cleanup();
          if (args[0]) {
            halt(stream);
          }
          callback.apply(null, args);
        }
      }
      function onAborted() {
        if (complete) return;
        done(createError(400, "request aborted", {
          code: "ECONNABORTED",
          expected: length,
          length,
          received,
          type: "request.aborted"
        }));
      }
      function onData(chunk2) {
        if (complete) return;
        received += chunk2.length;
        if (limit !== null && received > limit) {
          done(createError(413, "request entity too large", {
            limit,
            received,
            type: "entity.too.large"
          }));
        } else if (decoder) {
          buffer += decoder.write(chunk2);
        } else {
          buffer.push(chunk2);
        }
      }
      function onEnd(err) {
        if (complete) return;
        if (err) return done(err);
        if (length !== null && received !== length) {
          done(createError(400, "request size did not match content length", {
            expected: length,
            length,
            received,
            type: "request.size.invalid"
          }));
        } else {
          var string4 = decoder ? buffer + (decoder.end() || "") : Buffer.concat(buffer);
          done(null, string4);
        }
      }
      function cleanup() {
        buffer = null;
        stream.removeListener("aborted", onAborted);
        stream.removeListener("data", onData);
        stream.removeListener("end", onEnd);
        stream.removeListener("error", onEnd);
        stream.removeListener("close", cleanup);
      }
    }
    function tryRequireAsyncHooks() {
      try {
        return __require("async_hooks");
      } catch (e) {
        return {};
      }
    }
    function wrap(fn) {
      var res;
      if (asyncHooks.AsyncResource) {
        res = new asyncHooks.AsyncResource(fn.name || "bound-anonymous-fn");
      }
      if (!res || !res.runInAsyncScope) {
        return fn;
      }
      return res.runInAsyncScope.bind(res, fn, null);
    }
  }
});

// ../../node_modules/.pnpm/ee-first@1.1.1/node_modules/ee-first/index.js
var require_ee_first = __commonJS({
  "../../node_modules/.pnpm/ee-first@1.1.1/node_modules/ee-first/index.js"(exports, module) {
    "use strict";
    module.exports = first;
    function first(stuff, done) {
      if (!Array.isArray(stuff))
        throw new TypeError("arg must be an array of [ee, events...] arrays");
      var cleanups = [];
      for (var i = 0; i < stuff.length; i++) {
        var arr = stuff[i];
        if (!Array.isArray(arr) || arr.length < 2)
          throw new TypeError("each array member must be [ee, events...]");
        var ee = arr[0];
        for (var j = 1; j < arr.length; j++) {
          var event = arr[j];
          var fn = listener(event, callback);
          ee.on(event, fn);
          cleanups.push({
            ee,
            event,
            fn
          });
        }
      }
      function callback() {
        cleanup();
        done.apply(null, arguments);
      }
      function cleanup() {
        var x;
        for (var i2 = 0; i2 < cleanups.length; i2++) {
          x = cleanups[i2];
          x.ee.removeListener(x.event, x.fn);
        }
      }
      function thunk(fn2) {
        done = fn2;
      }
      thunk.cancel = cleanup;
      return thunk;
    }
    function listener(event, done) {
      return function onevent(arg1) {
        var args = new Array(arguments.length);
        var ee = this;
        var err = event === "error" ? arg1 : null;
        for (var i = 0; i < args.length; i++) {
          args[i] = arguments[i];
        }
        done(err, ee, event, args);
      };
    }
  }
});

// ../../node_modules/.pnpm/on-finished@2.4.1/node_modules/on-finished/index.js
var require_on_finished = __commonJS({
  "../../node_modules/.pnpm/on-finished@2.4.1/node_modules/on-finished/index.js"(exports, module) {
    "use strict";
    module.exports = onFinished;
    module.exports.isFinished = isFinished;
    var asyncHooks = tryRequireAsyncHooks();
    var first = require_ee_first();
    var defer = typeof setImmediate === "function" ? setImmediate : function(fn) {
      process.nextTick(fn.bind.apply(fn, arguments));
    };
    function onFinished(msg, listener) {
      if (isFinished(msg) !== false) {
        defer(listener, null, msg);
        return msg;
      }
      attachListener(msg, wrap(listener));
      return msg;
    }
    function isFinished(msg) {
      var socket = msg.socket;
      if (typeof msg.finished === "boolean") {
        return Boolean(msg.finished || socket && !socket.writable);
      }
      if (typeof msg.complete === "boolean") {
        return Boolean(msg.upgrade || !socket || !socket.readable || msg.complete && !msg.readable);
      }
      return void 0;
    }
    function attachFinishedListener(msg, callback) {
      var eeMsg;
      var eeSocket;
      var finished = false;
      function onFinish(error40) {
        eeMsg.cancel();
        eeSocket.cancel();
        finished = true;
        callback(error40);
      }
      eeMsg = eeSocket = first([[msg, "end", "finish"]], onFinish);
      function onSocket(socket) {
        msg.removeListener("socket", onSocket);
        if (finished) return;
        if (eeMsg !== eeSocket) return;
        eeSocket = first([[socket, "error", "close"]], onFinish);
      }
      if (msg.socket) {
        onSocket(msg.socket);
        return;
      }
      msg.on("socket", onSocket);
      if (msg.socket === void 0) {
        patchAssignSocket(msg, onSocket);
      }
    }
    function attachListener(msg, listener) {
      var attached = msg.__onFinished;
      if (!attached || !attached.queue) {
        attached = msg.__onFinished = createListener(msg);
        attachFinishedListener(msg, attached);
      }
      attached.queue.push(listener);
    }
    function createListener(msg) {
      function listener(err) {
        if (msg.__onFinished === listener) msg.__onFinished = null;
        if (!listener.queue) return;
        var queue = listener.queue;
        listener.queue = null;
        for (var i = 0; i < queue.length; i++) {
          queue[i](err, msg);
        }
      }
      listener.queue = [];
      return listener;
    }
    function patchAssignSocket(res, callback) {
      var assignSocket = res.assignSocket;
      if (typeof assignSocket !== "function") return;
      res.assignSocket = function _assignSocket(socket) {
        assignSocket.call(this, socket);
        callback(socket);
      };
    }
    function tryRequireAsyncHooks() {
      try {
        return __require("async_hooks");
      } catch (e) {
        return {};
      }
    }
    function wrap(fn) {
      var res;
      if (asyncHooks.AsyncResource) {
        res = new asyncHooks.AsyncResource(fn.name || "bound-anonymous-fn");
      }
      if (!res || !res.runInAsyncScope) {
        return fn;
      }
      return res.runInAsyncScope.bind(res, fn, null);
    }
  }
});

// ../../node_modules/.pnpm/body-parser@1.20.3/node_modules/body-parser/lib/read.js
var require_read = __commonJS({
  "../../node_modules/.pnpm/body-parser@1.20.3/node_modules/body-parser/lib/read.js"(exports, module) {
    "use strict";
    var createError = require_http_errors();
    var destroy = require_destroy();
    var getBody = require_raw_body();
    var iconv = require_lib();
    var onFinished = require_on_finished();
    var unpipe = require_unpipe();
    var zlib = __require("zlib");
    module.exports = read;
    function read(req, res, next, parse3, debug, options) {
      var length;
      var opts = options;
      var stream;
      req._body = true;
      var encoding = opts.encoding !== null ? opts.encoding : null;
      var verify = opts.verify;
      try {
        stream = contentstream(req, debug, opts.inflate);
        length = stream.length;
        stream.length = void 0;
      } catch (err) {
        return next(err);
      }
      opts.length = length;
      opts.encoding = verify ? null : encoding;
      if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) {
        return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
          charset: encoding.toLowerCase(),
          type: "charset.unsupported"
        }));
      }
      debug("read body");
      getBody(stream, opts, function(error40, body) {
        if (error40) {
          var _error;
          if (error40.type === "encoding.unsupported") {
            _error = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
              charset: encoding.toLowerCase(),
              type: "charset.unsupported"
            });
          } else {
            _error = createError(400, error40);
          }
          if (stream !== req) {
            unpipe(req);
            destroy(stream, true);
          }
          dump(req, function onfinished() {
            next(createError(400, _error));
          });
          return;
        }
        if (verify) {
          try {
            debug("verify body");
            verify(req, res, body, encoding);
          } catch (err) {
            next(createError(403, err, {
              body,
              type: err.type || "entity.verify.failed"
            }));
            return;
          }
        }
        var str = body;
        try {
          debug("parse body");
          str = typeof body !== "string" && encoding !== null ? iconv.decode(body, encoding) : body;
          req.body = parse3(str);
        } catch (err) {
          next(createError(400, err, {
            body: str,
            type: err.type || "entity.parse.failed"
          }));
          return;
        }
        next();
      });
    }
    function contentstream(req, debug, inflate) {
      var encoding = (req.headers["content-encoding"] || "identity").toLowerCase();
      var length = req.headers["content-length"];
      var stream;
      debug('content-encoding "%s"', encoding);
      if (inflate === false && encoding !== "identity") {
        throw createError(415, "content encoding unsupported", {
          encoding,
          type: "encoding.unsupported"
        });
      }
      switch (encoding) {
        case "deflate":
          stream = zlib.createInflate();
          debug("inflate body");
          req.pipe(stream);
          break;
        case "gzip":
          stream = zlib.createGunzip();
          debug("gunzip body");
          req.pipe(stream);
          break;
        case "identity":
          stream = req;
          stream.length = length;
          break;
        default:
          throw createError(415, 'unsupported content encoding "' + encoding + '"', {
            encoding,
            type: "encoding.unsupported"
          });
      }
      return stream;
    }
    function dump(req, callback) {
      if (onFinished.isFinished(req)) {
        callback(null);
      } else {
        onFinished(req, callback);
        req.resume();
      }
    }
  }
});

// ../../node_modules/.pnpm/media-typer@0.3.0/node_modules/media-typer/index.js
var require_media_typer = __commonJS({
  "../../node_modules/.pnpm/media-typer@0.3.0/node_modules/media-typer/index.js"(exports) {
    var paramRegExp = /; *([!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) *= *("(?:[ !\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u0020-\u007e])*"|[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) */g;
    var textRegExp = /^[\u0020-\u007e\u0080-\u00ff]+$/;
    var tokenRegExp = /^[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+$/;
    var qescRegExp = /\\([\u0000-\u007f])/g;
    var quoteRegExp = /([\\"])/g;
    var subtypeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.-]{0,126}$/;
    var typeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126}$/;
    var typeRegExp = /^ *([A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126})\/([A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}) *$/;
    exports.format = format;
    exports.parse = parse3;
    function format(obj) {
      if (!obj || typeof obj !== "object") {
        throw new TypeError("argument obj is required");
      }
      var parameters = obj.parameters;
      var subtype = obj.subtype;
      var suffix = obj.suffix;
      var type = obj.type;
      if (!type || !typeNameRegExp.test(type)) {
        throw new TypeError("invalid type");
      }
      if (!subtype || !subtypeNameRegExp.test(subtype)) {
        throw new TypeError("invalid subtype");
      }
      var string4 = type + "/" + subtype;
      if (suffix) {
        if (!typeNameRegExp.test(suffix)) {
          throw new TypeError("invalid suffix");
        }
        string4 += "+" + suffix;
      }
      if (parameters && typeof parameters === "object") {
        var param;
        var params = Object.keys(parameters).sort();
        for (var i = 0; i < params.length; i++) {
          param = params[i];
          if (!tokenRegExp.test(param)) {
            throw new TypeError("invalid parameter name");
          }
          string4 += "; " + param + "=" + qstring(parameters[param]);
        }
      }
      return string4;
    }
    function parse3(string4) {
      if (!string4) {
        throw new TypeError("argument string is required");
      }
      if (typeof string4 === "object") {
        string4 = getcontenttype(string4);
      }
      if (typeof string4 !== "string") {
        throw new TypeError("argument string is required to be a string");
      }
      var index2 = string4.indexOf(";");
      var type = index2 !== -1 ? string4.substr(0, index2) : string4;
      var key;
      var match;
      var obj = splitType(type);
      var params = {};
      var value;
      paramRegExp.lastIndex = index2;
      while (match = paramRegExp.exec(string4)) {
        if (match.index !== index2) {
          throw new TypeError("invalid parameter format");
        }
        index2 += match[0].length;
        key = match[1].toLowerCase();
        value = match[2];
        if (value[0] === '"') {
          value = value.substr(1, value.length - 2).replace(qescRegExp, "$1");
        }
        params[key] = value;
      }
      if (index2 !== -1 && index2 !== string4.length) {
        throw new TypeError("invalid parameter format");
      }
      obj.parameters = params;
      return obj;
    }
    function getcontenttype(obj) {
      if (typeof obj.getHeader === "function") {
        return obj.getHeader("content-type");
      }
      if (typeof obj.headers === "object") {
        return obj.headers && obj.headers["content-type"];
      }
    }
    function qstring(val) {
      var str = String(val);
      if (tokenRegExp.test(str)) {
        return str;
      }
      if (str.length > 0 && !textRegExp.test(str)) {
        throw new TypeError("invalid parameter value");
      }
      return '"' + str.replace(quoteRegExp, "\\$1") + '"';
    }
    function splitType(string4) {
      var match = typeRegExp.exec(string4.toLowerCase());
      if (!match) {
        throw new TypeError("invalid media type");
      }
      var type = match[1];
      var subtype = match[2];
      var suffix;
      var index2 = subtype.lastIndexOf("+");
      if (index2 !== -1) {
        suffix = subtype.substr(index2 + 1);
        subtype = subtype.substr(0, index2);
      }
      var obj = {
        type,
        subtype,
        suffix
      };
      return obj;
    }
  }
});

// ../../node_modules/.pnpm/mime-db@1.52.0/node_modules/mime-db/db.json
var require_db = __commonJS({
  "../../node_modules/.pnpm/mime-db@1.52.0/node_modules/mime-db/db.json"(exports, module) {
    module.exports = {
      "application/1d-interleaved-parityfec": {
        source: "iana"
      },
      "application/3gpdash-qoe-report+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/3gpp-ims+xml": {
        source: "iana",
        compressible: true
      },
      "application/3gpphal+json": {
        source: "iana",
        compressible: true
      },
      "application/3gpphalforms+json": {
        source: "iana",
        compressible: true
      },
      "application/a2l": {
        source: "iana"
      },
      "application/ace+cbor": {
        source: "iana"
      },
      "application/activemessage": {
        source: "iana"
      },
      "application/activity+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-costmap+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-costmapfilter+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-directory+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-endpointcost+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-endpointcostparams+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-endpointprop+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-endpointpropparams+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-error+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-networkmap+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-networkmapfilter+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-updatestreamcontrol+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-updatestreamparams+json": {
        source: "iana",
        compressible: true
      },
      "application/aml": {
        source: "iana"
      },
      "application/andrew-inset": {
        source: "iana",
        extensions: ["ez"]
      },
      "application/applefile": {
        source: "iana"
      },
      "application/applixware": {
        source: "apache",
        extensions: ["aw"]
      },
      "application/at+jwt": {
        source: "iana"
      },
      "application/atf": {
        source: "iana"
      },
      "application/atfx": {
        source: "iana"
      },
      "application/atom+xml": {
        source: "iana",
        compressible: true,
        extensions: ["atom"]
      },
      "application/atomcat+xml": {
        source: "iana",
        compressible: true,
        extensions: ["atomcat"]
      },
      "application/atomdeleted+xml": {
        source: "iana",
        compressible: true,
        extensions: ["atomdeleted"]
      },
      "application/atomicmail": {
        source: "iana"
      },
      "application/atomsvc+xml": {
        source: "iana",
        compressible: true,
        extensions: ["atomsvc"]
      },
      "application/atsc-dwd+xml": {
        source: "iana",
        compressible: true,
        extensions: ["dwd"]
      },
      "application/atsc-dynamic-event-message": {
        source: "iana"
      },
      "application/atsc-held+xml": {
        source: "iana",
        compressible: true,
        extensions: ["held"]
      },
      "application/atsc-rdt+json": {
        source: "iana",
        compressible: true
      },
      "application/atsc-rsat+xml": {
        source: "iana",
        compressible: true,
        extensions: ["rsat"]
      },
      "application/atxml": {
        source: "iana"
      },
      "application/auth-policy+xml": {
        source: "iana",
        compressible: true
      },
      "application/bacnet-xdd+zip": {
        source: "iana",
        compressible: false
      },
      "application/batch-smtp": {
        source: "iana"
      },
      "application/bdoc": {
        compressible: false,
        extensions: ["bdoc"]
      },
      "application/beep+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/calendar+json": {
        source: "iana",
        compressible: true
      },
      "application/calendar+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xcs"]
      },
      "application/call-completion": {
        source: "iana"
      },
      "application/cals-1840": {
        source: "iana"
      },
      "application/captive+json": {
        source: "iana",
        compressible: true
      },
      "application/cbor": {
        source: "iana"
      },
      "application/cbor-seq": {
        source: "iana"
      },
      "application/cccex": {
        source: "iana"
      },
      "application/ccmp+xml": {
        source: "iana",
        compressible: true
      },
      "application/ccxml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["ccxml"]
      },
      "application/cdfx+xml": {
        source: "iana",
        compressible: true,
        extensions: ["cdfx"]
      },
      "application/cdmi-capability": {
        source: "iana",
        extensions: ["cdmia"]
      },
      "application/cdmi-container": {
        source: "iana",
        extensions: ["cdmic"]
      },
      "application/cdmi-domain": {
        source: "iana",
        extensions: ["cdmid"]
      },
      "application/cdmi-object": {
        source: "iana",
        extensions: ["cdmio"]
      },
      "application/cdmi-queue": {
        source: "iana",
        extensions: ["cdmiq"]
      },
      "application/cdni": {
        source: "iana"
      },
      "application/cea": {
        source: "iana"
      },
      "application/cea-2018+xml": {
        source: "iana",
        compressible: true
      },
      "application/cellml+xml": {
        source: "iana",
        compressible: true
      },
      "application/cfw": {
        source: "iana"
      },
      "application/city+json": {
        source: "iana",
        compressible: true
      },
      "application/clr": {
        source: "iana"
      },
      "application/clue+xml": {
        source: "iana",
        compressible: true
      },
      "application/clue_info+xml": {
        source: "iana",
        compressible: true
      },
      "application/cms": {
        source: "iana"
      },
      "application/cnrp+xml": {
        source: "iana",
        compressible: true
      },
      "application/coap-group+json": {
        source: "iana",
        compressible: true
      },
      "application/coap-payload": {
        source: "iana"
      },
      "application/commonground": {
        source: "iana"
      },
      "application/conference-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/cose": {
        source: "iana"
      },
      "application/cose-key": {
        source: "iana"
      },
      "application/cose-key-set": {
        source: "iana"
      },
      "application/cpl+xml": {
        source: "iana",
        compressible: true,
        extensions: ["cpl"]
      },
      "application/csrattrs": {
        source: "iana"
      },
      "application/csta+xml": {
        source: "iana",
        compressible: true
      },
      "application/cstadata+xml": {
        source: "iana",
        compressible: true
      },
      "application/csvm+json": {
        source: "iana",
        compressible: true
      },
      "application/cu-seeme": {
        source: "apache",
        extensions: ["cu"]
      },
      "application/cwt": {
        source: "iana"
      },
      "application/cybercash": {
        source: "iana"
      },
      "application/dart": {
        compressible: true
      },
      "application/dash+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mpd"]
      },
      "application/dash-patch+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mpp"]
      },
      "application/dashdelta": {
        source: "iana"
      },
      "application/davmount+xml": {
        source: "iana",
        compressible: true,
        extensions: ["davmount"]
      },
      "application/dca-rft": {
        source: "iana"
      },
      "application/dcd": {
        source: "iana"
      },
      "application/dec-dx": {
        source: "iana"
      },
      "application/dialog-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/dicom": {
        source: "iana"
      },
      "application/dicom+json": {
        source: "iana",
        compressible: true
      },
      "application/dicom+xml": {
        source: "iana",
        compressible: true
      },
      "application/dii": {
        source: "iana"
      },
      "application/dit": {
        source: "iana"
      },
      "application/dns": {
        source: "iana"
      },
      "application/dns+json": {
        source: "iana",
        compressible: true
      },
      "application/dns-message": {
        source: "iana"
      },
      "application/docbook+xml": {
        source: "apache",
        compressible: true,
        extensions: ["dbk"]
      },
      "application/dots+cbor": {
        source: "iana"
      },
      "application/dskpp+xml": {
        source: "iana",
        compressible: true
      },
      "application/dssc+der": {
        source: "iana",
        extensions: ["dssc"]
      },
      "application/dssc+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xdssc"]
      },
      "application/dvcs": {
        source: "iana"
      },
      "application/ecmascript": {
        source: "iana",
        compressible: true,
        extensions: ["es", "ecma"]
      },
      "application/edi-consent": {
        source: "iana"
      },
      "application/edi-x12": {
        source: "iana",
        compressible: false
      },
      "application/edifact": {
        source: "iana",
        compressible: false
      },
      "application/efi": {
        source: "iana"
      },
      "application/elm+json": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/elm+xml": {
        source: "iana",
        compressible: true
      },
      "application/emergencycalldata.cap+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/emergencycalldata.comment+xml": {
        source: "iana",
        compressible: true
      },
      "application/emergencycalldata.control+xml": {
        source: "iana",
        compressible: true
      },
      "application/emergencycalldata.deviceinfo+xml": {
        source: "iana",
        compressible: true
      },
      "application/emergencycalldata.ecall.msd": {
        source: "iana"
      },
      "application/emergencycalldata.providerinfo+xml": {
        source: "iana",
        compressible: true
      },
      "application/emergencycalldata.serviceinfo+xml": {
        source: "iana",
        compressible: true
      },
      "application/emergencycalldata.subscriberinfo+xml": {
        source: "iana",
        compressible: true
      },
      "application/emergencycalldata.veds+xml": {
        source: "iana",
        compressible: true
      },
      "application/emma+xml": {
        source: "iana",
        compressible: true,
        extensions: ["emma"]
      },
      "application/emotionml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["emotionml"]
      },
      "application/encaprtp": {
        source: "iana"
      },
      "application/epp+xml": {
        source: "iana",
        compressible: true
      },
      "application/epub+zip": {
        source: "iana",
        compressible: false,
        extensions: ["epub"]
      },
      "application/eshop": {
        source: "iana"
      },
      "application/exi": {
        source: "iana",
        extensions: ["exi"]
      },
      "application/expect-ct-report+json": {
        source: "iana",
        compressible: true
      },
      "application/express": {
        source: "iana",
        extensions: ["exp"]
      },
      "application/fastinfoset": {
        source: "iana"
      },
      "application/fastsoap": {
        source: "iana"
      },
      "application/fdt+xml": {
        source: "iana",
        compressible: true,
        extensions: ["fdt"]
      },
      "application/fhir+json": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/fhir+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/fido.trusted-apps+json": {
        compressible: true
      },
      "application/fits": {
        source: "iana"
      },
      "application/flexfec": {
        source: "iana"
      },
      "application/font-sfnt": {
        source: "iana"
      },
      "application/font-tdpfr": {
        source: "iana",
        extensions: ["pfr"]
      },
      "application/font-woff": {
        source: "iana",
        compressible: false
      },
      "application/framework-attributes+xml": {
        source: "iana",
        compressible: true
      },
      "application/geo+json": {
        source: "iana",
        compressible: true,
        extensions: ["geojson"]
      },
      "application/geo+json-seq": {
        source: "iana"
      },
      "application/geopackage+sqlite3": {
        source: "iana"
      },
      "application/geoxacml+xml": {
        source: "iana",
        compressible: true
      },
      "application/gltf-buffer": {
        source: "iana"
      },
      "application/gml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["gml"]
      },
      "application/gpx+xml": {
        source: "apache",
        compressible: true,
        extensions: ["gpx"]
      },
      "application/gxf": {
        source: "apache",
        extensions: ["gxf"]
      },
      "application/gzip": {
        source: "iana",
        compressible: false,
        extensions: ["gz"]
      },
      "application/h224": {
        source: "iana"
      },
      "application/held+xml": {
        source: "iana",
        compressible: true
      },
      "application/hjson": {
        extensions: ["hjson"]
      },
      "application/http": {
        source: "iana"
      },
      "application/hyperstudio": {
        source: "iana",
        extensions: ["stk"]
      },
      "application/ibe-key-request+xml": {
        source: "iana",
        compressible: true
      },
      "application/ibe-pkg-reply+xml": {
        source: "iana",
        compressible: true
      },
      "application/ibe-pp-data": {
        source: "iana"
      },
      "application/iges": {
        source: "iana"
      },
      "application/im-iscomposing+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/index": {
        source: "iana"
      },
      "application/index.cmd": {
        source: "iana"
      },
      "application/index.obj": {
        source: "iana"
      },
      "application/index.response": {
        source: "iana"
      },
      "application/index.vnd": {
        source: "iana"
      },
      "application/inkml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["ink", "inkml"]
      },
      "application/iotp": {
        source: "iana"
      },
      "application/ipfix": {
        source: "iana",
        extensions: ["ipfix"]
      },
      "application/ipp": {
        source: "iana"
      },
      "application/isup": {
        source: "iana"
      },
      "application/its+xml": {
        source: "iana",
        compressible: true,
        extensions: ["its"]
      },
      "application/java-archive": {
        source: "apache",
        compressible: false,
        extensions: ["jar", "war", "ear"]
      },
      "application/java-serialized-object": {
        source: "apache",
        compressible: false,
        extensions: ["ser"]
      },
      "application/java-vm": {
        source: "apache",
        compressible: false,
        extensions: ["class"]
      },
      "application/javascript": {
        source: "iana",
        charset: "UTF-8",
        compressible: true,
        extensions: ["js", "mjs"]
      },
      "application/jf2feed+json": {
        source: "iana",
        compressible: true
      },
      "application/jose": {
        source: "iana"
      },
      "application/jose+json": {
        source: "iana",
        compressible: true
      },
      "application/jrd+json": {
        source: "iana",
        compressible: true
      },
      "application/jscalendar+json": {
        source: "iana",
        compressible: true
      },
      "application/json": {
        source: "iana",
        charset: "UTF-8",
        compressible: true,
        extensions: ["json", "map"]
      },
      "application/json-patch+json": {
        source: "iana",
        compressible: true
      },
      "application/json-seq": {
        source: "iana"
      },
      "application/json5": {
        extensions: ["json5"]
      },
      "application/jsonml+json": {
        source: "apache",
        compressible: true,
        extensions: ["jsonml"]
      },
      "application/jwk+json": {
        source: "iana",
        compressible: true
      },
      "application/jwk-set+json": {
        source: "iana",
        compressible: true
      },
      "application/jwt": {
        source: "iana"
      },
      "application/kpml-request+xml": {
        source: "iana",
        compressible: true
      },
      "application/kpml-response+xml": {
        source: "iana",
        compressible: true
      },
      "application/ld+json": {
        source: "iana",
        compressible: true,
        extensions: ["jsonld"]
      },
      "application/lgr+xml": {
        source: "iana",
        compressible: true,
        extensions: ["lgr"]
      },
      "application/link-format": {
        source: "iana"
      },
      "application/load-control+xml": {
        source: "iana",
        compressible: true
      },
      "application/lost+xml": {
        source: "iana",
        compressible: true,
        extensions: ["lostxml"]
      },
      "application/lostsync+xml": {
        source: "iana",
        compressible: true
      },
      "application/lpf+zip": {
        source: "iana",
        compressible: false
      },
      "application/lxf": {
        source: "iana"
      },
      "application/mac-binhex40": {
        source: "iana",
        extensions: ["hqx"]
      },
      "application/mac-compactpro": {
        source: "apache",
        extensions: ["cpt"]
      },
      "application/macwriteii": {
        source: "iana"
      },
      "application/mads+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mads"]
      },
      "application/manifest+json": {
        source: "iana",
        charset: "UTF-8",
        compressible: true,
        extensions: ["webmanifest"]
      },
      "application/marc": {
        source: "iana",
        extensions: ["mrc"]
      },
      "application/marcxml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mrcx"]
      },
      "application/mathematica": {
        source: "iana",
        extensions: ["ma", "nb", "mb"]
      },
      "application/mathml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mathml"]
      },
      "application/mathml-content+xml": {
        source: "iana",
        compressible: true
      },
      "application/mathml-presentation+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-associated-procedure-description+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-deregister+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-envelope+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-msk+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-msk-response+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-protection-description+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-reception-report+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-register+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-register-response+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-schedule+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-user-service-description+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbox": {
        source: "iana",
        extensions: ["mbox"]
      },
      "application/media-policy-dataset+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mpf"]
      },
      "application/media_control+xml": {
        source: "iana",
        compressible: true
      },
      "application/mediaservercontrol+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mscml"]
      },
      "application/merge-patch+json": {
        source: "iana",
        compressible: true
      },
      "application/metalink+xml": {
        source: "apache",
        compressible: true,
        extensions: ["metalink"]
      },
      "application/metalink4+xml": {
        source: "iana",
        compressible: true,
        extensions: ["meta4"]
      },
      "application/mets+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mets"]
      },
      "application/mf4": {
        source: "iana"
      },
      "application/mikey": {
        source: "iana"
      },
      "application/mipc": {
        source: "iana"
      },
      "application/missing-blocks+cbor-seq": {
        source: "iana"
      },
      "application/mmt-aei+xml": {
        source: "iana",
        compressible: true,
        extensions: ["maei"]
      },
      "application/mmt-usd+xml": {
        source: "iana",
        compressible: true,
        extensions: ["musd"]
      },
      "application/mods+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mods"]
      },
      "application/moss-keys": {
        source: "iana"
      },
      "application/moss-signature": {
        source: "iana"
      },
      "application/mosskey-data": {
        source: "iana"
      },
      "application/mosskey-request": {
        source: "iana"
      },
      "application/mp21": {
        source: "iana",
        extensions: ["m21", "mp21"]
      },
      "application/mp4": {
        source: "iana",
        extensions: ["mp4s", "m4p"]
      },
      "application/mpeg4-generic": {
        source: "iana"
      },
      "application/mpeg4-iod": {
        source: "iana"
      },
      "application/mpeg4-iod-xmt": {
        source: "iana"
      },
      "application/mrb-consumer+xml": {
        source: "iana",
        compressible: true
      },
      "application/mrb-publish+xml": {
        source: "iana",
        compressible: true
      },
      "application/msc-ivr+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/msc-mixer+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/msword": {
        source: "iana",
        compressible: false,
        extensions: ["doc", "dot"]
      },
      "application/mud+json": {
        source: "iana",
        compressible: true
      },
      "application/multipart-core": {
        source: "iana"
      },
      "application/mxf": {
        source: "iana",
        extensions: ["mxf"]
      },
      "application/n-quads": {
        source: "iana",
        extensions: ["nq"]
      },
      "application/n-triples": {
        source: "iana",
        extensions: ["nt"]
      },
      "application/nasdata": {
        source: "iana"
      },
      "application/news-checkgroups": {
        source: "iana",
        charset: "US-ASCII"
      },
      "application/news-groupinfo": {
        source: "iana",
        charset: "US-ASCII"
      },
      "application/news-transmission": {
        source: "iana"
      },
      "application/nlsml+xml": {
        source: "iana",
        compressible: true
      },
      "application/node": {
        source: "iana",
        extensions: ["cjs"]
      },
      "application/nss": {
        source: "iana"
      },
      "application/oauth-authz-req+jwt": {
        source: "iana"
      },
      "application/oblivious-dns-message": {
        source: "iana"
      },
      "application/ocsp-request": {
        source: "iana"
      },
      "application/ocsp-response": {
        source: "iana"
      },
      "application/octet-stream": {
        source: "iana",
        compressible: false,
        extensions: ["bin", "dms", "lrf", "mar", "so", "dist", "distz", "pkg", "bpk", "dump", "elc", "deploy", "exe", "dll", "deb", "dmg", "iso", "img", "msi", "msp", "msm", "buffer"]
      },
      "application/oda": {
        source: "iana",
        extensions: ["oda"]
      },
      "application/odm+xml": {
        source: "iana",
        compressible: true
      },
      "application/odx": {
        source: "iana"
      },
      "application/oebps-package+xml": {
        source: "iana",
        compressible: true,
        extensions: ["opf"]
      },
      "application/ogg": {
        source: "iana",
        compressible: false,
        extensions: ["ogx"]
      },
      "application/omdoc+xml": {
        source: "apache",
        compressible: true,
        extensions: ["omdoc"]
      },
      "application/onenote": {
        source: "apache",
        extensions: ["onetoc", "onetoc2", "onetmp", "onepkg"]
      },
      "application/opc-nodeset+xml": {
        source: "iana",
        compressible: true
      },
      "application/oscore": {
        source: "iana"
      },
      "application/oxps": {
        source: "iana",
        extensions: ["oxps"]
      },
      "application/p21": {
        source: "iana"
      },
      "application/p21+zip": {
        source: "iana",
        compressible: false
      },
      "application/p2p-overlay+xml": {
        source: "iana",
        compressible: true,
        extensions: ["relo"]
      },
      "application/parityfec": {
        source: "iana"
      },
      "application/passport": {
        source: "iana"
      },
      "application/patch-ops-error+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xer"]
      },
      "application/pdf": {
        source: "iana",
        compressible: false,
        extensions: ["pdf"]
      },
      "application/pdx": {
        source: "iana"
      },
      "application/pem-certificate-chain": {
        source: "iana"
      },
      "application/pgp-encrypted": {
        source: "iana",
        compressible: false,
        extensions: ["pgp"]
      },
      "application/pgp-keys": {
        source: "iana",
        extensions: ["asc"]
      },
      "application/pgp-signature": {
        source: "iana",
        extensions: ["asc", "sig"]
      },
      "application/pics-rules": {
        source: "apache",
        extensions: ["prf"]
      },
      "application/pidf+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/pidf-diff+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/pkcs10": {
        source: "iana",
        extensions: ["p10"]
      },
      "application/pkcs12": {
        source: "iana"
      },
      "application/pkcs7-mime": {
        source: "iana",
        extensions: ["p7m", "p7c"]
      },
      "application/pkcs7-signature": {
        source: "iana",
        extensions: ["p7s"]
      },
      "application/pkcs8": {
        source: "iana",
        extensions: ["p8"]
      },
      "application/pkcs8-encrypted": {
        source: "iana"
      },
      "application/pkix-attr-cert": {
        source: "iana",
        extensions: ["ac"]
      },
      "application/pkix-cert": {
        source: "iana",
        extensions: ["cer"]
      },
      "application/pkix-crl": {
        source: "iana",
        extensions: ["crl"]
      },
      "application/pkix-pkipath": {
        source: "iana",
        extensions: ["pkipath"]
      },
      "application/pkixcmp": {
        source: "iana",
        extensions: ["pki"]
      },
      "application/pls+xml": {
        source: "iana",
        compressible: true,
        extensions: ["pls"]
      },
      "application/poc-settings+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/postscript": {
        source: "iana",
        compressible: true,
        extensions: ["ai", "eps", "ps"]
      },
      "application/ppsp-tracker+json": {
        source: "iana",
        compressible: true
      },
      "application/problem+json": {
        source: "iana",
        compressible: true
      },
      "application/problem+xml": {
        source: "iana",
        compressible: true
      },
      "application/provenance+xml": {
        source: "iana",
        compressible: true,
        extensions: ["provx"]
      },
      "application/prs.alvestrand.titrax-sheet": {
        source: "iana"
      },
      "application/prs.cww": {
        source: "iana",
        extensions: ["cww"]
      },
      "application/prs.cyn": {
        source: "iana",
        charset: "7-BIT"
      },
      "application/prs.hpub+zip": {
        source: "iana",
        compressible: false
      },
      "application/prs.nprend": {
        source: "iana"
      },
      "application/prs.plucker": {
        source: "iana"
      },
      "application/prs.rdf-xml-crypt": {
        source: "iana"
      },
      "application/prs.xsf+xml": {
        source: "iana",
        compressible: true
      },
      "application/pskc+xml": {
        source: "iana",
        compressible: true,
        extensions: ["pskcxml"]
      },
      "application/pvd+json": {
        source: "iana",
        compressible: true
      },
      "application/qsig": {
        source: "iana"
      },
      "application/raml+yaml": {
        compressible: true,
        extensions: ["raml"]
      },
      "application/raptorfec": {
        source: "iana"
      },
      "application/rdap+json": {
        source: "iana",
        compressible: true
      },
      "application/rdf+xml": {
        source: "iana",
        compressible: true,
        extensions: ["rdf", "owl"]
      },
      "application/reginfo+xml": {
        source: "iana",
        compressible: true,
        extensions: ["rif"]
      },
      "application/relax-ng-compact-syntax": {
        source: "iana",
        extensions: ["rnc"]
      },
      "application/remote-printing": {
        source: "iana"
      },
      "application/reputon+json": {
        source: "iana",
        compressible: true
      },
      "application/resource-lists+xml": {
        source: "iana",
        compressible: true,
        extensions: ["rl"]
      },
      "application/resource-lists-diff+xml": {
        source: "iana",
        compressible: true,
        extensions: ["rld"]
      },
      "application/rfc+xml": {
        source: "iana",
        compressible: true
      },
      "application/riscos": {
        source: "iana"
      },
      "application/rlmi+xml": {
        source: "iana",
        compressible: true
      },
      "application/rls-services+xml": {
        source: "iana",
        compressible: true,
        extensions: ["rs"]
      },
      "application/route-apd+xml": {
        source: "iana",
        compressible: true,
        extensions: ["rapd"]
      },
      "application/route-s-tsid+xml": {
        source: "iana",
        compressible: true,
        extensions: ["sls"]
      },
      "application/route-usd+xml": {
        source: "iana",
        compressible: true,
        extensions: ["rusd"]
      },
      "application/rpki-ghostbusters": {
        source: "iana",
        extensions: ["gbr"]
      },
      "application/rpki-manifest": {
        source: "iana",
        extensions: ["mft"]
      },
      "application/rpki-publication": {
        source: "iana"
      },
      "application/rpki-roa": {
        source: "iana",
        extensions: ["roa"]
      },
      "application/rpki-updown": {
        source: "iana"
      },
      "application/rsd+xml": {
        source: "apache",
        compressible: true,
        extensions: ["rsd"]
      },
      "application/rss+xml": {
        source: "apache",
        compressible: true,
        extensions: ["rss"]
      },
      "application/rtf": {
        source: "iana",
        compressible: true,
        extensions: ["rtf"]
      },
      "application/rtploopback": {
        source: "iana"
      },
      "application/rtx": {
        source: "iana"
      },
      "application/samlassertion+xml": {
        source: "iana",
        compressible: true
      },
      "application/samlmetadata+xml": {
        source: "iana",
        compressible: true
      },
      "application/sarif+json": {
        source: "iana",
        compressible: true
      },
      "application/sarif-external-properties+json": {
        source: "iana",
        compressible: true
      },
      "application/sbe": {
        source: "iana"
      },
      "application/sbml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["sbml"]
      },
      "application/scaip+xml": {
        source: "iana",
        compressible: true
      },
      "application/scim+json": {
        source: "iana",
        compressible: true
      },
      "application/scvp-cv-request": {
        source: "iana",
        extensions: ["scq"]
      },
      "application/scvp-cv-response": {
        source: "iana",
        extensions: ["scs"]
      },
      "application/scvp-vp-request": {
        source: "iana",
        extensions: ["spq"]
      },
      "application/scvp-vp-response": {
        source: "iana",
        extensions: ["spp"]
      },
      "application/sdp": {
        source: "iana",
        extensions: ["sdp"]
      },
      "application/secevent+jwt": {
        source: "iana"
      },
      "application/senml+cbor": {
        source: "iana"
      },
      "application/senml+json": {
        source: "iana",
        compressible: true
      },
      "application/senml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["senmlx"]
      },
      "application/senml-etch+cbor": {
        source: "iana"
      },
      "application/senml-etch+json": {
        source: "iana",
        compressible: true
      },
      "application/senml-exi": {
        source: "iana"
      },
      "application/sensml+cbor": {
        source: "iana"
      },
      "application/sensml+json": {
        source: "iana",
        compressible: true
      },
      "application/sensml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["sensmlx"]
      },
      "application/sensml-exi": {
        source: "iana"
      },
      "application/sep+xml": {
        source: "iana",
        compressible: true
      },
      "application/sep-exi": {
        source: "iana"
      },
      "application/session-info": {
        source: "iana"
      },
      "application/set-payment": {
        source: "iana"
      },
      "application/set-payment-initiation": {
        source: "iana",
        extensions: ["setpay"]
      },
      "application/set-registration": {
        source: "iana"
      },
      "application/set-registration-initiation": {
        source: "iana",
        extensions: ["setreg"]
      },
      "application/sgml": {
        source: "iana"
      },
      "application/sgml-open-catalog": {
        source: "iana"
      },
      "application/shf+xml": {
        source: "iana",
        compressible: true,
        extensions: ["shf"]
      },
      "application/sieve": {
        source: "iana",
        extensions: ["siv", "sieve"]
      },
      "application/simple-filter+xml": {
        source: "iana",
        compressible: true
      },
      "application/simple-message-summary": {
        source: "iana"
      },
      "application/simplesymbolcontainer": {
        source: "iana"
      },
      "application/sipc": {
        source: "iana"
      },
      "application/slate": {
        source: "iana"
      },
      "application/smil": {
        source: "iana"
      },
      "application/smil+xml": {
        source: "iana",
        compressible: true,
        extensions: ["smi", "smil"]
      },
      "application/smpte336m": {
        source: "iana"
      },
      "application/soap+fastinfoset": {
        source: "iana"
      },
      "application/soap+xml": {
        source: "iana",
        compressible: true
      },
      "application/sparql-query": {
        source: "iana",
        extensions: ["rq"]
      },
      "application/sparql-results+xml": {
        source: "iana",
        compressible: true,
        extensions: ["srx"]
      },
      "application/spdx+json": {
        source: "iana",
        compressible: true
      },
      "application/spirits-event+xml": {
        source: "iana",
        compressible: true
      },
      "application/sql": {
        source: "iana"
      },
      "application/srgs": {
        source: "iana",
        extensions: ["gram"]
      },
      "application/srgs+xml": {
        source: "iana",
        compressible: true,
        extensions: ["grxml"]
      },
      "application/sru+xml": {
        source: "iana",
        compressible: true,
        extensions: ["sru"]
      },
      "application/ssdl+xml": {
        source: "apache",
        compressible: true,
        extensions: ["ssdl"]
      },
      "application/ssml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["ssml"]
      },
      "application/stix+json": {
        source: "iana",
        compressible: true
      },
      "application/swid+xml": {
        source: "iana",
        compressible: true,
        extensions: ["swidtag"]
      },
      "application/tamp-apex-update": {
        source: "iana"
      },
      "application/tamp-apex-update-confirm": {
        source: "iana"
      },
      "application/tamp-community-update": {
        source: "iana"
      },
      "application/tamp-community-update-confirm": {
        source: "iana"
      },
      "application/tamp-error": {
        source: "iana"
      },
      "application/tamp-sequence-adjust": {
        source: "iana"
      },
      "application/tamp-sequence-adjust-confirm": {
        source: "iana"
      },
      "application/tamp-status-query": {
        source: "iana"
      },
      "application/tamp-status-response": {
        source: "iana"
      },
      "application/tamp-update": {
        source: "iana"
      },
      "application/tamp-update-confirm": {
        source: "iana"
      },
      "application/tar": {
        compressible: true
      },
      "application/taxii+json": {
        source: "iana",
        compressible: true
      },
      "application/td+json": {
        source: "iana",
        compressible: true
      },
      "application/tei+xml": {
        source: "iana",
        compressible: true,
        extensions: ["tei", "teicorpus"]
      },
      "application/tetra_isi": {
        source: "iana"
      },
      "application/thraud+xml": {
        source: "iana",
        compressible: true,
        extensions: ["tfi"]
      },
      "application/timestamp-query": {
        source: "iana"
      },
      "application/timestamp-reply": {
        source: "iana"
      },
      "application/timestamped-data": {
        source: "iana",
        extensions: ["tsd"]
      },
      "application/tlsrpt+gzip": {
        source: "iana"
      },
      "application/tlsrpt+json": {
        source: "iana",
        compressible: true
      },
      "application/tnauthlist": {
        source: "iana"
      },
      "application/token-introspection+jwt": {
        source: "iana"
      },
      "application/toml": {
        compressible: true,
        extensions: ["toml"]
      },
      "application/trickle-ice-sdpfrag": {
        source: "iana"
      },
      "application/trig": {
        source: "iana",
        extensions: ["trig"]
      },
      "application/ttml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["ttml"]
      },
      "application/tve-trigger": {
        source: "iana"
      },
      "application/tzif": {
        source: "iana"
      },
      "application/tzif-leap": {
        source: "iana"
      },
      "application/ubjson": {
        compressible: false,
        extensions: ["ubj"]
      },
      "application/ulpfec": {
        source: "iana"
      },
      "application/urc-grpsheet+xml": {
        source: "iana",
        compressible: true
      },
      "application/urc-ressheet+xml": {
        source: "iana",
        compressible: true,
        extensions: ["rsheet"]
      },
      "application/urc-targetdesc+xml": {
        source: "iana",
        compressible: true,
        extensions: ["td"]
      },
      "application/urc-uisocketdesc+xml": {
        source: "iana",
        compressible: true
      },
      "application/vcard+json": {
        source: "iana",
        compressible: true
      },
      "application/vcard+xml": {
        source: "iana",
        compressible: true
      },
      "application/vemmi": {
        source: "iana"
      },
      "application/vividence.scriptfile": {
        source: "apache"
      },
      "application/vnd.1000minds.decision-model+xml": {
        source: "iana",
        compressible: true,
        extensions: ["1km"]
      },
      "application/vnd.3gpp-prose+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp-prose-pc3ch+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp-v2x-local-service-information": {
        source: "iana"
      },
      "application/vnd.3gpp.5gnas": {
        source: "iana"
      },
      "application/vnd.3gpp.access-transfer-events+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.bsf+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.gmop+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.gtpc": {
        source: "iana"
      },
      "application/vnd.3gpp.interworking-data": {
        source: "iana"
      },
      "application/vnd.3gpp.lpp": {
        source: "iana"
      },
      "application/vnd.3gpp.mc-signalling-ear": {
        source: "iana"
      },
      "application/vnd.3gpp.mcdata-affiliation-command+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcdata-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcdata-payload": {
        source: "iana"
      },
      "application/vnd.3gpp.mcdata-service-config+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcdata-signalling": {
        source: "iana"
      },
      "application/vnd.3gpp.mcdata-ue-config+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcdata-user-profile+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-affiliation-command+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-floor-request+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-location-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-mbms-usage-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-service-config+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-signed+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-ue-config+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-ue-init-config+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-user-profile+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcvideo-affiliation-command+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcvideo-affiliation-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcvideo-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcvideo-location-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcvideo-service-config+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcvideo-transmission-request+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcvideo-ue-config+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcvideo-user-profile+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mid-call+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.ngap": {
        source: "iana"
      },
      "application/vnd.3gpp.pfcp": {
        source: "iana"
      },
      "application/vnd.3gpp.pic-bw-large": {
        source: "iana",
        extensions: ["plb"]
      },
      "application/vnd.3gpp.pic-bw-small": {
        source: "iana",
        extensions: ["psb"]
      },
      "application/vnd.3gpp.pic-bw-var": {
        source: "iana",
        extensions: ["pvb"]
      },
      "application/vnd.3gpp.s1ap": {
        source: "iana"
      },
      "application/vnd.3gpp.sms": {
        source: "iana"
      },
      "application/vnd.3gpp.sms+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.srvcc-ext+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.srvcc-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.state-and-event-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.ussd+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp2.bcmcsinfo+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp2.sms": {
        source: "iana"
      },
      "application/vnd.3gpp2.tcap": {
        source: "iana",
        extensions: ["tcap"]
      },
      "application/vnd.3lightssoftware.imagescal": {
        source: "iana"
      },
      "application/vnd.3m.post-it-notes": {
        source: "iana",
        extensions: ["pwn"]
      },
      "application/vnd.accpac.simply.aso": {
        source: "iana",
        extensions: ["aso"]
      },
      "application/vnd.accpac.simply.imp": {
        source: "iana",
        extensions: ["imp"]
      },
      "application/vnd.acucobol": {
        source: "iana",
        extensions: ["acu"]
      },
      "application/vnd.acucorp": {
        source: "iana",
        extensions: ["atc", "acutc"]
      },
      "application/vnd.adobe.air-application-installer-package+zip": {
        source: "apache",
        compressible: false,
        extensions: ["air"]
      },
      "application/vnd.adobe.flash.movie": {
        source: "iana"
      },
      "application/vnd.adobe.formscentral.fcdt": {
        source: "iana",
        extensions: ["fcdt"]
      },
      "application/vnd.adobe.fxp": {
        source: "iana",
        extensions: ["fxp", "fxpl"]
      },
      "application/vnd.adobe.partial-upload": {
        source: "iana"
      },
      "application/vnd.adobe.xdp+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xdp"]
      },
      "application/vnd.adobe.xfdf": {
        source: "iana",
        extensions: ["xfdf"]
      },
      "application/vnd.aether.imp": {
        source: "iana"
      },
      "application/vnd.afpc.afplinedata": {
        source: "iana"
      },
      "application/vnd.afpc.afplinedata-pagedef": {
        source: "iana"
      },
      "application/vnd.afpc.cmoca-cmresource": {
        source: "iana"
      },
      "application/vnd.afpc.foca-charset": {
        source: "iana"
      },
      "application/vnd.afpc.foca-codedfont": {
        source: "iana"
      },
      "application/vnd.afpc.foca-codepage": {
        source: "iana"
      },
      "application/vnd.afpc.modca": {
        source: "iana"
      },
      "application/vnd.afpc.modca-cmtable": {
        source: "iana"
      },
      "application/vnd.afpc.modca-formdef": {
        source: "iana"
      },
      "application/vnd.afpc.modca-mediummap": {
        source: "iana"
      },
      "application/vnd.afpc.modca-objectcontainer": {
        source: "iana"
      },
      "application/vnd.afpc.modca-overlay": {
        source: "iana"
      },
      "application/vnd.afpc.modca-pagesegment": {
        source: "iana"
      },
      "application/vnd.age": {
        source: "iana",
        extensions: ["age"]
      },
      "application/vnd.ah-barcode": {
        source: "iana"
      },
      "application/vnd.ahead.space": {
        source: "iana",
        extensions: ["ahead"]
      },
      "application/vnd.airzip.filesecure.azf": {
        source: "iana",
        extensions: ["azf"]
      },
      "application/vnd.airzip.filesecure.azs": {
        source: "iana",
        extensions: ["azs"]
      },
      "application/vnd.amadeus+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.amazon.ebook": {
        source: "apache",
        extensions: ["azw"]
      },
      "application/vnd.amazon.mobi8-ebook": {
        source: "iana"
      },
      "application/vnd.americandynamics.acc": {
        source: "iana",
        extensions: ["acc"]
      },
      "application/vnd.amiga.ami": {
        source: "iana",
        extensions: ["ami"]
      },
      "application/vnd.amundsen.maze+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.android.ota": {
        source: "iana"
      },
      "application/vnd.android.package-archive": {
        source: "apache",
        compressible: false,
        extensions: ["apk"]
      },
      "application/vnd.anki": {
        source: "iana"
      },
      "application/vnd.anser-web-certificate-issue-initiation": {
        source: "iana",
        extensions: ["cii"]
      },
      "application/vnd.anser-web-funds-transfer-initiation": {
        source: "apache",
        extensions: ["fti"]
      },
      "application/vnd.antix.game-component": {
        source: "iana",
        extensions: ["atx"]
      },
      "application/vnd.apache.arrow.file": {
        source: "iana"
      },
      "application/vnd.apache.arrow.stream": {
        source: "iana"
      },
      "application/vnd.apache.thrift.binary": {
        source: "iana"
      },
      "application/vnd.apache.thrift.compact": {
        source: "iana"
      },
      "application/vnd.apache.thrift.json": {
        source: "iana"
      },
      "application/vnd.api+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.aplextor.warrp+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.apothekende.reservation+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.apple.installer+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mpkg"]
      },
      "application/vnd.apple.keynote": {
        source: "iana",
        extensions: ["key"]
      },
      "application/vnd.apple.mpegurl": {
        source: "iana",
        extensions: ["m3u8"]
      },
      "application/vnd.apple.numbers": {
        source: "iana",
        extensions: ["numbers"]
      },
      "application/vnd.apple.pages": {
        source: "iana",
        extensions: ["pages"]
      },
      "application/vnd.apple.pkpass": {
        compressible: false,
        extensions: ["pkpass"]
      },
      "application/vnd.arastra.swi": {
        source: "iana"
      },
      "application/vnd.aristanetworks.swi": {
        source: "iana",
        extensions: ["swi"]
      },
      "application/vnd.artisan+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.artsquare": {
        source: "iana"
      },
      "application/vnd.astraea-software.iota": {
        source: "iana",
        extensions: ["iota"]
      },
      "application/vnd.audiograph": {
        source: "iana",
        extensions: ["aep"]
      },
      "application/vnd.autopackage": {
        source: "iana"
      },
      "application/vnd.avalon+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.avistar+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.balsamiq.bmml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["bmml"]
      },
      "application/vnd.balsamiq.bmpr": {
        source: "iana"
      },
      "application/vnd.banana-accounting": {
        source: "iana"
      },
      "application/vnd.bbf.usp.error": {
        source: "iana"
      },
      "application/vnd.bbf.usp.msg": {
        source: "iana"
      },
      "application/vnd.bbf.usp.msg+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.bekitzur-stech+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.bint.med-content": {
        source: "iana"
      },
      "application/vnd.biopax.rdf+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.blink-idb-value-wrapper": {
        source: "iana"
      },
      "application/vnd.blueice.multipass": {
        source: "iana",
        extensions: ["mpm"]
      },
      "application/vnd.bluetooth.ep.oob": {
        source: "iana"
      },
      "application/vnd.bluetooth.le.oob": {
        source: "iana"
      },
      "application/vnd.bmi": {
        source: "iana",
        extensions: ["bmi"]
      },
      "application/vnd.bpf": {
        source: "iana"
      },
      "application/vnd.bpf3": {
        source: "iana"
      },
      "application/vnd.businessobjects": {
        source: "iana",
        extensions: ["rep"]
      },
      "application/vnd.byu.uapi+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.cab-jscript": {
        source: "iana"
      },
      "application/vnd.canon-cpdl": {
        source: "iana"
      },
      "application/vnd.canon-lips": {
        source: "iana"
      },
      "application/vnd.capasystems-pg+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.cendio.thinlinc.clientconf": {
        source: "iana"
      },
      "application/vnd.century-systems.tcp_stream": {
        source: "iana"
      },
      "application/vnd.chemdraw+xml": {
        source: "iana",
        compressible: true,
        extensions: ["cdxml"]
      },
      "application/vnd.chess-pgn": {
        source: "iana"
      },
      "application/vnd.chipnuts.karaoke-mmd": {
        source: "iana",
        extensions: ["mmd"]
      },
      "application/vnd.ciedi": {
        source: "iana"
      },
      "application/vnd.cinderella": {
        source: "iana",
        extensions: ["cdy"]
      },
      "application/vnd.cirpack.isdn-ext": {
        source: "iana"
      },
      "application/vnd.citationstyles.style+xml": {
        source: "iana",
        compressible: true,
        extensions: ["csl"]
      },
      "application/vnd.claymore": {
        source: "iana",
        extensions: ["cla"]
      },
      "application/vnd.cloanto.rp9": {
        source: "iana",
        extensions: ["rp9"]
      },
      "application/vnd.clonk.c4group": {
        source: "iana",
        extensions: ["c4g", "c4d", "c4f", "c4p", "c4u"]
      },
      "application/vnd.cluetrust.cartomobile-config": {
        source: "iana",
        extensions: ["c11amc"]
      },
      "application/vnd.cluetrust.cartomobile-config-pkg": {
        source: "iana",
        extensions: ["c11amz"]
      },
      "application/vnd.coffeescript": {
        source: "iana"
      },
      "application/vnd.collabio.xodocuments.document": {
        source: "iana"
      },
      "application/vnd.collabio.xodocuments.document-template": {
        source: "iana"
      },
      "application/vnd.collabio.xodocuments.presentation": {
        source: "iana"
      },
      "application/vnd.collabio.xodocuments.presentation-template": {
        source: "iana"
      },
      "application/vnd.collabio.xodocuments.spreadsheet": {
        source: "iana"
      },
      "application/vnd.collabio.xodocuments.spreadsheet-template": {
        source: "iana"
      },
      "application/vnd.collection+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.collection.doc+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.collection.next+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.comicbook+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.comicbook-rar": {
        source: "iana"
      },
      "application/vnd.commerce-battelle": {
        source: "iana"
      },
      "application/vnd.commonspace": {
        source: "iana",
        extensions: ["csp"]
      },
      "application/vnd.contact.cmsg": {
        source: "iana",
        extensions: ["cdbcmsg"]
      },
      "application/vnd.coreos.ignition+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.cosmocaller": {
        source: "iana",
        extensions: ["cmc"]
      },
      "application/vnd.crick.clicker": {
        source: "iana",
        extensions: ["clkx"]
      },
      "application/vnd.crick.clicker.keyboard": {
        source: "iana",
        extensions: ["clkk"]
      },
      "application/vnd.crick.clicker.palette": {
        source: "iana",
        extensions: ["clkp"]
      },
      "application/vnd.crick.clicker.template": {
        source: "iana",
        extensions: ["clkt"]
      },
      "application/vnd.crick.clicker.wordbank": {
        source: "iana",
        extensions: ["clkw"]
      },
      "application/vnd.criticaltools.wbs+xml": {
        source: "iana",
        compressible: true,
        extensions: ["wbs"]
      },
      "application/vnd.cryptii.pipe+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.crypto-shade-file": {
        source: "iana"
      },
      "application/vnd.cryptomator.encrypted": {
        source: "iana"
      },
      "application/vnd.cryptomator.vault": {
        source: "iana"
      },
      "application/vnd.ctc-posml": {
        source: "iana",
        extensions: ["pml"]
      },
      "application/vnd.ctct.ws+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.cups-pdf": {
        source: "iana"
      },
      "application/vnd.cups-postscript": {
        source: "iana"
      },
      "application/vnd.cups-ppd": {
        source: "iana",
        extensions: ["ppd"]
      },
      "application/vnd.cups-raster": {
        source: "iana"
      },
      "application/vnd.cups-raw": {
        source: "iana"
      },
      "application/vnd.curl": {
        source: "iana"
      },
      "application/vnd.curl.car": {
        source: "apache",
        extensions: ["car"]
      },
      "application/vnd.curl.pcurl": {
        source: "apache",
        extensions: ["pcurl"]
      },
      "application/vnd.cyan.dean.root+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.cybank": {
        source: "iana"
      },
      "application/vnd.cyclonedx+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.cyclonedx+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.d2l.coursepackage1p0+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.d3m-dataset": {
        source: "iana"
      },
      "application/vnd.d3m-problem": {
        source: "iana"
      },
      "application/vnd.dart": {
        source: "iana",
        compressible: true,
        extensions: ["dart"]
      },
      "application/vnd.data-vision.rdz": {
        source: "iana",
        extensions: ["rdz"]
      },
      "application/vnd.datapackage+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dataresource+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dbf": {
        source: "iana",
        extensions: ["dbf"]
      },
      "application/vnd.debian.binary-package": {
        source: "iana"
      },
      "application/vnd.dece.data": {
        source: "iana",
        extensions: ["uvf", "uvvf", "uvd", "uvvd"]
      },
      "application/vnd.dece.ttml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["uvt", "uvvt"]
      },
      "application/vnd.dece.unspecified": {
        source: "iana",
        extensions: ["uvx", "uvvx"]
      },
      "application/vnd.dece.zip": {
        source: "iana",
        extensions: ["uvz", "uvvz"]
      },
      "application/vnd.denovo.fcselayout-link": {
        source: "iana",
        extensions: ["fe_launch"]
      },
      "application/vnd.desmume.movie": {
        source: "iana"
      },
      "application/vnd.dir-bi.plate-dl-nosuffix": {
        source: "iana"
      },
      "application/vnd.dm.delegation+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dna": {
        source: "iana",
        extensions: ["dna"]
      },
      "application/vnd.document+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dolby.mlp": {
        source: "apache",
        extensions: ["mlp"]
      },
      "application/vnd.dolby.mobile.1": {
        source: "iana"
      },
      "application/vnd.dolby.mobile.2": {
        source: "iana"
      },
      "application/vnd.doremir.scorecloud-binary-document": {
        source: "iana"
      },
      "application/vnd.dpgraph": {
        source: "iana",
        extensions: ["dpg"]
      },
      "application/vnd.dreamfactory": {
        source: "iana",
        extensions: ["dfac"]
      },
      "application/vnd.drive+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ds-keypoint": {
        source: "apache",
        extensions: ["kpxx"]
      },
      "application/vnd.dtg.local": {
        source: "iana"
      },
      "application/vnd.dtg.local.flash": {
        source: "iana"
      },
      "application/vnd.dtg.local.html": {
        source: "iana"
      },
      "application/vnd.dvb.ait": {
        source: "iana",
        extensions: ["ait"]
      },
      "application/vnd.dvb.dvbisl+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dvb.dvbj": {
        source: "iana"
      },
      "application/vnd.dvb.esgcontainer": {
        source: "iana"
      },
      "application/vnd.dvb.ipdcdftnotifaccess": {
        source: "iana"
      },
      "application/vnd.dvb.ipdcesgaccess": {
        source: "iana"
      },
      "application/vnd.dvb.ipdcesgaccess2": {
        source: "iana"
      },
      "application/vnd.dvb.ipdcesgpdd": {
        source: "iana"
      },
      "application/vnd.dvb.ipdcroaming": {
        source: "iana"
      },
      "application/vnd.dvb.iptv.alfec-base": {
        source: "iana"
      },
      "application/vnd.dvb.iptv.alfec-enhancement": {
        source: "iana"
      },
      "application/vnd.dvb.notif-aggregate-root+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dvb.notif-container+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dvb.notif-generic+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dvb.notif-ia-msglist+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dvb.notif-ia-registration-request+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dvb.notif-ia-registration-response+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dvb.notif-init+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dvb.pfr": {
        source: "iana"
      },
      "application/vnd.dvb.service": {
        source: "iana",
        extensions: ["svc"]
      },
      "application/vnd.dxr": {
        source: "iana"
      },
      "application/vnd.dynageo": {
        source: "iana",
        extensions: ["geo"]
      },
      "application/vnd.dzr": {
        source: "iana"
      },
      "application/vnd.easykaraoke.cdgdownload": {
        source: "iana"
      },
      "application/vnd.ecdis-update": {
        source: "iana"
      },
      "application/vnd.ecip.rlp": {
        source: "iana"
      },
      "application/vnd.eclipse.ditto+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ecowin.chart": {
        source: "iana",
        extensions: ["mag"]
      },
      "application/vnd.ecowin.filerequest": {
        source: "iana"
      },
      "application/vnd.ecowin.fileupdate": {
        source: "iana"
      },
      "application/vnd.ecowin.series": {
        source: "iana"
      },
      "application/vnd.ecowin.seriesrequest": {
        source: "iana"
      },
      "application/vnd.ecowin.seriesupdate": {
        source: "iana"
      },
      "application/vnd.efi.img": {
        source: "iana"
      },
      "application/vnd.efi.iso": {
        source: "iana"
      },
      "application/vnd.emclient.accessrequest+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.enliven": {
        source: "iana",
        extensions: ["nml"]
      },
      "application/vnd.enphase.envoy": {
        source: "iana"
      },
      "application/vnd.eprints.data+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.epson.esf": {
        source: "iana",
        extensions: ["esf"]
      },
      "application/vnd.epson.msf": {
        source: "iana",
        extensions: ["msf"]
      },
      "application/vnd.epson.quickanime": {
        source: "iana",
        extensions: ["qam"]
      },
      "application/vnd.epson.salt": {
        source: "iana",
        extensions: ["slt"]
      },
      "application/vnd.epson.ssf": {
        source: "iana",
        extensions: ["ssf"]
      },
      "application/vnd.ericsson.quickcall": {
        source: "iana"
      },
      "application/vnd.espass-espass+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.eszigno3+xml": {
        source: "iana",
        compressible: true,
        extensions: ["es3", "et3"]
      },
      "application/vnd.etsi.aoc+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.asic-e+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.etsi.asic-s+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.etsi.cug+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.iptvcommand+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.iptvdiscovery+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.iptvprofile+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.iptvsad-bc+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.iptvsad-cod+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.iptvsad-npvr+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.iptvservice+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.iptvsync+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.iptvueprofile+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.mcid+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.mheg5": {
        source: "iana"
      },
      "application/vnd.etsi.overload-control-policy-dataset+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.pstn+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.sci+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.simservs+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.timestamp-token": {
        source: "iana"
      },
      "application/vnd.etsi.tsl+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.tsl.der": {
        source: "iana"
      },
      "application/vnd.eu.kasparian.car+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.eudora.data": {
        source: "iana"
      },
      "application/vnd.evolv.ecig.profile": {
        source: "iana"
      },
      "application/vnd.evolv.ecig.settings": {
        source: "iana"
      },
      "application/vnd.evolv.ecig.theme": {
        source: "iana"
      },
      "application/vnd.exstream-empower+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.exstream-package": {
        source: "iana"
      },
      "application/vnd.ezpix-album": {
        source: "iana",
        extensions: ["ez2"]
      },
      "application/vnd.ezpix-package": {
        source: "iana",
        extensions: ["ez3"]
      },
      "application/vnd.f-secure.mobile": {
        source: "iana"
      },
      "application/vnd.familysearch.gedcom+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.fastcopy-disk-image": {
        source: "iana"
      },
      "application/vnd.fdf": {
        source: "iana",
        extensions: ["fdf"]
      },
      "application/vnd.fdsn.mseed": {
        source: "iana",
        extensions: ["mseed"]
      },
      "application/vnd.fdsn.seed": {
        source: "iana",
        extensions: ["seed", "dataless"]
      },
      "application/vnd.ffsns": {
        source: "iana"
      },
      "application/vnd.ficlab.flb+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.filmit.zfc": {
        source: "iana"
      },
      "application/vnd.fints": {
        source: "iana"
      },
      "application/vnd.firemonkeys.cloudcell": {
        source: "iana"
      },
      "application/vnd.flographit": {
        source: "iana",
        extensions: ["gph"]
      },
      "application/vnd.fluxtime.clip": {
        source: "iana",
        extensions: ["ftc"]
      },
      "application/vnd.font-fontforge-sfd": {
        source: "iana"
      },
      "application/vnd.framemaker": {
        source: "iana",
        extensions: ["fm", "frame", "maker", "book"]
      },
      "application/vnd.frogans.fnc": {
        source: "iana",
        extensions: ["fnc"]
      },
      "application/vnd.frogans.ltf": {
        source: "iana",
        extensions: ["ltf"]
      },
      "application/vnd.fsc.weblaunch": {
        source: "iana",
        extensions: ["fsc"]
      },
      "application/vnd.fujifilm.fb.docuworks": {
        source: "iana"
      },
      "application/vnd.fujifilm.fb.docuworks.binder": {
        source: "iana"
      },
      "application/vnd.fujifilm.fb.docuworks.container": {
        source: "iana"
      },
      "application/vnd.fujifilm.fb.jfi+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.fujitsu.oasys": {
        source: "iana",
        extensions: ["oas"]
      },
      "application/vnd.fujitsu.oasys2": {
        source: "iana",
        extensions: ["oa2"]
      },
      "application/vnd.fujitsu.oasys3": {
        source: "iana",
        extensions: ["oa3"]
      },
      "application/vnd.fujitsu.oasysgp": {
        source: "iana",
        extensions: ["fg5"]
      },
      "application/vnd.fujitsu.oasysprs": {
        source: "iana",
        extensions: ["bh2"]
      },
      "application/vnd.fujixerox.art-ex": {
        source: "iana"
      },
      "application/vnd.fujixerox.art4": {
        source: "iana"
      },
      "application/vnd.fujixerox.ddd": {
        source: "iana",
        extensions: ["ddd"]
      },
      "application/vnd.fujixerox.docuworks": {
        source: "iana",
        extensions: ["xdw"]
      },
      "application/vnd.fujixerox.docuworks.binder": {
        source: "iana",
        extensions: ["xbd"]
      },
      "application/vnd.fujixerox.docuworks.container": {
        source: "iana"
      },
      "application/vnd.fujixerox.hbpl": {
        source: "iana"
      },
      "application/vnd.fut-misnet": {
        source: "iana"
      },
      "application/vnd.futoin+cbor": {
        source: "iana"
      },
      "application/vnd.futoin+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.fuzzysheet": {
        source: "iana",
        extensions: ["fzs"]
      },
      "application/vnd.genomatix.tuxedo": {
        source: "iana",
        extensions: ["txd"]
      },
      "application/vnd.gentics.grd+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.geo+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.geocube+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.geogebra.file": {
        source: "iana",
        extensions: ["ggb"]
      },
      "application/vnd.geogebra.slides": {
        source: "iana"
      },
      "application/vnd.geogebra.tool": {
        source: "iana",
        extensions: ["ggt"]
      },
      "application/vnd.geometry-explorer": {
        source: "iana",
        extensions: ["gex", "gre"]
      },
      "application/vnd.geonext": {
        source: "iana",
        extensions: ["gxt"]
      },
      "application/vnd.geoplan": {
        source: "iana",
        extensions: ["g2w"]
      },
      "application/vnd.geospace": {
        source: "iana",
        extensions: ["g3w"]
      },
      "application/vnd.gerber": {
        source: "iana"
      },
      "application/vnd.globalplatform.card-content-mgt": {
        source: "iana"
      },
      "application/vnd.globalplatform.card-content-mgt-response": {
        source: "iana"
      },
      "application/vnd.gmx": {
        source: "iana",
        extensions: ["gmx"]
      },
      "application/vnd.google-apps.document": {
        compressible: false,
        extensions: ["gdoc"]
      },
      "application/vnd.google-apps.presentation": {
        compressible: false,
        extensions: ["gslides"]
      },
      "application/vnd.google-apps.spreadsheet": {
        compressible: false,
        extensions: ["gsheet"]
      },
      "application/vnd.google-earth.kml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["kml"]
      },
      "application/vnd.google-earth.kmz": {
        source: "iana",
        compressible: false,
        extensions: ["kmz"]
      },
      "application/vnd.gov.sk.e-form+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.gov.sk.e-form+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.gov.sk.xmldatacontainer+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.grafeq": {
        source: "iana",
        extensions: ["gqf", "gqs"]
      },
      "application/vnd.gridmp": {
        source: "iana"
      },
      "application/vnd.groove-account": {
        source: "iana",
        extensions: ["gac"]
      },
      "application/vnd.groove-help": {
        source: "iana",
        extensions: ["ghf"]
      },
      "application/vnd.groove-identity-message": {
        source: "iana",
        extensions: ["gim"]
      },
      "application/vnd.groove-injector": {
        source: "iana",
        extensions: ["grv"]
      },
      "application/vnd.groove-tool-message": {
        source: "iana",
        extensions: ["gtm"]
      },
      "application/vnd.groove-tool-template": {
        source: "iana",
        extensions: ["tpl"]
      },
      "application/vnd.groove-vcard": {
        source: "iana",
        extensions: ["vcg"]
      },
      "application/vnd.hal+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.hal+xml": {
        source: "iana",
        compressible: true,
        extensions: ["hal"]
      },
      "application/vnd.handheld-entertainment+xml": {
        source: "iana",
        compressible: true,
        extensions: ["zmm"]
      },
      "application/vnd.hbci": {
        source: "iana",
        extensions: ["hbci"]
      },
      "application/vnd.hc+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.hcl-bireports": {
        source: "iana"
      },
      "application/vnd.hdt": {
        source: "iana"
      },
      "application/vnd.heroku+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.hhe.lesson-player": {
        source: "iana",
        extensions: ["les"]
      },
      "application/vnd.hl7cda+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/vnd.hl7v2+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/vnd.hp-hpgl": {
        source: "iana",
        extensions: ["hpgl"]
      },
      "application/vnd.hp-hpid": {
        source: "iana",
        extensions: ["hpid"]
      },
      "application/vnd.hp-hps": {
        source: "iana",
        extensions: ["hps"]
      },
      "application/vnd.hp-jlyt": {
        source: "iana",
        extensions: ["jlt"]
      },
      "application/vnd.hp-pcl": {
        source: "iana",
        extensions: ["pcl"]
      },
      "application/vnd.hp-pclxl": {
        source: "iana",
        extensions: ["pclxl"]
      },
      "application/vnd.httphone": {
        source: "iana"
      },
      "application/vnd.hydrostatix.sof-data": {
        source: "iana",
        extensions: ["sfd-hdstx"]
      },
      "application/vnd.hyper+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.hyper-item+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.hyperdrive+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.hzn-3d-crossword": {
        source: "iana"
      },
      "application/vnd.ibm.afplinedata": {
        source: "iana"
      },
      "application/vnd.ibm.electronic-media": {
        source: "iana"
      },
      "application/vnd.ibm.minipay": {
        source: "iana",
        extensions: ["mpy"]
      },
      "application/vnd.ibm.modcap": {
        source: "iana",
        extensions: ["afp", "listafp", "list3820"]
      },
      "application/vnd.ibm.rights-management": {
        source: "iana",
        extensions: ["irm"]
      },
      "application/vnd.ibm.secure-container": {
        source: "iana",
        extensions: ["sc"]
      },
      "application/vnd.iccprofile": {
        source: "iana",
        extensions: ["icc", "icm"]
      },
      "application/vnd.ieee.1905": {
        source: "iana"
      },
      "application/vnd.igloader": {
        source: "iana",
        extensions: ["igl"]
      },
      "application/vnd.imagemeter.folder+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.imagemeter.image+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.immervision-ivp": {
        source: "iana",
        extensions: ["ivp"]
      },
      "application/vnd.immervision-ivu": {
        source: "iana",
        extensions: ["ivu"]
      },
      "application/vnd.ims.imsccv1p1": {
        source: "iana"
      },
      "application/vnd.ims.imsccv1p2": {
        source: "iana"
      },
      "application/vnd.ims.imsccv1p3": {
        source: "iana"
      },
      "application/vnd.ims.lis.v2.result+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ims.lti.v2.toolconsumerprofile+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ims.lti.v2.toolproxy+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ims.lti.v2.toolproxy.id+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ims.lti.v2.toolsettings+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ims.lti.v2.toolsettings.simple+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.informedcontrol.rms+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.informix-visionary": {
        source: "iana"
      },
      "application/vnd.infotech.project": {
        source: "iana"
      },
      "application/vnd.infotech.project+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.innopath.wamp.notification": {
        source: "iana"
      },
      "application/vnd.insors.igm": {
        source: "iana",
        extensions: ["igm"]
      },
      "application/vnd.intercon.formnet": {
        source: "iana",
        extensions: ["xpw", "xpx"]
      },
      "application/vnd.intergeo": {
        source: "iana",
        extensions: ["i2g"]
      },
      "application/vnd.intertrust.digibox": {
        source: "iana"
      },
      "application/vnd.intertrust.nncp": {
        source: "iana"
      },
      "application/vnd.intu.qbo": {
        source: "iana",
        extensions: ["qbo"]
      },
      "application/vnd.intu.qfx": {
        source: "iana",
        extensions: ["qfx"]
      },
      "application/vnd.iptc.g2.catalogitem+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.iptc.g2.conceptitem+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.iptc.g2.knowledgeitem+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.iptc.g2.newsitem+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.iptc.g2.newsmessage+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.iptc.g2.packageitem+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.iptc.g2.planningitem+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ipunplugged.rcprofile": {
        source: "iana",
        extensions: ["rcprofile"]
      },
      "application/vnd.irepository.package+xml": {
        source: "iana",
        compressible: true,
        extensions: ["irp"]
      },
      "application/vnd.is-xpr": {
        source: "iana",
        extensions: ["xpr"]
      },
      "application/vnd.isac.fcs": {
        source: "iana",
        extensions: ["fcs"]
      },
      "application/vnd.iso11783-10+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.jam": {
        source: "iana",
        extensions: ["jam"]
      },
      "application/vnd.japannet-directory-service": {
        source: "iana"
      },
      "application/vnd.japannet-jpnstore-wakeup": {
        source: "iana"
      },
      "application/vnd.japannet-payment-wakeup": {
        source: "iana"
      },
      "application/vnd.japannet-registration": {
        source: "iana"
      },
      "application/vnd.japannet-registration-wakeup": {
        source: "iana"
      },
      "application/vnd.japannet-setstore-wakeup": {
        source: "iana"
      },
      "application/vnd.japannet-verification": {
        source: "iana"
      },
      "application/vnd.japannet-verification-wakeup": {
        source: "iana"
      },
      "application/vnd.jcp.javame.midlet-rms": {
        source: "iana",
        extensions: ["rms"]
      },
      "application/vnd.jisp": {
        source: "iana",
        extensions: ["jisp"]
      },
      "application/vnd.joost.joda-archive": {
        source: "iana",
        extensions: ["joda"]
      },
      "application/vnd.jsk.isdn-ngn": {
        source: "iana"
      },
      "application/vnd.kahootz": {
        source: "iana",
        extensions: ["ktz", "ktr"]
      },
      "application/vnd.kde.karbon": {
        source: "iana",
        extensions: ["karbon"]
      },
      "application/vnd.kde.kchart": {
        source: "iana",
        extensions: ["chrt"]
      },
      "application/vnd.kde.kformula": {
        source: "iana",
        extensions: ["kfo"]
      },
      "application/vnd.kde.kivio": {
        source: "iana",
        extensions: ["flw"]
      },
      "application/vnd.kde.kontour": {
        source: "iana",
        extensions: ["kon"]
      },
      "application/vnd.kde.kpresenter": {
        source: "iana",
        extensions: ["kpr", "kpt"]
      },
      "application/vnd.kde.kspread": {
        source: "iana",
        extensions: ["ksp"]
      },
      "application/vnd.kde.kword": {
        source: "iana",
        extensions: ["kwd", "kwt"]
      },
      "application/vnd.kenameaapp": {
        source: "iana",
        extensions: ["htke"]
      },
      "application/vnd.kidspiration": {
        source: "iana",
        extensions: ["kia"]
      },
      "application/vnd.kinar": {
        source: "iana",
        extensions: ["kne", "knp"]
      },
      "application/vnd.koan": {
        source: "iana",
        extensions: ["skp", "skd", "skt", "skm"]
      },
      "application/vnd.kodak-descriptor": {
        source: "iana",
        extensions: ["sse"]
      },
      "application/vnd.las": {
        source: "iana"
      },
      "application/vnd.las.las+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.las.las+xml": {
        source: "iana",
        compressible: true,
        extensions: ["lasxml"]
      },
      "application/vnd.laszip": {
        source: "iana"
      },
      "application/vnd.leap+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.liberty-request+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.llamagraphics.life-balance.desktop": {
        source: "iana",
        extensions: ["lbd"]
      },
      "application/vnd.llamagraphics.life-balance.exchange+xml": {
        source: "iana",
        compressible: true,
        extensions: ["lbe"]
      },
      "application/vnd.logipipe.circuit+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.loom": {
        source: "iana"
      },
      "application/vnd.lotus-1-2-3": {
        source: "iana",
        extensions: ["123"]
      },
      "application/vnd.lotus-approach": {
        source: "iana",
        extensions: ["apr"]
      },
      "application/vnd.lotus-freelance": {
        source: "iana",
        extensions: ["pre"]
      },
      "application/vnd.lotus-notes": {
        source: "iana",
        extensions: ["nsf"]
      },
      "application/vnd.lotus-organizer": {
        source: "iana",
        extensions: ["org"]
      },
      "application/vnd.lotus-screencam": {
        source: "iana",
        extensions: ["scm"]
      },
      "application/vnd.lotus-wordpro": {
        source: "iana",
        extensions: ["lwp"]
      },
      "application/vnd.macports.portpkg": {
        source: "iana",
        extensions: ["portpkg"]
      },
      "application/vnd.mapbox-vector-tile": {
        source: "iana",
        extensions: ["mvt"]
      },
      "application/vnd.marlin.drm.actiontoken+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.marlin.drm.conftoken+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.marlin.drm.license+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.marlin.drm.mdcf": {
        source: "iana"
      },
      "application/vnd.mason+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.maxar.archive.3tz+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.maxmind.maxmind-db": {
        source: "iana"
      },
      "application/vnd.mcd": {
        source: "iana",
        extensions: ["mcd"]
      },
      "application/vnd.medcalcdata": {
        source: "iana",
        extensions: ["mc1"]
      },
      "application/vnd.mediastation.cdkey": {
        source: "iana",
        extensions: ["cdkey"]
      },
      "application/vnd.meridian-slingshot": {
        source: "iana"
      },
      "application/vnd.mfer": {
        source: "iana",
        extensions: ["mwf"]
      },
      "application/vnd.mfmp": {
        source: "iana",
        extensions: ["mfm"]
      },
      "application/vnd.micro+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.micrografx.flo": {
        source: "iana",
        extensions: ["flo"]
      },
      "application/vnd.micrografx.igx": {
        source: "iana",
        extensions: ["igx"]
      },
      "application/vnd.microsoft.portable-executable": {
        source: "iana"
      },
      "application/vnd.microsoft.windows.thumbnail-cache": {
        source: "iana"
      },
      "application/vnd.miele+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.mif": {
        source: "iana",
        extensions: ["mif"]
      },
      "application/vnd.minisoft-hp3000-save": {
        source: "iana"
      },
      "application/vnd.mitsubishi.misty-guard.trustweb": {
        source: "iana"
      },
      "application/vnd.mobius.daf": {
        source: "iana",
        extensions: ["daf"]
      },
      "application/vnd.mobius.dis": {
        source: "iana",
        extensions: ["dis"]
      },
      "application/vnd.mobius.mbk": {
        source: "iana",
        extensions: ["mbk"]
      },
      "application/vnd.mobius.mqy": {
        source: "iana",
        extensions: ["mqy"]
      },
      "application/vnd.mobius.msl": {
        source: "iana",
        extensions: ["msl"]
      },
      "application/vnd.mobius.plc": {
        source: "iana",
        extensions: ["plc"]
      },
      "application/vnd.mobius.txf": {
        source: "iana",
        extensions: ["txf"]
      },
      "application/vnd.mophun.application": {
        source: "iana",
        extensions: ["mpn"]
      },
      "application/vnd.mophun.certificate": {
        source: "iana",
        extensions: ["mpc"]
      },
      "application/vnd.motorola.flexsuite": {
        source: "iana"
      },
      "application/vnd.motorola.flexsuite.adsi": {
        source: "iana"
      },
      "application/vnd.motorola.flexsuite.fis": {
        source: "iana"
      },
      "application/vnd.motorola.flexsuite.gotap": {
        source: "iana"
      },
      "application/vnd.motorola.flexsuite.kmr": {
        source: "iana"
      },
      "application/vnd.motorola.flexsuite.ttc": {
        source: "iana"
      },
      "application/vnd.motorola.flexsuite.wem": {
        source: "iana"
      },
      "application/vnd.motorola.iprm": {
        source: "iana"
      },
      "application/vnd.mozilla.xul+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xul"]
      },
      "application/vnd.ms-3mfdocument": {
        source: "iana"
      },
      "application/vnd.ms-artgalry": {
        source: "iana",
        extensions: ["cil"]
      },
      "application/vnd.ms-asf": {
        source: "iana"
      },
      "application/vnd.ms-cab-compressed": {
        source: "iana",
        extensions: ["cab"]
      },
      "application/vnd.ms-color.iccprofile": {
        source: "apache"
      },
      "application/vnd.ms-excel": {
        source: "iana",
        compressible: false,
        extensions: ["xls", "xlm", "xla", "xlc", "xlt", "xlw"]
      },
      "application/vnd.ms-excel.addin.macroenabled.12": {
        source: "iana",
        extensions: ["xlam"]
      },
      "application/vnd.ms-excel.sheet.binary.macroenabled.12": {
        source: "iana",
        extensions: ["xlsb"]
      },
      "application/vnd.ms-excel.sheet.macroenabled.12": {
        source: "iana",
        extensions: ["xlsm"]
      },
      "application/vnd.ms-excel.template.macroenabled.12": {
        source: "iana",
        extensions: ["xltm"]
      },
      "application/vnd.ms-fontobject": {
        source: "iana",
        compressible: true,
        extensions: ["eot"]
      },
      "application/vnd.ms-htmlhelp": {
        source: "iana",
        extensions: ["chm"]
      },
      "application/vnd.ms-ims": {
        source: "iana",
        extensions: ["ims"]
      },
      "application/vnd.ms-lrm": {
        source: "iana",
        extensions: ["lrm"]
      },
      "application/vnd.ms-office.activex+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ms-officetheme": {
        source: "iana",
        extensions: ["thmx"]
      },
      "application/vnd.ms-opentype": {
        source: "apache",
        compressible: true
      },
      "application/vnd.ms-outlook": {
        compressible: false,
        extensions: ["msg"]
      },
      "application/vnd.ms-package.obfuscated-opentype": {
        source: "apache"
      },
      "application/vnd.ms-pki.seccat": {
        source: "apache",
        extensions: ["cat"]
      },
      "application/vnd.ms-pki.stl": {
        source: "apache",
        extensions: ["stl"]
      },
      "application/vnd.ms-playready.initiator+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ms-powerpoint": {
        source: "iana",
        compressible: false,
        extensions: ["ppt", "pps", "pot"]
      },
      "application/vnd.ms-powerpoint.addin.macroenabled.12": {
        source: "iana",
        extensions: ["ppam"]
      },
      "application/vnd.ms-powerpoint.presentation.macroenabled.12": {
        source: "iana",
        extensions: ["pptm"]
      },
      "application/vnd.ms-powerpoint.slide.macroenabled.12": {
        source: "iana",
        extensions: ["sldm"]
      },
      "application/vnd.ms-powerpoint.slideshow.macroenabled.12": {
        source: "iana",
        extensions: ["ppsm"]
      },
      "application/vnd.ms-powerpoint.template.macroenabled.12": {
        source: "iana",
        extensions: ["potm"]
      },
      "application/vnd.ms-printdevicecapabilities+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ms-printing.printticket+xml": {
        source: "apache",
        compressible: true
      },
      "application/vnd.ms-printschematicket+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ms-project": {
        source: "iana",
        extensions: ["mpp", "mpt"]
      },
      "application/vnd.ms-tnef": {
        source: "iana"
      },
      "application/vnd.ms-windows.devicepairing": {
        source: "iana"
      },
      "application/vnd.ms-windows.nwprinting.oob": {
        source: "iana"
      },
      "application/vnd.ms-windows.printerpairing": {
        source: "iana"
      },
      "application/vnd.ms-windows.wsd.oob": {
        source: "iana"
      },
      "application/vnd.ms-wmdrm.lic-chlg-req": {
        source: "iana"
      },
      "application/vnd.ms-wmdrm.lic-resp": {
        source: "iana"
      },
      "application/vnd.ms-wmdrm.meter-chlg-req": {
        source: "iana"
      },
      "application/vnd.ms-wmdrm.meter-resp": {
        source: "iana"
      },
      "application/vnd.ms-word.document.macroenabled.12": {
        source: "iana",
        extensions: ["docm"]
      },
      "application/vnd.ms-word.template.macroenabled.12": {
        source: "iana",
        extensions: ["dotm"]
      },
      "application/vnd.ms-works": {
        source: "iana",
        extensions: ["wps", "wks", "wcm", "wdb"]
      },
      "application/vnd.ms-wpl": {
        source: "iana",
        extensions: ["wpl"]
      },
      "application/vnd.ms-xpsdocument": {
        source: "iana",
        compressible: false,
        extensions: ["xps"]
      },
      "application/vnd.msa-disk-image": {
        source: "iana"
      },
      "application/vnd.mseq": {
        source: "iana",
        extensions: ["mseq"]
      },
      "application/vnd.msign": {
        source: "iana"
      },
      "application/vnd.multiad.creator": {
        source: "iana"
      },
      "application/vnd.multiad.creator.cif": {
        source: "iana"
      },
      "application/vnd.music-niff": {
        source: "iana"
      },
      "application/vnd.musician": {
        source: "iana",
        extensions: ["mus"]
      },
      "application/vnd.muvee.style": {
        source: "iana",
        extensions: ["msty"]
      },
      "application/vnd.mynfc": {
        source: "iana",
        extensions: ["taglet"]
      },
      "application/vnd.nacamar.ybrid+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ncd.control": {
        source: "iana"
      },
      "application/vnd.ncd.reference": {
        source: "iana"
      },
      "application/vnd.nearst.inv+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.nebumind.line": {
        source: "iana"
      },
      "application/vnd.nervana": {
        source: "iana"
      },
      "application/vnd.netfpx": {
        source: "iana"
      },
      "application/vnd.neurolanguage.nlu": {
        source: "iana",
        extensions: ["nlu"]
      },
      "application/vnd.nimn": {
        source: "iana"
      },
      "application/vnd.nintendo.nitro.rom": {
        source: "iana"
      },
      "application/vnd.nintendo.snes.rom": {
        source: "iana"
      },
      "application/vnd.nitf": {
        source: "iana",
        extensions: ["ntf", "nitf"]
      },
      "application/vnd.noblenet-directory": {
        source: "iana",
        extensions: ["nnd"]
      },
      "application/vnd.noblenet-sealer": {
        source: "iana",
        extensions: ["nns"]
      },
      "application/vnd.noblenet-web": {
        source: "iana",
        extensions: ["nnw"]
      },
      "application/vnd.nokia.catalogs": {
        source: "iana"
      },
      "application/vnd.nokia.conml+wbxml": {
        source: "iana"
      },
      "application/vnd.nokia.conml+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.nokia.iptv.config+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.nokia.isds-radio-presets": {
        source: "iana"
      },
      "application/vnd.nokia.landmark+wbxml": {
        source: "iana"
      },
      "application/vnd.nokia.landmark+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.nokia.landmarkcollection+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.nokia.n-gage.ac+xml": {
        source: "iana",
        compressible: true,
        extensions: ["ac"]
      },
      "application/vnd.nokia.n-gage.data": {
        source: "iana",
        extensions: ["ngdat"]
      },
      "application/vnd.nokia.n-gage.symbian.install": {
        source: "iana",
        extensions: ["n-gage"]
      },
      "application/vnd.nokia.ncd": {
        source: "iana"
      },
      "application/vnd.nokia.pcd+wbxml": {
        source: "iana"
      },
      "application/vnd.nokia.pcd+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.nokia.radio-preset": {
        source: "iana",
        extensions: ["rpst"]
      },
      "application/vnd.nokia.radio-presets": {
        source: "iana",
        extensions: ["rpss"]
      },
      "application/vnd.novadigm.edm": {
        source: "iana",
        extensions: ["edm"]
      },
      "application/vnd.novadigm.edx": {
        source: "iana",
        extensions: ["edx"]
      },
      "application/vnd.novadigm.ext": {
        source: "iana",
        extensions: ["ext"]
      },
      "application/vnd.ntt-local.content-share": {
        source: "iana"
      },
      "application/vnd.ntt-local.file-transfer": {
        source: "iana"
      },
      "application/vnd.ntt-local.ogw_remote-access": {
        source: "iana"
      },
      "application/vnd.ntt-local.sip-ta_remote": {
        source: "iana"
      },
      "application/vnd.ntt-local.sip-ta_tcp_stream": {
        source: "iana"
      },
      "application/vnd.oasis.opendocument.chart": {
        source: "iana",
        extensions: ["odc"]
      },
      "application/vnd.oasis.opendocument.chart-template": {
        source: "iana",
        extensions: ["otc"]
      },
      "application/vnd.oasis.opendocument.database": {
        source: "iana",
        extensions: ["odb"]
      },
      "application/vnd.oasis.opendocument.formula": {
        source: "iana",
        extensions: ["odf"]
      },
      "application/vnd.oasis.opendocument.formula-template": {
        source: "iana",
        extensions: ["odft"]
      },
      "application/vnd.oasis.opendocument.graphics": {
        source: "iana",
        compressible: false,
        extensions: ["odg"]
      },
      "application/vnd.oasis.opendocument.graphics-template": {
        source: "iana",
        extensions: ["otg"]
      },
      "application/vnd.oasis.opendocument.image": {
        source: "iana",
        extensions: ["odi"]
      },
      "application/vnd.oasis.opendocument.image-template": {
        source: "iana",
        extensions: ["oti"]
      },
      "application/vnd.oasis.opendocument.presentation": {
        source: "iana",
        compressible: false,
        extensions: ["odp"]
      },
      "application/vnd.oasis.opendocument.presentation-template": {
        source: "iana",
        extensions: ["otp"]
      },
      "application/vnd.oasis.opendocument.spreadsheet": {
        source: "iana",
        compressible: false,
        extensions: ["ods"]
      },
      "application/vnd.oasis.opendocument.spreadsheet-template": {
        source: "iana",
        extensions: ["ots"]
      },
      "application/vnd.oasis.opendocument.text": {
        source: "iana",
        compressible: false,
        extensions: ["odt"]
      },
      "application/vnd.oasis.opendocument.text-master": {
        source: "iana",
        extensions: ["odm"]
      },
      "application/vnd.oasis.opendocument.text-template": {
        source: "iana",
        extensions: ["ott"]
      },
      "application/vnd.oasis.opendocument.text-web": {
        source: "iana",
        extensions: ["oth"]
      },
      "application/vnd.obn": {
        source: "iana"
      },
      "application/vnd.ocf+cbor": {
        source: "iana"
      },
      "application/vnd.oci.image.manifest.v1+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oftn.l10n+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oipf.contentaccessdownload+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oipf.contentaccessstreaming+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oipf.cspg-hexbinary": {
        source: "iana"
      },
      "application/vnd.oipf.dae.svg+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oipf.dae.xhtml+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oipf.mippvcontrolmessage+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oipf.pae.gem": {
        source: "iana"
      },
      "application/vnd.oipf.spdiscovery+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oipf.spdlist+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oipf.ueprofile+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oipf.userprofile+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.olpc-sugar": {
        source: "iana",
        extensions: ["xo"]
      },
      "application/vnd.oma-scws-config": {
        source: "iana"
      },
      "application/vnd.oma-scws-http-request": {
        source: "iana"
      },
      "application/vnd.oma-scws-http-response": {
        source: "iana"
      },
      "application/vnd.oma.bcast.associated-procedure-parameter+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.bcast.drm-trigger+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.bcast.imd+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.bcast.ltkm": {
        source: "iana"
      },
      "application/vnd.oma.bcast.notification+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.bcast.provisioningtrigger": {
        source: "iana"
      },
      "application/vnd.oma.bcast.sgboot": {
        source: "iana"
      },
      "application/vnd.oma.bcast.sgdd+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.bcast.sgdu": {
        source: "iana"
      },
      "application/vnd.oma.bcast.simple-symbol-container": {
        source: "iana"
      },
      "application/vnd.oma.bcast.smartcard-trigger+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.bcast.sprov+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.bcast.stkm": {
        source: "iana"
      },
      "application/vnd.oma.cab-address-book+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.cab-feature-handler+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.cab-pcc+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.cab-subs-invite+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.cab-user-prefs+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.dcd": {
        source: "iana"
      },
      "application/vnd.oma.dcdc": {
        source: "iana"
      },
      "application/vnd.oma.dd2+xml": {
        source: "iana",
        compressible: true,
        extensions: ["dd2"]
      },
      "application/vnd.oma.drm.risd+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.group-usage-list+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.lwm2m+cbor": {
        source: "iana"
      },
      "application/vnd.oma.lwm2m+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.lwm2m+tlv": {
        source: "iana"
      },
      "application/vnd.oma.pal+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.poc.detailed-progress-report+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.poc.final-report+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.poc.groups+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.poc.invocation-descriptor+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.poc.optimized-progress-report+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.push": {
        source: "iana"
      },
      "application/vnd.oma.scidm.messages+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.xcap-directory+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.omads-email+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/vnd.omads-file+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/vnd.omads-folder+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/vnd.omaloc-supl-init": {
        source: "iana"
      },
      "application/vnd.onepager": {
        source: "iana"
      },
      "application/vnd.onepagertamp": {
        source: "iana"
      },
      "application/vnd.onepagertamx": {
        source: "iana"
      },
      "application/vnd.onepagertat": {
        source: "iana"
      },
      "application/vnd.onepagertatp": {
        source: "iana"
      },
      "application/vnd.onepagertatx": {
        source: "iana"
      },
      "application/vnd.openblox.game+xml": {
        source: "iana",
        compressible: true,
        extensions: ["obgx"]
      },
      "application/vnd.openblox.game-binary": {
        source: "iana"
      },
      "application/vnd.openeye.oeb": {
        source: "iana"
      },
      "application/vnd.openofficeorg.extension": {
        source: "apache",
        extensions: ["oxt"]
      },
      "application/vnd.openstreetmap.data+xml": {
        source: "iana",
        compressible: true,
        extensions: ["osm"]
      },
      "application/vnd.opentimestamps.ots": {
        source: "iana"
      },
      "application/vnd.openxmlformats-officedocument.custom-properties+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.drawing+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.extended-properties+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.presentation": {
        source: "iana",
        compressible: false,
        extensions: ["pptx"]
      },
      "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.slide": {
        source: "iana",
        extensions: ["sldx"]
      },
      "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.slideshow": {
        source: "iana",
        extensions: ["ppsx"]
      },
      "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.template": {
        source: "iana",
        extensions: ["potx"]
      },
      "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {
        source: "iana",
        compressible: false,
        extensions: ["xlsx"]
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.template": {
        source: "iana",
        extensions: ["xltx"]
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.theme+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.themeoverride+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.vmldrawing": {
        source: "iana"
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document": {
        source: "iana",
        compressible: false,
        extensions: ["docx"]
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.template": {
        source: "iana",
        extensions: ["dotx"]
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-package.core-properties+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-package.relationships+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oracle.resource+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.orange.indata": {
        source: "iana"
      },
      "application/vnd.osa.netdeploy": {
        source: "iana"
      },
      "application/vnd.osgeo.mapguide.package": {
        source: "iana",
        extensions: ["mgp"]
      },
      "application/vnd.osgi.bundle": {
        source: "iana"
      },
      "application/vnd.osgi.dp": {
        source: "iana",
        extensions: ["dp"]
      },
      "application/vnd.osgi.subsystem": {
        source: "iana",
        extensions: ["esa"]
      },
      "application/vnd.otps.ct-kip+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oxli.countgraph": {
        source: "iana"
      },
      "application/vnd.pagerduty+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.palm": {
        source: "iana",
        extensions: ["pdb", "pqa", "oprc"]
      },
      "application/vnd.panoply": {
        source: "iana"
      },
      "application/vnd.paos.xml": {
        source: "iana"
      },
      "application/vnd.patentdive": {
        source: "iana"
      },
      "application/vnd.patientecommsdoc": {
        source: "iana"
      },
      "application/vnd.pawaafile": {
        source: "iana",
        extensions: ["paw"]
      },
      "application/vnd.pcos": {
        source: "iana"
      },
      "application/vnd.pg.format": {
        source: "iana",
        extensions: ["str"]
      },
      "application/vnd.pg.osasli": {
        source: "iana",
        extensions: ["ei6"]
      },
      "application/vnd.piaccess.application-licence": {
        source: "iana"
      },
      "application/vnd.picsel": {
        source: "iana",
        extensions: ["efif"]
      },
      "application/vnd.pmi.widget": {
        source: "iana",
        extensions: ["wg"]
      },
      "application/vnd.poc.group-advertisement+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.pocketlearn": {
        source: "iana",
        extensions: ["plf"]
      },
      "application/vnd.powerbuilder6": {
        source: "iana",
        extensions: ["pbd"]
      },
      "application/vnd.powerbuilder6-s": {
        source: "iana"
      },
      "application/vnd.powerbuilder7": {
        source: "iana"
      },
      "application/vnd.powerbuilder7-s": {
        source: "iana"
      },
      "application/vnd.powerbuilder75": {
        source: "iana"
      },
      "application/vnd.powerbuilder75-s": {
        source: "iana"
      },
      "application/vnd.preminet": {
        source: "iana"
      },
      "application/vnd.previewsystems.box": {
        source: "iana",
        extensions: ["box"]
      },
      "application/vnd.proteus.magazine": {
        source: "iana",
        extensions: ["mgz"]
      },
      "application/vnd.psfs": {
        source: "iana"
      },
      "application/vnd.publishare-delta-tree": {
        source: "iana",
        extensions: ["qps"]
      },
      "application/vnd.pvi.ptid1": {
        source: "iana",
        extensions: ["ptid"]
      },
      "application/vnd.pwg-multiplexed": {
        source: "iana"
      },
      "application/vnd.pwg-xhtml-print+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.qualcomm.brew-app-res": {
        source: "iana"
      },
      "application/vnd.quarantainenet": {
        source: "iana"
      },
      "application/vnd.quark.quarkxpress": {
        source: "iana",
        extensions: ["qxd", "qxt", "qwd", "qwt", "qxl", "qxb"]
      },
      "application/vnd.quobject-quoxdocument": {
        source: "iana"
      },
      "application/vnd.radisys.moml+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-audit+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-audit-conf+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-audit-conn+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-audit-dialog+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-audit-stream+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-conf+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-dialog+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-dialog-base+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-dialog-fax-detect+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-dialog-group+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-dialog-speech+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-dialog-transform+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.rainstor.data": {
        source: "iana"
      },
      "application/vnd.rapid": {
        source: "iana"
      },
      "application/vnd.rar": {
        source: "iana",
        extensions: ["rar"]
      },
      "application/vnd.realvnc.bed": {
        source: "iana",
        extensions: ["bed"]
      },
      "application/vnd.recordare.musicxml": {
        source: "iana",
        extensions: ["mxl"]
      },
      "application/vnd.recordare.musicxml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["musicxml"]
      },
      "application/vnd.renlearn.rlprint": {
        source: "iana"
      },
      "application/vnd.resilient.logic": {
        source: "iana"
      },
      "application/vnd.restful+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.rig.cryptonote": {
        source: "iana",
        extensions: ["cryptonote"]
      },
      "application/vnd.rim.cod": {
        source: "apache",
        extensions: ["cod"]
      },
      "application/vnd.rn-realmedia": {
        source: "apache",
        extensions: ["rm"]
      },
      "application/vnd.rn-realmedia-vbr": {
        source: "apache",
        extensions: ["rmvb"]
      },
      "application/vnd.route66.link66+xml": {
        source: "iana",
        compressible: true,
        extensions: ["link66"]
      },
      "application/vnd.rs-274x": {
        source: "iana"
      },
      "application/vnd.ruckus.download": {
        source: "iana"
      },
      "application/vnd.s3sms": {
        source: "iana"
      },
      "application/vnd.sailingtracker.track": {
        source: "iana",
        extensions: ["st"]
      },
      "application/vnd.sar": {
        source: "iana"
      },
      "application/vnd.sbm.cid": {
        source: "iana"
      },
      "application/vnd.sbm.mid2": {
        source: "iana"
      },
      "application/vnd.scribus": {
        source: "iana"
      },
      "application/vnd.sealed.3df": {
        source: "iana"
      },
      "application/vnd.sealed.csf": {
        source: "iana"
      },
      "application/vnd.sealed.doc": {
        source: "iana"
      },
      "application/vnd.sealed.eml": {
        source: "iana"
      },
      "application/vnd.sealed.mht": {
        source: "iana"
      },
      "application/vnd.sealed.net": {
        source: "iana"
      },
      "application/vnd.sealed.ppt": {
        source: "iana"
      },
      "application/vnd.sealed.tiff": {
        source: "iana"
      },
      "application/vnd.sealed.xls": {
        source: "iana"
      },
      "application/vnd.sealedmedia.softseal.html": {
        source: "iana"
      },
      "application/vnd.sealedmedia.softseal.pdf": {
        source: "iana"
      },
      "application/vnd.seemail": {
        source: "iana",
        extensions: ["see"]
      },
      "application/vnd.seis+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.sema": {
        source: "iana",
        extensions: ["sema"]
      },
      "application/vnd.semd": {
        source: "iana",
        extensions: ["semd"]
      },
      "application/vnd.semf": {
        source: "iana",
        extensions: ["semf"]
      },
      "application/vnd.shade-save-file": {
        source: "iana"
      },
      "application/vnd.shana.informed.formdata": {
        source: "iana",
        extensions: ["ifm"]
      },
      "application/vnd.shana.informed.formtemplate": {
        source: "iana",
        extensions: ["itp"]
      },
      "application/vnd.shana.informed.interchange": {
        source: "iana",
        extensions: ["iif"]
      },
      "application/vnd.shana.informed.package": {
        source: "iana",
        extensions: ["ipk"]
      },
      "application/vnd.shootproof+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.shopkick+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.shp": {
        source: "iana"
      },
      "application/vnd.shx": {
        source: "iana"
      },
      "application/vnd.sigrok.session": {
        source: "iana"
      },
      "application/vnd.simtech-mindmapper": {
        source: "iana",
        extensions: ["twd", "twds"]
      },
      "application/vnd.siren+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.smaf": {
        source: "iana",
        extensions: ["mmf"]
      },
      "application/vnd.smart.notebook": {
        source: "iana"
      },
      "application/vnd.smart.teacher": {
        source: "iana",
        extensions: ["teacher"]
      },
      "application/vnd.snesdev-page-table": {
        source: "iana"
      },
      "application/vnd.software602.filler.form+xml": {
        source: "iana",
        compressible: true,
        extensions: ["fo"]
      },
      "application/vnd.software602.filler.form-xml-zip": {
        source: "iana"
      },
      "application/vnd.solent.sdkm+xml": {
        source: "iana",
        compressible: true,
        extensions: ["sdkm", "sdkd"]
      },
      "application/vnd.spotfire.dxp": {
        source: "iana",
        extensions: ["dxp"]
      },
      "application/vnd.spotfire.sfs": {
        source: "iana",
        extensions: ["sfs"]
      },
      "application/vnd.sqlite3": {
        source: "iana"
      },
      "application/vnd.sss-cod": {
        source: "iana"
      },
      "application/vnd.sss-dtf": {
        source: "iana"
      },
      "application/vnd.sss-ntf": {
        source: "iana"
      },
      "application/vnd.stardivision.calc": {
        source: "apache",
        extensions: ["sdc"]
      },
      "application/vnd.stardivision.draw": {
        source: "apache",
        extensions: ["sda"]
      },
      "application/vnd.stardivision.impress": {
        source: "apache",
        extensions: ["sdd"]
      },
      "application/vnd.stardivision.math": {
        source: "apache",
        extensions: ["smf"]
      },
      "application/vnd.stardivision.writer": {
        source: "apache",
        extensions: ["sdw", "vor"]
      },
      "application/vnd.stardivision.writer-global": {
        source: "apache",
        extensions: ["sgl"]
      },
      "application/vnd.stepmania.package": {
        source: "iana",
        extensions: ["smzip"]
      },
      "application/vnd.stepmania.stepchart": {
        source: "iana",
        extensions: ["sm"]
      },
      "application/vnd.street-stream": {
        source: "iana"
      },
      "application/vnd.sun.wadl+xml": {
        source: "iana",
        compressible: true,
        extensions: ["wadl"]
      },
      "application/vnd.sun.xml.calc": {
        source: "apache",
        extensions: ["sxc"]
      },
      "application/vnd.sun.xml.calc.template": {
        source: "apache",
        extensions: ["stc"]
      },
      "application/vnd.sun.xml.draw": {
        source: "apache",
        extensions: ["sxd"]
      },
      "application/vnd.sun.xml.draw.template": {
        source: "apache",
        extensions: ["std"]
      },
      "application/vnd.sun.xml.impress": {
        source: "apache",
        extensions: ["sxi"]
      },
      "application/vnd.sun.xml.impress.template": {
        source: "apache",
        extensions: ["sti"]
      },
      "application/vnd.sun.xml.math": {
        source: "apache",
        extensions: ["sxm"]
      },
      "application/vnd.sun.xml.writer": {
        source: "apache",
        extensions: ["sxw"]
      },
      "application/vnd.sun.xml.writer.global": {
        source: "apache",
        extensions: ["sxg"]
      },
      "application/vnd.sun.xml.writer.template": {
        source: "apache",
        extensions: ["stw"]
      },
      "application/vnd.sus-calendar": {
        source: "iana",
        extensions: ["sus", "susp"]
      },
      "application/vnd.svd": {
        source: "iana",
        extensions: ["svd"]
      },
      "application/vnd.swiftview-ics": {
        source: "iana"
      },
      "application/vnd.sycle+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.syft+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.symbian.install": {
        source: "apache",
        extensions: ["sis", "sisx"]
      },
      "application/vnd.syncml+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true,
        extensions: ["xsm"]
      },
      "application/vnd.syncml.dm+wbxml": {
        source: "iana",
        charset: "UTF-8",
        extensions: ["bdm"]
      },
      "application/vnd.syncml.dm+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true,
        extensions: ["xdm"]
      },
      "application/vnd.syncml.dm.notification": {
        source: "iana"
      },
      "application/vnd.syncml.dmddf+wbxml": {
        source: "iana"
      },
      "application/vnd.syncml.dmddf+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true,
        extensions: ["ddf"]
      },
      "application/vnd.syncml.dmtnds+wbxml": {
        source: "iana"
      },
      "application/vnd.syncml.dmtnds+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/vnd.syncml.ds.notification": {
        source: "iana"
      },
      "application/vnd.tableschema+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.tao.intent-module-archive": {
        source: "iana",
        extensions: ["tao"]
      },
      "application/vnd.tcpdump.pcap": {
        source: "iana",
        extensions: ["pcap", "cap", "dmp"]
      },
      "application/vnd.think-cell.ppttc+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.tmd.mediaflex.api+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.tml": {
        source: "iana"
      },
      "application/vnd.tmobile-livetv": {
        source: "iana",
        extensions: ["tmo"]
      },
      "application/vnd.tri.onesource": {
        source: "iana"
      },
      "application/vnd.trid.tpt": {
        source: "iana",
        extensions: ["tpt"]
      },
      "application/vnd.triscape.mxs": {
        source: "iana",
        extensions: ["mxs"]
      },
      "application/vnd.trueapp": {
        source: "iana",
        extensions: ["tra"]
      },
      "application/vnd.truedoc": {
        source: "iana"
      },
      "application/vnd.ubisoft.webplayer": {
        source: "iana"
      },
      "application/vnd.ufdl": {
        source: "iana",
        extensions: ["ufd", "ufdl"]
      },
      "application/vnd.uiq.theme": {
        source: "iana",
        extensions: ["utz"]
      },
      "application/vnd.umajin": {
        source: "iana",
        extensions: ["umj"]
      },
      "application/vnd.unity": {
        source: "iana",
        extensions: ["unityweb"]
      },
      "application/vnd.uoml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["uoml"]
      },
      "application/vnd.uplanet.alert": {
        source: "iana"
      },
      "application/vnd.uplanet.alert-wbxml": {
        source: "iana"
      },
      "application/vnd.uplanet.bearer-choice": {
        source: "iana"
      },
      "application/vnd.uplanet.bearer-choice-wbxml": {
        source: "iana"
      },
      "application/vnd.uplanet.cacheop": {
        source: "iana"
      },
      "application/vnd.uplanet.cacheop-wbxml": {
        source: "iana"
      },
      "application/vnd.uplanet.channel": {
        source: "iana"
      },
      "application/vnd.uplanet.channel-wbxml": {
        source: "iana"
      },
      "application/vnd.uplanet.list": {
        source: "iana"
      },
      "application/vnd.uplanet.list-wbxml": {
        source: "iana"
      },
      "application/vnd.uplanet.listcmd": {
        source: "iana"
      },
      "application/vnd.uplanet.listcmd-wbxml": {
        source: "iana"
      },
      "application/vnd.uplanet.signal": {
        source: "iana"
      },
      "application/vnd.uri-map": {
        source: "iana"
      },
      "application/vnd.valve.source.material": {
        source: "iana"
      },
      "application/vnd.vcx": {
        source: "iana",
        extensions: ["vcx"]
      },
      "application/vnd.vd-study": {
        source: "iana"
      },
      "application/vnd.vectorworks": {
        source: "iana"
      },
      "application/vnd.vel+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.verimatrix.vcas": {
        source: "iana"
      },
      "application/vnd.veritone.aion+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.veryant.thin": {
        source: "iana"
      },
      "application/vnd.ves.encrypted": {
        source: "iana"
      },
      "application/vnd.vidsoft.vidconference": {
        source: "iana"
      },
      "application/vnd.visio": {
        source: "iana",
        extensions: ["vsd", "vst", "vss", "vsw"]
      },
      "application/vnd.visionary": {
        source: "iana",
        extensions: ["vis"]
      },
      "application/vnd.vividence.scriptfile": {
        source: "iana"
      },
      "application/vnd.vsf": {
        source: "iana",
        extensions: ["vsf"]
      },
      "application/vnd.wap.sic": {
        source: "iana"
      },
      "application/vnd.wap.slc": {
        source: "iana"
      },
      "application/vnd.wap.wbxml": {
        source: "iana",
        charset: "UTF-8",
        extensions: ["wbxml"]
      },
      "application/vnd.wap.wmlc": {
        source: "iana",
        extensions: ["wmlc"]
      },
      "application/vnd.wap.wmlscriptc": {
        source: "iana",
        extensions: ["wmlsc"]
      },
      "application/vnd.webturbo": {
        source: "iana",
        extensions: ["wtb"]
      },
      "application/vnd.wfa.dpp": {
        source: "iana"
      },
      "application/vnd.wfa.p2p": {
        source: "iana"
      },
      "application/vnd.wfa.wsc": {
        source: "iana"
      },
      "application/vnd.windows.devicepairing": {
        source: "iana"
      },
      "application/vnd.wmc": {
        source: "iana"
      },
      "application/vnd.wmf.bootstrap": {
        source: "iana"
      },
      "application/vnd.wolfram.mathematica": {
        source: "iana"
      },
      "application/vnd.wolfram.mathematica.package": {
        source: "iana"
      },
      "application/vnd.wolfram.player": {
        source: "iana",
        extensions: ["nbp"]
      },
      "application/vnd.wordperfect": {
        source: "iana",
        extensions: ["wpd"]
      },
      "application/vnd.wqd": {
        source: "iana",
        extensions: ["wqd"]
      },
      "application/vnd.wrq-hp3000-labelled": {
        source: "iana"
      },
      "application/vnd.wt.stf": {
        source: "iana",
        extensions: ["stf"]
      },
      "application/vnd.wv.csp+wbxml": {
        source: "iana"
      },
      "application/vnd.wv.csp+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.wv.ssp+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.xacml+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.xara": {
        source: "iana",
        extensions: ["xar"]
      },
      "application/vnd.xfdl": {
        source: "iana",
        extensions: ["xfdl"]
      },
      "application/vnd.xfdl.webform": {
        source: "iana"
      },
      "application/vnd.xmi+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.xmpie.cpkg": {
        source: "iana"
      },
      "application/vnd.xmpie.dpkg": {
        source: "iana"
      },
      "application/vnd.xmpie.plan": {
        source: "iana"
      },
      "application/vnd.xmpie.ppkg": {
        source: "iana"
      },
      "application/vnd.xmpie.xlim": {
        source: "iana"
      },
      "application/vnd.yamaha.hv-dic": {
        source: "iana",
        extensions: ["hvd"]
      },
      "application/vnd.yamaha.hv-script": {
        source: "iana",
        extensions: ["hvs"]
      },
      "application/vnd.yamaha.hv-voice": {
        source: "iana",
        extensions: ["hvp"]
      },
      "application/vnd.yamaha.openscoreformat": {
        source: "iana",
        extensions: ["osf"]
      },
      "application/vnd.yamaha.openscoreformat.osfpvg+xml": {
        source: "iana",
        compressible: true,
        extensions: ["osfpvg"]
      },
      "application/vnd.yamaha.remote-setup": {
        source: "iana"
      },
      "application/vnd.yamaha.smaf-audio": {
        source: "iana",
        extensions: ["saf"]
      },
      "application/vnd.yamaha.smaf-phrase": {
        source: "iana",
        extensions: ["spf"]
      },
      "application/vnd.yamaha.through-ngn": {
        source: "iana"
      },
      "application/vnd.yamaha.tunnel-udpencap": {
        source: "iana"
      },
      "application/vnd.yaoweme": {
        source: "iana"
      },
      "application/vnd.yellowriver-custom-menu": {
        source: "iana",
        extensions: ["cmp"]
      },
      "application/vnd.youtube.yt": {
        source: "iana"
      },
      "application/vnd.zul": {
        source: "iana",
        extensions: ["zir", "zirz"]
      },
      "application/vnd.zzazz.deck+xml": {
        source: "iana",
        compressible: true,
        extensions: ["zaz"]
      },
      "application/voicexml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["vxml"]
      },
      "application/voucher-cms+json": {
        source: "iana",
        compressible: true
      },
      "application/vq-rtcpxr": {
        source: "iana"
      },
      "application/wasm": {
        source: "iana",
        compressible: true,
        extensions: ["wasm"]
      },
      "application/watcherinfo+xml": {
        source: "iana",
        compressible: true,
        extensions: ["wif"]
      },
      "application/webpush-options+json": {
        source: "iana",
        compressible: true
      },
      "application/whoispp-query": {
        source: "iana"
      },
      "application/whoispp-response": {
        source: "iana"
      },
      "application/widget": {
        source: "iana",
        extensions: ["wgt"]
      },
      "application/winhlp": {
        source: "apache",
        extensions: ["hlp"]
      },
      "application/wita": {
        source: "iana"
      },
      "application/wordperfect5.1": {
        source: "iana"
      },
      "application/wsdl+xml": {
        source: "iana",
        compressible: true,
        extensions: ["wsdl"]
      },
      "application/wspolicy+xml": {
        source: "iana",
        compressible: true,
        extensions: ["wspolicy"]
      },
      "application/x-7z-compressed": {
        source: "apache",
        compressible: false,
        extensions: ["7z"]
      },
      "application/x-abiword": {
        source: "apache",
        extensions: ["abw"]
      },
      "application/x-ace-compressed": {
        source: "apache",
        extensions: ["ace"]
      },
      "application/x-amf": {
        source: "apache"
      },
      "application/x-apple-diskimage": {
        source: "apache",
        extensions: ["dmg"]
      },
      "application/x-arj": {
        compressible: false,
        extensions: ["arj"]
      },
      "application/x-authorware-bin": {
        source: "apache",
        extensions: ["aab", "x32", "u32", "vox"]
      },
      "application/x-authorware-map": {
        source: "apache",
        extensions: ["aam"]
      },
      "application/x-authorware-seg": {
        source: "apache",
        extensions: ["aas"]
      },
      "application/x-bcpio": {
        source: "apache",
        extensions: ["bcpio"]
      },
      "application/x-bdoc": {
        compressible: false,
        extensions: ["bdoc"]
      },
      "application/x-bittorrent": {
        source: "apache",
        extensions: ["torrent"]
      },
      "application/x-blorb": {
        source: "apache",
        extensions: ["blb", "blorb"]
      },
      "application/x-bzip": {
        source: "apache",
        compressible: false,
        extensions: ["bz"]
      },
      "application/x-bzip2": {
        source: "apache",
        compressible: false,
        extensions: ["bz2", "boz"]
      },
      "application/x-cbr": {
        source: "apache",
        extensions: ["cbr", "cba", "cbt", "cbz", "cb7"]
      },
      "application/x-cdlink": {
        source: "apache",
        extensions: ["vcd"]
      },
      "application/x-cfs-compressed": {
        source: "apache",
        extensions: ["cfs"]
      },
      "application/x-chat": {
        source: "apache",
        extensions: ["chat"]
      },
      "application/x-chess-pgn": {
        source: "apache",
        extensions: ["pgn"]
      },
      "application/x-chrome-extension": {
        extensions: ["crx"]
      },
      "application/x-cocoa": {
        source: "nginx",
        extensions: ["cco"]
      },
      "application/x-compress": {
        source: "apache"
      },
      "application/x-conference": {
        source: "apache",
        extensions: ["nsc"]
      },
      "application/x-cpio": {
        source: "apache",
        extensions: ["cpio"]
      },
      "application/x-csh": {
        source: "apache",
        extensions: ["csh"]
      },
      "application/x-deb": {
        compressible: false
      },
      "application/x-debian-package": {
        source: "apache",
        extensions: ["deb", "udeb"]
      },
      "application/x-dgc-compressed": {
        source: "apache",
        extensions: ["dgc"]
      },
      "application/x-director": {
        source: "apache",
        extensions: ["dir", "dcr", "dxr", "cst", "cct", "cxt", "w3d", "fgd", "swa"]
      },
      "application/x-doom": {
        source: "apache",
        extensions: ["wad"]
      },
      "application/x-dtbncx+xml": {
        source: "apache",
        compressible: true,
        extensions: ["ncx"]
      },
      "application/x-dtbook+xml": {
        source: "apache",
        compressible: true,
        extensions: ["dtb"]
      },
      "application/x-dtbresource+xml": {
        source: "apache",
        compressible: true,
        extensions: ["res"]
      },
      "application/x-dvi": {
        source: "apache",
        compressible: false,
        extensions: ["dvi"]
      },
      "application/x-envoy": {
        source: "apache",
        extensions: ["evy"]
      },
      "application/x-eva": {
        source: "apache",
        extensions: ["eva"]
      },
      "application/x-font-bdf": {
        source: "apache",
        extensions: ["bdf"]
      },
      "application/x-font-dos": {
        source: "apache"
      },
      "application/x-font-framemaker": {
        source: "apache"
      },
      "application/x-font-ghostscript": {
        source: "apache",
        extensions: ["gsf"]
      },
      "application/x-font-libgrx": {
        source: "apache"
      },
      "application/x-font-linux-psf": {
        source: "apache",
        extensions: ["psf"]
      },
      "application/x-font-pcf": {
        source: "apache",
        extensions: ["pcf"]
      },
      "application/x-font-snf": {
        source: "apache",
        extensions: ["snf"]
      },
      "application/x-font-speedo": {
        source: "apache"
      },
      "application/x-font-sunos-news": {
        source: "apache"
      },
      "application/x-font-type1": {
        source: "apache",
        extensions: ["pfa", "pfb", "pfm", "afm"]
      },
      "application/x-font-vfont": {
        source: "apache"
      },
      "application/x-freearc": {
        source: "apache",
        extensions: ["arc"]
      },
      "application/x-futuresplash": {
        source: "apache",
        extensions: ["spl"]
      },
      "application/x-gca-compressed": {
        source: "apache",
        extensions: ["gca"]
      },
      "application/x-glulx": {
        source: "apache",
        extensions: ["ulx"]
      },
      "application/x-gnumeric": {
        source: "apache",
        extensions: ["gnumeric"]
      },
      "application/x-gramps-xml": {
        source: "apache",
        extensions: ["gramps"]
      },
      "application/x-gtar": {
        source: "apache",
        extensions: ["gtar"]
      },
      "application/x-gzip": {
        source: "apache"
      },
      "application/x-hdf": {
        source: "apache",
        extensions: ["hdf"]
      },
      "application/x-httpd-php": {
        compressible: true,
        extensions: ["php"]
      },
      "application/x-install-instructions": {
        source: "apache",
        extensions: ["install"]
      },
      "application/x-iso9660-image": {
        source: "apache",
        extensions: ["iso"]
      },
      "application/x-iwork-keynote-sffkey": {
        extensions: ["key"]
      },
      "application/x-iwork-numbers-sffnumbers": {
        extensions: ["numbers"]
      },
      "application/x-iwork-pages-sffpages": {
        extensions: ["pages"]
      },
      "application/x-java-archive-diff": {
        source: "nginx",
        extensions: ["jardiff"]
      },
      "application/x-java-jnlp-file": {
        source: "apache",
        compressible: false,
        extensions: ["jnlp"]
      },
      "application/x-javascript": {
        compressible: true
      },
      "application/x-keepass2": {
        extensions: ["kdbx"]
      },
      "application/x-latex": {
        source: "apache",
        compressible: false,
        extensions: ["latex"]
      },
      "application/x-lua-bytecode": {
        extensions: ["luac"]
      },
      "application/x-lzh-compressed": {
        source: "apache",
        extensions: ["lzh", "lha"]
      },
      "application/x-makeself": {
        source: "nginx",
        extensions: ["run"]
      },
      "application/x-mie": {
        source: "apache",
        extensions: ["mie"]
      },
      "application/x-mobipocket-ebook": {
        source: "apache",
        extensions: ["prc", "mobi"]
      },
      "application/x-mpegurl": {
        compressible: false
      },
      "application/x-ms-application": {
        source: "apache",
        extensions: ["application"]
      },
      "application/x-ms-shortcut": {
        source: "apache",
        extensions: ["lnk"]
      },
      "application/x-ms-wmd": {
        source: "apache",
        extensions: ["wmd"]
      },
      "application/x-ms-wmz": {
        source: "apache",
        extensions: ["wmz"]
      },
      "application/x-ms-xbap": {
        source: "apache",
        extensions: ["xbap"]
      },
      "application/x-msaccess": {
        source: "apache",
        extensions: ["mdb"]
      },
      "application/x-msbinder": {
        source: "apache",
        extensions: ["obd"]
      },
      "application/x-mscardfile": {
        source: "apache",
        extensions: ["crd"]
      },
      "application/x-msclip": {
        source: "apache",
        extensions: ["clp"]
      },
      "application/x-msdos-program": {
        extensions: ["exe"]
      },
      "application/x-msdownload": {
        source: "apache",
        extensions: ["exe", "dll", "com", "bat", "msi"]
      },
      "application/x-msmediaview": {
        source: "apache",
        extensions: ["mvb", "m13", "m14"]
      },
      "application/x-msmetafile": {
        source: "apache",
        extensions: ["wmf", "wmz", "emf", "emz"]
      },
      "application/x-msmoney": {
        source: "apache",
        extensions: ["mny"]
      },
      "application/x-mspublisher": {
        source: "apache",
        extensions: ["pub"]
      },
      "application/x-msschedule": {
        source: "apache",
        extensions: ["scd"]
      },
      "application/x-msterminal": {
        source: "apache",
        extensions: ["trm"]
      },
      "application/x-mswrite": {
        source: "apache",
        extensions: ["wri"]
      },
      "application/x-netcdf": {
        source: "apache",
        extensions: ["nc", "cdf"]
      },
      "application/x-ns-proxy-autoconfig": {
        compressible: true,
        extensions: ["pac"]
      },
      "application/x-nzb": {
        source: "apache",
        extensions: ["nzb"]
      },
      "application/x-perl": {
        source: "nginx",
        extensions: ["pl", "pm"]
      },
      "application/x-pilot": {
        source: "nginx",
        extensions: ["prc", "pdb"]
      },
      "application/x-pkcs12": {
        source: "apache",
        compressible: false,
        extensions: ["p12", "pfx"]
      },
      "application/x-pkcs7-certificates": {
        source: "apache",
        extensions: ["p7b", "spc"]
      },
      "application/x-pkcs7-certreqresp": {
        source: "apache",
        extensions: ["p7r"]
      },
      "application/x-pki-message": {
        source: "iana"
      },
      "application/x-rar-compressed": {
        source: "apache",
        compressible: false,
        extensions: ["rar"]
      },
      "application/x-redhat-package-manager": {
        source: "nginx",
        extensions: ["rpm"]
      },
      "application/x-research-info-systems": {
        source: "apache",
        extensions: ["ris"]
      },
      "application/x-sea": {
        source: "nginx",
        extensions: ["sea"]
      },
      "application/x-sh": {
        source: "apache",
        compressible: true,
        extensions: ["sh"]
      },
      "application/x-shar": {
        source: "apache",
        extensions: ["shar"]
      },
      "application/x-shockwave-flash": {
        source: "apache",
        compressible: false,
        extensions: ["swf"]
      },
      "application/x-silverlight-app": {
        source: "apache",
        extensions: ["xap"]
      },
      "application/x-sql": {
        source: "apache",
        extensions: ["sql"]
      },
      "application/x-stuffit": {
        source: "apache",
        compressible: false,
        extensions: ["sit"]
      },
      "application/x-stuffitx": {
        source: "apache",
        extensions: ["sitx"]
      },
      "application/x-subrip": {
        source: "apache",
        extensions: ["srt"]
      },
      "application/x-sv4cpio": {
        source: "apache",
        extensions: ["sv4cpio"]
      },
      "application/x-sv4crc": {
        source: "apache",
        extensions: ["sv4crc"]
      },
      "application/x-t3vm-image": {
        source: "apache",
        extensions: ["t3"]
      },
      "application/x-tads": {
        source: "apache",
        extensions: ["gam"]
      },
      "application/x-tar": {
        source: "apache",
        compressible: true,
        extensions: ["tar"]
      },
      "application/x-tcl": {
        source: "apache",
        extensions: ["tcl", "tk"]
      },
      "application/x-tex": {
        source: "apache",
        extensions: ["tex"]
      },
      "application/x-tex-tfm": {
        source: "apache",
        extensions: ["tfm"]
      },
      "application/x-texinfo": {
        source: "apache",
        extensions: ["texinfo", "texi"]
      },
      "application/x-tgif": {
        source: "apache",
        extensions: ["obj"]
      },
      "application/x-ustar": {
        source: "apache",
        extensions: ["ustar"]
      },
      "application/x-virtualbox-hdd": {
        compressible: true,
        extensions: ["hdd"]
      },
      "application/x-virtualbox-ova": {
        compressible: true,
        extensions: ["ova"]
      },
      "application/x-virtualbox-ovf": {
        compressible: true,
        extensions: ["ovf"]
      },
      "application/x-virtualbox-vbox": {
        compressible: true,
        extensions: ["vbox"]
      },
      "application/x-virtualbox-vbox-extpack": {
        compressible: false,
        extensions: ["vbox-extpack"]
      },
      "application/x-virtualbox-vdi": {
        compressible: true,
        extensions: ["vdi"]
      },
      "application/x-virtualbox-vhd": {
        compressible: true,
        extensions: ["vhd"]
      },
      "application/x-virtualbox-vmdk": {
        compressible: true,
        extensions: ["vmdk"]
      },
      "application/x-wais-source": {
        source: "apache",
        extensions: ["src"]
      },
      "application/x-web-app-manifest+json": {
        compressible: true,
        extensions: ["webapp"]
      },
      "application/x-www-form-urlencoded": {
        source: "iana",
        compressible: true
      },
      "application/x-x509-ca-cert": {
        source: "iana",
        extensions: ["der", "crt", "pem"]
      },
      "application/x-x509-ca-ra-cert": {
        source: "iana"
      },
      "application/x-x509-next-ca-cert": {
        source: "iana"
      },
      "application/x-xfig": {
        source: "apache",
        extensions: ["fig"]
      },
      "application/x-xliff+xml": {
        source: "apache",
        compressible: true,
        extensions: ["xlf"]
      },
      "application/x-xpinstall": {
        source: "apache",
        compressible: false,
        extensions: ["xpi"]
      },
      "application/x-xz": {
        source: "apache",
        extensions: ["xz"]
      },
      "application/x-zmachine": {
        source: "apache",
        extensions: ["z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8"]
      },
      "application/x400-bp": {
        source: "iana"
      },
      "application/xacml+xml": {
        source: "iana",
        compressible: true
      },
      "application/xaml+xml": {
        source: "apache",
        compressible: true,
        extensions: ["xaml"]
      },
      "application/xcap-att+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xav"]
      },
      "application/xcap-caps+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xca"]
      },
      "application/xcap-diff+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xdf"]
      },
      "application/xcap-el+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xel"]
      },
      "application/xcap-error+xml": {
        source: "iana",
        compressible: true
      },
      "application/xcap-ns+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xns"]
      },
      "application/xcon-conference-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/xcon-conference-info-diff+xml": {
        source: "iana",
        compressible: true
      },
      "application/xenc+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xenc"]
      },
      "application/xhtml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xhtml", "xht"]
      },
      "application/xhtml-voice+xml": {
        source: "apache",
        compressible: true
      },
      "application/xliff+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xlf"]
      },
      "application/xml": {
        source: "iana",
        compressible: true,
        extensions: ["xml", "xsl", "xsd", "rng"]
      },
      "application/xml-dtd": {
        source: "iana",
        compressible: true,
        extensions: ["dtd"]
      },
      "application/xml-external-parsed-entity": {
        source: "iana"
      },
      "application/xml-patch+xml": {
        source: "iana",
        compressible: true
      },
      "application/xmpp+xml": {
        source: "iana",
        compressible: true
      },
      "application/xop+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xop"]
      },
      "application/xproc+xml": {
        source: "apache",
        compressible: true,
        extensions: ["xpl"]
      },
      "application/xslt+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xsl", "xslt"]
      },
      "application/xspf+xml": {
        source: "apache",
        compressible: true,
        extensions: ["xspf"]
      },
      "application/xv+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mxml", "xhvml", "xvml", "xvm"]
      },
      "application/yang": {
        source: "iana",
        extensions: ["yang"]
      },
      "application/yang-data+json": {
        source: "iana",
        compressible: true
      },
      "application/yang-data+xml": {
        source: "iana",
        compressible: true
      },
      "application/yang-patch+json": {
        source: "iana",
        compressible: true
      },
      "application/yang-patch+xml": {
        source: "iana",
        compressible: true
      },
      "application/yin+xml": {
        source: "iana",
        compressible: true,
        extensions: ["yin"]
      },
      "application/zip": {
        source: "iana",
        compressible: false,
        extensions: ["zip"]
      },
      "application/zlib": {
        source: "iana"
      },
      "application/zstd": {
        source: "iana"
      },
      "audio/1d-interleaved-parityfec": {
        source: "iana"
      },
      "audio/32kadpcm": {
        source: "iana"
      },
      "audio/3gpp": {
        source: "iana",
        compressible: false,
        extensions: ["3gpp"]
      },
      "audio/3gpp2": {
        source: "iana"
      },
      "audio/aac": {
        source: "iana"
      },
      "audio/ac3": {
        source: "iana"
      },
      "audio/adpcm": {
        source: "apache",
        extensions: ["adp"]
      },
      "audio/amr": {
        source: "iana",
        extensions: ["amr"]
      },
      "audio/amr-wb": {
        source: "iana"
      },
      "audio/amr-wb+": {
        source: "iana"
      },
      "audio/aptx": {
        source: "iana"
      },
      "audio/asc": {
        source: "iana"
      },
      "audio/atrac-advanced-lossless": {
        source: "iana"
      },
      "audio/atrac-x": {
        source: "iana"
      },
      "audio/atrac3": {
        source: "iana"
      },
      "audio/basic": {
        source: "iana",
        compressible: false,
        extensions: ["au", "snd"]
      },
      "audio/bv16": {
        source: "iana"
      },
      "audio/bv32": {
        source: "iana"
      },
      "audio/clearmode": {
        source: "iana"
      },
      "audio/cn": {
        source: "iana"
      },
      "audio/dat12": {
        source: "iana"
      },
      "audio/dls": {
        source: "iana"
      },
      "audio/dsr-es201108": {
        source: "iana"
      },
      "audio/dsr-es202050": {
        source: "iana"
      },
      "audio/dsr-es202211": {
        source: "iana"
      },
      "audio/dsr-es202212": {
        source: "iana"
      },
      "audio/dv": {
        source: "iana"
      },
      "audio/dvi4": {
        source: "iana"
      },
      "audio/eac3": {
        source: "iana"
      },
      "audio/encaprtp": {
        source: "iana"
      },
      "audio/evrc": {
        source: "iana"
      },
      "audio/evrc-qcp": {
        source: "iana"
      },
      "audio/evrc0": {
        source: "iana"
      },
      "audio/evrc1": {
        source: "iana"
      },
      "audio/evrcb": {
        source: "iana"
      },
      "audio/evrcb0": {
        source: "iana"
      },
      "audio/evrcb1": {
        source: "iana"
      },
      "audio/evrcnw": {
        source: "iana"
      },
      "audio/evrcnw0": {
        source: "iana"
      },
      "audio/evrcnw1": {
        source: "iana"
      },
      "audio/evrcwb": {
        source: "iana"
      },
      "audio/evrcwb0": {
        source: "iana"
      },
      "audio/evrcwb1": {
        source: "iana"
      },
      "audio/evs": {
        source: "iana"
      },
      "audio/flexfec": {
        source: "iana"
      },
      "audio/fwdred": {
        source: "iana"
      },
      "audio/g711-0": {
        source: "iana"
      },
      "audio/g719": {
        source: "iana"
      },
      "audio/g722": {
        source: "iana"
      },
      "audio/g7221": {
        source: "iana"
      },
      "audio/g723": {
        source: "iana"
      },
      "audio/g726-16": {
        source: "iana"
      },
      "audio/g726-24": {
        source: "iana"
      },
      "audio/g726-32": {
        source: "iana"
      },
      "audio/g726-40": {
        source: "iana"
      },
      "audio/g728": {
        source: "iana"
      },
      "audio/g729": {
        source: "iana"
      },
      "audio/g7291": {
        source: "iana"
      },
      "audio/g729d": {
        source: "iana"
      },
      "audio/g729e": {
        source: "iana"
      },
      "audio/gsm": {
        source: "iana"
      },
      "audio/gsm-efr": {
        source: "iana"
      },
      "audio/gsm-hr-08": {
        source: "iana"
      },
      "audio/ilbc": {
        source: "iana"
      },
      "audio/ip-mr_v2.5": {
        source: "iana"
      },
      "audio/isac": {
        source: "apache"
      },
      "audio/l16": {
        source: "iana"
      },
      "audio/l20": {
        source: "iana"
      },
      "audio/l24": {
        source: "iana",
        compressible: false
      },
      "audio/l8": {
        source: "iana"
      },
      "audio/lpc": {
        source: "iana"
      },
      "audio/melp": {
        source: "iana"
      },
      "audio/melp1200": {
        source: "iana"
      },
      "audio/melp2400": {
        source: "iana"
      },
      "audio/melp600": {
        source: "iana"
      },
      "audio/mhas": {
        source: "iana"
      },
      "audio/midi": {
        source: "apache",
        extensions: ["mid", "midi", "kar", "rmi"]
      },
      "audio/mobile-xmf": {
        source: "iana",
        extensions: ["mxmf"]
      },
      "audio/mp3": {
        compressible: false,
        extensions: ["mp3"]
      },
      "audio/mp4": {
        source: "iana",
        compressible: false,
        extensions: ["m4a", "mp4a"]
      },
      "audio/mp4a-latm": {
        source: "iana"
      },
      "audio/mpa": {
        source: "iana"
      },
      "audio/mpa-robust": {
        source: "iana"
      },
      "audio/mpeg": {
        source: "iana",
        compressible: false,
        extensions: ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"]
      },
      "audio/mpeg4-generic": {
        source: "iana"
      },
      "audio/musepack": {
        source: "apache"
      },
      "audio/ogg": {
        source: "iana",
        compressible: false,
        extensions: ["oga", "ogg", "spx", "opus"]
      },
      "audio/opus": {
        source: "iana"
      },
      "audio/parityfec": {
        source: "iana"
      },
      "audio/pcma": {
        source: "iana"
      },
      "audio/pcma-wb": {
        source: "iana"
      },
      "audio/pcmu": {
        source: "iana"
      },
      "audio/pcmu-wb": {
        source: "iana"
      },
      "audio/prs.sid": {
        source: "iana"
      },
      "audio/qcelp": {
        source: "iana"
      },
      "audio/raptorfec": {
        source: "iana"
      },
      "audio/red": {
        source: "iana"
      },
      "audio/rtp-enc-aescm128": {
        source: "iana"
      },
      "audio/rtp-midi": {
        source: "iana"
      },
      "audio/rtploopback": {
        source: "iana"
      },
      "audio/rtx": {
        source: "iana"
      },
      "audio/s3m": {
        source: "apache",
        extensions: ["s3m"]
      },
      "audio/scip": {
        source: "iana"
      },
      "audio/silk": {
        source: "apache",
        extensions: ["sil"]
      },
      "audio/smv": {
        source: "iana"
      },
      "audio/smv-qcp": {
        source: "iana"
      },
      "audio/smv0": {
        source: "iana"
      },
      "audio/sofa": {
        source: "iana"
      },
      "audio/sp-midi": {
        source: "iana"
      },
      "audio/speex": {
        source: "iana"
      },
      "audio/t140c": {
        source: "iana"
      },
      "audio/t38": {
        source: "iana"
      },
      "audio/telephone-event": {
        source: "iana"
      },
      "audio/tetra_acelp": {
        source: "iana"
      },
      "audio/tetra_acelp_bb": {
        source: "iana"
      },
      "audio/tone": {
        source: "iana"
      },
      "audio/tsvcis": {
        source: "iana"
      },
      "audio/uemclip": {
        source: "iana"
      },
      "audio/ulpfec": {
        source: "iana"
      },
      "audio/usac": {
        source: "iana"
      },
      "audio/vdvi": {
        source: "iana"
      },
      "audio/vmr-wb": {
        source: "iana"
      },
      "audio/vnd.3gpp.iufp": {
        source: "iana"
      },
      "audio/vnd.4sb": {
        source: "iana"
      },
      "audio/vnd.audiokoz": {
        source: "iana"
      },
      "audio/vnd.celp": {
        source: "iana"
      },
      "audio/vnd.cisco.nse": {
        source: "iana"
      },
      "audio/vnd.cmles.radio-events": {
        source: "iana"
      },
      "audio/vnd.cns.anp1": {
        source: "iana"
      },
      "audio/vnd.cns.inf1": {
        source: "iana"
      },
      "audio/vnd.dece.audio": {
        source: "iana",
        extensions: ["uva", "uvva"]
      },
      "audio/vnd.digital-winds": {
        source: "iana",
        extensions: ["eol"]
      },
      "audio/vnd.dlna.adts": {
        source: "iana"
      },
      "audio/vnd.dolby.heaac.1": {
        source: "iana"
      },
      "audio/vnd.dolby.heaac.2": {
        source: "iana"
      },
      "audio/vnd.dolby.mlp": {
        source: "iana"
      },
      "audio/vnd.dolby.mps": {
        source: "iana"
      },
      "audio/vnd.dolby.pl2": {
        source: "iana"
      },
      "audio/vnd.dolby.pl2x": {
        source: "iana"
      },
      "audio/vnd.dolby.pl2z": {
        source: "iana"
      },
      "audio/vnd.dolby.pulse.1": {
        source: "iana"
      },
      "audio/vnd.dra": {
        source: "iana",
        extensions: ["dra"]
      },
      "audio/vnd.dts": {
        source: "iana",
        extensions: ["dts"]
      },
      "audio/vnd.dts.hd": {
        source: "iana",
        extensions: ["dtshd"]
      },
      "audio/vnd.dts.uhd": {
        source: "iana"
      },
      "audio/vnd.dvb.file": {
        source: "iana"
      },
      "audio/vnd.everad.plj": {
        source: "iana"
      },
      "audio/vnd.hns.audio": {
        source: "iana"
      },
      "audio/vnd.lucent.voice": {
        source: "iana",
        extensions: ["lvp"]
      },
      "audio/vnd.ms-playready.media.pya": {
        source: "iana",
        extensions: ["pya"]
      },
      "audio/vnd.nokia.mobile-xmf": {
        source: "iana"
      },
      "audio/vnd.nortel.vbk": {
        source: "iana"
      },
      "audio/vnd.nuera.ecelp4800": {
        source: "iana",
        extensions: ["ecelp4800"]
      },
      "audio/vnd.nuera.ecelp7470": {
        source: "iana",
        extensions: ["ecelp7470"]
      },
      "audio/vnd.nuera.ecelp9600": {
        source: "iana",
        extensions: ["ecelp9600"]
      },
      "audio/vnd.octel.sbc": {
        source: "iana"
      },
      "audio/vnd.presonus.multitrack": {
        source: "iana"
      },
      "audio/vnd.qcelp": {
        source: "iana"
      },
      "audio/vnd.rhetorex.32kadpcm": {
        source: "iana"
      },
      "audio/vnd.rip": {
        source: "iana",
        extensions: ["rip"]
      },
      "audio/vnd.rn-realaudio": {
        compressible: false
      },
      "audio/vnd.sealedmedia.softseal.mpeg": {
        source: "iana"
      },
      "audio/vnd.vmx.cvsd": {
        source: "iana"
      },
      "audio/vnd.wave": {
        compressible: false
      },
      "audio/vorbis": {
        source: "iana",
        compressible: false
      },
      "audio/vorbis-config": {
        source: "iana"
      },
      "audio/wav": {
        compressible: false,
        extensions: ["wav"]
      },
      "audio/wave": {
        compressible: false,
        extensions: ["wav"]
      },
      "audio/webm": {
        source: "apache",
        compressible: false,
        extensions: ["weba"]
      },
      "audio/x-aac": {
        source: "apache",
        compressible: false,
        extensions: ["aac"]
      },
      "audio/x-aiff": {
        source: "apache",
        extensions: ["aif", "aiff", "aifc"]
      },
      "audio/x-caf": {
        source: "apache",
        compressible: false,
        extensions: ["caf"]
      },
      "audio/x-flac": {
        source: "apache",
        extensions: ["flac"]
      },
      "audio/x-m4a": {
        source: "nginx",
        extensions: ["m4a"]
      },
      "audio/x-matroska": {
        source: "apache",
        extensions: ["mka"]
      },
      "audio/x-mpegurl": {
        source: "apache",
        extensions: ["m3u"]
      },
      "audio/x-ms-wax": {
        source: "apache",
        extensions: ["wax"]
      },
      "audio/x-ms-wma": {
        source: "apache",
        extensions: ["wma"]
      },
      "audio/x-pn-realaudio": {
        source: "apache",
        extensions: ["ram", "ra"]
      },
      "audio/x-pn-realaudio-plugin": {
        source: "apache",
        extensions: ["rmp"]
      },
      "audio/x-realaudio": {
        source: "nginx",
        extensions: ["ra"]
      },
      "audio/x-tta": {
        source: "apache"
      },
      "audio/x-wav": {
        source: "apache",
        extensions: ["wav"]
      },
      "audio/xm": {
        source: "apache",
        extensions: ["xm"]
      },
      "chemical/x-cdx": {
        source: "apache",
        extensions: ["cdx"]
      },
      "chemical/x-cif": {
        source: "apache",
        extensions: ["cif"]
      },
      "chemical/x-cmdf": {
        source: "apache",
        extensions: ["cmdf"]
      },
      "chemical/x-cml": {
        source: "apache",
        extensions: ["cml"]
      },
      "chemical/x-csml": {
        source: "apache",
        extensions: ["csml"]
      },
      "chemical/x-pdb": {
        source: "apache"
      },
      "chemical/x-xyz": {
        source: "apache",
        extensions: ["xyz"]
      },
      "font/collection": {
        source: "iana",
        extensions: ["ttc"]
      },
      "font/otf": {
        source: "iana",
        compressible: true,
        extensions: ["otf"]
      },
      "font/sfnt": {
        source: "iana"
      },
      "font/ttf": {
        source: "iana",
        compressible: true,
        extensions: ["ttf"]
      },
      "font/woff": {
        source: "iana",
        extensions: ["woff"]
      },
      "font/woff2": {
        source: "iana",
        extensions: ["woff2"]
      },
      "image/aces": {
        source: "iana",
        extensions: ["exr"]
      },
      "image/apng": {
        compressible: false,
        extensions: ["apng"]
      },
      "image/avci": {
        source: "iana",
        extensions: ["avci"]
      },
      "image/avcs": {
        source: "iana",
        extensions: ["avcs"]
      },
      "image/avif": {
        source: "iana",
        compressible: false,
        extensions: ["avif"]
      },
      "image/bmp": {
        source: "iana",
        compressible: true,
        extensions: ["bmp"]
      },
      "image/cgm": {
        source: "iana",
        extensions: ["cgm"]
      },
      "image/dicom-rle": {
        source: "iana",
        extensions: ["drle"]
      },
      "image/emf": {
        source: "iana",
        extensions: ["emf"]
      },
      "image/fits": {
        source: "iana",
        extensions: ["fits"]
      },
      "image/g3fax": {
        source: "iana",
        extensions: ["g3"]
      },
      "image/gif": {
        source: "iana",
        compressible: false,
        extensions: ["gif"]
      },
      "image/heic": {
        source: "iana",
        extensions: ["heic"]
      },
      "image/heic-sequence": {
        source: "iana",
        extensions: ["heics"]
      },
      "image/heif": {
        source: "iana",
        extensions: ["heif"]
      },
      "image/heif-sequence": {
        source: "iana",
        extensions: ["heifs"]
      },
      "image/hej2k": {
        source: "iana",
        extensions: ["hej2"]
      },
      "image/hsj2": {
        source: "iana",
        extensions: ["hsj2"]
      },
      "image/ief": {
        source: "iana",
        extensions: ["ief"]
      },
      "image/jls": {
        source: "iana",
        extensions: ["jls"]
      },
      "image/jp2": {
        source: "iana",
        compressible: false,
        extensions: ["jp2", "jpg2"]
      },
      "image/jpeg": {
        source: "iana",
        compressible: false,
        extensions: ["jpeg", "jpg", "jpe"]
      },
      "image/jph": {
        source: "iana",
        extensions: ["jph"]
      },
      "image/jphc": {
        source: "iana",
        extensions: ["jhc"]
      },
      "image/jpm": {
        source: "iana",
        compressible: false,
        extensions: ["jpm"]
      },
      "image/jpx": {
        source: "iana",
        compressible: false,
        extensions: ["jpx", "jpf"]
      },
      "image/jxr": {
        source: "iana",
        extensions: ["jxr"]
      },
      "image/jxra": {
        source: "iana",
        extensions: ["jxra"]
      },
      "image/jxrs": {
        source: "iana",
        extensions: ["jxrs"]
      },
      "image/jxs": {
        source: "iana",
        extensions: ["jxs"]
      },
      "image/jxsc": {
        source: "iana",
        extensions: ["jxsc"]
      },
      "image/jxsi": {
        source: "iana",
        extensions: ["jxsi"]
      },
      "image/jxss": {
        source: "iana",
        extensions: ["jxss"]
      },
      "image/ktx": {
        source: "iana",
        extensions: ["ktx"]
      },
      "image/ktx2": {
        source: "iana",
        extensions: ["ktx2"]
      },
      "image/naplps": {
        source: "iana"
      },
      "image/pjpeg": {
        compressible: false
      },
      "image/png": {
        source: "iana",
        compressible: false,
        extensions: ["png"]
      },
      "image/prs.btif": {
        source: "iana",
        extensions: ["btif"]
      },
      "image/prs.pti": {
        source: "iana",
        extensions: ["pti"]
      },
      "image/pwg-raster": {
        source: "iana"
      },
      "image/sgi": {
        source: "apache",
        extensions: ["sgi"]
      },
      "image/svg+xml": {
        source: "iana",
        compressible: true,
        extensions: ["svg", "svgz"]
      },
      "image/t38": {
        source: "iana",
        extensions: ["t38"]
      },
      "image/tiff": {
        source: "iana",
        compressible: false,
        extensions: ["tif", "tiff"]
      },
      "image/tiff-fx": {
        source: "iana",
        extensions: ["tfx"]
      },
      "image/vnd.adobe.photoshop": {
        source: "iana",
        compressible: true,
        extensions: ["psd"]
      },
      "image/vnd.airzip.accelerator.azv": {
        source: "iana",
        extensions: ["azv"]
      },
      "image/vnd.cns.inf2": {
        source: "iana"
      },
      "image/vnd.dece.graphic": {
        source: "iana",
        extensions: ["uvi", "uvvi", "uvg", "uvvg"]
      },
      "image/vnd.djvu": {
        source: "iana",
        extensions: ["djvu", "djv"]
      },
      "image/vnd.dvb.subtitle": {
        source: "iana",
        extensions: ["sub"]
      },
      "image/vnd.dwg": {
        source: "iana",
        extensions: ["dwg"]
      },
      "image/vnd.dxf": {
        source: "iana",
        extensions: ["dxf"]
      },
      "image/vnd.fastbidsheet": {
        source: "iana",
        extensions: ["fbs"]
      },
      "image/vnd.fpx": {
        source: "iana",
        extensions: ["fpx"]
      },
      "image/vnd.fst": {
        source: "iana",
        extensions: ["fst"]
      },
      "image/vnd.fujixerox.edmics-mmr": {
        source: "iana",
        extensions: ["mmr"]
      },
      "image/vnd.fujixerox.edmics-rlc": {
        source: "iana",
        extensions: ["rlc"]
      },
      "image/vnd.globalgraphics.pgb": {
        source: "iana"
      },
      "image/vnd.microsoft.icon": {
        source: "iana",
        compressible: true,
        extensions: ["ico"]
      },
      "image/vnd.mix": {
        source: "iana"
      },
      "image/vnd.mozilla.apng": {
        source: "iana"
      },
      "image/vnd.ms-dds": {
        compressible: true,
        extensions: ["dds"]
      },
      "image/vnd.ms-modi": {
        source: "iana",
        extensions: ["mdi"]
      },
      "image/vnd.ms-photo": {
        source: "apache",
        extensions: ["wdp"]
      },
      "image/vnd.net-fpx": {
        source: "iana",
        extensions: ["npx"]
      },
      "image/vnd.pco.b16": {
        source: "iana",
        extensions: ["b16"]
      },
      "image/vnd.radiance": {
        source: "iana"
      },
      "image/vnd.sealed.png": {
        source: "iana"
      },
      "image/vnd.sealedmedia.softseal.gif": {
        source: "iana"
      },
      "image/vnd.sealedmedia.softseal.jpg": {
        source: "iana"
      },
      "image/vnd.svf": {
        source: "iana"
      },
      "image/vnd.tencent.tap": {
        source: "iana",
        extensions: ["tap"]
      },
      "image/vnd.valve.source.texture": {
        source: "iana",
        extensions: ["vtf"]
      },
      "image/vnd.wap.wbmp": {
        source: "iana",
        extensions: ["wbmp"]
      },
      "image/vnd.xiff": {
        source: "iana",
        extensions: ["xif"]
      },
      "image/vnd.zbrush.pcx": {
        source: "iana",
        extensions: ["pcx"]
      },
      "image/webp": {
        source: "apache",
        extensions: ["webp"]
      },
      "image/wmf": {
        source: "iana",
        extensions: ["wmf"]
      },
      "image/x-3ds": {
        source: "apache",
        extensions: ["3ds"]
      },
      "image/x-cmu-raster": {
        source: "apache",
        extensions: ["ras"]
      },
      "image/x-cmx": {
        source: "apache",
        extensions: ["cmx"]
      },
      "image/x-freehand": {
        source: "apache",
        extensions: ["fh", "fhc", "fh4", "fh5", "fh7"]
      },
      "image/x-icon": {
        source: "apache",
        compressible: true,
        extensions: ["ico"]
      },
      "image/x-jng": {
        source: "nginx",
        extensions: ["jng"]
      },
      "image/x-mrsid-image": {
        source: "apache",
        extensions: ["sid"]
      },
      "image/x-ms-bmp": {
        source: "nginx",
        compressible: true,
        extensions: ["bmp"]
      },
      "image/x-pcx": {
        source: "apache",
        extensions: ["pcx"]
      },
      "image/x-pict": {
        source: "apache",
        extensions: ["pic", "pct"]
      },
      "image/x-portable-anymap": {
        source: "apache",
        extensions: ["pnm"]
      },
      "image/x-portable-bitmap": {
        source: "apache",
        extensions: ["pbm"]
      },
      "image/x-portable-graymap": {
        source: "apache",
        extensions: ["pgm"]
      },
      "image/x-portable-pixmap": {
        source: "apache",
        extensions: ["ppm"]
      },
      "image/x-rgb": {
        source: "apache",
        extensions: ["rgb"]
      },
      "image/x-tga": {
        source: "apache",
        extensions: ["tga"]
      },
      "image/x-xbitmap": {
        source: "apache",
        extensions: ["xbm"]
      },
      "image/x-xcf": {
        compressible: false
      },
      "image/x-xpixmap": {
        source: "apache",
        extensions: ["xpm"]
      },
      "image/x-xwindowdump": {
        source: "apache",
        extensions: ["xwd"]
      },
      "message/cpim": {
        source: "iana"
      },
      "message/delivery-status": {
        source: "iana"
      },
      "message/disposition-notification": {
        source: "iana",
        extensions: [
          "disposition-notification"
        ]
      },
      "message/external-body": {
        source: "iana"
      },
      "message/feedback-report": {
        source: "iana"
      },
      "message/global": {
        source: "iana",
        extensions: ["u8msg"]
      },
      "message/global-delivery-status": {
        source: "iana",
        extensions: ["u8dsn"]
      },
      "message/global-disposition-notification": {
        source: "iana",
        extensions: ["u8mdn"]
      },
      "message/global-headers": {
        source: "iana",
        extensions: ["u8hdr"]
      },
      "message/http": {
        source: "iana",
        compressible: false
      },
      "message/imdn+xml": {
        source: "iana",
        compressible: true
      },
      "message/news": {
        source: "iana"
      },
      "message/partial": {
        source: "iana",
        compressible: false
      },
      "message/rfc822": {
        source: "iana",
        compressible: true,
        extensions: ["eml", "mime"]
      },
      "message/s-http": {
        source: "iana"
      },
      "message/sip": {
        source: "iana"
      },
      "message/sipfrag": {
        source: "iana"
      },
      "message/tracking-status": {
        source: "iana"
      },
      "message/vnd.si.simp": {
        source: "iana"
      },
      "message/vnd.wfa.wsc": {
        source: "iana",
        extensions: ["wsc"]
      },
      "model/3mf": {
        source: "iana",
        extensions: ["3mf"]
      },
      "model/e57": {
        source: "iana"
      },
      "model/gltf+json": {
        source: "iana",
        compressible: true,
        extensions: ["gltf"]
      },
      "model/gltf-binary": {
        source: "iana",
        compressible: true,
        extensions: ["glb"]
      },
      "model/iges": {
        source: "iana",
        compressible: false,
        extensions: ["igs", "iges"]
      },
      "model/mesh": {
        source: "iana",
        compressible: false,
        extensions: ["msh", "mesh", "silo"]
      },
      "model/mtl": {
        source: "iana",
        extensions: ["mtl"]
      },
      "model/obj": {
        source: "iana",
        extensions: ["obj"]
      },
      "model/step": {
        source: "iana"
      },
      "model/step+xml": {
        source: "iana",
        compressible: true,
        extensions: ["stpx"]
      },
      "model/step+zip": {
        source: "iana",
        compressible: false,
        extensions: ["stpz"]
      },
      "model/step-xml+zip": {
        source: "iana",
        compressible: false,
        extensions: ["stpxz"]
      },
      "model/stl": {
        source: "iana",
        extensions: ["stl"]
      },
      "model/vnd.collada+xml": {
        source: "iana",
        compressible: true,
        extensions: ["dae"]
      },
      "model/vnd.dwf": {
        source: "iana",
        extensions: ["dwf"]
      },
      "model/vnd.flatland.3dml": {
        source: "iana"
      },
      "model/vnd.gdl": {
        source: "iana",
        extensions: ["gdl"]
      },
      "model/vnd.gs-gdl": {
        source: "apache"
      },
      "model/vnd.gs.gdl": {
        source: "iana"
      },
      "model/vnd.gtw": {
        source: "iana",
        extensions: ["gtw"]
      },
      "model/vnd.moml+xml": {
        source: "iana",
        compressible: true
      },
      "model/vnd.mts": {
        source: "iana",
        extensions: ["mts"]
      },
      "model/vnd.opengex": {
        source: "iana",
        extensions: ["ogex"]
      },
      "model/vnd.parasolid.transmit.binary": {
        source: "iana",
        extensions: ["x_b"]
      },
      "model/vnd.parasolid.transmit.text": {
        source: "iana",
        extensions: ["x_t"]
      },
      "model/vnd.pytha.pyox": {
        source: "iana"
      },
      "model/vnd.rosette.annotated-data-model": {
        source: "iana"
      },
      "model/vnd.sap.vds": {
        source: "iana",
        extensions: ["vds"]
      },
      "model/vnd.usdz+zip": {
        source: "iana",
        compressible: false,
        extensions: ["usdz"]
      },
      "model/vnd.valve.source.compiled-map": {
        source: "iana",
        extensions: ["bsp"]
      },
      "model/vnd.vtu": {
        source: "iana",
        extensions: ["vtu"]
      },
      "model/vrml": {
        source: "iana",
        compressible: false,
        extensions: ["wrl", "vrml"]
      },
      "model/x3d+binary": {
        source: "apache",
        compressible: false,
        extensions: ["x3db", "x3dbz"]
      },
      "model/x3d+fastinfoset": {
        source: "iana",
        extensions: ["x3db"]
      },
      "model/x3d+vrml": {
        source: "apache",
        compressible: false,
        extensions: ["x3dv", "x3dvz"]
      },
      "model/x3d+xml": {
        source: "iana",
        compressible: true,
        extensions: ["x3d", "x3dz"]
      },
      "model/x3d-vrml": {
        source: "iana",
        extensions: ["x3dv"]
      },
      "multipart/alternative": {
        source: "iana",
        compressible: false
      },
      "multipart/appledouble": {
        source: "iana"
      },
      "multipart/byteranges": {
        source: "iana"
      },
      "multipart/digest": {
        source: "iana"
      },
      "multipart/encrypted": {
        source: "iana",
        compressible: false
      },
      "multipart/form-data": {
        source: "iana",
        compressible: false
      },
      "multipart/header-set": {
        source: "iana"
      },
      "multipart/mixed": {
        source: "iana"
      },
      "multipart/multilingual": {
        source: "iana"
      },
      "multipart/parallel": {
        source: "iana"
      },
      "multipart/related": {
        source: "iana",
        compressible: false
      },
      "multipart/report": {
        source: "iana"
      },
      "multipart/signed": {
        source: "iana",
        compressible: false
      },
      "multipart/vnd.bint.med-plus": {
        source: "iana"
      },
      "multipart/voice-message": {
        source: "iana"
      },
      "multipart/x-mixed-replace": {
        source: "iana"
      },
      "text/1d-interleaved-parityfec": {
        source: "iana"
      },
      "text/cache-manifest": {
        source: "iana",
        compressible: true,
        extensions: ["appcache", "manifest"]
      },
      "text/calendar": {
        source: "iana",
        extensions: ["ics", "ifb"]
      },
      "text/calender": {
        compressible: true
      },
      "text/cmd": {
        compressible: true
      },
      "text/coffeescript": {
        extensions: ["coffee", "litcoffee"]
      },
      "text/cql": {
        source: "iana"
      },
      "text/cql-expression": {
        source: "iana"
      },
      "text/cql-identifier": {
        source: "iana"
      },
      "text/css": {
        source: "iana",
        charset: "UTF-8",
        compressible: true,
        extensions: ["css"]
      },
      "text/csv": {
        source: "iana",
        compressible: true,
        extensions: ["csv"]
      },
      "text/csv-schema": {
        source: "iana"
      },
      "text/directory": {
        source: "iana"
      },
      "text/dns": {
        source: "iana"
      },
      "text/ecmascript": {
        source: "iana"
      },
      "text/encaprtp": {
        source: "iana"
      },
      "text/enriched": {
        source: "iana"
      },
      "text/fhirpath": {
        source: "iana"
      },
      "text/flexfec": {
        source: "iana"
      },
      "text/fwdred": {
        source: "iana"
      },
      "text/gff3": {
        source: "iana"
      },
      "text/grammar-ref-list": {
        source: "iana"
      },
      "text/html": {
        source: "iana",
        compressible: true,
        extensions: ["html", "htm", "shtml"]
      },
      "text/jade": {
        extensions: ["jade"]
      },
      "text/javascript": {
        source: "iana",
        compressible: true
      },
      "text/jcr-cnd": {
        source: "iana"
      },
      "text/jsx": {
        compressible: true,
        extensions: ["jsx"]
      },
      "text/less": {
        compressible: true,
        extensions: ["less"]
      },
      "text/markdown": {
        source: "iana",
        compressible: true,
        extensions: ["markdown", "md"]
      },
      "text/mathml": {
        source: "nginx",
        extensions: ["mml"]
      },
      "text/mdx": {
        compressible: true,
        extensions: ["mdx"]
      },
      "text/mizar": {
        source: "iana"
      },
      "text/n3": {
        source: "iana",
        charset: "UTF-8",
        compressible: true,
        extensions: ["n3"]
      },
      "text/parameters": {
        source: "iana",
        charset: "UTF-8"
      },
      "text/parityfec": {
        source: "iana"
      },
      "text/plain": {
        source: "iana",
        compressible: true,
        extensions: ["txt", "text", "conf", "def", "list", "log", "in", "ini"]
      },
      "text/provenance-notation": {
        source: "iana",
        charset: "UTF-8"
      },
      "text/prs.fallenstein.rst": {
        source: "iana"
      },
      "text/prs.lines.tag": {
        source: "iana",
        extensions: ["dsc"]
      },
      "text/prs.prop.logic": {
        source: "iana"
      },
      "text/raptorfec": {
        source: "iana"
      },
      "text/red": {
        source: "iana"
      },
      "text/rfc822-headers": {
        source: "iana"
      },
      "text/richtext": {
        source: "iana",
        compressible: true,
        extensions: ["rtx"]
      },
      "text/rtf": {
        source: "iana",
        compressible: true,
        extensions: ["rtf"]
      },
      "text/rtp-enc-aescm128": {
        source: "iana"
      },
      "text/rtploopback": {
        source: "iana"
      },
      "text/rtx": {
        source: "iana"
      },
      "text/sgml": {
        source: "iana",
        extensions: ["sgml", "sgm"]
      },
      "text/shaclc": {
        source: "iana"
      },
      "text/shex": {
        source: "iana",
        extensions: ["shex"]
      },
      "text/slim": {
        extensions: ["slim", "slm"]
      },
      "text/spdx": {
        source: "iana",
        extensions: ["spdx"]
      },
      "text/strings": {
        source: "iana"
      },
      "text/stylus": {
        extensions: ["stylus", "styl"]
      },
      "text/t140": {
        source: "iana"
      },
      "text/tab-separated-values": {
        source: "iana",
        compressible: true,
        extensions: ["tsv"]
      },
      "text/troff": {
        source: "iana",
        extensions: ["t", "tr", "roff", "man", "me", "ms"]
      },
      "text/turtle": {
        source: "iana",
        charset: "UTF-8",
        extensions: ["ttl"]
      },
      "text/ulpfec": {
        source: "iana"
      },
      "text/uri-list": {
        source: "iana",
        compressible: true,
        extensions: ["uri", "uris", "urls"]
      },
      "text/vcard": {
        source: "iana",
        compressible: true,
        extensions: ["vcard"]
      },
      "text/vnd.a": {
        source: "iana"
      },
      "text/vnd.abc": {
        source: "iana"
      },
      "text/vnd.ascii-art": {
        source: "iana"
      },
      "text/vnd.curl": {
        source: "iana",
        extensions: ["curl"]
      },
      "text/vnd.curl.dcurl": {
        source: "apache",
        extensions: ["dcurl"]
      },
      "text/vnd.curl.mcurl": {
        source: "apache",
        extensions: ["mcurl"]
      },
      "text/vnd.curl.scurl": {
        source: "apache",
        extensions: ["scurl"]
      },
      "text/vnd.debian.copyright": {
        source: "iana",
        charset: "UTF-8"
      },
      "text/vnd.dmclientscript": {
        source: "iana"
      },
      "text/vnd.dvb.subtitle": {
        source: "iana",
        extensions: ["sub"]
      },
      "text/vnd.esmertec.theme-descriptor": {
        source: "iana",
        charset: "UTF-8"
      },
      "text/vnd.familysearch.gedcom": {
        source: "iana",
        extensions: ["ged"]
      },
      "text/vnd.ficlab.flt": {
        source: "iana"
      },
      "text/vnd.fly": {
        source: "iana",
        extensions: ["fly"]
      },
      "text/vnd.fmi.flexstor": {
        source: "iana",
        extensions: ["flx"]
      },
      "text/vnd.gml": {
        source: "iana"
      },
      "text/vnd.graphviz": {
        source: "iana",
        extensions: ["gv"]
      },
      "text/vnd.hans": {
        source: "iana"
      },
      "text/vnd.hgl": {
        source: "iana"
      },
      "text/vnd.in3d.3dml": {
        source: "iana",
        extensions: ["3dml"]
      },
      "text/vnd.in3d.spot": {
        source: "iana",
        extensions: ["spot"]
      },
      "text/vnd.iptc.newsml": {
        source: "iana"
      },
      "text/vnd.iptc.nitf": {
        source: "iana"
      },
      "text/vnd.latex-z": {
        source: "iana"
      },
      "text/vnd.motorola.reflex": {
        source: "iana"
      },
      "text/vnd.ms-mediapackage": {
        source: "iana"
      },
      "text/vnd.net2phone.commcenter.command": {
        source: "iana"
      },
      "text/vnd.radisys.msml-basic-layout": {
        source: "iana"
      },
      "text/vnd.senx.warpscript": {
        source: "iana"
      },
      "text/vnd.si.uricatalogue": {
        source: "iana"
      },
      "text/vnd.sosi": {
        source: "iana"
      },
      "text/vnd.sun.j2me.app-descriptor": {
        source: "iana",
        charset: "UTF-8",
        extensions: ["jad"]
      },
      "text/vnd.trolltech.linguist": {
        source: "iana",
        charset: "UTF-8"
      },
      "text/vnd.wap.si": {
        source: "iana"
      },
      "text/vnd.wap.sl": {
        source: "iana"
      },
      "text/vnd.wap.wml": {
        source: "iana",
        extensions: ["wml"]
      },
      "text/vnd.wap.wmlscript": {
        source: "iana",
        extensions: ["wmls"]
      },
      "text/vtt": {
        source: "iana",
        charset: "UTF-8",
        compressible: true,
        extensions: ["vtt"]
      },
      "text/x-asm": {
        source: "apache",
        extensions: ["s", "asm"]
      },
      "text/x-c": {
        source: "apache",
        extensions: ["c", "cc", "cxx", "cpp", "h", "hh", "dic"]
      },
      "text/x-component": {
        source: "nginx",
        extensions: ["htc"]
      },
      "text/x-fortran": {
        source: "apache",
        extensions: ["f", "for", "f77", "f90"]
      },
      "text/x-gwt-rpc": {
        compressible: true
      },
      "text/x-handlebars-template": {
        extensions: ["hbs"]
      },
      "text/x-java-source": {
        source: "apache",
        extensions: ["java"]
      },
      "text/x-jquery-tmpl": {
        compressible: true
      },
      "text/x-lua": {
        extensions: ["lua"]
      },
      "text/x-markdown": {
        compressible: true,
        extensions: ["mkd"]
      },
      "text/x-nfo": {
        source: "apache",
        extensions: ["nfo"]
      },
      "text/x-opml": {
        source: "apache",
        extensions: ["opml"]
      },
      "text/x-org": {
        compressible: true,
        extensions: ["org"]
      },
      "text/x-pascal": {
        source: "apache",
        extensions: ["p", "pas"]
      },
      "text/x-processing": {
        compressible: true,
        extensions: ["pde"]
      },
      "text/x-sass": {
        extensions: ["sass"]
      },
      "text/x-scss": {
        extensions: ["scss"]
      },
      "text/x-setext": {
        source: "apache",
        extensions: ["etx"]
      },
      "text/x-sfv": {
        source: "apache",
        extensions: ["sfv"]
      },
      "text/x-suse-ymp": {
        compressible: true,
        extensions: ["ymp"]
      },
      "text/x-uuencode": {
        source: "apache",
        extensions: ["uu"]
      },
      "text/x-vcalendar": {
        source: "apache",
        extensions: ["vcs"]
      },
      "text/x-vcard": {
        source: "apache",
        extensions: ["vcf"]
      },
      "text/xml": {
        source: "iana",
        compressible: true,
        extensions: ["xml"]
      },
      "text/xml-external-parsed-entity": {
        source: "iana"
      },
      "text/yaml": {
        compressible: true,
        extensions: ["yaml", "yml"]
      },
      "video/1d-interleaved-parityfec": {
        source: "iana"
      },
      "video/3gpp": {
        source: "iana",
        extensions: ["3gp", "3gpp"]
      },
      "video/3gpp-tt": {
        source: "iana"
      },
      "video/3gpp2": {
        source: "iana",
        extensions: ["3g2"]
      },
      "video/av1": {
        source: "iana"
      },
      "video/bmpeg": {
        source: "iana"
      },
      "video/bt656": {
        source: "iana"
      },
      "video/celb": {
        source: "iana"
      },
      "video/dv": {
        source: "iana"
      },
      "video/encaprtp": {
        source: "iana"
      },
      "video/ffv1": {
        source: "iana"
      },
      "video/flexfec": {
        source: "iana"
      },
      "video/h261": {
        source: "iana",
        extensions: ["h261"]
      },
      "video/h263": {
        source: "iana",
        extensions: ["h263"]
      },
      "video/h263-1998": {
        source: "iana"
      },
      "video/h263-2000": {
        source: "iana"
      },
      "video/h264": {
        source: "iana",
        extensions: ["h264"]
      },
      "video/h264-rcdo": {
        source: "iana"
      },
      "video/h264-svc": {
        source: "iana"
      },
      "video/h265": {
        source: "iana"
      },
      "video/iso.segment": {
        source: "iana",
        extensions: ["m4s"]
      },
      "video/jpeg": {
        source: "iana",
        extensions: ["jpgv"]
      },
      "video/jpeg2000": {
        source: "iana"
      },
      "video/jpm": {
        source: "apache",
        extensions: ["jpm", "jpgm"]
      },
      "video/jxsv": {
        source: "iana"
      },
      "video/mj2": {
        source: "iana",
        extensions: ["mj2", "mjp2"]
      },
      "video/mp1s": {
        source: "iana"
      },
      "video/mp2p": {
        source: "iana"
      },
      "video/mp2t": {
        source: "iana",
        extensions: ["ts"]
      },
      "video/mp4": {
        source: "iana",
        compressible: false,
        extensions: ["mp4", "mp4v", "mpg4"]
      },
      "video/mp4v-es": {
        source: "iana"
      },
      "video/mpeg": {
        source: "iana",
        compressible: false,
        extensions: ["mpeg", "mpg", "mpe", "m1v", "m2v"]
      },
      "video/mpeg4-generic": {
        source: "iana"
      },
      "video/mpv": {
        source: "iana"
      },
      "video/nv": {
        source: "iana"
      },
      "video/ogg": {
        source: "iana",
        compressible: false,
        extensions: ["ogv"]
      },
      "video/parityfec": {
        source: "iana"
      },
      "video/pointer": {
        source: "iana"
      },
      "video/quicktime": {
        source: "iana",
        compressible: false,
        extensions: ["qt", "mov"]
      },
      "video/raptorfec": {
        source: "iana"
      },
      "video/raw": {
        source: "iana"
      },
      "video/rtp-enc-aescm128": {
        source: "iana"
      },
      "video/rtploopback": {
        source: "iana"
      },
      "video/rtx": {
        source: "iana"
      },
      "video/scip": {
        source: "iana"
      },
      "video/smpte291": {
        source: "iana"
      },
      "video/smpte292m": {
        source: "iana"
      },
      "video/ulpfec": {
        source: "iana"
      },
      "video/vc1": {
        source: "iana"
      },
      "video/vc2": {
        source: "iana"
      },
      "video/vnd.cctv": {
        source: "iana"
      },
      "video/vnd.dece.hd": {
        source: "iana",
        extensions: ["uvh", "uvvh"]
      },
      "video/vnd.dece.mobile": {
        source: "iana",
        extensions: ["uvm", "uvvm"]
      },
      "video/vnd.dece.mp4": {
        source: "iana"
      },
      "video/vnd.dece.pd": {
        source: "iana",
        extensions: ["uvp", "uvvp"]
      },
      "video/vnd.dece.sd": {
        source: "iana",
        extensions: ["uvs", "uvvs"]
      },
      "video/vnd.dece.video": {
        source: "iana",
        extensions: ["uvv", "uvvv"]
      },
      "video/vnd.directv.mpeg": {
        source: "iana"
      },
      "video/vnd.directv.mpeg-tts": {
        source: "iana"
      },
      "video/vnd.dlna.mpeg-tts": {
        source: "iana"
      },
      "video/vnd.dvb.file": {
        source: "iana",
        extensions: ["dvb"]
      },
      "video/vnd.fvt": {
        source: "iana",
        extensions: ["fvt"]
      },
      "video/vnd.hns.video": {
        source: "iana"
      },
      "video/vnd.iptvforum.1dparityfec-1010": {
        source: "iana"
      },
      "video/vnd.iptvforum.1dparityfec-2005": {
        source: "iana"
      },
      "video/vnd.iptvforum.2dparityfec-1010": {
        source: "iana"
      },
      "video/vnd.iptvforum.2dparityfec-2005": {
        source: "iana"
      },
      "video/vnd.iptvforum.ttsavc": {
        source: "iana"
      },
      "video/vnd.iptvforum.ttsmpeg2": {
        source: "iana"
      },
      "video/vnd.motorola.video": {
        source: "iana"
      },
      "video/vnd.motorola.videop": {
        source: "iana"
      },
      "video/vnd.mpegurl": {
        source: "iana",
        extensions: ["mxu", "m4u"]
      },
      "video/vnd.ms-playready.media.pyv": {
        source: "iana",
        extensions: ["pyv"]
      },
      "video/vnd.nokia.interleaved-multimedia": {
        source: "iana"
      },
      "video/vnd.nokia.mp4vr": {
        source: "iana"
      },
      "video/vnd.nokia.videovoip": {
        source: "iana"
      },
      "video/vnd.objectvideo": {
        source: "iana"
      },
      "video/vnd.radgamettools.bink": {
        source: "iana"
      },
      "video/vnd.radgamettools.smacker": {
        source: "iana"
      },
      "video/vnd.sealed.mpeg1": {
        source: "iana"
      },
      "video/vnd.sealed.mpeg4": {
        source: "iana"
      },
      "video/vnd.sealed.swf": {
        source: "iana"
      },
      "video/vnd.sealedmedia.softseal.mov": {
        source: "iana"
      },
      "video/vnd.uvvu.mp4": {
        source: "iana",
        extensions: ["uvu", "uvvu"]
      },
      "video/vnd.vivo": {
        source: "iana",
        extensions: ["viv"]
      },
      "video/vnd.youtube.yt": {
        source: "iana"
      },
      "video/vp8": {
        source: "iana"
      },
      "video/vp9": {
        source: "iana"
      },
      "video/webm": {
        source: "apache",
        compressible: false,
        extensions: ["webm"]
      },
      "video/x-f4v": {
        source: "apache",
        extensions: ["f4v"]
      },
      "video/x-fli": {
        source: "apache",
        extensions: ["fli"]
      },
      "video/x-flv": {
        source: "apache",
        compressible: false,
        extensions: ["flv"]
      },
      "video/x-m4v": {
        source: "apache",
        extensions: ["m4v"]
      },
      "video/x-matroska": {
        source: "apache",
        compressible: false,
        extensions: ["mkv", "mk3d", "mks"]
      },
      "video/x-mng": {
        source: "apache",
        extensions: ["mng"]
      },
      "video/x-ms-asf": {
        source: "apache",
        extensions: ["asf", "asx"]
      },
      "video/x-ms-vob": {
        source: "apache",
        extensions: ["vob"]
      },
      "video/x-ms-wm": {
        source: "apache",
        extensions: ["wm"]
      },
      "video/x-ms-wmv": {
        source: "apache",
        compressible: false,
        extensions: ["wmv"]
      },
      "video/x-ms-wmx": {
        source: "apache",
        extensions: ["wmx"]
      },
      "video/x-ms-wvx": {
        source: "apache",
        extensions: ["wvx"]
      },
      "video/x-msvideo": {
        source: "apache",
        extensions: ["avi"]
      },
      "video/x-sgi-movie": {
        source: "apache",
        extensions: ["movie"]
      },
      "video/x-smv": {
        source: "apache",
        extensions: ["smv"]
      },
      "x-conference/x-cooltalk": {
        source: "apache",
        extensions: ["ice"]
      },
      "x-shader/x-fragment": {
        compressible: true
      },
      "x-shader/x-vertex": {
        compressible: true
      }
    };
  }
});

// ../../node_modules/.pnpm/mime-db@1.52.0/node_modules/mime-db/index.js
var require_mime_db = __commonJS({
  "../../node_modules/.pnpm/mime-db@1.52.0/node_modules/mime-db/index.js"(exports, module) {
    module.exports = require_db();
  }
});

// ../../node_modules/.pnpm/mime-types@2.1.35/node_modules/mime-types/index.js
var require_mime_types = __commonJS({
  "../../node_modules/.pnpm/mime-types@2.1.35/node_modules/mime-types/index.js"(exports) {
    "use strict";
    var db2 = require_mime_db();
    var extname = __require("path").extname;
    var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/;
    var TEXT_TYPE_REGEXP = /^text\//i;
    exports.charset = charset;
    exports.charsets = { lookup: charset };
    exports.contentType = contentType;
    exports.extension = extension;
    exports.extensions = /* @__PURE__ */ Object.create(null);
    exports.lookup = lookup;
    exports.types = /* @__PURE__ */ Object.create(null);
    populateMaps(exports.extensions, exports.types);
    function charset(type) {
      if (!type || typeof type !== "string") {
        return false;
      }
      var match = EXTRACT_TYPE_REGEXP.exec(type);
      var mime = match && db2[match[1].toLowerCase()];
      if (mime && mime.charset) {
        return mime.charset;
      }
      if (match && TEXT_TYPE_REGEXP.test(match[1])) {
        return "UTF-8";
      }
      return false;
    }
    function contentType(str) {
      if (!str || typeof str !== "string") {
        return false;
      }
      var mime = str.indexOf("/") === -1 ? exports.lookup(str) : str;
      if (!mime) {
        return false;
      }
      if (mime.indexOf("charset") === -1) {
        var charset2 = exports.charset(mime);
        if (charset2) mime += "; charset=" + charset2.toLowerCase();
      }
      return mime;
    }
    function extension(type) {
      if (!type || typeof type !== "string") {
        return false;
      }
      var match = EXTRACT_TYPE_REGEXP.exec(type);
      var exts = match && exports.extensions[match[1].toLowerCase()];
      if (!exts || !exts.length) {
        return false;
      }
      return exts[0];
    }
    function lookup(path4) {
      if (!path4 || typeof path4 !== "string") {
        return false;
      }
      var extension2 = extname("x." + path4).toLowerCase().substr(1);
      if (!extension2) {
        return false;
      }
      return exports.types[extension2] || false;
    }
    function populateMaps(extensions, types3) {
      var preference = ["nginx", "apache", void 0, "iana"];
      Object.keys(db2).forEach(function forEachMimeType(type) {
        var mime = db2[type];
        var exts = mime.extensions;
        if (!exts || !exts.length) {
          return;
        }
        extensions[type] = exts;
        for (var i = 0; i < exts.length; i++) {
          var extension2 = exts[i];
          if (types3[extension2]) {
            var from = preference.indexOf(db2[types3[extension2]].source);
            var to = preference.indexOf(mime.source);
            if (types3[extension2] !== "application/octet-stream" && (from > to || from === to && types3[extension2].substr(0, 12) === "application/")) {
              continue;
            }
          }
          types3[extension2] = type;
        }
      });
    }
  }
});

// ../../node_modules/.pnpm/type-is@1.6.18/node_modules/type-is/index.js
var require_type_is = __commonJS({
  "../../node_modules/.pnpm/type-is@1.6.18/node_modules/type-is/index.js"(exports, module) {
    "use strict";
    var typer = require_media_typer();
    var mime = require_mime_types();
    module.exports = typeofrequest;
    module.exports.is = typeis;
    module.exports.hasBody = hasbody;
    module.exports.normalize = normalize;
    module.exports.match = mimeMatch;
    function typeis(value, types_) {
      var i;
      var types3 = types_;
      var val = tryNormalizeType(value);
      if (!val) {
        return false;
      }
      if (types3 && !Array.isArray(types3)) {
        types3 = new Array(arguments.length - 1);
        for (i = 0; i < types3.length; i++) {
          types3[i] = arguments[i + 1];
        }
      }
      if (!types3 || !types3.length) {
        return val;
      }
      var type;
      for (i = 0; i < types3.length; i++) {
        if (mimeMatch(normalize(type = types3[i]), val)) {
          return type[0] === "+" || type.indexOf("*") !== -1 ? val : type;
        }
      }
      return false;
    }
    function hasbody(req) {
      return req.headers["transfer-encoding"] !== void 0 || !isNaN(req.headers["content-length"]);
    }
    function typeofrequest(req, types_) {
      var types3 = types_;
      if (!hasbody(req)) {
        return null;
      }
      if (arguments.length > 2) {
        types3 = new Array(arguments.length - 1);
        for (var i = 0; i < types3.length; i++) {
          types3[i] = arguments[i + 1];
        }
      }
      var value = req.headers["content-type"];
      return typeis(value, types3);
    }
    function normalize(type) {
      if (typeof type !== "string") {
        return false;
      }
      switch (type) {
        case "urlencoded":
          return "application/x-www-form-urlencoded";
        case "multipart":
          return "multipart/*";
      }
      if (type[0] === "+") {
        return "*/*" + type;
      }
      return type.indexOf("/") === -1 ? mime.lookup(type) : type;
    }
    function mimeMatch(expected, actual) {
      if (expected === false) {
        return false;
      }
      var actualParts = actual.split("/");
      var expectedParts = expected.split("/");
      if (actualParts.length !== 2 || expectedParts.length !== 2) {
        return false;
      }
      if (expectedParts[0] !== "*" && expectedParts[0] !== actualParts[0]) {
        return false;
      }
      if (expectedParts[1].substr(0, 2) === "*+") {
        return expectedParts[1].length <= actualParts[1].length + 1 && expectedParts[1].substr(1) === actualParts[1].substr(1 - expectedParts[1].length);
      }
      if (expectedParts[1] !== "*" && expectedParts[1] !== actualParts[1]) {
        return false;
      }
      return true;
    }
    function normalizeType(value) {
      var type = typer.parse(value);
      type.parameters = void 0;
      return typer.format(type);
    }
    function tryNormalizeType(value) {
      if (!value) {
        return null;
      }
      try {
        return normalizeType(value);
      } catch (err) {
        return null;
      }
    }
  }
});

// ../../node_modules/.pnpm/body-parser@1.20.3/node_modules/body-parser/lib/types/json.js
var require_json = __commonJS({
  "../../node_modules/.pnpm/body-parser@1.20.3/node_modules/body-parser/lib/types/json.js"(exports, module) {
    "use strict";
    var bytes = require_bytes();
    var contentType = require_content_type();
    var createError = require_http_errors();
    var debug = require_src()("body-parser:json");
    var read = require_read();
    var typeis = require_type_is();
    module.exports = json3;
    var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*([^\x20\x09\x0a\x0d])/;
    var JSON_SYNTAX_CHAR = "#";
    var JSON_SYNTAX_REGEXP = /#+/g;
    function json3(options) {
      var opts = options || {};
      var limit = typeof opts.limit !== "number" ? bytes.parse(opts.limit || "100kb") : opts.limit;
      var inflate = opts.inflate !== false;
      var reviver = opts.reviver;
      var strict = opts.strict !== false;
      var type = opts.type || "application/json";
      var verify = opts.verify || false;
      if (verify !== false && typeof verify !== "function") {
        throw new TypeError("option verify must be function");
      }
      var shouldParse = typeof type !== "function" ? typeChecker(type) : type;
      function parse3(body) {
        if (body.length === 0) {
          return {};
        }
        if (strict) {
          var first = firstchar(body);
          if (first !== "{" && first !== "[") {
            debug("strict violation");
            throw createStrictSyntaxError(body, first);
          }
        }
        try {
          debug("parse json");
          return JSON.parse(body, reviver);
        } catch (e) {
          throw normalizeJsonSyntaxError(e, {
            message: e.message,
            stack: e.stack
          });
        }
      }
      return function jsonParser(req, res, next) {
        if (req._body) {
          debug("body already parsed");
          next();
          return;
        }
        req.body = req.body || {};
        if (!typeis.hasBody(req)) {
          debug("skip empty body");
          next();
          return;
        }
        debug("content-type %j", req.headers["content-type"]);
        if (!shouldParse(req)) {
          debug("skip parsing");
          next();
          return;
        }
        var charset = getCharset(req) || "utf-8";
        if (charset.slice(0, 4) !== "utf-") {
          debug("invalid charset");
          next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', {
            charset,
            type: "charset.unsupported"
          }));
          return;
        }
        read(req, res, next, parse3, debug, {
          encoding: charset,
          inflate,
          limit,
          verify
        });
      };
    }
    function createStrictSyntaxError(str, char2) {
      var index2 = str.indexOf(char2);
      var partial2 = "";
      if (index2 !== -1) {
        partial2 = str.substring(0, index2) + JSON_SYNTAX_CHAR;
        for (var i = index2 + 1; i < str.length; i++) {
          partial2 += JSON_SYNTAX_CHAR;
        }
      }
      try {
        JSON.parse(partial2);
        throw new SyntaxError("strict violation");
      } catch (e) {
        return normalizeJsonSyntaxError(e, {
          message: e.message.replace(JSON_SYNTAX_REGEXP, function(placeholder) {
            return str.substring(index2, index2 + placeholder.length);
          }),
          stack: e.stack
        });
      }
    }
    function firstchar(str) {
      var match = FIRST_CHAR_REGEXP.exec(str);
      return match ? match[1] : void 0;
    }
    function getCharset(req) {
      try {
        return (contentType.parse(req).parameters.charset || "").toLowerCase();
      } catch (e) {
        return void 0;
      }
    }
    function normalizeJsonSyntaxError(error40, obj) {
      var keys = Object.getOwnPropertyNames(error40);
      for (var i = 0; i < keys.length; i++) {
        var key = keys[i];
        if (key !== "stack" && key !== "message") {
          delete error40[key];
        }
      }
      error40.stack = obj.stack.replace(error40.message, obj.message);
      error40.message = obj.message;
      return error40;
    }
    function typeChecker(type) {
      return function checkType(req) {
        return Boolean(typeis(req, type));
      };
    }
  }
});

// ../../node_modules/.pnpm/body-parser@1.20.3/node_modules/body-parser/lib/types/raw.js
var require_raw = __commonJS({
  "../../node_modules/.pnpm/body-parser@1.20.3/node_modules/body-parser/lib/types/raw.js"(exports, module) {
    "use strict";
    var bytes = require_bytes();
    var debug = require_src()("body-parser:raw");
    var read = require_read();
    var typeis = require_type_is();
    module.exports = raw;
    function raw(options) {
      var opts = options || {};
      var inflate = opts.inflate !== false;
      var limit = typeof opts.limit !== "number" ? bytes.parse(opts.limit || "100kb") : opts.limit;
      var type = opts.type || "application/octet-stream";
      var verify = opts.verify || false;
      if (verify !== false && typeof verify !== "function") {
        throw new TypeError("option verify must be function");
      }
      var shouldParse = typeof type !== "function" ? typeChecker(type) : type;
      function parse3(buf) {
        return buf;
      }
      return function rawParser(req, res, next) {
        if (req._body) {
          debug("body already parsed");
          next();
          return;
        }
        req.body = req.body || {};
        if (!typeis.hasBody(req)) {
          debug("skip empty body");
          next();
          return;
        }
        debug("content-type %j", req.headers["content-type"]);
        if (!shouldParse(req)) {
          debug("skip parsing");
          next();
          return;
        }
        read(req, res, next, parse3, debug, {
          encoding: null,
          inflate,
          limit,
          verify
        });
      };
    }
    function typeChecker(type) {
      return function checkType(req) {
        return Boolean(typeis(req, type));
      };
    }
  }
});

// ../../node_modules/.pnpm/body-parser@1.20.3/node_modules/body-parser/lib/types/text.js
var require_text = __commonJS({
  "../../node_modules/.pnpm/body-parser@1.20.3/node_modules/body-parser/lib/types/text.js"(exports, module) {
    "use strict";
    var bytes = require_bytes();
    var contentType = require_content_type();
    var debug = require_src()("body-parser:text");
    var read = require_read();
    var typeis = require_type_is();
    module.exports = text2;
    function text2(options) {
      var opts = options || {};
      var defaultCharset = opts.defaultCharset || "utf-8";
      var inflate = opts.inflate !== false;
      var limit = typeof opts.limit !== "number" ? bytes.parse(opts.limit || "100kb") : opts.limit;
      var type = opts.type || "text/plain";
      var verify = opts.verify || false;
      if (verify !== false && typeof verify !== "function") {
        throw new TypeError("option verify must be function");
      }
      var shouldParse = typeof type !== "function" ? typeChecker(type) : type;
      function parse3(buf) {
        return buf;
      }
      return function textParser(req, res, next) {
        if (req._body) {
          debug("body already parsed");
          next();
          return;
        }
        req.body = req.body || {};
        if (!typeis.hasBody(req)) {
          debug("skip empty body");
          next();
          return;
        }
        debug("content-type %j", req.headers["content-type"]);
        if (!shouldParse(req)) {
          debug("skip parsing");
          next();
          return;
        }
        var charset = getCharset(req) || defaultCharset;
        read(req, res, next, parse3, debug, {
          encoding: charset,
          inflate,
          limit,
          verify
        });
      };
    }
    function getCharset(req) {
      try {
        return (contentType.parse(req).parameters.charset || "").toLowerCase();
      } catch (e) {
        return void 0;
      }
    }
    function typeChecker(type) {
      return function checkType(req) {
        return Boolean(typeis(req, type));
      };
    }
  }
});

// ../../node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/type.js
var require_type = __commonJS({
  "../../node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/type.js"(exports, module) {
    "use strict";
    module.exports = TypeError;
  }
});

// ../../node_modules/.pnpm/object-inspect@1.13.4/node_modules/object-inspect/util.inspect.js
var require_util_inspect = __commonJS({
  "../../node_modules/.pnpm/object-inspect@1.13.4/node_modules/object-inspect/util.inspect.js"(exports, module) {
    module.exports = __require("util").inspect;
  }
});

// ../../node_modules/.pnpm/object-inspect@1.13.4/node_modules/object-inspect/index.js
var require_object_inspect = __commonJS({
  "../../node_modules/.pnpm/object-inspect@1.13.4/node_modules/object-inspect/index.js"(exports, module) {
    var hasMap = typeof Map === "function" && Map.prototype;
    var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, "size") : null;
    var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === "function" ? mapSizeDescriptor.get : null;
    var mapForEach = hasMap && Map.prototype.forEach;
    var hasSet = typeof Set === "function" && Set.prototype;
    var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, "size") : null;
    var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === "function" ? setSizeDescriptor.get : null;
    var setForEach = hasSet && Set.prototype.forEach;
    var hasWeakMap = typeof WeakMap === "function" && WeakMap.prototype;
    var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null;
    var hasWeakSet = typeof WeakSet === "function" && WeakSet.prototype;
    var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null;
    var hasWeakRef = typeof WeakRef === "function" && WeakRef.prototype;
    var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null;
    var booleanValueOf = Boolean.prototype.valueOf;
    var objectToString = Object.prototype.toString;
    var functionToString = Function.prototype.toString;
    var $match = String.prototype.match;
    var $slice = String.prototype.slice;
    var $replace = String.prototype.replace;
    var $toUpperCase = String.prototype.toUpperCase;
    var $toLowerCase = String.prototype.toLowerCase;
    var $test = RegExp.prototype.test;
    var $concat = Array.prototype.concat;
    var $join = Array.prototype.join;
    var $arrSlice = Array.prototype.slice;
    var $floor = Math.floor;
    var bigIntValueOf = typeof BigInt === "function" ? BigInt.prototype.valueOf : null;
    var gOPS = Object.getOwnPropertySymbols;
    var symToString = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? Symbol.prototype.toString : null;
    var hasShammedSymbols = typeof Symbol === "function" && typeof Symbol.iterator === "object";
    var toStringTag = typeof Symbol === "function" && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? "object" : "symbol") ? Symbol.toStringTag : null;
    var isEnumerable = Object.prototype.propertyIsEnumerable;
    var gPO = (typeof Reflect === "function" ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ([].__proto__ === Array.prototype ? function(O) {
      return O.__proto__;
    } : null);
    function addNumericSeparator(num, str) {
      if (num === Infinity || num === -Infinity || num !== num || num && num > -1e3 && num < 1e3 || $test.call(/e/, str)) {
        return str;
      }
      var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;
      if (typeof num === "number") {
        var int2 = num < 0 ? -$floor(-num) : $floor(num);
        if (int2 !== num) {
          var intStr = String(int2);
          var dec = $slice.call(str, intStr.length + 1);
          return $replace.call(intStr, sepRegex, "$&_") + "." + $replace.call($replace.call(dec, /([0-9]{3})/g, "$&_"), /_$/, "");
        }
      }
      return $replace.call(str, sepRegex, "$&_");
    }
    var utilInspect = require_util_inspect();
    var inspectCustom = utilInspect.custom;
    var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null;
    var quotes = {
      __proto__: null,
      "double": '"',
      single: "'"
    };
    var quoteREs = {
      __proto__: null,
      "double": /(["\\])/g,
      single: /(['\\])/g
    };
    module.exports = function inspect_(obj, options, depth, seen) {
      var opts = options || {};
      if (has(opts, "quoteStyle") && !has(quotes, opts.quoteStyle)) {
        throw new TypeError('option "quoteStyle" must be "single" or "double"');
      }
      if (has(opts, "maxStringLength") && (typeof opts.maxStringLength === "number" ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity : opts.maxStringLength !== null)) {
        throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');
      }
      var customInspect = has(opts, "customInspect") ? opts.customInspect : true;
      if (typeof customInspect !== "boolean" && customInspect !== "symbol") {
        throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");
      }
      if (has(opts, "indent") && opts.indent !== null && opts.indent !== "	" && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0)) {
        throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');
      }
      if (has(opts, "numericSeparator") && typeof opts.numericSeparator !== "boolean") {
        throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');
      }
      var numericSeparator = opts.numericSeparator;
      if (typeof obj === "undefined") {
        return "undefined";
      }
      if (obj === null) {
        return "null";
      }
      if (typeof obj === "boolean") {
        return obj ? "true" : "false";
      }
      if (typeof obj === "string") {
        return inspectString(obj, opts);
      }
      if (typeof obj === "number") {
        if (obj === 0) {
          return Infinity / obj > 0 ? "0" : "-0";
        }
        var str = String(obj);
        return numericSeparator ? addNumericSeparator(obj, str) : str;
      }
      if (typeof obj === "bigint") {
        var bigIntStr = String(obj) + "n";
        return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr;
      }
      var maxDepth = typeof opts.depth === "undefined" ? 5 : opts.depth;
      if (typeof depth === "undefined") {
        depth = 0;
      }
      if (depth >= maxDepth && maxDepth > 0 && typeof obj === "object") {
        return isArray(obj) ? "[Array]" : "[Object]";
      }
      var indent = getIndent(opts, depth);
      if (typeof seen === "undefined") {
        seen = [];
      } else if (indexOf(seen, obj) >= 0) {
        return "[Circular]";
      }
      function inspect(value, from, noIndent) {
        if (from) {
          seen = $arrSlice.call(seen);
          seen.push(from);
        }
        if (noIndent) {
          var newOpts = {
            depth: opts.depth
          };
          if (has(opts, "quoteStyle")) {
            newOpts.quoteStyle = opts.quoteStyle;
          }
          return inspect_(value, newOpts, depth + 1, seen);
        }
        return inspect_(value, opts, depth + 1, seen);
      }
      if (typeof obj === "function" && !isRegExp(obj)) {
        var name = nameOf(obj);
        var keys = arrObjKeys(obj, inspect);
        return "[Function" + (name ? ": " + name : " (anonymous)") + "]" + (keys.length > 0 ? " { " + $join.call(keys, ", ") + " }" : "");
      }
      if (isSymbol(obj)) {
        var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, "$1") : symToString.call(obj);
        return typeof obj === "object" && !hasShammedSymbols ? markBoxed(symString) : symString;
      }
      if (isElement(obj)) {
        var s = "<" + $toLowerCase.call(String(obj.nodeName));
        var attrs = obj.attributes || [];
        for (var i = 0; i < attrs.length; i++) {
          s += " " + attrs[i].name + "=" + wrapQuotes(quote(attrs[i].value), "double", opts);
        }
        s += ">";
        if (obj.childNodes && obj.childNodes.length) {
          s += "...";
        }
        s += "</" + $toLowerCase.call(String(obj.nodeName)) + ">";
        return s;
      }
      if (isArray(obj)) {
        if (obj.length === 0) {
          return "[]";
        }
        var xs = arrObjKeys(obj, inspect);
        if (indent && !singleLineValues(xs)) {
          return "[" + indentedJoin(xs, indent) + "]";
        }
        return "[ " + $join.call(xs, ", ") + " ]";
      }
      if (isError(obj)) {
        var parts = arrObjKeys(obj, inspect);
        if (!("cause" in Error.prototype) && "cause" in obj && !isEnumerable.call(obj, "cause")) {
          return "{ [" + String(obj) + "] " + $join.call($concat.call("[cause]: " + inspect(obj.cause), parts), ", ") + " }";
        }
        if (parts.length === 0) {
          return "[" + String(obj) + "]";
        }
        return "{ [" + String(obj) + "] " + $join.call(parts, ", ") + " }";
      }
      if (typeof obj === "object" && customInspect) {
        if (inspectSymbol && typeof obj[inspectSymbol] === "function" && utilInspect) {
          return utilInspect(obj, { depth: maxDepth - depth });
        } else if (customInspect !== "symbol" && typeof obj.inspect === "function") {
          return obj.inspect();
        }
      }
      if (isMap(obj)) {
        var mapParts = [];
        if (mapForEach) {
          mapForEach.call(obj, function(value, key) {
            mapParts.push(inspect(key, obj, true) + " => " + inspect(value, obj));
          });
        }
        return collectionOf("Map", mapSize.call(obj), mapParts, indent);
      }
      if (isSet(obj)) {
        var setParts = [];
        if (setForEach) {
          setForEach.call(obj, function(value) {
            setParts.push(inspect(value, obj));
          });
        }
        return collectionOf("Set", setSize.call(obj), setParts, indent);
      }
      if (isWeakMap(obj)) {
        return weakCollectionOf("WeakMap");
      }
      if (isWeakSet(obj)) {
        return weakCollectionOf("WeakSet");
      }
      if (isWeakRef(obj)) {
        return weakCollectionOf("WeakRef");
      }
      if (isNumber(obj)) {
        return markBoxed(inspect(Number(obj)));
      }
      if (isBigInt(obj)) {
        return markBoxed(inspect(bigIntValueOf.call(obj)));
      }
      if (isBoolean(obj)) {
        return markBoxed(booleanValueOf.call(obj));
      }
      if (isString(obj)) {
        return markBoxed(inspect(String(obj)));
      }
      if (typeof window !== "undefined" && obj === window) {
        return "{ [object Window] }";
      }
      if (typeof globalThis !== "undefined" && obj === globalThis || typeof global !== "undefined" && obj === global) {
        return "{ [object globalThis] }";
      }
      if (!isDate(obj) && !isRegExp(obj)) {
        var ys = arrObjKeys(obj, inspect);
        var isPlainObject2 = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object;
        var protoTag = obj instanceof Object ? "" : "null prototype";
        var stringTag = !isPlainObject2 && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? "Object" : "";
        var constructorTag = isPlainObject2 || typeof obj.constructor !== "function" ? "" : obj.constructor.name ? obj.constructor.name + " " : "";
        var tag = constructorTag + (stringTag || protoTag ? "[" + $join.call($concat.call([], stringTag || [], protoTag || []), ": ") + "] " : "");
        if (ys.length === 0) {
          return tag + "{}";
        }
        if (indent) {
          return tag + "{" + indentedJoin(ys, indent) + "}";
        }
        return tag + "{ " + $join.call(ys, ", ") + " }";
      }
      return String(obj);
    };
    function wrapQuotes(s, defaultStyle, opts) {
      var style = opts.quoteStyle || defaultStyle;
      var quoteChar = quotes[style];
      return quoteChar + s + quoteChar;
    }
    function quote(s) {
      return $replace.call(String(s), /"/g, "&quot;");
    }
    function canTrustToString(obj) {
      return !toStringTag || !(typeof obj === "object" && (toStringTag in obj || typeof obj[toStringTag] !== "undefined"));
    }
    function isArray(obj) {
      return toStr(obj) === "[object Array]" && canTrustToString(obj);
    }
    function isDate(obj) {
      return toStr(obj) === "[object Date]" && canTrustToString(obj);
    }
    function isRegExp(obj) {
      return toStr(obj) === "[object RegExp]" && canTrustToString(obj);
    }
    function isError(obj) {
      return toStr(obj) === "[object Error]" && canTrustToString(obj);
    }
    function isString(obj) {
      return toStr(obj) === "[object String]" && canTrustToString(obj);
    }
    function isNumber(obj) {
      return toStr(obj) === "[object Number]" && canTrustToString(obj);
    }
    function isBoolean(obj) {
      return toStr(obj) === "[object Boolean]" && canTrustToString(obj);
    }
    function isSymbol(obj) {
      if (hasShammedSymbols) {
        return obj && typeof obj === "object" && obj instanceof Symbol;
      }
      if (typeof obj === "symbol") {
        return true;
      }
      if (!obj || typeof obj !== "object" || !symToString) {
        return false;
      }
      try {
        symToString.call(obj);
        return true;
      } catch (e) {
      }
      return false;
    }
    function isBigInt(obj) {
      if (!obj || typeof obj !== "object" || !bigIntValueOf) {
        return false;
      }
      try {
        bigIntValueOf.call(obj);
        return true;
      } catch (e) {
      }
      return false;
    }
    var hasOwn = Object.prototype.hasOwnProperty || function(key) {
      return key in this;
    };
    function has(obj, key) {
      return hasOwn.call(obj, key);
    }
    function toStr(obj) {
      return objectToString.call(obj);
    }
    function nameOf(f) {
      if (f.name) {
        return f.name;
      }
      var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/);
      if (m) {
        return m[1];
      }
      return null;
    }
    function indexOf(xs, x) {
      if (xs.indexOf) {
        return xs.indexOf(x);
      }
      for (var i = 0, l = xs.length; i < l; i++) {
        if (xs[i] === x) {
          return i;
        }
      }
      return -1;
    }
    function isMap(x) {
      if (!mapSize || !x || typeof x !== "object") {
        return false;
      }
      try {
        mapSize.call(x);
        try {
          setSize.call(x);
        } catch (s) {
          return true;
        }
        return x instanceof Map;
      } catch (e) {
      }
      return false;
    }
    function isWeakMap(x) {
      if (!weakMapHas || !x || typeof x !== "object") {
        return false;
      }
      try {
        weakMapHas.call(x, weakMapHas);
        try {
          weakSetHas.call(x, weakSetHas);
        } catch (s) {
          return true;
        }
        return x instanceof WeakMap;
      } catch (e) {
      }
      return false;
    }
    function isWeakRef(x) {
      if (!weakRefDeref || !x || typeof x !== "object") {
        return false;
      }
      try {
        weakRefDeref.call(x);
        return true;
      } catch (e) {
      }
      return false;
    }
    function isSet(x) {
      if (!setSize || !x || typeof x !== "object") {
        return false;
      }
      try {
        setSize.call(x);
        try {
          mapSize.call(x);
        } catch (m) {
          return true;
        }
        return x instanceof Set;
      } catch (e) {
      }
      return false;
    }
    function isWeakSet(x) {
      if (!weakSetHas || !x || typeof x !== "object") {
        return false;
      }
      try {
        weakSetHas.call(x, weakSetHas);
        try {
          weakMapHas.call(x, weakMapHas);
        } catch (s) {
          return true;
        }
        return x instanceof WeakSet;
      } catch (e) {
      }
      return false;
    }
    function isElement(x) {
      if (!x || typeof x !== "object") {
        return false;
      }
      if (typeof HTMLElement !== "undefined" && x instanceof HTMLElement) {
        return true;
      }
      return typeof x.nodeName === "string" && typeof x.getAttribute === "function";
    }
    function inspectString(str, opts) {
      if (str.length > opts.maxStringLength) {
        var remaining = str.length - opts.maxStringLength;
        var trailer = "... " + remaining + " more character" + (remaining > 1 ? "s" : "");
        return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer;
      }
      var quoteRE = quoteREs[opts.quoteStyle || "single"];
      quoteRE.lastIndex = 0;
      var s = $replace.call($replace.call(str, quoteRE, "\\$1"), /[\x00-\x1f]/g, lowbyte);
      return wrapQuotes(s, "single", opts);
    }
    function lowbyte(c) {
      var n = c.charCodeAt(0);
      var x = {
        8: "b",
        9: "t",
        10: "n",
        12: "f",
        13: "r"
      }[n];
      if (x) {
        return "\\" + x;
      }
      return "\\x" + (n < 16 ? "0" : "") + $toUpperCase.call(n.toString(16));
    }
    function markBoxed(str) {
      return "Object(" + str + ")";
    }
    function weakCollectionOf(type) {
      return type + " { ? }";
    }
    function collectionOf(type, size, entries, indent) {
      var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ", ");
      return type + " (" + size + ") {" + joinedEntries + "}";
    }
    function singleLineValues(xs) {
      for (var i = 0; i < xs.length; i++) {
        if (indexOf(xs[i], "\n") >= 0) {
          return false;
        }
      }
      return true;
    }
    function getIndent(opts, depth) {
      var baseIndent;
      if (opts.indent === "	") {
        baseIndent = "	";
      } else if (typeof opts.indent === "number" && opts.indent > 0) {
        baseIndent = $join.call(Array(opts.indent + 1), " ");
      } else {
        return null;
      }
      return {
        base: baseIndent,
        prev: $join.call(Array(depth + 1), baseIndent)
      };
    }
    function indentedJoin(xs, indent) {
      if (xs.length === 0) {
        return "";
      }
      var lineJoiner = "\n" + indent.prev + indent.base;
      return lineJoiner + $join.call(xs, "," + lineJoiner) + "\n" + indent.prev;
    }
    function arrObjKeys(obj, inspect) {
      var isArr = isArray(obj);
      var xs = [];
      if (isArr) {
        xs.length = obj.length;
        for (var i = 0; i < obj.length; i++) {
          xs[i] = has(obj, i) ? inspect(obj[i], obj) : "";
        }
      }
      var syms = typeof gOPS === "function" ? gOPS(obj) : [];
      var symMap;
      if (hasShammedSymbols) {
        symMap = {};
        for (var k = 0; k < syms.length; k++) {
          symMap["$" + syms[k]] = syms[k];
        }
      }
      for (var key in obj) {
        if (!has(obj, key)) {
          continue;
        }
        if (isArr && String(Number(key)) === key && key < obj.length) {
          continue;
        }
        if (hasShammedSymbols && symMap["$" + key] instanceof Symbol) {
          continue;
        } else if ($test.call(/[^\w$]/, key)) {
          xs.push(inspect(key, obj) + ": " + inspect(obj[key], obj));
        } else {
          xs.push(key + ": " + inspect(obj[key], obj));
        }
      }
      if (typeof gOPS === "function") {
        for (var j = 0; j < syms.length; j++) {
          if (isEnumerable.call(obj, syms[j])) {
            xs.push("[" + inspect(syms[j]) + "]: " + inspect(obj[syms[j]], obj));
          }
        }
      }
      return xs;
    }
  }
});

// ../../node_modules/.pnpm/side-channel-list@1.0.1/node_modules/side-channel-list/index.js
var require_side_channel_list = __commonJS({
  "../../node_modules/.pnpm/side-channel-list@1.0.1/node_modules/side-channel-list/index.js"(exports, module) {
    "use strict";
    var inspect = require_object_inspect();
    var $TypeError = require_type();
    var listGetNode = function(list, key, isDelete) {
      var prev = list;
      var curr;
      for (; (curr = prev.next) != null; prev = curr) {
        if (curr.key === key) {
          prev.next = curr.next;
          if (!isDelete) {
            curr.next = /** @type {NonNullable<typeof list.next>} */
            list.next;
            list.next = curr;
          }
          return curr;
        }
      }
    };
    var listGet = function(objects, key) {
      if (!objects) {
        return void 0;
      }
      var node = listGetNode(objects, key);
      return node && node.value;
    };
    var listSet = function(objects, key, value) {
      var node = listGetNode(objects, key);
      if (node) {
        node.value = value;
      } else {
        objects.next = /** @type {import('./list.d.ts').ListNode<typeof value, typeof key>} */
        {
          // eslint-disable-line no-param-reassign, no-extra-parens
          key,
          next: objects.next,
          value
        };
      }
    };
    var listHas = function(objects, key) {
      if (!objects) {
        return false;
      }
      return !!listGetNode(objects, key);
    };
    var listDelete = function(objects, key) {
      if (objects) {
        return listGetNode(objects, key, true);
      }
    };
    module.exports = function getSideChannelList() {
      var $o;
      var channel = {
        assert: function(key) {
          if (!channel.has(key)) {
            throw new $TypeError("Side channel does not contain " + inspect(key));
          }
        },
        "delete": function(key) {
          var deletedNode = listDelete($o, key);
          if (deletedNode && $o && !$o.next) {
            $o = void 0;
          }
          return !!deletedNode;
        },
        get: function(key) {
          return listGet($o, key);
        },
        has: function(key) {
          return listHas($o, key);
        },
        set: function(key, value) {
          if (!$o) {
            $o = {
              next: void 0
            };
          }
          listSet(
            /** @type {NonNullable<typeof $o>} */
            $o,
            key,
            value
          );
        }
      };
      return channel;
    };
  }
});

// ../../node_modules/.pnpm/es-object-atoms@1.1.1/node_modules/es-object-atoms/index.js
var require_es_object_atoms = __commonJS({
  "../../node_modules/.pnpm/es-object-atoms@1.1.1/node_modules/es-object-atoms/index.js"(exports, module) {
    "use strict";
    module.exports = Object;
  }
});

// ../../node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/index.js
var require_es_errors = __commonJS({
  "../../node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/index.js"(exports, module) {
    "use strict";
    module.exports = Error;
  }
});

// ../../node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/eval.js
var require_eval = __commonJS({
  "../../node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/eval.js"(exports, module) {
    "use strict";
    module.exports = EvalError;
  }
});

// ../../node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/range.js
var require_range = __commonJS({
  "../../node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/range.js"(exports, module) {
    "use strict";
    module.exports = RangeError;
  }
});

// ../../node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/ref.js
var require_ref = __commonJS({
  "../../node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/ref.js"(exports, module) {
    "use strict";
    module.exports = ReferenceError;
  }
});

// ../../node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/syntax.js
var require_syntax = __commonJS({
  "../../node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/syntax.js"(exports, module) {
    "use strict";
    module.exports = SyntaxError;
  }
});

// ../../node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/uri.js
var require_uri = __commonJS({
  "../../node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/uri.js"(exports, module) {
    "use strict";
    module.exports = URIError;
  }
});

// ../../node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/abs.js
var require_abs = __commonJS({
  "../../node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/abs.js"(exports, module) {
    "use strict";
    module.exports = Math.abs;
  }
});

// ../../node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/floor.js
var require_floor = __commonJS({
  "../../node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/floor.js"(exports, module) {
    "use strict";
    module.exports = Math.floor;
  }
});

// ../../node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/max.js
var require_max = __commonJS({
  "../../node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/max.js"(exports, module) {
    "use strict";
    module.exports = Math.max;
  }
});

// ../../node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/min.js
var require_min = __commonJS({
  "../../node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/min.js"(exports, module) {
    "use strict";
    module.exports = Math.min;
  }
});

// ../../node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/pow.js
var require_pow = __commonJS({
  "../../node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/pow.js"(exports, module) {
    "use strict";
    module.exports = Math.pow;
  }
});

// ../../node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/round.js
var require_round = __commonJS({
  "../../node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/round.js"(exports, module) {
    "use strict";
    module.exports = Math.round;
  }
});

// ../../node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/isNaN.js
var require_isNaN = __commonJS({
  "../../node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/isNaN.js"(exports, module) {
    "use strict";
    module.exports = Number.isNaN || function isNaN2(a) {
      return a !== a;
    };
  }
});

// ../../node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/sign.js
var require_sign = __commonJS({
  "../../node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/sign.js"(exports, module) {
    "use strict";
    var $isNaN = require_isNaN();
    module.exports = function sign(number4) {
      if ($isNaN(number4) || number4 === 0) {
        return number4;
      }
      return number4 < 0 ? -1 : 1;
    };
  }
});

// ../../node_modules/.pnpm/gopd@1.2.0/node_modules/gopd/gOPD.js
var require_gOPD = __commonJS({
  "../../node_modules/.pnpm/gopd@1.2.0/node_modules/gopd/gOPD.js"(exports, module) {
    "use strict";
    module.exports = Object.getOwnPropertyDescriptor;
  }
});

// ../../node_modules/.pnpm/gopd@1.2.0/node_modules/gopd/index.js
var require_gopd = __commonJS({
  "../../node_modules/.pnpm/gopd@1.2.0/node_modules/gopd/index.js"(exports, module) {
    "use strict";
    var $gOPD = require_gOPD();
    if ($gOPD) {
      try {
        $gOPD([], "length");
      } catch (e) {
        $gOPD = null;
      }
    }
    module.exports = $gOPD;
  }
});

// ../../node_modules/.pnpm/es-define-property@1.0.1/node_modules/es-define-property/index.js
var require_es_define_property = __commonJS({
  "../../node_modules/.pnpm/es-define-property@1.0.1/node_modules/es-define-property/index.js"(exports, module) {
    "use strict";
    var $defineProperty = Object.defineProperty || false;
    if ($defineProperty) {
      try {
        $defineProperty({}, "a", { value: 1 });
      } catch (e) {
        $defineProperty = false;
      }
    }
    module.exports = $defineProperty;
  }
});

// ../../node_modules/.pnpm/has-symbols@1.1.0/node_modules/has-symbols/shams.js
var require_shams = __commonJS({
  "../../node_modules/.pnpm/has-symbols@1.1.0/node_modules/has-symbols/shams.js"(exports, module) {
    "use strict";
    module.exports = function hasSymbols() {
      if (typeof Symbol !== "function" || typeof Object.getOwnPropertySymbols !== "function") {
        return false;
      }
      if (typeof Symbol.iterator === "symbol") {
        return true;
      }
      var obj = {};
      var sym = /* @__PURE__ */ Symbol("test");
      var symObj = Object(sym);
      if (typeof sym === "string") {
        return false;
      }
      if (Object.prototype.toString.call(sym) !== "[object Symbol]") {
        return false;
      }
      if (Object.prototype.toString.call(symObj) !== "[object Symbol]") {
        return false;
      }
      var symVal = 42;
      obj[sym] = symVal;
      for (var _ in obj) {
        return false;
      }
      if (typeof Object.keys === "function" && Object.keys(obj).length !== 0) {
        return false;
      }
      if (typeof Object.getOwnPropertyNames === "function" && Object.getOwnPropertyNames(obj).length !== 0) {
        return false;
      }
      var syms = Object.getOwnPropertySymbols(obj);
      if (syms.length !== 1 || syms[0] !== sym) {
        return false;
      }
      if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) {
        return false;
      }
      if (typeof Object.getOwnPropertyDescriptor === "function") {
        var descriptor = (
          /** @type {PropertyDescriptor} */
          Object.getOwnPropertyDescriptor(obj, sym)
        );
        if (descriptor.value !== symVal || descriptor.enumerable !== true) {
          return false;
        }
      }
      return true;
    };
  }
});

// ../../node_modules/.pnpm/has-symbols@1.1.0/node_modules/has-symbols/index.js
var require_has_symbols = __commonJS({
  "../../node_modules/.pnpm/has-symbols@1.1.0/node_modules/has-symbols/index.js"(exports, module) {
    "use strict";
    var origSymbol = typeof Symbol !== "undefined" && Symbol;
    var hasSymbolSham = require_shams();
    module.exports = function hasNativeSymbols() {
      if (typeof origSymbol !== "function") {
        return false;
      }
      if (typeof Symbol !== "function") {
        return false;
      }
      if (typeof origSymbol("foo") !== "symbol") {
        return false;
      }
      if (typeof /* @__PURE__ */ Symbol("bar") !== "symbol") {
        return false;
      }
      return hasSymbolSham();
    };
  }
});

// ../../node_modules/.pnpm/get-proto@1.0.1/node_modules/get-proto/Reflect.getPrototypeOf.js
var require_Reflect_getPrototypeOf = __commonJS({
  "../../node_modules/.pnpm/get-proto@1.0.1/node_modules/get-proto/Reflect.getPrototypeOf.js"(exports, module) {
    "use strict";
    module.exports = typeof Reflect !== "undefined" && Reflect.getPrototypeOf || null;
  }
});

// ../../node_modules/.pnpm/get-proto@1.0.1/node_modules/get-proto/Object.getPrototypeOf.js
var require_Object_getPrototypeOf = __commonJS({
  "../../node_modules/.pnpm/get-proto@1.0.1/node_modules/get-proto/Object.getPrototypeOf.js"(exports, module) {
    "use strict";
    var $Object = require_es_object_atoms();
    module.exports = $Object.getPrototypeOf || null;
  }
});

// ../../node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/implementation.js
var require_implementation = __commonJS({
  "../../node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/implementation.js"(exports, module) {
    "use strict";
    var ERROR_MESSAGE = "Function.prototype.bind called on incompatible ";
    var toStr = Object.prototype.toString;
    var max = Math.max;
    var funcType = "[object Function]";
    var concatty = function concatty2(a, b) {
      var arr = [];
      for (var i = 0; i < a.length; i += 1) {
        arr[i] = a[i];
      }
      for (var j = 0; j < b.length; j += 1) {
        arr[j + a.length] = b[j];
      }
      return arr;
    };
    var slicy = function slicy2(arrLike, offset) {
      var arr = [];
      for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) {
        arr[j] = arrLike[i];
      }
      return arr;
    };
    var joiny = function(arr, joiner) {
      var str = "";
      for (var i = 0; i < arr.length; i += 1) {
        str += arr[i];
        if (i + 1 < arr.length) {
          str += joiner;
        }
      }
      return str;
    };
    module.exports = function bind(that) {
      var target = this;
      if (typeof target !== "function" || toStr.apply(target) !== funcType) {
        throw new TypeError(ERROR_MESSAGE + target);
      }
      var args = slicy(arguments, 1);
      var bound;
      var binder = function() {
        if (this instanceof bound) {
          var result = target.apply(
            this,
            concatty(args, arguments)
          );
          if (Object(result) === result) {
            return result;
          }
          return this;
        }
        return target.apply(
          that,
          concatty(args, arguments)
        );
      };
      var boundLength = max(0, target.length - args.length);
      var boundArgs = [];
      for (var i = 0; i < boundLength; i++) {
        boundArgs[i] = "$" + i;
      }
      bound = Function("binder", "return function (" + joiny(boundArgs, ",") + "){ return binder.apply(this,arguments); }")(binder);
      if (target.prototype) {
        var Empty = function Empty2() {
        };
        Empty.prototype = target.prototype;
        bound.prototype = new Empty();
        Empty.prototype = null;
      }
      return bound;
    };
  }
});

// ../../node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/index.js
var require_function_bind = __commonJS({
  "../../node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/index.js"(exports, module) {
    "use strict";
    var implementation = require_implementation();
    module.exports = Function.prototype.bind || implementation;
  }
});

// ../../node_modules/.pnpm/call-bind-apply-helpers@1.0.2/node_modules/call-bind-apply-helpers/functionCall.js
var require_functionCall = __commonJS({
  "../../node_modules/.pnpm/call-bind-apply-helpers@1.0.2/node_modules/call-bind-apply-helpers/functionCall.js"(exports, module) {
    "use strict";
    module.exports = Function.prototype.call;
  }
});

// ../../node_modules/.pnpm/call-bind-apply-helpers@1.0.2/node_modules/call-bind-apply-helpers/functionApply.js
var require_functionApply = __commonJS({
  "../../node_modules/.pnpm/call-bind-apply-helpers@1.0.2/node_modules/call-bind-apply-helpers/functionApply.js"(exports, module) {
    "use strict";
    module.exports = Function.prototype.apply;
  }
});

// ../../node_modules/.pnpm/call-bind-apply-helpers@1.0.2/node_modules/call-bind-apply-helpers/reflectApply.js
var require_reflectApply = __commonJS({
  "../../node_modules/.pnpm/call-bind-apply-helpers@1.0.2/node_modules/call-bind-apply-helpers/reflectApply.js"(exports, module) {
    "use strict";
    module.exports = typeof Reflect !== "undefined" && Reflect && Reflect.apply;
  }
});

// ../../node_modules/.pnpm/call-bind-apply-helpers@1.0.2/node_modules/call-bind-apply-helpers/actualApply.js
var require_actualApply = __commonJS({
  "../../node_modules/.pnpm/call-bind-apply-helpers@1.0.2/node_modules/call-bind-apply-helpers/actualApply.js"(exports, module) {
    "use strict";
    var bind = require_function_bind();
    var $apply = require_functionApply();
    var $call = require_functionCall();
    var $reflectApply = require_reflectApply();
    module.exports = $reflectApply || bind.call($call, $apply);
  }
});

// ../../node_modules/.pnpm/call-bind-apply-helpers@1.0.2/node_modules/call-bind-apply-helpers/index.js
var require_call_bind_apply_helpers = __commonJS({
  "../../node_modules/.pnpm/call-bind-apply-helpers@1.0.2/node_modules/call-bind-apply-helpers/index.js"(exports, module) {
    "use strict";
    var bind = require_function_bind();
    var $TypeError = require_type();
    var $call = require_functionCall();
    var $actualApply = require_actualApply();
    module.exports = function callBindBasic(args) {
      if (args.length < 1 || typeof args[0] !== "function") {
        throw new $TypeError("a function is required");
      }
      return $actualApply(bind, $call, args);
    };
  }
});

// ../../node_modules/.pnpm/dunder-proto@1.0.1/node_modules/dunder-proto/get.js
var require_get = __commonJS({
  "../../node_modules/.pnpm/dunder-proto@1.0.1/node_modules/dunder-proto/get.js"(exports, module) {
    "use strict";
    var callBind = require_call_bind_apply_helpers();
    var gOPD = require_gopd();
    var hasProtoAccessor;
    try {
      hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */
      [].__proto__ === Array.prototype;
    } catch (e) {
      if (!e || typeof e !== "object" || !("code" in e) || e.code !== "ERR_PROTO_ACCESS") {
        throw e;
      }
    }
    var desc2 = !!hasProtoAccessor && gOPD && gOPD(
      Object.prototype,
      /** @type {keyof typeof Object.prototype} */
      "__proto__"
    );
    var $Object = Object;
    var $getPrototypeOf = $Object.getPrototypeOf;
    module.exports = desc2 && typeof desc2.get === "function" ? callBind([desc2.get]) : typeof $getPrototypeOf === "function" ? (
      /** @type {import('./get')} */
      function getDunder(value) {
        return $getPrototypeOf(value == null ? value : $Object(value));
      }
    ) : false;
  }
});

// ../../node_modules/.pnpm/get-proto@1.0.1/node_modules/get-proto/index.js
var require_get_proto = __commonJS({
  "../../node_modules/.pnpm/get-proto@1.0.1/node_modules/get-proto/index.js"(exports, module) {
    "use strict";
    var reflectGetProto = require_Reflect_getPrototypeOf();
    var originalGetProto = require_Object_getPrototypeOf();
    var getDunderProto = require_get();
    module.exports = reflectGetProto ? function getProto(O) {
      return reflectGetProto(O);
    } : originalGetProto ? function getProto(O) {
      if (!O || typeof O !== "object" && typeof O !== "function") {
        throw new TypeError("getProto: not an object");
      }
      return originalGetProto(O);
    } : getDunderProto ? function getProto(O) {
      return getDunderProto(O);
    } : null;
  }
});

// ../../node_modules/.pnpm/hasown@2.0.3/node_modules/hasown/index.js
var require_hasown = __commonJS({
  "../../node_modules/.pnpm/hasown@2.0.3/node_modules/hasown/index.js"(exports, module) {
    "use strict";
    var call = Function.prototype.call;
    var $hasOwn = Object.prototype.hasOwnProperty;
    var bind = require_function_bind();
    module.exports = bind.call(call, $hasOwn);
  }
});

// ../../node_modules/.pnpm/get-intrinsic@1.3.0/node_modules/get-intrinsic/index.js
var require_get_intrinsic = __commonJS({
  "../../node_modules/.pnpm/get-intrinsic@1.3.0/node_modules/get-intrinsic/index.js"(exports, module) {
    "use strict";
    var undefined2;
    var $Object = require_es_object_atoms();
    var $Error = require_es_errors();
    var $EvalError = require_eval();
    var $RangeError = require_range();
    var $ReferenceError = require_ref();
    var $SyntaxError = require_syntax();
    var $TypeError = require_type();
    var $URIError = require_uri();
    var abs = require_abs();
    var floor = require_floor();
    var max = require_max();
    var min = require_min();
    var pow = require_pow();
    var round = require_round();
    var sign = require_sign();
    var $Function = Function;
    var getEvalledConstructor = function(expressionSyntax) {
      try {
        return $Function('"use strict"; return (' + expressionSyntax + ").constructor;")();
      } catch (e) {
      }
    };
    var $gOPD = require_gopd();
    var $defineProperty = require_es_define_property();
    var throwTypeError = function() {
      throw new $TypeError();
    };
    var ThrowTypeError = $gOPD ? (function() {
      try {
        arguments.callee;
        return throwTypeError;
      } catch (calleeThrows) {
        try {
          return $gOPD(arguments, "callee").get;
        } catch (gOPDthrows) {
          return throwTypeError;
        }
      }
    })() : throwTypeError;
    var hasSymbols = require_has_symbols()();
    var getProto = require_get_proto();
    var $ObjectGPO = require_Object_getPrototypeOf();
    var $ReflectGPO = require_Reflect_getPrototypeOf();
    var $apply = require_functionApply();
    var $call = require_functionCall();
    var needsEval = {};
    var TypedArray = typeof Uint8Array === "undefined" || !getProto ? undefined2 : getProto(Uint8Array);
    var INTRINSICS = {
      __proto__: null,
      "%AggregateError%": typeof AggregateError === "undefined" ? undefined2 : AggregateError,
      "%Array%": Array,
      "%ArrayBuffer%": typeof ArrayBuffer === "undefined" ? undefined2 : ArrayBuffer,
      "%ArrayIteratorPrototype%": hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined2,
      "%AsyncFromSyncIteratorPrototype%": undefined2,
      "%AsyncFunction%": needsEval,
      "%AsyncGenerator%": needsEval,
      "%AsyncGeneratorFunction%": needsEval,
      "%AsyncIteratorPrototype%": needsEval,
      "%Atomics%": typeof Atomics === "undefined" ? undefined2 : Atomics,
      "%BigInt%": typeof BigInt === "undefined" ? undefined2 : BigInt,
      "%BigInt64Array%": typeof BigInt64Array === "undefined" ? undefined2 : BigInt64Array,
      "%BigUint64Array%": typeof BigUint64Array === "undefined" ? undefined2 : BigUint64Array,
      "%Boolean%": Boolean,
      "%DataView%": typeof DataView === "undefined" ? undefined2 : DataView,
      "%Date%": Date,
      "%decodeURI%": decodeURI,
      "%decodeURIComponent%": decodeURIComponent,
      "%encodeURI%": encodeURI,
      "%encodeURIComponent%": encodeURIComponent,
      "%Error%": $Error,
      "%eval%": eval,
      // eslint-disable-line no-eval
      "%EvalError%": $EvalError,
      "%Float16Array%": typeof Float16Array === "undefined" ? undefined2 : Float16Array,
      "%Float32Array%": typeof Float32Array === "undefined" ? undefined2 : Float32Array,
      "%Float64Array%": typeof Float64Array === "undefined" ? undefined2 : Float64Array,
      "%FinalizationRegistry%": typeof FinalizationRegistry === "undefined" ? undefined2 : FinalizationRegistry,
      "%Function%": $Function,
      "%GeneratorFunction%": needsEval,
      "%Int8Array%": typeof Int8Array === "undefined" ? undefined2 : Int8Array,
      "%Int16Array%": typeof Int16Array === "undefined" ? undefined2 : Int16Array,
      "%Int32Array%": typeof Int32Array === "undefined" ? undefined2 : Int32Array,
      "%isFinite%": isFinite,
      "%isNaN%": isNaN,
      "%IteratorPrototype%": hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined2,
      "%JSON%": typeof JSON === "object" ? JSON : undefined2,
      "%Map%": typeof Map === "undefined" ? undefined2 : Map,
      "%MapIteratorPrototype%": typeof Map === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto((/* @__PURE__ */ new Map())[Symbol.iterator]()),
      "%Math%": Math,
      "%Number%": Number,
      "%Object%": $Object,
      "%Object.getOwnPropertyDescriptor%": $gOPD,
      "%parseFloat%": parseFloat,
      "%parseInt%": parseInt,
      "%Promise%": typeof Promise === "undefined" ? undefined2 : Promise,
      "%Proxy%": typeof Proxy === "undefined" ? undefined2 : Proxy,
      "%RangeError%": $RangeError,
      "%ReferenceError%": $ReferenceError,
      "%Reflect%": typeof Reflect === "undefined" ? undefined2 : Reflect,
      "%RegExp%": RegExp,
      "%Set%": typeof Set === "undefined" ? undefined2 : Set,
      "%SetIteratorPrototype%": typeof Set === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto((/* @__PURE__ */ new Set())[Symbol.iterator]()),
      "%SharedArrayBuffer%": typeof SharedArrayBuffer === "undefined" ? undefined2 : SharedArrayBuffer,
      "%String%": String,
      "%StringIteratorPrototype%": hasSymbols && getProto ? getProto(""[Symbol.iterator]()) : undefined2,
      "%Symbol%": hasSymbols ? Symbol : undefined2,
      "%SyntaxError%": $SyntaxError,
      "%ThrowTypeError%": ThrowTypeError,
      "%TypedArray%": TypedArray,
      "%TypeError%": $TypeError,
      "%Uint8Array%": typeof Uint8Array === "undefined" ? undefined2 : Uint8Array,
      "%Uint8ClampedArray%": typeof Uint8ClampedArray === "undefined" ? undefined2 : Uint8ClampedArray,
      "%Uint16Array%": typeof Uint16Array === "undefined" ? undefined2 : Uint16Array,
      "%Uint32Array%": typeof Uint32Array === "undefined" ? undefined2 : Uint32Array,
      "%URIError%": $URIError,
      "%WeakMap%": typeof WeakMap === "undefined" ? undefined2 : WeakMap,
      "%WeakRef%": typeof WeakRef === "undefined" ? undefined2 : WeakRef,
      "%WeakSet%": typeof WeakSet === "undefined" ? undefined2 : WeakSet,
      "%Function.prototype.call%": $call,
      "%Function.prototype.apply%": $apply,
      "%Object.defineProperty%": $defineProperty,
      "%Object.getPrototypeOf%": $ObjectGPO,
      "%Math.abs%": abs,
      "%Math.floor%": floor,
      "%Math.max%": max,
      "%Math.min%": min,
      "%Math.pow%": pow,
      "%Math.round%": round,
      "%Math.sign%": sign,
      "%Reflect.getPrototypeOf%": $ReflectGPO
    };
    if (getProto) {
      try {
        null.error;
      } catch (e) {
        errorProto = getProto(getProto(e));
        INTRINSICS["%Error.prototype%"] = errorProto;
      }
    }
    var errorProto;
    var doEval = function doEval2(name) {
      var value;
      if (name === "%AsyncFunction%") {
        value = getEvalledConstructor("async function () {}");
      } else if (name === "%GeneratorFunction%") {
        value = getEvalledConstructor("function* () {}");
      } else if (name === "%AsyncGeneratorFunction%") {
        value = getEvalledConstructor("async function* () {}");
      } else if (name === "%AsyncGenerator%") {
        var fn = doEval2("%AsyncGeneratorFunction%");
        if (fn) {
          value = fn.prototype;
        }
      } else if (name === "%AsyncIteratorPrototype%") {
        var gen = doEval2("%AsyncGenerator%");
        if (gen && getProto) {
          value = getProto(gen.prototype);
        }
      }
      INTRINSICS[name] = value;
      return value;
    };
    var LEGACY_ALIASES = {
      __proto__: null,
      "%ArrayBufferPrototype%": ["ArrayBuffer", "prototype"],
      "%ArrayPrototype%": ["Array", "prototype"],
      "%ArrayProto_entries%": ["Array", "prototype", "entries"],
      "%ArrayProto_forEach%": ["Array", "prototype", "forEach"],
      "%ArrayProto_keys%": ["Array", "prototype", "keys"],
      "%ArrayProto_values%": ["Array", "prototype", "values"],
      "%AsyncFunctionPrototype%": ["AsyncFunction", "prototype"],
      "%AsyncGenerator%": ["AsyncGeneratorFunction", "prototype"],
      "%AsyncGeneratorPrototype%": ["AsyncGeneratorFunction", "prototype", "prototype"],
      "%BooleanPrototype%": ["Boolean", "prototype"],
      "%DataViewPrototype%": ["DataView", "prototype"],
      "%DatePrototype%": ["Date", "prototype"],
      "%ErrorPrototype%": ["Error", "prototype"],
      "%EvalErrorPrototype%": ["EvalError", "prototype"],
      "%Float32ArrayPrototype%": ["Float32Array", "prototype"],
      "%Float64ArrayPrototype%": ["Float64Array", "prototype"],
      "%FunctionPrototype%": ["Function", "prototype"],
      "%Generator%": ["GeneratorFunction", "prototype"],
      "%GeneratorPrototype%": ["GeneratorFunction", "prototype", "prototype"],
      "%Int8ArrayPrototype%": ["Int8Array", "prototype"],
      "%Int16ArrayPrototype%": ["Int16Array", "prototype"],
      "%Int32ArrayPrototype%": ["Int32Array", "prototype"],
      "%JSONParse%": ["JSON", "parse"],
      "%JSONStringify%": ["JSON", "stringify"],
      "%MapPrototype%": ["Map", "prototype"],
      "%NumberPrototype%": ["Number", "prototype"],
      "%ObjectPrototype%": ["Object", "prototype"],
      "%ObjProto_toString%": ["Object", "prototype", "toString"],
      "%ObjProto_valueOf%": ["Object", "prototype", "valueOf"],
      "%PromisePrototype%": ["Promise", "prototype"],
      "%PromiseProto_then%": ["Promise", "prototype", "then"],
      "%Promise_all%": ["Promise", "all"],
      "%Promise_reject%": ["Promise", "reject"],
      "%Promise_resolve%": ["Promise", "resolve"],
      "%RangeErrorPrototype%": ["RangeError", "prototype"],
      "%ReferenceErrorPrototype%": ["ReferenceError", "prototype"],
      "%RegExpPrototype%": ["RegExp", "prototype"],
      "%SetPrototype%": ["Set", "prototype"],
      "%SharedArrayBufferPrototype%": ["SharedArrayBuffer", "prototype"],
      "%StringPrototype%": ["String", "prototype"],
      "%SymbolPrototype%": ["Symbol", "prototype"],
      "%SyntaxErrorPrototype%": ["SyntaxError", "prototype"],
      "%TypedArrayPrototype%": ["TypedArray", "prototype"],
      "%TypeErrorPrototype%": ["TypeError", "prototype"],
      "%Uint8ArrayPrototype%": ["Uint8Array", "prototype"],
      "%Uint8ClampedArrayPrototype%": ["Uint8ClampedArray", "prototype"],
      "%Uint16ArrayPrototype%": ["Uint16Array", "prototype"],
      "%Uint32ArrayPrototype%": ["Uint32Array", "prototype"],
      "%URIErrorPrototype%": ["URIError", "prototype"],
      "%WeakMapPrototype%": ["WeakMap", "prototype"],
      "%WeakSetPrototype%": ["WeakSet", "prototype"]
    };
    var bind = require_function_bind();
    var hasOwn = require_hasown();
    var $concat = bind.call($call, Array.prototype.concat);
    var $spliceApply = bind.call($apply, Array.prototype.splice);
    var $replace = bind.call($call, String.prototype.replace);
    var $strSlice = bind.call($call, String.prototype.slice);
    var $exec = bind.call($call, RegExp.prototype.exec);
    var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
    var reEscapeChar = /\\(\\)?/g;
    var stringToPath = function stringToPath2(string4) {
      var first = $strSlice(string4, 0, 1);
      var last = $strSlice(string4, -1);
      if (first === "%" && last !== "%") {
        throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`");
      } else if (last === "%" && first !== "%") {
        throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`");
      }
      var result = [];
      $replace(string4, rePropName, function(match, number4, quote, subString) {
        result[result.length] = quote ? $replace(subString, reEscapeChar, "$1") : number4 || match;
      });
      return result;
    };
    var getBaseIntrinsic = function getBaseIntrinsic2(name, allowMissing) {
      var intrinsicName = name;
      var alias;
      if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
        alias = LEGACY_ALIASES[intrinsicName];
        intrinsicName = "%" + alias[0] + "%";
      }
      if (hasOwn(INTRINSICS, intrinsicName)) {
        var value = INTRINSICS[intrinsicName];
        if (value === needsEval) {
          value = doEval(intrinsicName);
        }
        if (typeof value === "undefined" && !allowMissing) {
          throw new $TypeError("intrinsic " + name + " exists, but is not available. Please file an issue!");
        }
        return {
          alias,
          name: intrinsicName,
          value
        };
      }
      throw new $SyntaxError("intrinsic " + name + " does not exist!");
    };
    module.exports = function GetIntrinsic(name, allowMissing) {
      if (typeof name !== "string" || name.length === 0) {
        throw new $TypeError("intrinsic name must be a non-empty string");
      }
      if (arguments.length > 1 && typeof allowMissing !== "boolean") {
        throw new $TypeError('"allowMissing" argument must be a boolean');
      }
      if ($exec(/^%?[^%]*%?$/, name) === null) {
        throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name");
      }
      var parts = stringToPath(name);
      var intrinsicBaseName = parts.length > 0 ? parts[0] : "";
      var intrinsic = getBaseIntrinsic("%" + intrinsicBaseName + "%", allowMissing);
      var intrinsicRealName = intrinsic.name;
      var value = intrinsic.value;
      var skipFurtherCaching = false;
      var alias = intrinsic.alias;
      if (alias) {
        intrinsicBaseName = alias[0];
        $spliceApply(parts, $concat([0, 1], alias));
      }
      for (var i = 1, isOwn = true; i < parts.length; i += 1) {
        var part = parts[i];
        var first = $strSlice(part, 0, 1);
        var last = $strSlice(part, -1);
        if ((first === '"' || first === "'" || first === "`" || (last === '"' || last === "'" || last === "`")) && first !== last) {
          throw new $SyntaxError("property names with quotes must have matching quotes");
        }
        if (part === "constructor" || !isOwn) {
          skipFurtherCaching = true;
        }
        intrinsicBaseName += "." + part;
        intrinsicRealName = "%" + intrinsicBaseName + "%";
        if (hasOwn(INTRINSICS, intrinsicRealName)) {
          value = INTRINSICS[intrinsicRealName];
        } else if (value != null) {
          if (!(part in value)) {
            if (!allowMissing) {
              throw new $TypeError("base intrinsic for " + name + " exists, but the property is not available.");
            }
            return void undefined2;
          }
          if ($gOPD && i + 1 >= parts.length) {
            var desc2 = $gOPD(value, part);
            isOwn = !!desc2;
            if (isOwn && "get" in desc2 && !("originalValue" in desc2.get)) {
              value = desc2.get;
            } else {
              value = value[part];
            }
          } else {
            isOwn = hasOwn(value, part);
            value = value[part];
          }
          if (isOwn && !skipFurtherCaching) {
            INTRINSICS[intrinsicRealName] = value;
          }
        }
      }
      return value;
    };
  }
});

// ../../node_modules/.pnpm/call-bound@1.0.4/node_modules/call-bound/index.js
var require_call_bound = __commonJS({
  "../../node_modules/.pnpm/call-bound@1.0.4/node_modules/call-bound/index.js"(exports, module) {
    "use strict";
    var GetIntrinsic = require_get_intrinsic();
    var callBindBasic = require_call_bind_apply_helpers();
    var $indexOf = callBindBasic([GetIntrinsic("%String.prototype.indexOf%")]);
    module.exports = function callBoundIntrinsic(name, allowMissing) {
      var intrinsic = (
        /** @type {(this: unknown, ...args: unknown[]) => unknown} */
        GetIntrinsic(name, !!allowMissing)
      );
      if (typeof intrinsic === "function" && $indexOf(name, ".prototype.") > -1) {
        return callBindBasic(
          /** @type {const} */
          [intrinsic]
        );
      }
      return intrinsic;
    };
  }
});

// ../../node_modules/.pnpm/side-channel-map@1.0.1/node_modules/side-channel-map/index.js
var require_side_channel_map = __commonJS({
  "../../node_modules/.pnpm/side-channel-map@1.0.1/node_modules/side-channel-map/index.js"(exports, module) {
    "use strict";
    var GetIntrinsic = require_get_intrinsic();
    var callBound = require_call_bound();
    var inspect = require_object_inspect();
    var $TypeError = require_type();
    var $Map = GetIntrinsic("%Map%", true);
    var $mapGet = callBound("Map.prototype.get", true);
    var $mapSet = callBound("Map.prototype.set", true);
    var $mapHas = callBound("Map.prototype.has", true);
    var $mapDelete = callBound("Map.prototype.delete", true);
    var $mapSize = callBound("Map.prototype.size", true);
    module.exports = !!$Map && /** @type {Exclude<import('.'), false>} */
    function getSideChannelMap() {
      var $m;
      var channel = {
        assert: function(key) {
          if (!channel.has(key)) {
            throw new $TypeError("Side channel does not contain " + inspect(key));
          }
        },
        "delete": function(key) {
          if ($m) {
            var result = $mapDelete($m, key);
            if ($mapSize($m) === 0) {
              $m = void 0;
            }
            return result;
          }
          return false;
        },
        get: function(key) {
          if ($m) {
            return $mapGet($m, key);
          }
        },
        has: function(key) {
          if ($m) {
            return $mapHas($m, key);
          }
          return false;
        },
        set: function(key, value) {
          if (!$m) {
            $m = new $Map();
          }
          $mapSet($m, key, value);
        }
      };
      return channel;
    };
  }
});

// ../../node_modules/.pnpm/side-channel-weakmap@1.0.2/node_modules/side-channel-weakmap/index.js
var require_side_channel_weakmap = __commonJS({
  "../../node_modules/.pnpm/side-channel-weakmap@1.0.2/node_modules/side-channel-weakmap/index.js"(exports, module) {
    "use strict";
    var GetIntrinsic = require_get_intrinsic();
    var callBound = require_call_bound();
    var inspect = require_object_inspect();
    var getSideChannelMap = require_side_channel_map();
    var $TypeError = require_type();
    var $WeakMap = GetIntrinsic("%WeakMap%", true);
    var $weakMapGet = callBound("WeakMap.prototype.get", true);
    var $weakMapSet = callBound("WeakMap.prototype.set", true);
    var $weakMapHas = callBound("WeakMap.prototype.has", true);
    var $weakMapDelete = callBound("WeakMap.prototype.delete", true);
    module.exports = $WeakMap ? (
      /** @type {Exclude<import('.'), false>} */
      function getSideChannelWeakMap() {
        var $wm;
        var $m;
        var channel = {
          assert: function(key) {
            if (!channel.has(key)) {
              throw new $TypeError("Side channel does not contain " + inspect(key));
            }
          },
          "delete": function(key) {
            if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) {
              if ($wm) {
                return $weakMapDelete($wm, key);
              }
            } else if (getSideChannelMap) {
              if ($m) {
                return $m["delete"](key);
              }
            }
            return false;
          },
          get: function(key) {
            if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) {
              if ($wm) {
                return $weakMapGet($wm, key);
              }
            }
            return $m && $m.get(key);
          },
          has: function(key) {
            if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) {
              if ($wm) {
                return $weakMapHas($wm, key);
              }
            }
            return !!$m && $m.has(key);
          },
          set: function(key, value) {
            if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) {
              if (!$wm) {
                $wm = new $WeakMap();
              }
              $weakMapSet($wm, key, value);
            } else if (getSideChannelMap) {
              if (!$m) {
                $m = getSideChannelMap();
              }
              $m.set(key, value);
            }
          }
        };
        return channel;
      }
    ) : getSideChannelMap;
  }
});

// ../../node_modules/.pnpm/side-channel@1.1.0/node_modules/side-channel/index.js
var require_side_channel = __commonJS({
  "../../node_modules/.pnpm/side-channel@1.1.0/node_modules/side-channel/index.js"(exports, module) {
    "use strict";
    var $TypeError = require_type();
    var inspect = require_object_inspect();
    var getSideChannelList = require_side_channel_list();
    var getSideChannelMap = require_side_channel_map();
    var getSideChannelWeakMap = require_side_channel_weakmap();
    var makeChannel = getSideChannelWeakMap || getSideChannelMap || getSideChannelList;
    module.exports = function getSideChannel() {
      var $channelData;
      var channel = {
        assert: function(key) {
          if (!channel.has(key)) {
            throw new $TypeError("Side channel does not contain " + inspect(key));
          }
        },
        "delete": function(key) {
          return !!$channelData && $channelData["delete"](key);
        },
        get: function(key) {
          return $channelData && $channelData.get(key);
        },
        has: function(key) {
          return !!$channelData && $channelData.has(key);
        },
        set: function(key, value) {
          if (!$channelData) {
            $channelData = makeChannel();
          }
          $channelData.set(key, value);
        }
      };
      return channel;
    };
  }
});

// ../../node_modules/.pnpm/qs@6.13.0/node_modules/qs/lib/formats.js
var require_formats = __commonJS({
  "../../node_modules/.pnpm/qs@6.13.0/node_modules/qs/lib/formats.js"(exports, module) {
    "use strict";
    var replace = String.prototype.replace;
    var percentTwenties = /%20/g;
    var Format = {
      RFC1738: "RFC1738",
      RFC3986: "RFC3986"
    };
    module.exports = {
      "default": Format.RFC3986,
      formatters: {
        RFC1738: function(value) {
          return replace.call(value, percentTwenties, "+");
        },
        RFC3986: function(value) {
          return String(value);
        }
      },
      RFC1738: Format.RFC1738,
      RFC3986: Format.RFC3986
    };
  }
});

// ../../node_modules/.pnpm/qs@6.13.0/node_modules/qs/lib/utils.js
var require_utils = __commonJS({
  "../../node_modules/.pnpm/qs@6.13.0/node_modules/qs/lib/utils.js"(exports, module) {
    "use strict";
    var formats = require_formats();
    var has = Object.prototype.hasOwnProperty;
    var isArray = Array.isArray;
    var hexTable = (function() {
      var array2 = [];
      for (var i = 0; i < 256; ++i) {
        array2.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase());
      }
      return array2;
    })();
    var compactQueue = function compactQueue2(queue) {
      while (queue.length > 1) {
        var item = queue.pop();
        var obj = item.obj[item.prop];
        if (isArray(obj)) {
          var compacted = [];
          for (var j = 0; j < obj.length; ++j) {
            if (typeof obj[j] !== "undefined") {
              compacted.push(obj[j]);
            }
          }
          item.obj[item.prop] = compacted;
        }
      }
    };
    var arrayToObject = function arrayToObject2(source, options) {
      var obj = options && options.plainObjects ? /* @__PURE__ */ Object.create(null) : {};
      for (var i = 0; i < source.length; ++i) {
        if (typeof source[i] !== "undefined") {
          obj[i] = source[i];
        }
      }
      return obj;
    };
    var merge2 = function merge3(target, source, options) {
      if (!source) {
        return target;
      }
      if (typeof source !== "object") {
        if (isArray(target)) {
          target.push(source);
        } else if (target && typeof target === "object") {
          if (options && (options.plainObjects || options.allowPrototypes) || !has.call(Object.prototype, source)) {
            target[source] = true;
          }
        } else {
          return [target, source];
        }
        return target;
      }
      if (!target || typeof target !== "object") {
        return [target].concat(source);
      }
      var mergeTarget = target;
      if (isArray(target) && !isArray(source)) {
        mergeTarget = arrayToObject(target, options);
      }
      if (isArray(target) && isArray(source)) {
        source.forEach(function(item, i) {
          if (has.call(target, i)) {
            var targetItem = target[i];
            if (targetItem && typeof targetItem === "object" && item && typeof item === "object") {
              target[i] = merge3(targetItem, item, options);
            } else {
              target.push(item);
            }
          } else {
            target[i] = item;
          }
        });
        return target;
      }
      return Object.keys(source).reduce(function(acc, key) {
        var value = source[key];
        if (has.call(acc, key)) {
          acc[key] = merge3(acc[key], value, options);
        } else {
          acc[key] = value;
        }
        return acc;
      }, mergeTarget);
    };
    var assign = function assignSingleSource(target, source) {
      return Object.keys(source).reduce(function(acc, key) {
        acc[key] = source[key];
        return acc;
      }, target);
    };
    var decode = function(str, decoder, charset) {
      var strWithoutPlus = str.replace(/\+/g, " ");
      if (charset === "iso-8859-1") {
        return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);
      }
      try {
        return decodeURIComponent(strWithoutPlus);
      } catch (e) {
        return strWithoutPlus;
      }
    };
    var limit = 1024;
    var encode = function encode2(str, defaultEncoder, charset, kind, format) {
      if (str.length === 0) {
        return str;
      }
      var string4 = str;
      if (typeof str === "symbol") {
        string4 = Symbol.prototype.toString.call(str);
      } else if (typeof str !== "string") {
        string4 = String(str);
      }
      if (charset === "iso-8859-1") {
        return escape(string4).replace(/%u[0-9a-f]{4}/gi, function($0) {
          return "%26%23" + parseInt($0.slice(2), 16) + "%3B";
        });
      }
      var out = "";
      for (var j = 0; j < string4.length; j += limit) {
        var segment = string4.length >= limit ? string4.slice(j, j + limit) : string4;
        var arr = [];
        for (var i = 0; i < segment.length; ++i) {
          var c = segment.charCodeAt(i);
          if (c === 45 || c === 46 || c === 95 || c === 126 || c >= 48 && c <= 57 || c >= 65 && c <= 90 || c >= 97 && c <= 122 || format === formats.RFC1738 && (c === 40 || c === 41)) {
            arr[arr.length] = segment.charAt(i);
            continue;
          }
          if (c < 128) {
            arr[arr.length] = hexTable[c];
            continue;
          }
          if (c < 2048) {
            arr[arr.length] = hexTable[192 | c >> 6] + hexTable[128 | c & 63];
            continue;
          }
          if (c < 55296 || c >= 57344) {
            arr[arr.length] = hexTable[224 | c >> 12] + hexTable[128 | c >> 6 & 63] + hexTable[128 | c & 63];
            continue;
          }
          i += 1;
          c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i) & 1023);
          arr[arr.length] = hexTable[240 | c >> 18] + hexTable[128 | c >> 12 & 63] + hexTable[128 | c >> 6 & 63] + hexTable[128 | c & 63];
        }
        out += arr.join("");
      }
      return out;
    };
    var compact = function compact2(value) {
      var queue = [{ obj: { o: value }, prop: "o" }];
      var refs = [];
      for (var i = 0; i < queue.length; ++i) {
        var item = queue[i];
        var obj = item.obj[item.prop];
        var keys = Object.keys(obj);
        for (var j = 0; j < keys.length; ++j) {
          var key = keys[j];
          var val = obj[key];
          if (typeof val === "object" && val !== null && refs.indexOf(val) === -1) {
            queue.push({ obj, prop: key });
            refs.push(val);
          }
        }
      }
      compactQueue(queue);
      return value;
    };
    var isRegExp = function isRegExp2(obj) {
      return Object.prototype.toString.call(obj) === "[object RegExp]";
    };
    var isBuffer = function isBuffer2(obj) {
      if (!obj || typeof obj !== "object") {
        return false;
      }
      return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
    };
    var combine = function combine2(a, b) {
      return [].concat(a, b);
    };
    var maybeMap = function maybeMap2(val, fn) {
      if (isArray(val)) {
        var mapped = [];
        for (var i = 0; i < val.length; i += 1) {
          mapped.push(fn(val[i]));
        }
        return mapped;
      }
      return fn(val);
    };
    module.exports = {
      arrayToObject,
      assign,
      combine,
      compact,
      decode,
      encode,
      isBuffer,
      isRegExp,
      maybeMap,
      merge: merge2
    };
  }
});

// ../../node_modules/.pnpm/qs@6.13.0/node_modules/qs/lib/stringify.js
var require_stringify = __commonJS({
  "../../node_modules/.pnpm/qs@6.13.0/node_modules/qs/lib/stringify.js"(exports, module) {
    "use strict";
    var getSideChannel = require_side_channel();
    var utils = require_utils();
    var formats = require_formats();
    var has = Object.prototype.hasOwnProperty;
    var arrayPrefixGenerators = {
      brackets: function brackets(prefix) {
        return prefix + "[]";
      },
      comma: "comma",
      indices: function indices(prefix, key) {
        return prefix + "[" + key + "]";
      },
      repeat: function repeat(prefix) {
        return prefix;
      }
    };
    var isArray = Array.isArray;
    var push = Array.prototype.push;
    var pushToArray = function(arr, valueOrArray) {
      push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]);
    };
    var toISO = Date.prototype.toISOString;
    var defaultFormat = formats["default"];
    var defaults2 = {
      addQueryPrefix: false,
      allowDots: false,
      allowEmptyArrays: false,
      arrayFormat: "indices",
      charset: "utf-8",
      charsetSentinel: false,
      delimiter: "&",
      encode: true,
      encodeDotInKeys: false,
      encoder: utils.encode,
      encodeValuesOnly: false,
      format: defaultFormat,
      formatter: formats.formatters[defaultFormat],
      // deprecated
      indices: false,
      serializeDate: function serializeDate(date6) {
        return toISO.call(date6);
      },
      skipNulls: false,
      strictNullHandling: false
    };
    var isNonNullishPrimitive = function isNonNullishPrimitive2(v) {
      return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint";
    };
    var sentinel = {};
    var stringify = function stringify2(object2, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) {
      var obj = object2;
      var tmpSc = sideChannel;
      var step = 0;
      var findFlag = false;
      while ((tmpSc = tmpSc.get(sentinel)) !== void 0 && !findFlag) {
        var pos = tmpSc.get(object2);
        step += 1;
        if (typeof pos !== "undefined") {
          if (pos === step) {
            throw new RangeError("Cyclic object value");
          } else {
            findFlag = true;
          }
        }
        if (typeof tmpSc.get(sentinel) === "undefined") {
          step = 0;
        }
      }
      if (typeof filter === "function") {
        obj = filter(prefix, obj);
      } else if (obj instanceof Date) {
        obj = serializeDate(obj);
      } else if (generateArrayPrefix === "comma" && isArray(obj)) {
        obj = utils.maybeMap(obj, function(value2) {
          if (value2 instanceof Date) {
            return serializeDate(value2);
          }
          return value2;
        });
      }
      if (obj === null) {
        if (strictNullHandling) {
          return encoder && !encodeValuesOnly ? encoder(prefix, defaults2.encoder, charset, "key", format) : prefix;
        }
        obj = "";
      }
      if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) {
        if (encoder) {
          var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults2.encoder, charset, "key", format);
          return [formatter(keyValue) + "=" + formatter(encoder(obj, defaults2.encoder, charset, "value", format))];
        }
        return [formatter(prefix) + "=" + formatter(String(obj))];
      }
      var values = [];
      if (typeof obj === "undefined") {
        return values;
      }
      var objKeys;
      if (generateArrayPrefix === "comma" && isArray(obj)) {
        if (encodeValuesOnly && encoder) {
          obj = utils.maybeMap(obj, encoder);
        }
        objKeys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }];
      } else if (isArray(filter)) {
        objKeys = filter;
      } else {
        var keys = Object.keys(obj);
        objKeys = sort ? keys.sort(sort) : keys;
      }
      var encodedPrefix = encodeDotInKeys ? prefix.replace(/\./g, "%2E") : prefix;
      var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encodedPrefix + "[]" : encodedPrefix;
      if (allowEmptyArrays && isArray(obj) && obj.length === 0) {
        return adjustedPrefix + "[]";
      }
      for (var j = 0; j < objKeys.length; ++j) {
        var key = objKeys[j];
        var value = typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key];
        if (skipNulls && value === null) {
          continue;
        }
        var encodedKey = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key;
        var keyPrefix = isArray(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjustedPrefix, encodedKey) : adjustedPrefix : adjustedPrefix + (allowDots ? "." + encodedKey : "[" + encodedKey + "]");
        sideChannel.set(object2, step);
        var valueSideChannel = getSideChannel();
        valueSideChannel.set(sentinel, sideChannel);
        pushToArray(values, stringify2(
          value,
          keyPrefix,
          generateArrayPrefix,
          commaRoundTrip,
          allowEmptyArrays,
          strictNullHandling,
          skipNulls,
          encodeDotInKeys,
          generateArrayPrefix === "comma" && encodeValuesOnly && isArray(obj) ? null : encoder,
          filter,
          sort,
          allowDots,
          serializeDate,
          format,
          formatter,
          encodeValuesOnly,
          charset,
          valueSideChannel
        ));
      }
      return values;
    };
    var normalizeStringifyOptions = function normalizeStringifyOptions2(opts) {
      if (!opts) {
        return defaults2;
      }
      if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") {
        throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");
      }
      if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") {
        throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");
      }
      if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") {
        throw new TypeError("Encoder has to be a function.");
      }
      var charset = opts.charset || defaults2.charset;
      if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") {
        throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");
      }
      var format = formats["default"];
      if (typeof opts.format !== "undefined") {
        if (!has.call(formats.formatters, opts.format)) {
          throw new TypeError("Unknown format option provided.");
        }
        format = opts.format;
      }
      var formatter = formats.formatters[format];
      var filter = defaults2.filter;
      if (typeof opts.filter === "function" || isArray(opts.filter)) {
        filter = opts.filter;
      }
      var arrayFormat;
      if (opts.arrayFormat in arrayPrefixGenerators) {
        arrayFormat = opts.arrayFormat;
      } else if ("indices" in opts) {
        arrayFormat = opts.indices ? "indices" : "repeat";
      } else {
        arrayFormat = defaults2.arrayFormat;
      }
      if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") {
        throw new TypeError("`commaRoundTrip` must be a boolean, or absent");
      }
      var allowDots = typeof opts.allowDots === "undefined" ? opts.encodeDotInKeys === true ? true : defaults2.allowDots : !!opts.allowDots;
      return {
        addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults2.addQueryPrefix,
        allowDots,
        allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults2.allowEmptyArrays,
        arrayFormat,
        charset,
        charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults2.charsetSentinel,
        commaRoundTrip: opts.commaRoundTrip,
        delimiter: typeof opts.delimiter === "undefined" ? defaults2.delimiter : opts.delimiter,
        encode: typeof opts.encode === "boolean" ? opts.encode : defaults2.encode,
        encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults2.encodeDotInKeys,
        encoder: typeof opts.encoder === "function" ? opts.encoder : defaults2.encoder,
        encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults2.encodeValuesOnly,
        filter,
        format,
        formatter,
        serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults2.serializeDate,
        skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults2.skipNulls,
        sort: typeof opts.sort === "function" ? opts.sort : null,
        strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults2.strictNullHandling
      };
    };
    module.exports = function(object2, opts) {
      var obj = object2;
      var options = normalizeStringifyOptions(opts);
      var objKeys;
      var filter;
      if (typeof options.filter === "function") {
        filter = options.filter;
        obj = filter("", obj);
      } else if (isArray(options.filter)) {
        filter = options.filter;
        objKeys = filter;
      }
      var keys = [];
      if (typeof obj !== "object" || obj === null) {
        return "";
      }
      var generateArrayPrefix = arrayPrefixGenerators[options.arrayFormat];
      var commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip;
      if (!objKeys) {
        objKeys = Object.keys(obj);
      }
      if (options.sort) {
        objKeys.sort(options.sort);
      }
      var sideChannel = getSideChannel();
      for (var i = 0; i < objKeys.length; ++i) {
        var key = objKeys[i];
        if (options.skipNulls && obj[key] === null) {
          continue;
        }
        pushToArray(keys, stringify(
          obj[key],
          key,
          generateArrayPrefix,
          commaRoundTrip,
          options.allowEmptyArrays,
          options.strictNullHandling,
          options.skipNulls,
          options.encodeDotInKeys,
          options.encode ? options.encoder : null,
          options.filter,
          options.sort,
          options.allowDots,
          options.serializeDate,
          options.format,
          options.formatter,
          options.encodeValuesOnly,
          options.charset,
          sideChannel
        ));
      }
      var joined = keys.join(options.delimiter);
      var prefix = options.addQueryPrefix === true ? "?" : "";
      if (options.charsetSentinel) {
        if (options.charset === "iso-8859-1") {
          prefix += "utf8=%26%2310003%3B&";
        } else {
          prefix += "utf8=%E2%9C%93&";
        }
      }
      return joined.length > 0 ? prefix + joined : "";
    };
  }
});

// ../../node_modules/.pnpm/qs@6.13.0/node_modules/qs/lib/parse.js
var require_parse = __commonJS({
  "../../node_modules/.pnpm/qs@6.13.0/node_modules/qs/lib/parse.js"(exports, module) {
    "use strict";
    var utils = require_utils();
    var has = Object.prototype.hasOwnProperty;
    var isArray = Array.isArray;
    var defaults2 = {
      allowDots: false,
      allowEmptyArrays: false,
      allowPrototypes: false,
      allowSparse: false,
      arrayLimit: 20,
      charset: "utf-8",
      charsetSentinel: false,
      comma: false,
      decodeDotInKeys: false,
      decoder: utils.decode,
      delimiter: "&",
      depth: 5,
      duplicates: "combine",
      ignoreQueryPrefix: false,
      interpretNumericEntities: false,
      parameterLimit: 1e3,
      parseArrays: true,
      plainObjects: false,
      strictDepth: false,
      strictNullHandling: false
    };
    var interpretNumericEntities = function(str) {
      return str.replace(/&#(\d+);/g, function($0, numberStr) {
        return String.fromCharCode(parseInt(numberStr, 10));
      });
    };
    var parseArrayValue = function(val, options) {
      if (val && typeof val === "string" && options.comma && val.indexOf(",") > -1) {
        return val.split(",");
      }
      return val;
    };
    var isoSentinel = "utf8=%26%2310003%3B";
    var charsetSentinel = "utf8=%E2%9C%93";
    var parseValues = function parseQueryStringValues(str, options) {
      var obj = { __proto__: null };
      var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, "") : str;
      cleanStr = cleanStr.replace(/%5B/gi, "[").replace(/%5D/gi, "]");
      var limit = options.parameterLimit === Infinity ? void 0 : options.parameterLimit;
      var parts = cleanStr.split(options.delimiter, limit);
      var skipIndex = -1;
      var i;
      var charset = options.charset;
      if (options.charsetSentinel) {
        for (i = 0; i < parts.length; ++i) {
          if (parts[i].indexOf("utf8=") === 0) {
            if (parts[i] === charsetSentinel) {
              charset = "utf-8";
            } else if (parts[i] === isoSentinel) {
              charset = "iso-8859-1";
            }
            skipIndex = i;
            i = parts.length;
          }
        }
      }
      for (i = 0; i < parts.length; ++i) {
        if (i === skipIndex) {
          continue;
        }
        var part = parts[i];
        var bracketEqualsPos = part.indexOf("]=");
        var pos = bracketEqualsPos === -1 ? part.indexOf("=") : bracketEqualsPos + 1;
        var key, val;
        if (pos === -1) {
          key = options.decoder(part, defaults2.decoder, charset, "key");
          val = options.strictNullHandling ? null : "";
        } else {
          key = options.decoder(part.slice(0, pos), defaults2.decoder, charset, "key");
          val = utils.maybeMap(
            parseArrayValue(part.slice(pos + 1), options),
            function(encodedVal) {
              return options.decoder(encodedVal, defaults2.decoder, charset, "value");
            }
          );
        }
        if (val && options.interpretNumericEntities && charset === "iso-8859-1") {
          val = interpretNumericEntities(val);
        }
        if (part.indexOf("[]=") > -1) {
          val = isArray(val) ? [val] : val;
        }
        var existing = has.call(obj, key);
        if (existing && options.duplicates === "combine") {
          obj[key] = utils.combine(obj[key], val);
        } else if (!existing || options.duplicates === "last") {
          obj[key] = val;
        }
      }
      return obj;
    };
    var parseObject = function(chain, val, options, valuesParsed) {
      var leaf = valuesParsed ? val : parseArrayValue(val, options);
      for (var i = chain.length - 1; i >= 0; --i) {
        var obj;
        var root = chain[i];
        if (root === "[]" && options.parseArrays) {
          obj = options.allowEmptyArrays && (leaf === "" || options.strictNullHandling && leaf === null) ? [] : [].concat(leaf);
        } else {
          obj = options.plainObjects ? /* @__PURE__ */ Object.create(null) : {};
          var cleanRoot = root.charAt(0) === "[" && root.charAt(root.length - 1) === "]" ? root.slice(1, -1) : root;
          var decodedRoot = options.decodeDotInKeys ? cleanRoot.replace(/%2E/g, ".") : cleanRoot;
          var index2 = parseInt(decodedRoot, 10);
          if (!options.parseArrays && decodedRoot === "") {
            obj = { 0: leaf };
          } else if (!isNaN(index2) && root !== decodedRoot && String(index2) === decodedRoot && index2 >= 0 && (options.parseArrays && index2 <= options.arrayLimit)) {
            obj = [];
            obj[index2] = leaf;
          } else if (decodedRoot !== "__proto__") {
            obj[decodedRoot] = leaf;
          }
        }
        leaf = obj;
      }
      return leaf;
    };
    var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) {
      if (!givenKey) {
        return;
      }
      var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, "[$1]") : givenKey;
      var brackets = /(\[[^[\]]*])/;
      var child = /(\[[^[\]]*])/g;
      var segment = options.depth > 0 && brackets.exec(key);
      var parent = segment ? key.slice(0, segment.index) : key;
      var keys = [];
      if (parent) {
        if (!options.plainObjects && has.call(Object.prototype, parent)) {
          if (!options.allowPrototypes) {
            return;
          }
        }
        keys.push(parent);
      }
      var i = 0;
      while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) {
        i += 1;
        if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) {
          if (!options.allowPrototypes) {
            return;
          }
        }
        keys.push(segment[1]);
      }
      if (segment) {
        if (options.strictDepth === true) {
          throw new RangeError("Input depth exceeded depth option of " + options.depth + " and strictDepth is true");
        }
        keys.push("[" + key.slice(segment.index) + "]");
      }
      return parseObject(keys, val, options, valuesParsed);
    };
    var normalizeParseOptions = function normalizeParseOptions2(opts) {
      if (!opts) {
        return defaults2;
      }
      if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") {
        throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");
      }
      if (typeof opts.decodeDotInKeys !== "undefined" && typeof opts.decodeDotInKeys !== "boolean") {
        throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");
      }
      if (opts.decoder !== null && typeof opts.decoder !== "undefined" && typeof opts.decoder !== "function") {
        throw new TypeError("Decoder has to be a function.");
      }
      if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") {
        throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");
      }
      var charset = typeof opts.charset === "undefined" ? defaults2.charset : opts.charset;
      var duplicates = typeof opts.duplicates === "undefined" ? defaults2.duplicates : opts.duplicates;
      if (duplicates !== "combine" && duplicates !== "first" && duplicates !== "last") {
        throw new TypeError("The duplicates option must be either combine, first, or last");
      }
      var allowDots = typeof opts.allowDots === "undefined" ? opts.decodeDotInKeys === true ? true : defaults2.allowDots : !!opts.allowDots;
      return {
        allowDots,
        allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults2.allowEmptyArrays,
        allowPrototypes: typeof opts.allowPrototypes === "boolean" ? opts.allowPrototypes : defaults2.allowPrototypes,
        allowSparse: typeof opts.allowSparse === "boolean" ? opts.allowSparse : defaults2.allowSparse,
        arrayLimit: typeof opts.arrayLimit === "number" ? opts.arrayLimit : defaults2.arrayLimit,
        charset,
        charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults2.charsetSentinel,
        comma: typeof opts.comma === "boolean" ? opts.comma : defaults2.comma,
        decodeDotInKeys: typeof opts.decodeDotInKeys === "boolean" ? opts.decodeDotInKeys : defaults2.decodeDotInKeys,
        decoder: typeof opts.decoder === "function" ? opts.decoder : defaults2.decoder,
        delimiter: typeof opts.delimiter === "string" || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults2.delimiter,
        // eslint-disable-next-line no-implicit-coercion, no-extra-parens
        depth: typeof opts.depth === "number" || opts.depth === false ? +opts.depth : defaults2.depth,
        duplicates,
        ignoreQueryPrefix: opts.ignoreQueryPrefix === true,
        interpretNumericEntities: typeof opts.interpretNumericEntities === "boolean" ? opts.interpretNumericEntities : defaults2.interpretNumericEntities,
        parameterLimit: typeof opts.parameterLimit === "number" ? opts.parameterLimit : defaults2.parameterLimit,
        parseArrays: opts.parseArrays !== false,
        plainObjects: typeof opts.plainObjects === "boolean" ? opts.plainObjects : defaults2.plainObjects,
        strictDepth: typeof opts.strictDepth === "boolean" ? !!opts.strictDepth : defaults2.strictDepth,
        strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults2.strictNullHandling
      };
    };
    module.exports = function(str, opts) {
      var options = normalizeParseOptions(opts);
      if (str === "" || str === null || typeof str === "undefined") {
        return options.plainObjects ? /* @__PURE__ */ Object.create(null) : {};
      }
      var tempObj = typeof str === "string" ? parseValues(str, options) : str;
      var obj = options.plainObjects ? /* @__PURE__ */ Object.create(null) : {};
      var keys = Object.keys(tempObj);
      for (var i = 0; i < keys.length; ++i) {
        var key = keys[i];
        var newObj = parseKeys(key, tempObj[key], options, typeof str === "string");
        obj = utils.merge(obj, newObj, options);
      }
      if (options.allowSparse === true) {
        return obj;
      }
      return utils.compact(obj);
    };
  }
});

// ../../node_modules/.pnpm/qs@6.13.0/node_modules/qs/lib/index.js
var require_lib2 = __commonJS({
  "../../node_modules/.pnpm/qs@6.13.0/node_modules/qs/lib/index.js"(exports, module) {
    "use strict";
    var stringify = require_stringify();
    var parse3 = require_parse();
    var formats = require_formats();
    module.exports = {
      formats,
      parse: parse3,
      stringify
    };
  }
});

// ../../node_modules/.pnpm/body-parser@1.20.3/node_modules/body-parser/lib/types/urlencoded.js
var require_urlencoded = __commonJS({
  "../../node_modules/.pnpm/body-parser@1.20.3/node_modules/body-parser/lib/types/urlencoded.js"(exports, module) {
    "use strict";
    var bytes = require_bytes();
    var contentType = require_content_type();
    var createError = require_http_errors();
    var debug = require_src()("body-parser:urlencoded");
    var deprecate = require_depd()("body-parser");
    var read = require_read();
    var typeis = require_type_is();
    module.exports = urlencoded;
    var parsers = /* @__PURE__ */ Object.create(null);
    function urlencoded(options) {
      var opts = options || {};
      if (opts.extended === void 0) {
        deprecate("undefined extended: provide extended option");
      }
      var extended = opts.extended !== false;
      var inflate = opts.inflate !== false;
      var limit = typeof opts.limit !== "number" ? bytes.parse(opts.limit || "100kb") : opts.limit;
      var type = opts.type || "application/x-www-form-urlencoded";
      var verify = opts.verify || false;
      var depth = typeof opts.depth !== "number" ? Number(opts.depth || 32) : opts.depth;
      if (verify !== false && typeof verify !== "function") {
        throw new TypeError("option verify must be function");
      }
      var queryparse = extended ? extendedparser(opts) : simpleparser(opts);
      var shouldParse = typeof type !== "function" ? typeChecker(type) : type;
      function parse3(body) {
        return body.length ? queryparse(body) : {};
      }
      return function urlencodedParser(req, res, next) {
        if (req._body) {
          debug("body already parsed");
          next();
          return;
        }
        req.body = req.body || {};
        if (!typeis.hasBody(req)) {
          debug("skip empty body");
          next();
          return;
        }
        debug("content-type %j", req.headers["content-type"]);
        if (!shouldParse(req)) {
          debug("skip parsing");
          next();
          return;
        }
        var charset = getCharset(req) || "utf-8";
        if (charset !== "utf-8") {
          debug("invalid charset");
          next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', {
            charset,
            type: "charset.unsupported"
          }));
          return;
        }
        read(req, res, next, parse3, debug, {
          debug,
          encoding: charset,
          inflate,
          limit,
          verify,
          depth
        });
      };
    }
    function extendedparser(options) {
      var parameterLimit = options.parameterLimit !== void 0 ? options.parameterLimit : 1e3;
      var depth = typeof options.depth !== "number" ? Number(options.depth || 32) : options.depth;
      var parse3 = parser("qs");
      if (isNaN(parameterLimit) || parameterLimit < 1) {
        throw new TypeError("option parameterLimit must be a positive number");
      }
      if (isNaN(depth) || depth < 0) {
        throw new TypeError("option depth must be a zero or a positive number");
      }
      if (isFinite(parameterLimit)) {
        parameterLimit = parameterLimit | 0;
      }
      return function queryparse(body) {
        var paramCount = parameterCount(body, parameterLimit);
        if (paramCount === void 0) {
          debug("too many parameters");
          throw createError(413, "too many parameters", {
            type: "parameters.too.many"
          });
        }
        var arrayLimit = Math.max(100, paramCount);
        debug("parse extended urlencoding");
        try {
          return parse3(body, {
            allowPrototypes: true,
            arrayLimit,
            depth,
            strictDepth: true,
            parameterLimit
          });
        } catch (err) {
          if (err instanceof RangeError) {
            throw createError(400, "The input exceeded the depth", {
              type: "querystring.parse.rangeError"
            });
          } else {
            throw err;
          }
        }
      };
    }
    function getCharset(req) {
      try {
        return (contentType.parse(req).parameters.charset || "").toLowerCase();
      } catch (e) {
        return void 0;
      }
    }
    function parameterCount(body, limit) {
      var count3 = 0;
      var index2 = 0;
      while ((index2 = body.indexOf("&", index2)) !== -1) {
        count3++;
        index2++;
        if (count3 === limit) {
          return void 0;
        }
      }
      return count3;
    }
    function parser(name) {
      var mod = parsers[name];
      if (mod !== void 0) {
        return mod.parse;
      }
      switch (name) {
        case "qs":
          mod = require_lib2();
          break;
        case "querystring":
          mod = __require("querystring");
          break;
      }
      parsers[name] = mod;
      return mod.parse;
    }
    function simpleparser(options) {
      var parameterLimit = options.parameterLimit !== void 0 ? options.parameterLimit : 1e3;
      var parse3 = parser("querystring");
      if (isNaN(parameterLimit) || parameterLimit < 1) {
        throw new TypeError("option parameterLimit must be a positive number");
      }
      if (isFinite(parameterLimit)) {
        parameterLimit = parameterLimit | 0;
      }
      return function queryparse(body) {
        var paramCount = parameterCount(body, parameterLimit);
        if (paramCount === void 0) {
          debug("too many parameters");
          throw createError(413, "too many parameters", {
            type: "parameters.too.many"
          });
        }
        debug("parse urlencoding");
        return parse3(body, void 0, void 0, { maxKeys: parameterLimit });
      };
    }
    function typeChecker(type) {
      return function checkType(req) {
        return Boolean(typeis(req, type));
      };
    }
  }
});

// ../../node_modules/.pnpm/body-parser@1.20.3/node_modules/body-parser/index.js
var require_body_parser = __commonJS({
  "../../node_modules/.pnpm/body-parser@1.20.3/node_modules/body-parser/index.js"(exports, module) {
    "use strict";
    var deprecate = require_depd()("body-parser");
    var parsers = /* @__PURE__ */ Object.create(null);
    exports = module.exports = deprecate.function(
      bodyParser,
      "bodyParser: use individual json/urlencoded middlewares"
    );
    Object.defineProperty(exports, "json", {
      configurable: true,
      enumerable: true,
      get: createParserGetter("json")
    });
    Object.defineProperty(exports, "raw", {
      configurable: true,
      enumerable: true,
      get: createParserGetter("raw")
    });
    Object.defineProperty(exports, "text", {
      configurable: true,
      enumerable: true,
      get: createParserGetter("text")
    });
    Object.defineProperty(exports, "urlencoded", {
      configurable: true,
      enumerable: true,
      get: createParserGetter("urlencoded")
    });
    function bodyParser(options) {
      var opts = Object.create(options || null, {
        type: {
          configurable: true,
          enumerable: true,
          value: void 0,
          writable: true
        }
      });
      var _urlencoded = exports.urlencoded(opts);
      var _json = exports.json(opts);
      return function bodyParser2(req, res, next) {
        _json(req, res, function(err) {
          if (err) return next(err);
          _urlencoded(req, res, next);
        });
      };
    }
    function createParserGetter(name) {
      return function get() {
        return loadParser(name);
      };
    }
    function loadParser(parserName) {
      var parser = parsers[parserName];
      if (parser !== void 0) {
        return parser;
      }
      switch (parserName) {
        case "json":
          parser = require_json();
          break;
        case "raw":
          parser = require_raw();
          break;
        case "text":
          parser = require_text();
          break;
        case "urlencoded":
          parser = require_urlencoded();
          break;
      }
      return parsers[parserName] = parser;
    }
  }
});

// ../../node_modules/.pnpm/merge-descriptors@1.0.3/node_modules/merge-descriptors/index.js
var require_merge_descriptors = __commonJS({
  "../../node_modules/.pnpm/merge-descriptors@1.0.3/node_modules/merge-descriptors/index.js"(exports, module) {
    "use strict";
    module.exports = merge2;
    var hasOwnProperty = Object.prototype.hasOwnProperty;
    function merge2(dest, src, redefine) {
      if (!dest) {
        throw new TypeError("argument dest is required");
      }
      if (!src) {
        throw new TypeError("argument src is required");
      }
      if (redefine === void 0) {
        redefine = true;
      }
      Object.getOwnPropertyNames(src).forEach(function forEachOwnPropertyName(name) {
        if (!redefine && hasOwnProperty.call(dest, name)) {
          return;
        }
        var descriptor = Object.getOwnPropertyDescriptor(src, name);
        Object.defineProperty(dest, name, descriptor);
      });
      return dest;
    }
  }
});

// ../../node_modules/.pnpm/encodeurl@2.0.0/node_modules/encodeurl/index.js
var require_encodeurl = __commonJS({
  "../../node_modules/.pnpm/encodeurl@2.0.0/node_modules/encodeurl/index.js"(exports, module) {
    "use strict";
    module.exports = encodeUrl;
    var ENCODE_CHARS_REGEXP = /(?:[^\x21\x23-\x3B\x3D\x3F-\x5F\x61-\x7A\x7C\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g;
    var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g;
    var UNMATCHED_SURROGATE_PAIR_REPLACE = "$1\uFFFD$2";
    function encodeUrl(url2) {
      return String(url2).replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE).replace(ENCODE_CHARS_REGEXP, encodeURI);
    }
  }
});

// ../../node_modules/.pnpm/escape-html@1.0.3/node_modules/escape-html/index.js
var require_escape_html = __commonJS({
  "../../node_modules/.pnpm/escape-html@1.0.3/node_modules/escape-html/index.js"(exports, module) {
    "use strict";
    var matchHtmlRegExp = /["'&<>]/;
    module.exports = escapeHtml2;
    function escapeHtml2(string4) {
      var str = "" + string4;
      var match = matchHtmlRegExp.exec(str);
      if (!match) {
        return str;
      }
      var escape2;
      var html = "";
      var index2 = 0;
      var lastIndex = 0;
      for (index2 = match.index; index2 < str.length; index2++) {
        switch (str.charCodeAt(index2)) {
          case 34:
            escape2 = "&quot;";
            break;
          case 38:
            escape2 = "&amp;";
            break;
          case 39:
            escape2 = "&#39;";
            break;
          case 60:
            escape2 = "&lt;";
            break;
          case 62:
            escape2 = "&gt;";
            break;
          default:
            continue;
        }
        if (lastIndex !== index2) {
          html += str.substring(lastIndex, index2);
        }
        lastIndex = index2 + 1;
        html += escape2;
      }
      return lastIndex !== index2 ? html + str.substring(lastIndex, index2) : html;
    }
  }
});

// ../../node_modules/.pnpm/parseurl@1.3.3/node_modules/parseurl/index.js
var require_parseurl = __commonJS({
  "../../node_modules/.pnpm/parseurl@1.3.3/node_modules/parseurl/index.js"(exports, module) {
    "use strict";
    var url2 = __require("url");
    var parse3 = url2.parse;
    var Url = url2.Url;
    module.exports = parseurl;
    module.exports.original = originalurl;
    function parseurl(req) {
      var url3 = req.url;
      if (url3 === void 0) {
        return void 0;
      }
      var parsed = req._parsedUrl;
      if (fresh(url3, parsed)) {
        return parsed;
      }
      parsed = fastparse(url3);
      parsed._raw = url3;
      return req._parsedUrl = parsed;
    }
    function originalurl(req) {
      var url3 = req.originalUrl;
      if (typeof url3 !== "string") {
        return parseurl(req);
      }
      var parsed = req._parsedOriginalUrl;
      if (fresh(url3, parsed)) {
        return parsed;
      }
      parsed = fastparse(url3);
      parsed._raw = url3;
      return req._parsedOriginalUrl = parsed;
    }
    function fastparse(str) {
      if (typeof str !== "string" || str.charCodeAt(0) !== 47) {
        return parse3(str);
      }
      var pathname = str;
      var query = null;
      var search = null;
      for (var i = 1; i < str.length; i++) {
        switch (str.charCodeAt(i)) {
          case 63:
            if (search === null) {
              pathname = str.substring(0, i);
              query = str.substring(i + 1);
              search = str.substring(i);
            }
            break;
          case 9:
          /* \t */
          case 10:
          /* \n */
          case 12:
          /* \f */
          case 13:
          /* \r */
          case 32:
          /*    */
          case 35:
          /* #  */
          case 160:
          case 65279:
            return parse3(str);
        }
      }
      var url3 = Url !== void 0 ? new Url() : {};
      url3.path = str;
      url3.href = str;
      url3.pathname = pathname;
      if (search !== null) {
        url3.query = query;
        url3.search = search;
      }
      return url3;
    }
    function fresh(url3, parsedUrl) {
      return typeof parsedUrl === "object" && parsedUrl !== null && (Url === void 0 || parsedUrl instanceof Url) && parsedUrl._raw === url3;
    }
  }
});

// ../../node_modules/.pnpm/finalhandler@1.3.1/node_modules/finalhandler/index.js
var require_finalhandler = __commonJS({
  "../../node_modules/.pnpm/finalhandler@1.3.1/node_modules/finalhandler/index.js"(exports, module) {
    "use strict";
    var debug = require_src()("finalhandler");
    var encodeUrl = require_encodeurl();
    var escapeHtml2 = require_escape_html();
    var onFinished = require_on_finished();
    var parseUrl = require_parseurl();
    var statuses = require_statuses();
    var unpipe = require_unpipe();
    var DOUBLE_SPACE_REGEXP = /\x20{2}/g;
    var NEWLINE_REGEXP = /\n/g;
    var defer = typeof setImmediate === "function" ? setImmediate : function(fn) {
      process.nextTick(fn.bind.apply(fn, arguments));
    };
    var isFinished = onFinished.isFinished;
    function createHtmlDocument(message) {
      var body = escapeHtml2(message).replace(NEWLINE_REGEXP, "<br>").replace(DOUBLE_SPACE_REGEXP, " &nbsp;");
      return '<!DOCTYPE html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n<title>Error</title>\n</head>\n<body>\n<pre>' + body + "</pre>\n</body>\n</html>\n";
    }
    module.exports = finalhandler;
    function finalhandler(req, res, options) {
      var opts = options || {};
      var env = opts.env || process.env.NODE_ENV || "development";
      var onerror = opts.onerror;
      return function(err) {
        var headers;
        var msg;
        var status;
        if (!err && headersSent(res)) {
          debug("cannot 404 after headers sent");
          return;
        }
        if (err) {
          status = getErrorStatusCode(err);
          if (status === void 0) {
            status = getResponseStatusCode(res);
          } else {
            headers = getErrorHeaders(err);
          }
          msg = getErrorMessage(err, status, env);
        } else {
          status = 404;
          msg = "Cannot " + req.method + " " + encodeUrl(getResourceName(req));
        }
        debug("default %s", status);
        if (err && onerror) {
          defer(onerror, err, req, res);
        }
        if (headersSent(res)) {
          debug("cannot %d after headers sent", status);
          if (req.socket) {
            req.socket.destroy();
          }
          return;
        }
        send(req, res, status, headers, msg);
      };
    }
    function getErrorHeaders(err) {
      if (!err.headers || typeof err.headers !== "object") {
        return void 0;
      }
      var headers = /* @__PURE__ */ Object.create(null);
      var keys = Object.keys(err.headers);
      for (var i = 0; i < keys.length; i++) {
        var key = keys[i];
        headers[key] = err.headers[key];
      }
      return headers;
    }
    function getErrorMessage(err, status, env) {
      var msg;
      if (env !== "production") {
        msg = err.stack;
        if (!msg && typeof err.toString === "function") {
          msg = err.toString();
        }
      }
      return msg || statuses.message[status];
    }
    function getErrorStatusCode(err) {
      if (typeof err.status === "number" && err.status >= 400 && err.status < 600) {
        return err.status;
      }
      if (typeof err.statusCode === "number" && err.statusCode >= 400 && err.statusCode < 600) {
        return err.statusCode;
      }
      return void 0;
    }
    function getResourceName(req) {
      try {
        return parseUrl.original(req).pathname;
      } catch (e) {
        return "resource";
      }
    }
    function getResponseStatusCode(res) {
      var status = res.statusCode;
      if (typeof status !== "number" || status < 400 || status > 599) {
        status = 500;
      }
      return status;
    }
    function headersSent(res) {
      return typeof res.headersSent !== "boolean" ? Boolean(res._header) : res.headersSent;
    }
    function send(req, res, status, headers, message) {
      function write() {
        var body = createHtmlDocument(message);
        res.statusCode = status;
        if (req.httpVersionMajor < 2) {
          res.statusMessage = statuses.message[status];
        }
        res.removeHeader("Content-Encoding");
        res.removeHeader("Content-Language");
        res.removeHeader("Content-Range");
        setHeaders(res, headers);
        res.setHeader("Content-Security-Policy", "default-src 'none'");
        res.setHeader("X-Content-Type-Options", "nosniff");
        res.setHeader("Content-Type", "text/html; charset=utf-8");
        res.setHeader("Content-Length", Buffer.byteLength(body, "utf8"));
        if (req.method === "HEAD") {
          res.end();
          return;
        }
        res.end(body, "utf8");
      }
      if (isFinished(req)) {
        write();
        return;
      }
      unpipe(req);
      onFinished(req, write);
      req.resume();
    }
    function setHeaders(res, headers) {
      if (!headers) {
        return;
      }
      var keys = Object.keys(headers);
      for (var i = 0; i < keys.length; i++) {
        var key = keys[i];
        res.setHeader(key, headers[key]);
      }
    }
  }
});

// ../../node_modules/.pnpm/array-flatten@1.1.1/node_modules/array-flatten/array-flatten.js
var require_array_flatten = __commonJS({
  "../../node_modules/.pnpm/array-flatten@1.1.1/node_modules/array-flatten/array-flatten.js"(exports, module) {
    "use strict";
    module.exports = arrayFlatten;
    function flattenWithDepth(array2, result, depth) {
      for (var i = 0; i < array2.length; i++) {
        var value = array2[i];
        if (depth > 0 && Array.isArray(value)) {
          flattenWithDepth(value, result, depth - 1);
        } else {
          result.push(value);
        }
      }
      return result;
    }
    function flattenForever(array2, result) {
      for (var i = 0; i < array2.length; i++) {
        var value = array2[i];
        if (Array.isArray(value)) {
          flattenForever(value, result);
        } else {
          result.push(value);
        }
      }
      return result;
    }
    function arrayFlatten(array2, depth) {
      if (depth == null) {
        return flattenForever(array2, []);
      }
      return flattenWithDepth(array2, [], depth);
    }
  }
});

// ../../node_modules/.pnpm/path-to-regexp@0.1.12/node_modules/path-to-regexp/index.js
var require_path_to_regexp = __commonJS({
  "../../node_modules/.pnpm/path-to-regexp@0.1.12/node_modules/path-to-regexp/index.js"(exports, module) {
    module.exports = pathToRegexp;
    var MATCHING_GROUP_REGEXP = /\\.|\((?:\?<(.*?)>)?(?!\?)/g;
    function pathToRegexp(path4, keys, options) {
      options = options || {};
      keys = keys || [];
      var strict = options.strict;
      var end = options.end !== false;
      var flags = options.sensitive ? "" : "i";
      var lookahead = options.lookahead !== false;
      var extraOffset = 0;
      var keysOffset = keys.length;
      var i = 0;
      var name = 0;
      var pos = 0;
      var backtrack = "";
      var m;
      if (path4 instanceof RegExp) {
        while (m = MATCHING_GROUP_REGEXP.exec(path4.source)) {
          if (m[0][0] === "\\") continue;
          keys.push({
            name: m[1] || name++,
            optional: false,
            offset: m.index
          });
        }
        return path4;
      }
      if (Array.isArray(path4)) {
        path4 = path4.map(function(value) {
          return pathToRegexp(value, keys, options).source;
        });
        return new RegExp(path4.join("|"), flags);
      }
      if (typeof path4 !== "string") {
        throw new TypeError("path must be a string, array of strings, or regular expression");
      }
      path4 = path4.replace(
        /\\.|(\/)?(\.)?:(\w+)(\(.*?\))?(\*)?(\?)?|[.*]|\/\(/g,
        function(match, slash, format, key, capture, star, optional2, offset) {
          if (match[0] === "\\") {
            backtrack += match;
            pos += 2;
            return match;
          }
          if (match === ".") {
            backtrack += "\\.";
            extraOffset += 1;
            pos += 1;
            return "\\.";
          }
          if (slash || format) {
            backtrack = "";
          } else {
            backtrack += path4.slice(pos, offset);
          }
          pos = offset + match.length;
          if (match === "*") {
            extraOffset += 3;
            return "(.*)";
          }
          if (match === "/(") {
            backtrack += "/";
            extraOffset += 2;
            return "/(?:";
          }
          slash = slash || "";
          format = format ? "\\." : "";
          optional2 = optional2 || "";
          capture = capture ? capture.replace(/\\.|\*/, function(m2) {
            return m2 === "*" ? "(.*)" : m2;
          }) : backtrack ? "((?:(?!/|" + backtrack + ").)+?)" : "([^/" + format + "]+?)";
          keys.push({
            name: key,
            optional: !!optional2,
            offset: offset + extraOffset
          });
          var result = "(?:" + format + slash + capture + (star ? "((?:[/" + format + "].+?)?)" : "") + ")" + optional2;
          extraOffset += result.length - match.length;
          return result;
        }
      );
      while (m = MATCHING_GROUP_REGEXP.exec(path4)) {
        if (m[0][0] === "\\") continue;
        if (keysOffset + i === keys.length || keys[keysOffset + i].offset > m.index) {
          keys.splice(keysOffset + i, 0, {
            name: name++,
            // Unnamed matching groups must be consistently linear.
            optional: false,
            offset: m.index
          });
        }
        i++;
      }
      path4 += strict ? "" : path4[path4.length - 1] === "/" ? "?" : "/?";
      if (end) {
        path4 += "$";
      } else if (path4[path4.length - 1] !== "/") {
        path4 += lookahead ? "(?=/|$)" : "(?:/|$)";
      }
      return new RegExp("^" + path4, flags);
    }
  }
});

// ../../node_modules/.pnpm/express@4.21.2/node_modules/express/lib/router/layer.js
var require_layer = __commonJS({
  "../../node_modules/.pnpm/express@4.21.2/node_modules/express/lib/router/layer.js"(exports, module) {
    "use strict";
    var pathRegexp = require_path_to_regexp();
    var debug = require_src()("express:router:layer");
    var hasOwnProperty = Object.prototype.hasOwnProperty;
    module.exports = Layer;
    function Layer(path4, options, fn) {
      if (!(this instanceof Layer)) {
        return new Layer(path4, options, fn);
      }
      debug("new %o", path4);
      var opts = options || {};
      this.handle = fn;
      this.name = fn.name || "<anonymous>";
      this.params = void 0;
      this.path = void 0;
      this.regexp = pathRegexp(path4, this.keys = [], opts);
      this.regexp.fast_star = path4 === "*";
      this.regexp.fast_slash = path4 === "/" && opts.end === false;
    }
    Layer.prototype.handle_error = function handle_error(error40, req, res, next) {
      var fn = this.handle;
      if (fn.length !== 4) {
        return next(error40);
      }
      try {
        fn(error40, req, res, next);
      } catch (err) {
        next(err);
      }
    };
    Layer.prototype.handle_request = function handle(req, res, next) {
      var fn = this.handle;
      if (fn.length > 3) {
        return next();
      }
      try {
        fn(req, res, next);
      } catch (err) {
        next(err);
      }
    };
    Layer.prototype.match = function match(path4) {
      var match2;
      if (path4 != null) {
        if (this.regexp.fast_slash) {
          this.params = {};
          this.path = "";
          return true;
        }
        if (this.regexp.fast_star) {
          this.params = { "0": decode_param(path4) };
          this.path = path4;
          return true;
        }
        match2 = this.regexp.exec(path4);
      }
      if (!match2) {
        this.params = void 0;
        this.path = void 0;
        return false;
      }
      this.params = {};
      this.path = match2[0];
      var keys = this.keys;
      var params = this.params;
      for (var i = 1; i < match2.length; i++) {
        var key = keys[i - 1];
        var prop = key.name;
        var val = decode_param(match2[i]);
        if (val !== void 0 || !hasOwnProperty.call(params, prop)) {
          params[prop] = val;
        }
      }
      return true;
    };
    function decode_param(val) {
      if (typeof val !== "string" || val.length === 0) {
        return val;
      }
      try {
        return decodeURIComponent(val);
      } catch (err) {
        if (err instanceof URIError) {
          err.message = "Failed to decode param '" + val + "'";
          err.status = err.statusCode = 400;
        }
        throw err;
      }
    }
  }
});

// ../../node_modules/.pnpm/methods@1.1.2/node_modules/methods/index.js
var require_methods = __commonJS({
  "../../node_modules/.pnpm/methods@1.1.2/node_modules/methods/index.js"(exports, module) {
    "use strict";
    var http2 = __require("http");
    module.exports = getCurrentNodeMethods() || getBasicNodeMethods();
    function getCurrentNodeMethods() {
      return http2.METHODS && http2.METHODS.map(function lowerCaseMethod(method) {
        return method.toLowerCase();
      });
    }
    function getBasicNodeMethods() {
      return [
        "get",
        "post",
        "put",
        "head",
        "delete",
        "options",
        "trace",
        "copy",
        "lock",
        "mkcol",
        "move",
        "purge",
        "propfind",
        "proppatch",
        "unlock",
        "report",
        "mkactivity",
        "checkout",
        "merge",
        "m-search",
        "notify",
        "subscribe",
        "unsubscribe",
        "patch",
        "search",
        "connect"
      ];
    }
  }
});

// ../../node_modules/.pnpm/express@4.21.2/node_modules/express/lib/router/route.js
var require_route = __commonJS({
  "../../node_modules/.pnpm/express@4.21.2/node_modules/express/lib/router/route.js"(exports, module) {
    "use strict";
    var debug = require_src()("express:router:route");
    var flatten = require_array_flatten();
    var Layer = require_layer();
    var methods = require_methods();
    var slice = Array.prototype.slice;
    var toString = Object.prototype.toString;
    module.exports = Route;
    function Route(path4) {
      this.path = path4;
      this.stack = [];
      debug("new %o", path4);
      this.methods = {};
    }
    Route.prototype._handles_method = function _handles_method(method) {
      if (this.methods._all) {
        return true;
      }
      var name = typeof method === "string" ? method.toLowerCase() : method;
      if (name === "head" && !this.methods["head"]) {
        name = "get";
      }
      return Boolean(this.methods[name]);
    };
    Route.prototype._options = function _options() {
      var methods2 = Object.keys(this.methods);
      if (this.methods.get && !this.methods.head) {
        methods2.push("head");
      }
      for (var i = 0; i < methods2.length; i++) {
        methods2[i] = methods2[i].toUpperCase();
      }
      return methods2;
    };
    Route.prototype.dispatch = function dispatch(req, res, done) {
      var idx = 0;
      var stack = this.stack;
      var sync = 0;
      if (stack.length === 0) {
        return done();
      }
      var method = typeof req.method === "string" ? req.method.toLowerCase() : req.method;
      if (method === "head" && !this.methods["head"]) {
        method = "get";
      }
      req.route = this;
      next();
      function next(err) {
        if (err && err === "route") {
          return done();
        }
        if (err && err === "router") {
          return done(err);
        }
        if (++sync > 100) {
          return setImmediate(next, err);
        }
        var layer = stack[idx++];
        if (!layer) {
          return done(err);
        }
        if (layer.method && layer.method !== method) {
          next(err);
        } else if (err) {
          layer.handle_error(err, req, res, next);
        } else {
          layer.handle_request(req, res, next);
        }
        sync = 0;
      }
    };
    Route.prototype.all = function all() {
      var handles = flatten(slice.call(arguments));
      for (var i = 0; i < handles.length; i++) {
        var handle = handles[i];
        if (typeof handle !== "function") {
          var type = toString.call(handle);
          var msg = "Route.all() requires a callback function but got a " + type;
          throw new TypeError(msg);
        }
        var layer = Layer("/", {}, handle);
        layer.method = void 0;
        this.methods._all = true;
        this.stack.push(layer);
      }
      return this;
    };
    methods.forEach(function(method) {
      Route.prototype[method] = function() {
        var handles = flatten(slice.call(arguments));
        for (var i = 0; i < handles.length; i++) {
          var handle = handles[i];
          if (typeof handle !== "function") {
            var type = toString.call(handle);
            var msg = "Route." + method + "() requires a callback function but got a " + type;
            throw new Error(msg);
          }
          debug("%s %o", method, this.path);
          var layer = Layer("/", {}, handle);
          layer.method = method;
          this.methods[method] = true;
          this.stack.push(layer);
        }
        return this;
      };
    });
  }
});

// ../../node_modules/.pnpm/utils-merge@1.0.1/node_modules/utils-merge/index.js
var require_utils_merge = __commonJS({
  "../../node_modules/.pnpm/utils-merge@1.0.1/node_modules/utils-merge/index.js"(exports, module) {
    exports = module.exports = function(a, b) {
      if (a && b) {
        for (var key in b) {
          a[key] = b[key];
        }
      }
      return a;
    };
  }
});

// ../../node_modules/.pnpm/express@4.21.2/node_modules/express/lib/router/index.js
var require_router = __commonJS({
  "../../node_modules/.pnpm/express@4.21.2/node_modules/express/lib/router/index.js"(exports, module) {
    "use strict";
    var Route = require_route();
    var Layer = require_layer();
    var methods = require_methods();
    var mixin = require_utils_merge();
    var debug = require_src()("express:router");
    var deprecate = require_depd()("express");
    var flatten = require_array_flatten();
    var parseUrl = require_parseurl();
    var setPrototypeOf = require_setprototypeof();
    var objectRegExp = /^\[object (\S+)\]$/;
    var slice = Array.prototype.slice;
    var toString = Object.prototype.toString;
    var proto = module.exports = function(options) {
      var opts = options || {};
      function router16(req, res, next) {
        router16.handle(req, res, next);
      }
      setPrototypeOf(router16, proto);
      router16.params = {};
      router16._params = [];
      router16.caseSensitive = opts.caseSensitive;
      router16.mergeParams = opts.mergeParams;
      router16.strict = opts.strict;
      router16.stack = [];
      return router16;
    };
    proto.param = function param(name, fn) {
      if (typeof name === "function") {
        deprecate("router.param(fn): Refactor to use path params");
        this._params.push(name);
        return;
      }
      var params = this._params;
      var len = params.length;
      var ret;
      if (name[0] === ":") {
        deprecate("router.param(" + JSON.stringify(name) + ", fn): Use router.param(" + JSON.stringify(name.slice(1)) + ", fn) instead");
        name = name.slice(1);
      }
      for (var i = 0; i < len; ++i) {
        if (ret = params[i](name, fn)) {
          fn = ret;
        }
      }
      if ("function" !== typeof fn) {
        throw new Error("invalid param() call for " + name + ", got " + fn);
      }
      (this.params[name] = this.params[name] || []).push(fn);
      return this;
    };
    proto.handle = function handle(req, res, out) {
      var self = this;
      debug("dispatching %s %s", req.method, req.url);
      var idx = 0;
      var protohost = getProtohost(req.url) || "";
      var removed = "";
      var slashAdded = false;
      var sync = 0;
      var paramcalled = {};
      var options = [];
      var stack = self.stack;
      var parentParams = req.params;
      var parentUrl = req.baseUrl || "";
      var done = restore(out, req, "baseUrl", "next", "params");
      req.next = next;
      if (req.method === "OPTIONS") {
        done = wrap(done, function(old, err) {
          if (err || options.length === 0) return old(err);
          sendOptionsResponse(res, options, old);
        });
      }
      req.baseUrl = parentUrl;
      req.originalUrl = req.originalUrl || req.url;
      next();
      function next(err) {
        var layerError = err === "route" ? null : err;
        if (slashAdded) {
          req.url = req.url.slice(1);
          slashAdded = false;
        }
        if (removed.length !== 0) {
          req.baseUrl = parentUrl;
          req.url = protohost + removed + req.url.slice(protohost.length);
          removed = "";
        }
        if (layerError === "router") {
          setImmediate(done, null);
          return;
        }
        if (idx >= stack.length) {
          setImmediate(done, layerError);
          return;
        }
        if (++sync > 100) {
          return setImmediate(next, err);
        }
        var path4 = getPathname(req);
        if (path4 == null) {
          return done(layerError);
        }
        var layer;
        var match;
        var route;
        while (match !== true && idx < stack.length) {
          layer = stack[idx++];
          match = matchLayer(layer, path4);
          route = layer.route;
          if (typeof match !== "boolean") {
            layerError = layerError || match;
          }
          if (match !== true) {
            continue;
          }
          if (!route) {
            continue;
          }
          if (layerError) {
            match = false;
            continue;
          }
          var method = req.method;
          var has_method = route._handles_method(method);
          if (!has_method && method === "OPTIONS") {
            appendMethods(options, route._options());
          }
          if (!has_method && method !== "HEAD") {
            match = false;
          }
        }
        if (match !== true) {
          return done(layerError);
        }
        if (route) {
          req.route = route;
        }
        req.params = self.mergeParams ? mergeParams(layer.params, parentParams) : layer.params;
        var layerPath = layer.path;
        self.process_params(layer, paramcalled, req, res, function(err2) {
          if (err2) {
            next(layerError || err2);
          } else if (route) {
            layer.handle_request(req, res, next);
          } else {
            trim_prefix(layer, layerError, layerPath, path4);
          }
          sync = 0;
        });
      }
      function trim_prefix(layer, layerError, layerPath, path4) {
        if (layerPath.length !== 0) {
          if (layerPath !== path4.slice(0, layerPath.length)) {
            next(layerError);
            return;
          }
          var c = path4[layerPath.length];
          if (c && c !== "/" && c !== ".") return next(layerError);
          debug("trim prefix (%s) from url %s", layerPath, req.url);
          removed = layerPath;
          req.url = protohost + req.url.slice(protohost.length + removed.length);
          if (!protohost && req.url[0] !== "/") {
            req.url = "/" + req.url;
            slashAdded = true;
          }
          req.baseUrl = parentUrl + (removed[removed.length - 1] === "/" ? removed.substring(0, removed.length - 1) : removed);
        }
        debug("%s %s : %s", layer.name, layerPath, req.originalUrl);
        if (layerError) {
          layer.handle_error(layerError, req, res, next);
        } else {
          layer.handle_request(req, res, next);
        }
      }
    };
    proto.process_params = function process_params(layer, called, req, res, done) {
      var params = this.params;
      var keys = layer.keys;
      if (!keys || keys.length === 0) {
        return done();
      }
      var i = 0;
      var name;
      var paramIndex = 0;
      var key;
      var paramVal;
      var paramCallbacks;
      var paramCalled;
      function param(err) {
        if (err) {
          return done(err);
        }
        if (i >= keys.length) {
          return done();
        }
        paramIndex = 0;
        key = keys[i++];
        name = key.name;
        paramVal = req.params[name];
        paramCallbacks = params[name];
        paramCalled = called[name];
        if (paramVal === void 0 || !paramCallbacks) {
          return param();
        }
        if (paramCalled && (paramCalled.match === paramVal || paramCalled.error && paramCalled.error !== "route")) {
          req.params[name] = paramCalled.value;
          return param(paramCalled.error);
        }
        called[name] = paramCalled = {
          error: null,
          match: paramVal,
          value: paramVal
        };
        paramCallback();
      }
      function paramCallback(err) {
        var fn = paramCallbacks[paramIndex++];
        paramCalled.value = req.params[key.name];
        if (err) {
          paramCalled.error = err;
          param(err);
          return;
        }
        if (!fn) return param();
        try {
          fn(req, res, paramCallback, paramVal, key.name);
        } catch (e) {
          paramCallback(e);
        }
      }
      param();
    };
    proto.use = function use(fn) {
      var offset = 0;
      var path4 = "/";
      if (typeof fn !== "function") {
        var arg = fn;
        while (Array.isArray(arg) && arg.length !== 0) {
          arg = arg[0];
        }
        if (typeof arg !== "function") {
          offset = 1;
          path4 = fn;
        }
      }
      var callbacks = flatten(slice.call(arguments, offset));
      if (callbacks.length === 0) {
        throw new TypeError("Router.use() requires a middleware function");
      }
      for (var i = 0; i < callbacks.length; i++) {
        var fn = callbacks[i];
        if (typeof fn !== "function") {
          throw new TypeError("Router.use() requires a middleware function but got a " + gettype(fn));
        }
        debug("use %o %s", path4, fn.name || "<anonymous>");
        var layer = new Layer(path4, {
          sensitive: this.caseSensitive,
          strict: false,
          end: false
        }, fn);
        layer.route = void 0;
        this.stack.push(layer);
      }
      return this;
    };
    proto.route = function route(path4) {
      var route2 = new Route(path4);
      var layer = new Layer(path4, {
        sensitive: this.caseSensitive,
        strict: this.strict,
        end: true
      }, route2.dispatch.bind(route2));
      layer.route = route2;
      this.stack.push(layer);
      return route2;
    };
    methods.concat("all").forEach(function(method) {
      proto[method] = function(path4) {
        var route = this.route(path4);
        route[method].apply(route, slice.call(arguments, 1));
        return this;
      };
    });
    function appendMethods(list, addition) {
      for (var i = 0; i < addition.length; i++) {
        var method = addition[i];
        if (list.indexOf(method) === -1) {
          list.push(method);
        }
      }
    }
    function getPathname(req) {
      try {
        return parseUrl(req).pathname;
      } catch (err) {
        return void 0;
      }
    }
    function getProtohost(url2) {
      if (typeof url2 !== "string" || url2.length === 0 || url2[0] === "/") {
        return void 0;
      }
      var searchIndex = url2.indexOf("?");
      var pathLength = searchIndex !== -1 ? searchIndex : url2.length;
      var fqdnIndex = url2.slice(0, pathLength).indexOf("://");
      return fqdnIndex !== -1 ? url2.substring(0, url2.indexOf("/", 3 + fqdnIndex)) : void 0;
    }
    function gettype(obj) {
      var type = typeof obj;
      if (type !== "object") {
        return type;
      }
      return toString.call(obj).replace(objectRegExp, "$1");
    }
    function matchLayer(layer, path4) {
      try {
        return layer.match(path4);
      } catch (err) {
        return err;
      }
    }
    function mergeParams(params, parent) {
      if (typeof parent !== "object" || !parent) {
        return params;
      }
      var obj = mixin({}, parent);
      if (!(0 in params) || !(0 in parent)) {
        return mixin(obj, params);
      }
      var i = 0;
      var o = 0;
      while (i in params) {
        i++;
      }
      while (o in parent) {
        o++;
      }
      for (i--; i >= 0; i--) {
        params[i + o] = params[i];
        if (i < o) {
          delete params[i];
        }
      }
      return mixin(obj, params);
    }
    function restore(fn, obj) {
      var props = new Array(arguments.length - 2);
      var vals = new Array(arguments.length - 2);
      for (var i = 0; i < props.length; i++) {
        props[i] = arguments[i + 2];
        vals[i] = obj[props[i]];
      }
      return function() {
        for (var i2 = 0; i2 < props.length; i2++) {
          obj[props[i2]] = vals[i2];
        }
        return fn.apply(this, arguments);
      };
    }
    function sendOptionsResponse(res, options, next) {
      try {
        var body = options.join(",");
        res.set("Allow", body);
        res.send(body);
      } catch (err) {
        next(err);
      }
    }
    function wrap(old, fn) {
      return function proxy() {
        var args = new Array(arguments.length + 1);
        args[0] = old;
        for (var i = 0, len = arguments.length; i < len; i++) {
          args[i + 1] = arguments[i];
        }
        fn.apply(this, args);
      };
    }
  }
});

// ../../node_modules/.pnpm/express@4.21.2/node_modules/express/lib/middleware/init.js
var require_init = __commonJS({
  "../../node_modules/.pnpm/express@4.21.2/node_modules/express/lib/middleware/init.js"(exports) {
    "use strict";
    var setPrototypeOf = require_setprototypeof();
    exports.init = function(app3) {
      return function expressInit(req, res, next) {
        if (app3.enabled("x-powered-by")) res.setHeader("X-Powered-By", "Express");
        req.res = res;
        res.req = req;
        req.next = next;
        setPrototypeOf(req, app3.request);
        setPrototypeOf(res, app3.response);
        res.locals = res.locals || /* @__PURE__ */ Object.create(null);
        next();
      };
    };
  }
});

// ../../node_modules/.pnpm/express@4.21.2/node_modules/express/lib/middleware/query.js
var require_query = __commonJS({
  "../../node_modules/.pnpm/express@4.21.2/node_modules/express/lib/middleware/query.js"(exports, module) {
    "use strict";
    var merge2 = require_utils_merge();
    var parseUrl = require_parseurl();
    var qs = require_lib2();
    module.exports = function query(options) {
      var opts = merge2({}, options);
      var queryparse = qs.parse;
      if (typeof options === "function") {
        queryparse = options;
        opts = void 0;
      }
      if (opts !== void 0 && opts.allowPrototypes === void 0) {
        opts.allowPrototypes = true;
      }
      return function query2(req, res, next) {
        if (!req.query) {
          var val = parseUrl(req).query;
          req.query = queryparse(val, opts);
        }
        next();
      };
    };
  }
});

// ../../node_modules/.pnpm/express@4.21.2/node_modules/express/lib/view.js
var require_view = __commonJS({
  "../../node_modules/.pnpm/express@4.21.2/node_modules/express/lib/view.js"(exports, module) {
    "use strict";
    var debug = require_src()("express:view");
    var path4 = __require("path");
    var fs2 = __require("fs");
    var dirname = path4.dirname;
    var basename = path4.basename;
    var extname = path4.extname;
    var join = path4.join;
    var resolve = path4.resolve;
    module.exports = View2;
    function View2(name, options) {
      var opts = options || {};
      this.defaultEngine = opts.defaultEngine;
      this.ext = extname(name);
      this.name = name;
      this.root = opts.root;
      if (!this.ext && !this.defaultEngine) {
        throw new Error("No default engine was specified and no extension was provided.");
      }
      var fileName = name;
      if (!this.ext) {
        this.ext = this.defaultEngine[0] !== "." ? "." + this.defaultEngine : this.defaultEngine;
        fileName += this.ext;
      }
      if (!opts.engines[this.ext]) {
        var mod = this.ext.slice(1);
        debug('require "%s"', mod);
        var fn = __require(mod).__express;
        if (typeof fn !== "function") {
          throw new Error('Module "' + mod + '" does not provide a view engine.');
        }
        opts.engines[this.ext] = fn;
      }
      this.engine = opts.engines[this.ext];
      this.path = this.lookup(fileName);
    }
    View2.prototype.lookup = function lookup(name) {
      var path5;
      var roots = [].concat(this.root);
      debug('lookup "%s"', name);
      for (var i = 0; i < roots.length && !path5; i++) {
        var root = roots[i];
        var loc = resolve(root, name);
        var dir = dirname(loc);
        var file2 = basename(loc);
        path5 = this.resolve(dir, file2);
      }
      return path5;
    };
    View2.prototype.render = function render(options, callback) {
      debug('render "%s"', this.path);
      this.engine(this.path, options, callback);
    };
    View2.prototype.resolve = function resolve2(dir, file2) {
      var ext = this.ext;
      var path5 = join(dir, file2);
      var stat = tryStat(path5);
      if (stat && stat.isFile()) {
        return path5;
      }
      path5 = join(dir, basename(file2, ext), "index" + ext);
      stat = tryStat(path5);
      if (stat && stat.isFile()) {
        return path5;
      }
    };
    function tryStat(path5) {
      debug('stat "%s"', path5);
      try {
        return fs2.statSync(path5);
      } catch (e) {
        return void 0;
      }
    }
  }
});

// ../../node_modules/.pnpm/safe-buffer@5.2.1/node_modules/safe-buffer/index.js
var require_safe_buffer = __commonJS({
  "../../node_modules/.pnpm/safe-buffer@5.2.1/node_modules/safe-buffer/index.js"(exports, module) {
    var buffer = __require("buffer");
    var Buffer3 = buffer.Buffer;
    function copyProps(src, dst) {
      for (var key in src) {
        dst[key] = src[key];
      }
    }
    if (Buffer3.from && Buffer3.alloc && Buffer3.allocUnsafe && Buffer3.allocUnsafeSlow) {
      module.exports = buffer;
    } else {
      copyProps(buffer, exports);
      exports.Buffer = SafeBuffer;
    }
    function SafeBuffer(arg, encodingOrOffset, length) {
      return Buffer3(arg, encodingOrOffset, length);
    }
    SafeBuffer.prototype = Object.create(Buffer3.prototype);
    copyProps(Buffer3, SafeBuffer);
    SafeBuffer.from = function(arg, encodingOrOffset, length) {
      if (typeof arg === "number") {
        throw new TypeError("Argument must not be a number");
      }
      return Buffer3(arg, encodingOrOffset, length);
    };
    SafeBuffer.alloc = function(size, fill, encoding) {
      if (typeof size !== "number") {
        throw new TypeError("Argument must be a number");
      }
      var buf = Buffer3(size);
      if (fill !== void 0) {
        if (typeof encoding === "string") {
          buf.fill(fill, encoding);
        } else {
          buf.fill(fill);
        }
      } else {
        buf.fill(0);
      }
      return buf;
    };
    SafeBuffer.allocUnsafe = function(size) {
      if (typeof size !== "number") {
        throw new TypeError("Argument must be a number");
      }
      return Buffer3(size);
    };
    SafeBuffer.allocUnsafeSlow = function(size) {
      if (typeof size !== "number") {
        throw new TypeError("Argument must be a number");
      }
      return buffer.SlowBuffer(size);
    };
  }
});

// ../../node_modules/.pnpm/content-disposition@0.5.4/node_modules/content-disposition/index.js
var require_content_disposition = __commonJS({
  "../../node_modules/.pnpm/content-disposition@0.5.4/node_modules/content-disposition/index.js"(exports, module) {
    "use strict";
    module.exports = contentDisposition;
    module.exports.parse = parse3;
    var basename = __require("path").basename;
    var Buffer3 = require_safe_buffer().Buffer;
    var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g;
    var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/;
    var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g;
    var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g;
    var QESC_REGEXP = /\\([\u0000-\u007f])/g;
    var QUOTE_REGEXP = /([\\"])/g;
    var PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g;
    var TEXT_REGEXP = /^[\x20-\x7e\x80-\xff]+$/;
    var TOKEN_REGEXP = /^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/;
    var EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/;
    var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/;
    function contentDisposition(filename, options) {
      var opts = options || {};
      var type = opts.type || "attachment";
      var params = createparams(filename, opts.fallback);
      return format(new ContentDisposition(type, params));
    }
    function createparams(filename, fallback) {
      if (filename === void 0) {
        return;
      }
      var params = {};
      if (typeof filename !== "string") {
        throw new TypeError("filename must be a string");
      }
      if (fallback === void 0) {
        fallback = true;
      }
      if (typeof fallback !== "string" && typeof fallback !== "boolean") {
        throw new TypeError("fallback must be a string or boolean");
      }
      if (typeof fallback === "string" && NON_LATIN1_REGEXP.test(fallback)) {
        throw new TypeError("fallback must be ISO-8859-1 string");
      }
      var name = basename(filename);
      var isQuotedString = TEXT_REGEXP.test(name);
      var fallbackName = typeof fallback !== "string" ? fallback && getlatin1(name) : basename(fallback);
      var hasFallback = typeof fallbackName === "string" && fallbackName !== name;
      if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name)) {
        params["filename*"] = name;
      }
      if (isQuotedString || hasFallback) {
        params.filename = hasFallback ? fallbackName : name;
      }
      return params;
    }
    function format(obj) {
      var parameters = obj.parameters;
      var type = obj.type;
      if (!type || typeof type !== "string" || !TOKEN_REGEXP.test(type)) {
        throw new TypeError("invalid type");
      }
      var string4 = String(type).toLowerCase();
      if (parameters && typeof parameters === "object") {
        var param;
        var params = Object.keys(parameters).sort();
        for (var i = 0; i < params.length; i++) {
          param = params[i];
          var val = param.substr(-1) === "*" ? ustring(parameters[param]) : qstring(parameters[param]);
          string4 += "; " + param + "=" + val;
        }
      }
      return string4;
    }
    function decodefield(str) {
      var match = EXT_VALUE_REGEXP.exec(str);
      if (!match) {
        throw new TypeError("invalid extended field value");
      }
      var charset = match[1].toLowerCase();
      var encoded = match[2];
      var value;
      var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode);
      switch (charset) {
        case "iso-8859-1":
          value = getlatin1(binary);
          break;
        case "utf-8":
          value = Buffer3.from(binary, "binary").toString("utf8");
          break;
        default:
          throw new TypeError("unsupported charset in extended field");
      }
      return value;
    }
    function getlatin1(val) {
      return String(val).replace(NON_LATIN1_REGEXP, "?");
    }
    function parse3(string4) {
      if (!string4 || typeof string4 !== "string") {
        throw new TypeError("argument string is required");
      }
      var match = DISPOSITION_TYPE_REGEXP.exec(string4);
      if (!match) {
        throw new TypeError("invalid type format");
      }
      var index2 = match[0].length;
      var type = match[1].toLowerCase();
      var key;
      var names = [];
      var params = {};
      var value;
      index2 = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ";" ? index2 - 1 : index2;
      while (match = PARAM_REGEXP.exec(string4)) {
        if (match.index !== index2) {
          throw new TypeError("invalid parameter format");
        }
        index2 += match[0].length;
        key = match[1].toLowerCase();
        value = match[2];
        if (names.indexOf(key) !== -1) {
          throw new TypeError("invalid duplicate parameter");
        }
        names.push(key);
        if (key.indexOf("*") + 1 === key.length) {
          key = key.slice(0, -1);
          value = decodefield(value);
          params[key] = value;
          continue;
        }
        if (typeof params[key] === "string") {
          continue;
        }
        if (value[0] === '"') {
          value = value.substr(1, value.length - 2).replace(QESC_REGEXP, "$1");
        }
        params[key] = value;
      }
      if (index2 !== -1 && index2 !== string4.length) {
        throw new TypeError("invalid parameter format");
      }
      return new ContentDisposition(type, params);
    }
    function pdecode(str, hex) {
      return String.fromCharCode(parseInt(hex, 16));
    }
    function pencode(char2) {
      return "%" + String(char2).charCodeAt(0).toString(16).toUpperCase();
    }
    function qstring(val) {
      var str = String(val);
      return '"' + str.replace(QUOTE_REGEXP, "\\$1") + '"';
    }
    function ustring(val) {
      var str = String(val);
      var encoded = encodeURIComponent(str).replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode);
      return "UTF-8''" + encoded;
    }
    function ContentDisposition(type, parameters) {
      this.type = type;
      this.parameters = parameters;
    }
  }
});

// ../../node_modules/.pnpm/encodeurl@1.0.2/node_modules/encodeurl/index.js
var require_encodeurl2 = __commonJS({
  "../../node_modules/.pnpm/encodeurl@1.0.2/node_modules/encodeurl/index.js"(exports, module) {
    "use strict";
    module.exports = encodeUrl;
    var ENCODE_CHARS_REGEXP = /(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x61-\x7A\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g;
    var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g;
    var UNMATCHED_SURROGATE_PAIR_REPLACE = "$1\uFFFD$2";
    function encodeUrl(url2) {
      return String(url2).replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE).replace(ENCODE_CHARS_REGEXP, encodeURI);
    }
  }
});

// ../../node_modules/.pnpm/etag@1.8.1/node_modules/etag/index.js
var require_etag = __commonJS({
  "../../node_modules/.pnpm/etag@1.8.1/node_modules/etag/index.js"(exports, module) {
    "use strict";
    module.exports = etag;
    var crypto4 = __require("crypto");
    var Stats = __require("fs").Stats;
    var toString = Object.prototype.toString;
    function entitytag(entity) {
      if (entity.length === 0) {
        return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"';
      }
      var hash2 = crypto4.createHash("sha1").update(entity, "utf8").digest("base64").substring(0, 27);
      var len = typeof entity === "string" ? Buffer.byteLength(entity, "utf8") : entity.length;
      return '"' + len.toString(16) + "-" + hash2 + '"';
    }
    function etag(entity, options) {
      if (entity == null) {
        throw new TypeError("argument entity is required");
      }
      var isStats = isstats(entity);
      var weak = options && typeof options.weak === "boolean" ? options.weak : isStats;
      if (!isStats && typeof entity !== "string" && !Buffer.isBuffer(entity)) {
        throw new TypeError("argument entity must be string, Buffer, or fs.Stats");
      }
      var tag = isStats ? stattag(entity) : entitytag(entity);
      return weak ? "W/" + tag : tag;
    }
    function isstats(obj) {
      if (typeof Stats === "function" && obj instanceof Stats) {
        return true;
      }
      return obj && typeof obj === "object" && "ctime" in obj && toString.call(obj.ctime) === "[object Date]" && "mtime" in obj && toString.call(obj.mtime) === "[object Date]" && "ino" in obj && typeof obj.ino === "number" && "size" in obj && typeof obj.size === "number";
    }
    function stattag(stat) {
      var mtime = stat.mtime.getTime().toString(16);
      var size = stat.size.toString(16);
      return '"' + size + "-" + mtime + '"';
    }
  }
});

// ../../node_modules/.pnpm/fresh@0.5.2/node_modules/fresh/index.js
var require_fresh = __commonJS({
  "../../node_modules/.pnpm/fresh@0.5.2/node_modules/fresh/index.js"(exports, module) {
    "use strict";
    var CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/;
    module.exports = fresh;
    function fresh(reqHeaders, resHeaders) {
      var modifiedSince = reqHeaders["if-modified-since"];
      var noneMatch = reqHeaders["if-none-match"];
      if (!modifiedSince && !noneMatch) {
        return false;
      }
      var cacheControl = reqHeaders["cache-control"];
      if (cacheControl && CACHE_CONTROL_NO_CACHE_REGEXP.test(cacheControl)) {
        return false;
      }
      if (noneMatch && noneMatch !== "*") {
        var etag = resHeaders["etag"];
        if (!etag) {
          return false;
        }
        var etagStale = true;
        var matches = parseTokenList(noneMatch);
        for (var i = 0; i < matches.length; i++) {
          var match = matches[i];
          if (match === etag || match === "W/" + etag || "W/" + match === etag) {
            etagStale = false;
            break;
          }
        }
        if (etagStale) {
          return false;
        }
      }
      if (modifiedSince) {
        var lastModified = resHeaders["last-modified"];
        var modifiedStale = !lastModified || !(parseHttpDate(lastModified) <= parseHttpDate(modifiedSince));
        if (modifiedStale) {
          return false;
        }
      }
      return true;
    }
    function parseHttpDate(date6) {
      var timestamp2 = date6 && Date.parse(date6);
      return typeof timestamp2 === "number" ? timestamp2 : NaN;
    }
    function parseTokenList(str) {
      var end = 0;
      var list = [];
      var start = 0;
      for (var i = 0, len = str.length; i < len; i++) {
        switch (str.charCodeAt(i)) {
          case 32:
            if (start === end) {
              start = end = i + 1;
            }
            break;
          case 44:
            list.push(str.substring(start, end));
            start = end = i + 1;
            break;
          default:
            end = i + 1;
            break;
        }
      }
      list.push(str.substring(start, end));
      return list;
    }
  }
});

// ../../node_modules/.pnpm/mime@1.6.0/node_modules/mime/types.json
var require_types = __commonJS({
  "../../node_modules/.pnpm/mime@1.6.0/node_modules/mime/types.json"(exports, module) {
    module.exports = { "application/andrew-inset": ["ez"], "application/applixware": ["aw"], "application/atom+xml": ["atom"], "application/atomcat+xml": ["atomcat"], "application/atomsvc+xml": ["atomsvc"], "application/bdoc": ["bdoc"], "application/ccxml+xml": ["ccxml"], "application/cdmi-capability": ["cdmia"], "application/cdmi-container": ["cdmic"], "application/cdmi-domain": ["cdmid"], "application/cdmi-object": ["cdmio"], "application/cdmi-queue": ["cdmiq"], "application/cu-seeme": ["cu"], "application/dash+xml": ["mpd"], "application/davmount+xml": ["davmount"], "application/docbook+xml": ["dbk"], "application/dssc+der": ["dssc"], "application/dssc+xml": ["xdssc"], "application/ecmascript": ["ecma"], "application/emma+xml": ["emma"], "application/epub+zip": ["epub"], "application/exi": ["exi"], "application/font-tdpfr": ["pfr"], "application/font-woff": [], "application/font-woff2": [], "application/geo+json": ["geojson"], "application/gml+xml": ["gml"], "application/gpx+xml": ["gpx"], "application/gxf": ["gxf"], "application/gzip": ["gz"], "application/hyperstudio": ["stk"], "application/inkml+xml": ["ink", "inkml"], "application/ipfix": ["ipfix"], "application/java-archive": ["jar", "war", "ear"], "application/java-serialized-object": ["ser"], "application/java-vm": ["class"], "application/javascript": ["js", "mjs"], "application/json": ["json", "map"], "application/json5": ["json5"], "application/jsonml+json": ["jsonml"], "application/ld+json": ["jsonld"], "application/lost+xml": ["lostxml"], "application/mac-binhex40": ["hqx"], "application/mac-compactpro": ["cpt"], "application/mads+xml": ["mads"], "application/manifest+json": ["webmanifest"], "application/marc": ["mrc"], "application/marcxml+xml": ["mrcx"], "application/mathematica": ["ma", "nb", "mb"], "application/mathml+xml": ["mathml"], "application/mbox": ["mbox"], "application/mediaservercontrol+xml": ["mscml"], "application/metalink+xml": ["metalink"], "application/metalink4+xml": ["meta4"], "application/mets+xml": ["mets"], "application/mods+xml": ["mods"], "application/mp21": ["m21", "mp21"], "application/mp4": ["mp4s", "m4p"], "application/msword": ["doc", "dot"], "application/mxf": ["mxf"], "application/octet-stream": ["bin", "dms", "lrf", "mar", "so", "dist", "distz", "pkg", "bpk", "dump", "elc", "deploy", "exe", "dll", "deb", "dmg", "iso", "img", "msi", "msp", "msm", "buffer"], "application/oda": ["oda"], "application/oebps-package+xml": ["opf"], "application/ogg": ["ogx"], "application/omdoc+xml": ["omdoc"], "application/onenote": ["onetoc", "onetoc2", "onetmp", "onepkg"], "application/oxps": ["oxps"], "application/patch-ops-error+xml": ["xer"], "application/pdf": ["pdf"], "application/pgp-encrypted": ["pgp"], "application/pgp-signature": ["asc", "sig"], "application/pics-rules": ["prf"], "application/pkcs10": ["p10"], "application/pkcs7-mime": ["p7m", "p7c"], "application/pkcs7-signature": ["p7s"], "application/pkcs8": ["p8"], "application/pkix-attr-cert": ["ac"], "application/pkix-cert": ["cer"], "application/pkix-crl": ["crl"], "application/pkix-pkipath": ["pkipath"], "application/pkixcmp": ["pki"], "application/pls+xml": ["pls"], "application/postscript": ["ai", "eps", "ps"], "application/prs.cww": ["cww"], "application/pskc+xml": ["pskcxml"], "application/raml+yaml": ["raml"], "application/rdf+xml": ["rdf"], "application/reginfo+xml": ["rif"], "application/relax-ng-compact-syntax": ["rnc"], "application/resource-lists+xml": ["rl"], "application/resource-lists-diff+xml": ["rld"], "application/rls-services+xml": ["rs"], "application/rpki-ghostbusters": ["gbr"], "application/rpki-manifest": ["mft"], "application/rpki-roa": ["roa"], "application/rsd+xml": ["rsd"], "application/rss+xml": ["rss"], "application/rtf": ["rtf"], "application/sbml+xml": ["sbml"], "application/scvp-cv-request": ["scq"], "application/scvp-cv-response": ["scs"], "application/scvp-vp-request": ["spq"], "application/scvp-vp-response": ["spp"], "application/sdp": ["sdp"], "application/set-payment-initiation": ["setpay"], "application/set-registration-initiation": ["setreg"], "application/shf+xml": ["shf"], "application/smil+xml": ["smi", "smil"], "application/sparql-query": ["rq"], "application/sparql-results+xml": ["srx"], "application/srgs": ["gram"], "application/srgs+xml": ["grxml"], "application/sru+xml": ["sru"], "application/ssdl+xml": ["ssdl"], "application/ssml+xml": ["ssml"], "application/tei+xml": ["tei", "teicorpus"], "application/thraud+xml": ["tfi"], "application/timestamped-data": ["tsd"], "application/vnd.3gpp.pic-bw-large": ["plb"], "application/vnd.3gpp.pic-bw-small": ["psb"], "application/vnd.3gpp.pic-bw-var": ["pvb"], "application/vnd.3gpp2.tcap": ["tcap"], "application/vnd.3m.post-it-notes": ["pwn"], "application/vnd.accpac.simply.aso": ["aso"], "application/vnd.accpac.simply.imp": ["imp"], "application/vnd.acucobol": ["acu"], "application/vnd.acucorp": ["atc", "acutc"], "application/vnd.adobe.air-application-installer-package+zip": ["air"], "application/vnd.adobe.formscentral.fcdt": ["fcdt"], "application/vnd.adobe.fxp": ["fxp", "fxpl"], "application/vnd.adobe.xdp+xml": ["xdp"], "application/vnd.adobe.xfdf": ["xfdf"], "application/vnd.ahead.space": ["ahead"], "application/vnd.airzip.filesecure.azf": ["azf"], "application/vnd.airzip.filesecure.azs": ["azs"], "application/vnd.amazon.ebook": ["azw"], "application/vnd.americandynamics.acc": ["acc"], "application/vnd.amiga.ami": ["ami"], "application/vnd.android.package-archive": ["apk"], "application/vnd.anser-web-certificate-issue-initiation": ["cii"], "application/vnd.anser-web-funds-transfer-initiation": ["fti"], "application/vnd.antix.game-component": ["atx"], "application/vnd.apple.installer+xml": ["mpkg"], "application/vnd.apple.mpegurl": ["m3u8"], "application/vnd.apple.pkpass": ["pkpass"], "application/vnd.aristanetworks.swi": ["swi"], "application/vnd.astraea-software.iota": ["iota"], "application/vnd.audiograph": ["aep"], "application/vnd.blueice.multipass": ["mpm"], "application/vnd.bmi": ["bmi"], "application/vnd.businessobjects": ["rep"], "application/vnd.chemdraw+xml": ["cdxml"], "application/vnd.chipnuts.karaoke-mmd": ["mmd"], "application/vnd.cinderella": ["cdy"], "application/vnd.claymore": ["cla"], "application/vnd.cloanto.rp9": ["rp9"], "application/vnd.clonk.c4group": ["c4g", "c4d", "c4f", "c4p", "c4u"], "application/vnd.cluetrust.cartomobile-config": ["c11amc"], "application/vnd.cluetrust.cartomobile-config-pkg": ["c11amz"], "application/vnd.commonspace": ["csp"], "application/vnd.contact.cmsg": ["cdbcmsg"], "application/vnd.cosmocaller": ["cmc"], "application/vnd.crick.clicker": ["clkx"], "application/vnd.crick.clicker.keyboard": ["clkk"], "application/vnd.crick.clicker.palette": ["clkp"], "application/vnd.crick.clicker.template": ["clkt"], "application/vnd.crick.clicker.wordbank": ["clkw"], "application/vnd.criticaltools.wbs+xml": ["wbs"], "application/vnd.ctc-posml": ["pml"], "application/vnd.cups-ppd": ["ppd"], "application/vnd.curl.car": ["car"], "application/vnd.curl.pcurl": ["pcurl"], "application/vnd.dart": ["dart"], "application/vnd.data-vision.rdz": ["rdz"], "application/vnd.dece.data": ["uvf", "uvvf", "uvd", "uvvd"], "application/vnd.dece.ttml+xml": ["uvt", "uvvt"], "application/vnd.dece.unspecified": ["uvx", "uvvx"], "application/vnd.dece.zip": ["uvz", "uvvz"], "application/vnd.denovo.fcselayout-link": ["fe_launch"], "application/vnd.dna": ["dna"], "application/vnd.dolby.mlp": ["mlp"], "application/vnd.dpgraph": ["dpg"], "application/vnd.dreamfactory": ["dfac"], "application/vnd.ds-keypoint": ["kpxx"], "application/vnd.dvb.ait": ["ait"], "application/vnd.dvb.service": ["svc"], "application/vnd.dynageo": ["geo"], "application/vnd.ecowin.chart": ["mag"], "application/vnd.enliven": ["nml"], "application/vnd.epson.esf": ["esf"], "application/vnd.epson.msf": ["msf"], "application/vnd.epson.quickanime": ["qam"], "application/vnd.epson.salt": ["slt"], "application/vnd.epson.ssf": ["ssf"], "application/vnd.eszigno3+xml": ["es3", "et3"], "application/vnd.ezpix-album": ["ez2"], "application/vnd.ezpix-package": ["ez3"], "application/vnd.fdf": ["fdf"], "application/vnd.fdsn.mseed": ["mseed"], "application/vnd.fdsn.seed": ["seed", "dataless"], "application/vnd.flographit": ["gph"], "application/vnd.fluxtime.clip": ["ftc"], "application/vnd.framemaker": ["fm", "frame", "maker", "book"], "application/vnd.frogans.fnc": ["fnc"], "application/vnd.frogans.ltf": ["ltf"], "application/vnd.fsc.weblaunch": ["fsc"], "application/vnd.fujitsu.oasys": ["oas"], "application/vnd.fujitsu.oasys2": ["oa2"], "application/vnd.fujitsu.oasys3": ["oa3"], "application/vnd.fujitsu.oasysgp": ["fg5"], "application/vnd.fujitsu.oasysprs": ["bh2"], "application/vnd.fujixerox.ddd": ["ddd"], "application/vnd.fujixerox.docuworks": ["xdw"], "application/vnd.fujixerox.docuworks.binder": ["xbd"], "application/vnd.fuzzysheet": ["fzs"], "application/vnd.genomatix.tuxedo": ["txd"], "application/vnd.geogebra.file": ["ggb"], "application/vnd.geogebra.tool": ["ggt"], "application/vnd.geometry-explorer": ["gex", "gre"], "application/vnd.geonext": ["gxt"], "application/vnd.geoplan": ["g2w"], "application/vnd.geospace": ["g3w"], "application/vnd.gmx": ["gmx"], "application/vnd.google-apps.document": ["gdoc"], "application/vnd.google-apps.presentation": ["gslides"], "application/vnd.google-apps.spreadsheet": ["gsheet"], "application/vnd.google-earth.kml+xml": ["kml"], "application/vnd.google-earth.kmz": ["kmz"], "application/vnd.grafeq": ["gqf", "gqs"], "application/vnd.groove-account": ["gac"], "application/vnd.groove-help": ["ghf"], "application/vnd.groove-identity-message": ["gim"], "application/vnd.groove-injector": ["grv"], "application/vnd.groove-tool-message": ["gtm"], "application/vnd.groove-tool-template": ["tpl"], "application/vnd.groove-vcard": ["vcg"], "application/vnd.hal+xml": ["hal"], "application/vnd.handheld-entertainment+xml": ["zmm"], "application/vnd.hbci": ["hbci"], "application/vnd.hhe.lesson-player": ["les"], "application/vnd.hp-hpgl": ["hpgl"], "application/vnd.hp-hpid": ["hpid"], "application/vnd.hp-hps": ["hps"], "application/vnd.hp-jlyt": ["jlt"], "application/vnd.hp-pcl": ["pcl"], "application/vnd.hp-pclxl": ["pclxl"], "application/vnd.hydrostatix.sof-data": ["sfd-hdstx"], "application/vnd.ibm.minipay": ["mpy"], "application/vnd.ibm.modcap": ["afp", "listafp", "list3820"], "application/vnd.ibm.rights-management": ["irm"], "application/vnd.ibm.secure-container": ["sc"], "application/vnd.iccprofile": ["icc", "icm"], "application/vnd.igloader": ["igl"], "application/vnd.immervision-ivp": ["ivp"], "application/vnd.immervision-ivu": ["ivu"], "application/vnd.insors.igm": ["igm"], "application/vnd.intercon.formnet": ["xpw", "xpx"], "application/vnd.intergeo": ["i2g"], "application/vnd.intu.qbo": ["qbo"], "application/vnd.intu.qfx": ["qfx"], "application/vnd.ipunplugged.rcprofile": ["rcprofile"], "application/vnd.irepository.package+xml": ["irp"], "application/vnd.is-xpr": ["xpr"], "application/vnd.isac.fcs": ["fcs"], "application/vnd.jam": ["jam"], "application/vnd.jcp.javame.midlet-rms": ["rms"], "application/vnd.jisp": ["jisp"], "application/vnd.joost.joda-archive": ["joda"], "application/vnd.kahootz": ["ktz", "ktr"], "application/vnd.kde.karbon": ["karbon"], "application/vnd.kde.kchart": ["chrt"], "application/vnd.kde.kformula": ["kfo"], "application/vnd.kde.kivio": ["flw"], "application/vnd.kde.kontour": ["kon"], "application/vnd.kde.kpresenter": ["kpr", "kpt"], "application/vnd.kde.kspread": ["ksp"], "application/vnd.kde.kword": ["kwd", "kwt"], "application/vnd.kenameaapp": ["htke"], "application/vnd.kidspiration": ["kia"], "application/vnd.kinar": ["kne", "knp"], "application/vnd.koan": ["skp", "skd", "skt", "skm"], "application/vnd.kodak-descriptor": ["sse"], "application/vnd.las.las+xml": ["lasxml"], "application/vnd.llamagraphics.life-balance.desktop": ["lbd"], "application/vnd.llamagraphics.life-balance.exchange+xml": ["lbe"], "application/vnd.lotus-1-2-3": ["123"], "application/vnd.lotus-approach": ["apr"], "application/vnd.lotus-freelance": ["pre"], "application/vnd.lotus-notes": ["nsf"], "application/vnd.lotus-organizer": ["org"], "application/vnd.lotus-screencam": ["scm"], "application/vnd.lotus-wordpro": ["lwp"], "application/vnd.macports.portpkg": ["portpkg"], "application/vnd.mcd": ["mcd"], "application/vnd.medcalcdata": ["mc1"], "application/vnd.mediastation.cdkey": ["cdkey"], "application/vnd.mfer": ["mwf"], "application/vnd.mfmp": ["mfm"], "application/vnd.micrografx.flo": ["flo"], "application/vnd.micrografx.igx": ["igx"], "application/vnd.mif": ["mif"], "application/vnd.mobius.daf": ["daf"], "application/vnd.mobius.dis": ["dis"], "application/vnd.mobius.mbk": ["mbk"], "application/vnd.mobius.mqy": ["mqy"], "application/vnd.mobius.msl": ["msl"], "application/vnd.mobius.plc": ["plc"], "application/vnd.mobius.txf": ["txf"], "application/vnd.mophun.application": ["mpn"], "application/vnd.mophun.certificate": ["mpc"], "application/vnd.mozilla.xul+xml": ["xul"], "application/vnd.ms-artgalry": ["cil"], "application/vnd.ms-cab-compressed": ["cab"], "application/vnd.ms-excel": ["xls", "xlm", "xla", "xlc", "xlt", "xlw"], "application/vnd.ms-excel.addin.macroenabled.12": ["xlam"], "application/vnd.ms-excel.sheet.binary.macroenabled.12": ["xlsb"], "application/vnd.ms-excel.sheet.macroenabled.12": ["xlsm"], "application/vnd.ms-excel.template.macroenabled.12": ["xltm"], "application/vnd.ms-fontobject": ["eot"], "application/vnd.ms-htmlhelp": ["chm"], "application/vnd.ms-ims": ["ims"], "application/vnd.ms-lrm": ["lrm"], "application/vnd.ms-officetheme": ["thmx"], "application/vnd.ms-outlook": ["msg"], "application/vnd.ms-pki.seccat": ["cat"], "application/vnd.ms-pki.stl": ["stl"], "application/vnd.ms-powerpoint": ["ppt", "pps", "pot"], "application/vnd.ms-powerpoint.addin.macroenabled.12": ["ppam"], "application/vnd.ms-powerpoint.presentation.macroenabled.12": ["pptm"], "application/vnd.ms-powerpoint.slide.macroenabled.12": ["sldm"], "application/vnd.ms-powerpoint.slideshow.macroenabled.12": ["ppsm"], "application/vnd.ms-powerpoint.template.macroenabled.12": ["potm"], "application/vnd.ms-project": ["mpp", "mpt"], "application/vnd.ms-word.document.macroenabled.12": ["docm"], "application/vnd.ms-word.template.macroenabled.12": ["dotm"], "application/vnd.ms-works": ["wps", "wks", "wcm", "wdb"], "application/vnd.ms-wpl": ["wpl"], "application/vnd.ms-xpsdocument": ["xps"], "application/vnd.mseq": ["mseq"], "application/vnd.musician": ["mus"], "application/vnd.muvee.style": ["msty"], "application/vnd.mynfc": ["taglet"], "application/vnd.neurolanguage.nlu": ["nlu"], "application/vnd.nitf": ["ntf", "nitf"], "application/vnd.noblenet-directory": ["nnd"], "application/vnd.noblenet-sealer": ["nns"], "application/vnd.noblenet-web": ["nnw"], "application/vnd.nokia.n-gage.data": ["ngdat"], "application/vnd.nokia.n-gage.symbian.install": ["n-gage"], "application/vnd.nokia.radio-preset": ["rpst"], "application/vnd.nokia.radio-presets": ["rpss"], "application/vnd.novadigm.edm": ["edm"], "application/vnd.novadigm.edx": ["edx"], "application/vnd.novadigm.ext": ["ext"], "application/vnd.oasis.opendocument.chart": ["odc"], "application/vnd.oasis.opendocument.chart-template": ["otc"], "application/vnd.oasis.opendocument.database": ["odb"], "application/vnd.oasis.opendocument.formula": ["odf"], "application/vnd.oasis.opendocument.formula-template": ["odft"], "application/vnd.oasis.opendocument.graphics": ["odg"], "application/vnd.oasis.opendocument.graphics-template": ["otg"], "application/vnd.oasis.opendocument.image": ["odi"], "application/vnd.oasis.opendocument.image-template": ["oti"], "application/vnd.oasis.opendocument.presentation": ["odp"], "application/vnd.oasis.opendocument.presentation-template": ["otp"], "application/vnd.oasis.opendocument.spreadsheet": ["ods"], "application/vnd.oasis.opendocument.spreadsheet-template": ["ots"], "application/vnd.oasis.opendocument.text": ["odt"], "application/vnd.oasis.opendocument.text-master": ["odm"], "application/vnd.oasis.opendocument.text-template": ["ott"], "application/vnd.oasis.opendocument.text-web": ["oth"], "application/vnd.olpc-sugar": ["xo"], "application/vnd.oma.dd2+xml": ["dd2"], "application/vnd.openofficeorg.extension": ["oxt"], "application/vnd.openxmlformats-officedocument.presentationml.presentation": ["pptx"], "application/vnd.openxmlformats-officedocument.presentationml.slide": ["sldx"], "application/vnd.openxmlformats-officedocument.presentationml.slideshow": ["ppsx"], "application/vnd.openxmlformats-officedocument.presentationml.template": ["potx"], "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ["xlsx"], "application/vnd.openxmlformats-officedocument.spreadsheetml.template": ["xltx"], "application/vnd.openxmlformats-officedocument.wordprocessingml.document": ["docx"], "application/vnd.openxmlformats-officedocument.wordprocessingml.template": ["dotx"], "application/vnd.osgeo.mapguide.package": ["mgp"], "application/vnd.osgi.dp": ["dp"], "application/vnd.osgi.subsystem": ["esa"], "application/vnd.palm": ["pdb", "pqa", "oprc"], "application/vnd.pawaafile": ["paw"], "application/vnd.pg.format": ["str"], "application/vnd.pg.osasli": ["ei6"], "application/vnd.picsel": ["efif"], "application/vnd.pmi.widget": ["wg"], "application/vnd.pocketlearn": ["plf"], "application/vnd.powerbuilder6": ["pbd"], "application/vnd.previewsystems.box": ["box"], "application/vnd.proteus.magazine": ["mgz"], "application/vnd.publishare-delta-tree": ["qps"], "application/vnd.pvi.ptid1": ["ptid"], "application/vnd.quark.quarkxpress": ["qxd", "qxt", "qwd", "qwt", "qxl", "qxb"], "application/vnd.realvnc.bed": ["bed"], "application/vnd.recordare.musicxml": ["mxl"], "application/vnd.recordare.musicxml+xml": ["musicxml"], "application/vnd.rig.cryptonote": ["cryptonote"], "application/vnd.rim.cod": ["cod"], "application/vnd.rn-realmedia": ["rm"], "application/vnd.rn-realmedia-vbr": ["rmvb"], "application/vnd.route66.link66+xml": ["link66"], "application/vnd.sailingtracker.track": ["st"], "application/vnd.seemail": ["see"], "application/vnd.sema": ["sema"], "application/vnd.semd": ["semd"], "application/vnd.semf": ["semf"], "application/vnd.shana.informed.formdata": ["ifm"], "application/vnd.shana.informed.formtemplate": ["itp"], "application/vnd.shana.informed.interchange": ["iif"], "application/vnd.shana.informed.package": ["ipk"], "application/vnd.simtech-mindmapper": ["twd", "twds"], "application/vnd.smaf": ["mmf"], "application/vnd.smart.teacher": ["teacher"], "application/vnd.solent.sdkm+xml": ["sdkm", "sdkd"], "application/vnd.spotfire.dxp": ["dxp"], "application/vnd.spotfire.sfs": ["sfs"], "application/vnd.stardivision.calc": ["sdc"], "application/vnd.stardivision.draw": ["sda"], "application/vnd.stardivision.impress": ["sdd"], "application/vnd.stardivision.math": ["smf"], "application/vnd.stardivision.writer": ["sdw", "vor"], "application/vnd.stardivision.writer-global": ["sgl"], "application/vnd.stepmania.package": ["smzip"], "application/vnd.stepmania.stepchart": ["sm"], "application/vnd.sun.wadl+xml": ["wadl"], "application/vnd.sun.xml.calc": ["sxc"], "application/vnd.sun.xml.calc.template": ["stc"], "application/vnd.sun.xml.draw": ["sxd"], "application/vnd.sun.xml.draw.template": ["std"], "application/vnd.sun.xml.impress": ["sxi"], "application/vnd.sun.xml.impress.template": ["sti"], "application/vnd.sun.xml.math": ["sxm"], "application/vnd.sun.xml.writer": ["sxw"], "application/vnd.sun.xml.writer.global": ["sxg"], "application/vnd.sun.xml.writer.template": ["stw"], "application/vnd.sus-calendar": ["sus", "susp"], "application/vnd.svd": ["svd"], "application/vnd.symbian.install": ["sis", "sisx"], "application/vnd.syncml+xml": ["xsm"], "application/vnd.syncml.dm+wbxml": ["bdm"], "application/vnd.syncml.dm+xml": ["xdm"], "application/vnd.tao.intent-module-archive": ["tao"], "application/vnd.tcpdump.pcap": ["pcap", "cap", "dmp"], "application/vnd.tmobile-livetv": ["tmo"], "application/vnd.trid.tpt": ["tpt"], "application/vnd.triscape.mxs": ["mxs"], "application/vnd.trueapp": ["tra"], "application/vnd.ufdl": ["ufd", "ufdl"], "application/vnd.uiq.theme": ["utz"], "application/vnd.umajin": ["umj"], "application/vnd.unity": ["unityweb"], "application/vnd.uoml+xml": ["uoml"], "application/vnd.vcx": ["vcx"], "application/vnd.visio": ["vsd", "vst", "vss", "vsw"], "application/vnd.visionary": ["vis"], "application/vnd.vsf": ["vsf"], "application/vnd.wap.wbxml": ["wbxml"], "application/vnd.wap.wmlc": ["wmlc"], "application/vnd.wap.wmlscriptc": ["wmlsc"], "application/vnd.webturbo": ["wtb"], "application/vnd.wolfram.player": ["nbp"], "application/vnd.wordperfect": ["wpd"], "application/vnd.wqd": ["wqd"], "application/vnd.wt.stf": ["stf"], "application/vnd.xara": ["xar"], "application/vnd.xfdl": ["xfdl"], "application/vnd.yamaha.hv-dic": ["hvd"], "application/vnd.yamaha.hv-script": ["hvs"], "application/vnd.yamaha.hv-voice": ["hvp"], "application/vnd.yamaha.openscoreformat": ["osf"], "application/vnd.yamaha.openscoreformat.osfpvg+xml": ["osfpvg"], "application/vnd.yamaha.smaf-audio": ["saf"], "application/vnd.yamaha.smaf-phrase": ["spf"], "application/vnd.yellowriver-custom-menu": ["cmp"], "application/vnd.zul": ["zir", "zirz"], "application/vnd.zzazz.deck+xml": ["zaz"], "application/voicexml+xml": ["vxml"], "application/wasm": ["wasm"], "application/widget": ["wgt"], "application/winhlp": ["hlp"], "application/wsdl+xml": ["wsdl"], "application/wspolicy+xml": ["wspolicy"], "application/x-7z-compressed": ["7z"], "application/x-abiword": ["abw"], "application/x-ace-compressed": ["ace"], "application/x-apple-diskimage": [], "application/x-arj": ["arj"], "application/x-authorware-bin": ["aab", "x32", "u32", "vox"], "application/x-authorware-map": ["aam"], "application/x-authorware-seg": ["aas"], "application/x-bcpio": ["bcpio"], "application/x-bdoc": [], "application/x-bittorrent": ["torrent"], "application/x-blorb": ["blb", "blorb"], "application/x-bzip": ["bz"], "application/x-bzip2": ["bz2", "boz"], "application/x-cbr": ["cbr", "cba", "cbt", "cbz", "cb7"], "application/x-cdlink": ["vcd"], "application/x-cfs-compressed": ["cfs"], "application/x-chat": ["chat"], "application/x-chess-pgn": ["pgn"], "application/x-chrome-extension": ["crx"], "application/x-cocoa": ["cco"], "application/x-conference": ["nsc"], "application/x-cpio": ["cpio"], "application/x-csh": ["csh"], "application/x-debian-package": ["udeb"], "application/x-dgc-compressed": ["dgc"], "application/x-director": ["dir", "dcr", "dxr", "cst", "cct", "cxt", "w3d", "fgd", "swa"], "application/x-doom": ["wad"], "application/x-dtbncx+xml": ["ncx"], "application/x-dtbook+xml": ["dtb"], "application/x-dtbresource+xml": ["res"], "application/x-dvi": ["dvi"], "application/x-envoy": ["evy"], "application/x-eva": ["eva"], "application/x-font-bdf": ["bdf"], "application/x-font-ghostscript": ["gsf"], "application/x-font-linux-psf": ["psf"], "application/x-font-pcf": ["pcf"], "application/x-font-snf": ["snf"], "application/x-font-type1": ["pfa", "pfb", "pfm", "afm"], "application/x-freearc": ["arc"], "application/x-futuresplash": ["spl"], "application/x-gca-compressed": ["gca"], "application/x-glulx": ["ulx"], "application/x-gnumeric": ["gnumeric"], "application/x-gramps-xml": ["gramps"], "application/x-gtar": ["gtar"], "application/x-hdf": ["hdf"], "application/x-httpd-php": ["php"], "application/x-install-instructions": ["install"], "application/x-iso9660-image": [], "application/x-java-archive-diff": ["jardiff"], "application/x-java-jnlp-file": ["jnlp"], "application/x-latex": ["latex"], "application/x-lua-bytecode": ["luac"], "application/x-lzh-compressed": ["lzh", "lha"], "application/x-makeself": ["run"], "application/x-mie": ["mie"], "application/x-mobipocket-ebook": ["prc", "mobi"], "application/x-ms-application": ["application"], "application/x-ms-shortcut": ["lnk"], "application/x-ms-wmd": ["wmd"], "application/x-ms-wmz": ["wmz"], "application/x-ms-xbap": ["xbap"], "application/x-msaccess": ["mdb"], "application/x-msbinder": ["obd"], "application/x-mscardfile": ["crd"], "application/x-msclip": ["clp"], "application/x-msdos-program": [], "application/x-msdownload": ["com", "bat"], "application/x-msmediaview": ["mvb", "m13", "m14"], "application/x-msmetafile": ["wmf", "emf", "emz"], "application/x-msmoney": ["mny"], "application/x-mspublisher": ["pub"], "application/x-msschedule": ["scd"], "application/x-msterminal": ["trm"], "application/x-mswrite": ["wri"], "application/x-netcdf": ["nc", "cdf"], "application/x-ns-proxy-autoconfig": ["pac"], "application/x-nzb": ["nzb"], "application/x-perl": ["pl", "pm"], "application/x-pilot": [], "application/x-pkcs12": ["p12", "pfx"], "application/x-pkcs7-certificates": ["p7b", "spc"], "application/x-pkcs7-certreqresp": ["p7r"], "application/x-rar-compressed": ["rar"], "application/x-redhat-package-manager": ["rpm"], "application/x-research-info-systems": ["ris"], "application/x-sea": ["sea"], "application/x-sh": ["sh"], "application/x-shar": ["shar"], "application/x-shockwave-flash": ["swf"], "application/x-silverlight-app": ["xap"], "application/x-sql": ["sql"], "application/x-stuffit": ["sit"], "application/x-stuffitx": ["sitx"], "application/x-subrip": ["srt"], "application/x-sv4cpio": ["sv4cpio"], "application/x-sv4crc": ["sv4crc"], "application/x-t3vm-image": ["t3"], "application/x-tads": ["gam"], "application/x-tar": ["tar"], "application/x-tcl": ["tcl", "tk"], "application/x-tex": ["tex"], "application/x-tex-tfm": ["tfm"], "application/x-texinfo": ["texinfo", "texi"], "application/x-tgif": ["obj"], "application/x-ustar": ["ustar"], "application/x-virtualbox-hdd": ["hdd"], "application/x-virtualbox-ova": ["ova"], "application/x-virtualbox-ovf": ["ovf"], "application/x-virtualbox-vbox": ["vbox"], "application/x-virtualbox-vbox-extpack": ["vbox-extpack"], "application/x-virtualbox-vdi": ["vdi"], "application/x-virtualbox-vhd": ["vhd"], "application/x-virtualbox-vmdk": ["vmdk"], "application/x-wais-source": ["src"], "application/x-web-app-manifest+json": ["webapp"], "application/x-x509-ca-cert": ["der", "crt", "pem"], "application/x-xfig": ["fig"], "application/x-xliff+xml": ["xlf"], "application/x-xpinstall": ["xpi"], "application/x-xz": ["xz"], "application/x-zmachine": ["z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8"], "application/xaml+xml": ["xaml"], "application/xcap-diff+xml": ["xdf"], "application/xenc+xml": ["xenc"], "application/xhtml+xml": ["xhtml", "xht"], "application/xml": ["xml", "xsl", "xsd", "rng"], "application/xml-dtd": ["dtd"], "application/xop+xml": ["xop"], "application/xproc+xml": ["xpl"], "application/xslt+xml": ["xslt"], "application/xspf+xml": ["xspf"], "application/xv+xml": ["mxml", "xhvml", "xvml", "xvm"], "application/yang": ["yang"], "application/yin+xml": ["yin"], "application/zip": ["zip"], "audio/3gpp": [], "audio/adpcm": ["adp"], "audio/basic": ["au", "snd"], "audio/midi": ["mid", "midi", "kar", "rmi"], "audio/mp3": [], "audio/mp4": ["m4a", "mp4a"], "audio/mpeg": ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"], "audio/ogg": ["oga", "ogg", "spx"], "audio/s3m": ["s3m"], "audio/silk": ["sil"], "audio/vnd.dece.audio": ["uva", "uvva"], "audio/vnd.digital-winds": ["eol"], "audio/vnd.dra": ["dra"], "audio/vnd.dts": ["dts"], "audio/vnd.dts.hd": ["dtshd"], "audio/vnd.lucent.voice": ["lvp"], "audio/vnd.ms-playready.media.pya": ["pya"], "audio/vnd.nuera.ecelp4800": ["ecelp4800"], "audio/vnd.nuera.ecelp7470": ["ecelp7470"], "audio/vnd.nuera.ecelp9600": ["ecelp9600"], "audio/vnd.rip": ["rip"], "audio/wav": ["wav"], "audio/wave": [], "audio/webm": ["weba"], "audio/x-aac": ["aac"], "audio/x-aiff": ["aif", "aiff", "aifc"], "audio/x-caf": ["caf"], "audio/x-flac": ["flac"], "audio/x-m4a": [], "audio/x-matroska": ["mka"], "audio/x-mpegurl": ["m3u"], "audio/x-ms-wax": ["wax"], "audio/x-ms-wma": ["wma"], "audio/x-pn-realaudio": ["ram", "ra"], "audio/x-pn-realaudio-plugin": ["rmp"], "audio/x-realaudio": [], "audio/x-wav": [], "audio/xm": ["xm"], "chemical/x-cdx": ["cdx"], "chemical/x-cif": ["cif"], "chemical/x-cmdf": ["cmdf"], "chemical/x-cml": ["cml"], "chemical/x-csml": ["csml"], "chemical/x-xyz": ["xyz"], "font/collection": ["ttc"], "font/otf": ["otf"], "font/ttf": ["ttf"], "font/woff": ["woff"], "font/woff2": ["woff2"], "image/apng": ["apng"], "image/bmp": ["bmp"], "image/cgm": ["cgm"], "image/g3fax": ["g3"], "image/gif": ["gif"], "image/ief": ["ief"], "image/jp2": ["jp2", "jpg2"], "image/jpeg": ["jpeg", "jpg", "jpe"], "image/jpm": ["jpm"], "image/jpx": ["jpx", "jpf"], "image/ktx": ["ktx"], "image/png": ["png"], "image/prs.btif": ["btif"], "image/sgi": ["sgi"], "image/svg+xml": ["svg", "svgz"], "image/tiff": ["tiff", "tif"], "image/vnd.adobe.photoshop": ["psd"], "image/vnd.dece.graphic": ["uvi", "uvvi", "uvg", "uvvg"], "image/vnd.djvu": ["djvu", "djv"], "image/vnd.dvb.subtitle": [], "image/vnd.dwg": ["dwg"], "image/vnd.dxf": ["dxf"], "image/vnd.fastbidsheet": ["fbs"], "image/vnd.fpx": ["fpx"], "image/vnd.fst": ["fst"], "image/vnd.fujixerox.edmics-mmr": ["mmr"], "image/vnd.fujixerox.edmics-rlc": ["rlc"], "image/vnd.ms-modi": ["mdi"], "image/vnd.ms-photo": ["wdp"], "image/vnd.net-fpx": ["npx"], "image/vnd.wap.wbmp": ["wbmp"], "image/vnd.xiff": ["xif"], "image/webp": ["webp"], "image/x-3ds": ["3ds"], "image/x-cmu-raster": ["ras"], "image/x-cmx": ["cmx"], "image/x-freehand": ["fh", "fhc", "fh4", "fh5", "fh7"], "image/x-icon": ["ico"], "image/x-jng": ["jng"], "image/x-mrsid-image": ["sid"], "image/x-ms-bmp": [], "image/x-pcx": ["pcx"], "image/x-pict": ["pic", "pct"], "image/x-portable-anymap": ["pnm"], "image/x-portable-bitmap": ["pbm"], "image/x-portable-graymap": ["pgm"], "image/x-portable-pixmap": ["ppm"], "image/x-rgb": ["rgb"], "image/x-tga": ["tga"], "image/x-xbitmap": ["xbm"], "image/x-xpixmap": ["xpm"], "image/x-xwindowdump": ["xwd"], "message/rfc822": ["eml", "mime"], "model/gltf+json": ["gltf"], "model/gltf-binary": ["glb"], "model/iges": ["igs", "iges"], "model/mesh": ["msh", "mesh", "silo"], "model/vnd.collada+xml": ["dae"], "model/vnd.dwf": ["dwf"], "model/vnd.gdl": ["gdl"], "model/vnd.gtw": ["gtw"], "model/vnd.mts": ["mts"], "model/vnd.vtu": ["vtu"], "model/vrml": ["wrl", "vrml"], "model/x3d+binary": ["x3db", "x3dbz"], "model/x3d+vrml": ["x3dv", "x3dvz"], "model/x3d+xml": ["x3d", "x3dz"], "text/cache-manifest": ["appcache", "manifest"], "text/calendar": ["ics", "ifb"], "text/coffeescript": ["coffee", "litcoffee"], "text/css": ["css"], "text/csv": ["csv"], "text/hjson": ["hjson"], "text/html": ["html", "htm", "shtml"], "text/jade": ["jade"], "text/jsx": ["jsx"], "text/less": ["less"], "text/markdown": ["markdown", "md"], "text/mathml": ["mml"], "text/n3": ["n3"], "text/plain": ["txt", "text", "conf", "def", "list", "log", "in", "ini"], "text/prs.lines.tag": ["dsc"], "text/richtext": ["rtx"], "text/rtf": [], "text/sgml": ["sgml", "sgm"], "text/slim": ["slim", "slm"], "text/stylus": ["stylus", "styl"], "text/tab-separated-values": ["tsv"], "text/troff": ["t", "tr", "roff", "man", "me", "ms"], "text/turtle": ["ttl"], "text/uri-list": ["uri", "uris", "urls"], "text/vcard": ["vcard"], "text/vnd.curl": ["curl"], "text/vnd.curl.dcurl": ["dcurl"], "text/vnd.curl.mcurl": ["mcurl"], "text/vnd.curl.scurl": ["scurl"], "text/vnd.dvb.subtitle": ["sub"], "text/vnd.fly": ["fly"], "text/vnd.fmi.flexstor": ["flx"], "text/vnd.graphviz": ["gv"], "text/vnd.in3d.3dml": ["3dml"], "text/vnd.in3d.spot": ["spot"], "text/vnd.sun.j2me.app-descriptor": ["jad"], "text/vnd.wap.wml": ["wml"], "text/vnd.wap.wmlscript": ["wmls"], "text/vtt": ["vtt"], "text/x-asm": ["s", "asm"], "text/x-c": ["c", "cc", "cxx", "cpp", "h", "hh", "dic"], "text/x-component": ["htc"], "text/x-fortran": ["f", "for", "f77", "f90"], "text/x-handlebars-template": ["hbs"], "text/x-java-source": ["java"], "text/x-lua": ["lua"], "text/x-markdown": ["mkd"], "text/x-nfo": ["nfo"], "text/x-opml": ["opml"], "text/x-org": [], "text/x-pascal": ["p", "pas"], "text/x-processing": ["pde"], "text/x-sass": ["sass"], "text/x-scss": ["scss"], "text/x-setext": ["etx"], "text/x-sfv": ["sfv"], "text/x-suse-ymp": ["ymp"], "text/x-uuencode": ["uu"], "text/x-vcalendar": ["vcs"], "text/x-vcard": ["vcf"], "text/xml": [], "text/yaml": ["yaml", "yml"], "video/3gpp": ["3gp", "3gpp"], "video/3gpp2": ["3g2"], "video/h261": ["h261"], "video/h263": ["h263"], "video/h264": ["h264"], "video/jpeg": ["jpgv"], "video/jpm": ["jpgm"], "video/mj2": ["mj2", "mjp2"], "video/mp2t": ["ts"], "video/mp4": ["mp4", "mp4v", "mpg4"], "video/mpeg": ["mpeg", "mpg", "mpe", "m1v", "m2v"], "video/ogg": ["ogv"], "video/quicktime": ["qt", "mov"], "video/vnd.dece.hd": ["uvh", "uvvh"], "video/vnd.dece.mobile": ["uvm", "uvvm"], "video/vnd.dece.pd": ["uvp", "uvvp"], "video/vnd.dece.sd": ["uvs", "uvvs"], "video/vnd.dece.video": ["uvv", "uvvv"], "video/vnd.dvb.file": ["dvb"], "video/vnd.fvt": ["fvt"], "video/vnd.mpegurl": ["mxu", "m4u"], "video/vnd.ms-playready.media.pyv": ["pyv"], "video/vnd.uvvu.mp4": ["uvu", "uvvu"], "video/vnd.vivo": ["viv"], "video/webm": ["webm"], "video/x-f4v": ["f4v"], "video/x-fli": ["fli"], "video/x-flv": ["flv"], "video/x-m4v": ["m4v"], "video/x-matroska": ["mkv", "mk3d", "mks"], "video/x-mng": ["mng"], "video/x-ms-asf": ["asf", "asx"], "video/x-ms-vob": ["vob"], "video/x-ms-wm": ["wm"], "video/x-ms-wmv": ["wmv"], "video/x-ms-wmx": ["wmx"], "video/x-ms-wvx": ["wvx"], "video/x-msvideo": ["avi"], "video/x-sgi-movie": ["movie"], "video/x-smv": ["smv"], "x-conference/x-cooltalk": ["ice"] };
  }
});

// ../../node_modules/.pnpm/mime@1.6.0/node_modules/mime/mime.js
var require_mime = __commonJS({
  "../../node_modules/.pnpm/mime@1.6.0/node_modules/mime/mime.js"(exports, module) {
    var path4 = __require("path");
    var fs2 = __require("fs");
    function Mime() {
      this.types = /* @__PURE__ */ Object.create(null);
      this.extensions = /* @__PURE__ */ Object.create(null);
    }
    Mime.prototype.define = function(map2) {
      for (var type in map2) {
        var exts = map2[type];
        for (var i = 0; i < exts.length; i++) {
          if (process.env.DEBUG_MIME && this.types[exts[i]]) {
            console.warn((this._loading || "define()").replace(/.*\//, ""), 'changes "' + exts[i] + '" extension type from ' + this.types[exts[i]] + " to " + type);
          }
          this.types[exts[i]] = type;
        }
        if (!this.extensions[type]) {
          this.extensions[type] = exts[0];
        }
      }
    };
    Mime.prototype.load = function(file2) {
      this._loading = file2;
      var map2 = {}, content = fs2.readFileSync(file2, "ascii"), lines = content.split(/[\r\n]+/);
      lines.forEach(function(line2) {
        var fields = line2.replace(/\s*#.*|^\s*|\s*$/g, "").split(/\s+/);
        map2[fields.shift()] = fields;
      });
      this.define(map2);
      this._loading = null;
    };
    Mime.prototype.lookup = function(path5, fallback) {
      var ext = path5.replace(/^.*[\.\/\\]/, "").toLowerCase();
      return this.types[ext] || fallback || this.default_type;
    };
    Mime.prototype.extension = function(mimeType) {
      var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase();
      return this.extensions[type];
    };
    var mime = new Mime();
    mime.define(require_types());
    mime.default_type = mime.lookup("bin");
    mime.Mime = Mime;
    mime.charsets = {
      lookup: function(mimeType, fallback) {
        return /^text\/|^application\/(javascript|json)/.test(mimeType) ? "UTF-8" : fallback;
      }
    };
    module.exports = mime;
  }
});

// ../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js
var require_ms2 = __commonJS({
  "../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js"(exports, module) {
    var s = 1e3;
    var m = s * 60;
    var h = m * 60;
    var d = h * 24;
    var w = d * 7;
    var y = d * 365.25;
    module.exports = function(val, options) {
      options = options || {};
      var type = typeof val;
      if (type === "string" && val.length > 0) {
        return parse3(val);
      } else if (type === "number" && isFinite(val)) {
        return options.long ? fmtLong(val) : fmtShort(val);
      }
      throw new Error(
        "val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
      );
    };
    function parse3(str) {
      str = String(str);
      if (str.length > 100) {
        return;
      }
      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
      );
      if (!match) {
        return;
      }
      var n = parseFloat(match[1]);
      var type = (match[2] || "ms").toLowerCase();
      switch (type) {
        case "years":
        case "year":
        case "yrs":
        case "yr":
        case "y":
          return n * y;
        case "weeks":
        case "week":
        case "w":
          return n * w;
        case "days":
        case "day":
        case "d":
          return n * d;
        case "hours":
        case "hour":
        case "hrs":
        case "hr":
        case "h":
          return n * h;
        case "minutes":
        case "minute":
        case "mins":
        case "min":
        case "m":
          return n * m;
        case "seconds":
        case "second":
        case "secs":
        case "sec":
        case "s":
          return n * s;
        case "milliseconds":
        case "millisecond":
        case "msecs":
        case "msec":
        case "ms":
          return n;
        default:
          return void 0;
      }
    }
    function fmtShort(ms) {
      var msAbs = Math.abs(ms);
      if (msAbs >= d) {
        return Math.round(ms / d) + "d";
      }
      if (msAbs >= h) {
        return Math.round(ms / h) + "h";
      }
      if (msAbs >= m) {
        return Math.round(ms / m) + "m";
      }
      if (msAbs >= s) {
        return Math.round(ms / s) + "s";
      }
      return ms + "ms";
    }
    function fmtLong(ms) {
      var msAbs = Math.abs(ms);
      if (msAbs >= d) {
        return plural(ms, msAbs, d, "day");
      }
      if (msAbs >= h) {
        return plural(ms, msAbs, h, "hour");
      }
      if (msAbs >= m) {
        return plural(ms, msAbs, m, "minute");
      }
      if (msAbs >= s) {
        return plural(ms, msAbs, s, "second");
      }
      return ms + " ms";
    }
    function plural(ms, msAbs, n, name) {
      var isPlural = msAbs >= n * 1.5;
      return Math.round(ms / n) + " " + name + (isPlural ? "s" : "");
    }
  }
});

// ../../node_modules/.pnpm/range-parser@1.2.1/node_modules/range-parser/index.js
var require_range_parser = __commonJS({
  "../../node_modules/.pnpm/range-parser@1.2.1/node_modules/range-parser/index.js"(exports, module) {
    "use strict";
    module.exports = rangeParser;
    function rangeParser(size, str, options) {
      if (typeof str !== "string") {
        throw new TypeError("argument str must be a string");
      }
      var index2 = str.indexOf("=");
      if (index2 === -1) {
        return -2;
      }
      var arr = str.slice(index2 + 1).split(",");
      var ranges = [];
      ranges.type = str.slice(0, index2);
      for (var i = 0; i < arr.length; i++) {
        var range = arr[i].split("-");
        var start = parseInt(range[0], 10);
        var end = parseInt(range[1], 10);
        if (isNaN(start)) {
          start = size - end;
          end = size - 1;
        } else if (isNaN(end)) {
          end = size - 1;
        }
        if (end > size - 1) {
          end = size - 1;
        }
        if (isNaN(start) || isNaN(end) || start > end || start < 0) {
          continue;
        }
        ranges.push({
          start,
          end
        });
      }
      if (ranges.length < 1) {
        return -1;
      }
      return options && options.combine ? combineRanges(ranges) : ranges;
    }
    function combineRanges(ranges) {
      var ordered = ranges.map(mapWithIndex).sort(sortByRangeStart);
      for (var j = 0, i = 1; i < ordered.length; i++) {
        var range = ordered[i];
        var current = ordered[j];
        if (range.start > current.end + 1) {
          ordered[++j] = range;
        } else if (range.end > current.end) {
          current.end = range.end;
          current.index = Math.min(current.index, range.index);
        }
      }
      ordered.length = j + 1;
      var combined = ordered.sort(sortByRangeIndex).map(mapWithoutIndex);
      combined.type = ranges.type;
      return combined;
    }
    function mapWithIndex(range, index2) {
      return {
        start: range.start,
        end: range.end,
        index: index2
      };
    }
    function mapWithoutIndex(range) {
      return {
        start: range.start,
        end: range.end
      };
    }
    function sortByRangeIndex(a, b) {
      return a.index - b.index;
    }
    function sortByRangeStart(a, b) {
      return a.start - b.start;
    }
  }
});

// ../../node_modules/.pnpm/send@0.19.0/node_modules/send/index.js
var require_send = __commonJS({
  "../../node_modules/.pnpm/send@0.19.0/node_modules/send/index.js"(exports, module) {
    "use strict";
    var createError = require_http_errors();
    var debug = require_src()("send");
    var deprecate = require_depd()("send");
    var destroy = require_destroy();
    var encodeUrl = require_encodeurl2();
    var escapeHtml2 = require_escape_html();
    var etag = require_etag();
    var fresh = require_fresh();
    var fs2 = __require("fs");
    var mime = require_mime();
    var ms = require_ms2();
    var onFinished = require_on_finished();
    var parseRange = require_range_parser();
    var path4 = __require("path");
    var statuses = require_statuses();
    var Stream = __require("stream");
    var util2 = __require("util");
    var extname = path4.extname;
    var join = path4.join;
    var normalize = path4.normalize;
    var resolve = path4.resolve;
    var sep = path4.sep;
    var BYTES_RANGE_REGEXP = /^ *bytes=/;
    var MAX_MAXAGE = 60 * 60 * 24 * 365 * 1e3;
    var UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/;
    module.exports = send;
    module.exports.mime = mime;
    function send(req, path5, options) {
      return new SendStream(req, path5, options);
    }
    function SendStream(req, path5, options) {
      Stream.call(this);
      var opts = options || {};
      this.options = opts;
      this.path = path5;
      this.req = req;
      this._acceptRanges = opts.acceptRanges !== void 0 ? Boolean(opts.acceptRanges) : true;
      this._cacheControl = opts.cacheControl !== void 0 ? Boolean(opts.cacheControl) : true;
      this._etag = opts.etag !== void 0 ? Boolean(opts.etag) : true;
      this._dotfiles = opts.dotfiles !== void 0 ? opts.dotfiles : "ignore";
      if (this._dotfiles !== "ignore" && this._dotfiles !== "allow" && this._dotfiles !== "deny") {
        throw new TypeError('dotfiles option must be "allow", "deny", or "ignore"');
      }
      this._hidden = Boolean(opts.hidden);
      if (opts.hidden !== void 0) {
        deprecate("hidden: use dotfiles: '" + (this._hidden ? "allow" : "ignore") + "' instead");
      }
      if (opts.dotfiles === void 0) {
        this._dotfiles = void 0;
      }
      this._extensions = opts.extensions !== void 0 ? normalizeList(opts.extensions, "extensions option") : [];
      this._immutable = opts.immutable !== void 0 ? Boolean(opts.immutable) : false;
      this._index = opts.index !== void 0 ? normalizeList(opts.index, "index option") : ["index.html"];
      this._lastModified = opts.lastModified !== void 0 ? Boolean(opts.lastModified) : true;
      this._maxage = opts.maxAge || opts.maxage;
      this._maxage = typeof this._maxage === "string" ? ms(this._maxage) : Number(this._maxage);
      this._maxage = !isNaN(this._maxage) ? Math.min(Math.max(0, this._maxage), MAX_MAXAGE) : 0;
      this._root = opts.root ? resolve(opts.root) : null;
      if (!this._root && opts.from) {
        this.from(opts.from);
      }
    }
    util2.inherits(SendStream, Stream);
    SendStream.prototype.etag = deprecate.function(function etag2(val) {
      this._etag = Boolean(val);
      debug("etag %s", this._etag);
      return this;
    }, "send.etag: pass etag as option");
    SendStream.prototype.hidden = deprecate.function(function hidden(val) {
      this._hidden = Boolean(val);
      this._dotfiles = void 0;
      debug("hidden %s", this._hidden);
      return this;
    }, "send.hidden: use dotfiles option");
    SendStream.prototype.index = deprecate.function(function index2(paths) {
      var index3 = !paths ? [] : normalizeList(paths, "paths argument");
      debug("index %o", paths);
      this._index = index3;
      return this;
    }, "send.index: pass index as option");
    SendStream.prototype.root = function root(path5) {
      this._root = resolve(String(path5));
      debug("root %s", this._root);
      return this;
    };
    SendStream.prototype.from = deprecate.function(
      SendStream.prototype.root,
      "send.from: pass root as option"
    );
    SendStream.prototype.root = deprecate.function(
      SendStream.prototype.root,
      "send.root: pass root as option"
    );
    SendStream.prototype.maxage = deprecate.function(function maxage(maxAge) {
      this._maxage = typeof maxAge === "string" ? ms(maxAge) : Number(maxAge);
      this._maxage = !isNaN(this._maxage) ? Math.min(Math.max(0, this._maxage), MAX_MAXAGE) : 0;
      debug("max-age %d", this._maxage);
      return this;
    }, "send.maxage: pass maxAge as option");
    SendStream.prototype.error = function error40(status, err) {
      if (hasListeners(this, "error")) {
        return this.emit("error", createHttpError(status, err));
      }
      var res = this.res;
      var msg = statuses.message[status] || String(status);
      var doc = createHtmlDocument("Error", escapeHtml2(msg));
      clearHeaders(res);
      if (err && err.headers) {
        setHeaders(res, err.headers);
      }
      res.statusCode = status;
      res.setHeader("Content-Type", "text/html; charset=UTF-8");
      res.setHeader("Content-Length", Buffer.byteLength(doc));
      res.setHeader("Content-Security-Policy", "default-src 'none'");
      res.setHeader("X-Content-Type-Options", "nosniff");
      res.end(doc);
    };
    SendStream.prototype.hasTrailingSlash = function hasTrailingSlash() {
      return this.path[this.path.length - 1] === "/";
    };
    SendStream.prototype.isConditionalGET = function isConditionalGET() {
      return this.req.headers["if-match"] || this.req.headers["if-unmodified-since"] || this.req.headers["if-none-match"] || this.req.headers["if-modified-since"];
    };
    SendStream.prototype.isPreconditionFailure = function isPreconditionFailure() {
      var req = this.req;
      var res = this.res;
      var match = req.headers["if-match"];
      if (match) {
        var etag2 = res.getHeader("ETag");
        return !etag2 || match !== "*" && parseTokenList(match).every(function(match2) {
          return match2 !== etag2 && match2 !== "W/" + etag2 && "W/" + match2 !== etag2;
        });
      }
      var unmodifiedSince = parseHttpDate(req.headers["if-unmodified-since"]);
      if (!isNaN(unmodifiedSince)) {
        var lastModified = parseHttpDate(res.getHeader("Last-Modified"));
        return isNaN(lastModified) || lastModified > unmodifiedSince;
      }
      return false;
    };
    SendStream.prototype.removeContentHeaderFields = function removeContentHeaderFields() {
      var res = this.res;
      res.removeHeader("Content-Encoding");
      res.removeHeader("Content-Language");
      res.removeHeader("Content-Length");
      res.removeHeader("Content-Range");
      res.removeHeader("Content-Type");
    };
    SendStream.prototype.notModified = function notModified() {
      var res = this.res;
      debug("not modified");
      this.removeContentHeaderFields();
      res.statusCode = 304;
      res.end();
    };
    SendStream.prototype.headersAlreadySent = function headersAlreadySent() {
      var err = new Error("Can't set headers after they are sent.");
      debug("headers already sent");
      this.error(500, err);
    };
    SendStream.prototype.isCachable = function isCachable() {
      var statusCode = this.res.statusCode;
      return statusCode >= 200 && statusCode < 300 || statusCode === 304;
    };
    SendStream.prototype.onStatError = function onStatError(error40) {
      switch (error40.code) {
        case "ENAMETOOLONG":
        case "ENOENT":
        case "ENOTDIR":
          this.error(404, error40);
          break;
        default:
          this.error(500, error40);
          break;
      }
    };
    SendStream.prototype.isFresh = function isFresh() {
      return fresh(this.req.headers, {
        etag: this.res.getHeader("ETag"),
        "last-modified": this.res.getHeader("Last-Modified")
      });
    };
    SendStream.prototype.isRangeFresh = function isRangeFresh() {
      var ifRange = this.req.headers["if-range"];
      if (!ifRange) {
        return true;
      }
      if (ifRange.indexOf('"') !== -1) {
        var etag2 = this.res.getHeader("ETag");
        return Boolean(etag2 && ifRange.indexOf(etag2) !== -1);
      }
      var lastModified = this.res.getHeader("Last-Modified");
      return parseHttpDate(lastModified) <= parseHttpDate(ifRange);
    };
    SendStream.prototype.redirect = function redirect(path5) {
      var res = this.res;
      if (hasListeners(this, "directory")) {
        this.emit("directory", res, path5);
        return;
      }
      if (this.hasTrailingSlash()) {
        this.error(403);
        return;
      }
      var loc = encodeUrl(collapseLeadingSlashes(this.path + "/"));
      var doc = createHtmlDocument("Redirecting", "Redirecting to " + escapeHtml2(loc));
      res.statusCode = 301;
      res.setHeader("Content-Type", "text/html; charset=UTF-8");
      res.setHeader("Content-Length", Buffer.byteLength(doc));
      res.setHeader("Content-Security-Policy", "default-src 'none'");
      res.setHeader("X-Content-Type-Options", "nosniff");
      res.setHeader("Location", loc);
      res.end(doc);
    };
    SendStream.prototype.pipe = function pipe2(res) {
      var root = this._root;
      this.res = res;
      var path5 = decode(this.path);
      if (path5 === -1) {
        this.error(400);
        return res;
      }
      if (~path5.indexOf("\0")) {
        this.error(400);
        return res;
      }
      var parts;
      if (root !== null) {
        if (path5) {
          path5 = normalize("." + sep + path5);
        }
        if (UP_PATH_REGEXP.test(path5)) {
          debug('malicious path "%s"', path5);
          this.error(403);
          return res;
        }
        parts = path5.split(sep);
        path5 = normalize(join(root, path5));
      } else {
        if (UP_PATH_REGEXP.test(path5)) {
          debug('malicious path "%s"', path5);
          this.error(403);
          return res;
        }
        parts = normalize(path5).split(sep);
        path5 = resolve(path5);
      }
      if (containsDotFile(parts)) {
        var access = this._dotfiles;
        if (access === void 0) {
          access = parts[parts.length - 1][0] === "." ? this._hidden ? "allow" : "ignore" : "allow";
        }
        debug('%s dotfile "%s"', access, path5);
        switch (access) {
          case "allow":
            break;
          case "deny":
            this.error(403);
            return res;
          case "ignore":
          default:
            this.error(404);
            return res;
        }
      }
      if (this._index.length && this.hasTrailingSlash()) {
        this.sendIndex(path5);
        return res;
      }
      this.sendFile(path5);
      return res;
    };
    SendStream.prototype.send = function send2(path5, stat) {
      var len = stat.size;
      var options = this.options;
      var opts = {};
      var res = this.res;
      var req = this.req;
      var ranges = req.headers.range;
      var offset = options.start || 0;
      if (headersSent(res)) {
        this.headersAlreadySent();
        return;
      }
      debug('pipe "%s"', path5);
      this.setHeader(path5, stat);
      this.type(path5);
      if (this.isConditionalGET()) {
        if (this.isPreconditionFailure()) {
          this.error(412);
          return;
        }
        if (this.isCachable() && this.isFresh()) {
          this.notModified();
          return;
        }
      }
      len = Math.max(0, len - offset);
      if (options.end !== void 0) {
        var bytes = options.end - offset + 1;
        if (len > bytes) len = bytes;
      }
      if (this._acceptRanges && BYTES_RANGE_REGEXP.test(ranges)) {
        ranges = parseRange(len, ranges, {
          combine: true
        });
        if (!this.isRangeFresh()) {
          debug("range stale");
          ranges = -2;
        }
        if (ranges === -1) {
          debug("range unsatisfiable");
          res.setHeader("Content-Range", contentRange("bytes", len));
          return this.error(416, {
            headers: { "Content-Range": res.getHeader("Content-Range") }
          });
        }
        if (ranges !== -2 && ranges.length === 1) {
          debug("range %j", ranges);
          res.statusCode = 206;
          res.setHeader("Content-Range", contentRange("bytes", len, ranges[0]));
          offset += ranges[0].start;
          len = ranges[0].end - ranges[0].start + 1;
        }
      }
      for (var prop in options) {
        opts[prop] = options[prop];
      }
      opts.start = offset;
      opts.end = Math.max(offset, offset + len - 1);
      res.setHeader("Content-Length", len);
      if (req.method === "HEAD") {
        res.end();
        return;
      }
      this.stream(path5, opts);
    };
    SendStream.prototype.sendFile = function sendFile(path5) {
      var i = 0;
      var self = this;
      debug('stat "%s"', path5);
      fs2.stat(path5, function onstat(err, stat) {
        if (err && err.code === "ENOENT" && !extname(path5) && path5[path5.length - 1] !== sep) {
          return next(err);
        }
        if (err) return self.onStatError(err);
        if (stat.isDirectory()) return self.redirect(path5);
        self.emit("file", path5, stat);
        self.send(path5, stat);
      });
      function next(err) {
        if (self._extensions.length <= i) {
          return err ? self.onStatError(err) : self.error(404);
        }
        var p = path5 + "." + self._extensions[i++];
        debug('stat "%s"', p);
        fs2.stat(p, function(err2, stat) {
          if (err2) return next(err2);
          if (stat.isDirectory()) return next();
          self.emit("file", p, stat);
          self.send(p, stat);
        });
      }
    };
    SendStream.prototype.sendIndex = function sendIndex(path5) {
      var i = -1;
      var self = this;
      function next(err) {
        if (++i >= self._index.length) {
          if (err) return self.onStatError(err);
          return self.error(404);
        }
        var p = join(path5, self._index[i]);
        debug('stat "%s"', p);
        fs2.stat(p, function(err2, stat) {
          if (err2) return next(err2);
          if (stat.isDirectory()) return next();
          self.emit("file", p, stat);
          self.send(p, stat);
        });
      }
      next();
    };
    SendStream.prototype.stream = function stream(path5, options) {
      var self = this;
      var res = this.res;
      var stream2 = fs2.createReadStream(path5, options);
      this.emit("stream", stream2);
      stream2.pipe(res);
      function cleanup() {
        destroy(stream2, true);
      }
      onFinished(res, cleanup);
      stream2.on("error", function onerror(err) {
        cleanup();
        self.onStatError(err);
      });
      stream2.on("end", function onend() {
        self.emit("end");
      });
    };
    SendStream.prototype.type = function type(path5) {
      var res = this.res;
      if (res.getHeader("Content-Type")) return;
      var type2 = mime.lookup(path5);
      if (!type2) {
        debug("no content-type");
        return;
      }
      var charset = mime.charsets.lookup(type2);
      debug("content-type %s", type2);
      res.setHeader("Content-Type", type2 + (charset ? "; charset=" + charset : ""));
    };
    SendStream.prototype.setHeader = function setHeader(path5, stat) {
      var res = this.res;
      this.emit("headers", res, path5, stat);
      if (this._acceptRanges && !res.getHeader("Accept-Ranges")) {
        debug("accept ranges");
        res.setHeader("Accept-Ranges", "bytes");
      }
      if (this._cacheControl && !res.getHeader("Cache-Control")) {
        var cacheControl = "public, max-age=" + Math.floor(this._maxage / 1e3);
        if (this._immutable) {
          cacheControl += ", immutable";
        }
        debug("cache-control %s", cacheControl);
        res.setHeader("Cache-Control", cacheControl);
      }
      if (this._lastModified && !res.getHeader("Last-Modified")) {
        var modified = stat.mtime.toUTCString();
        debug("modified %s", modified);
        res.setHeader("Last-Modified", modified);
      }
      if (this._etag && !res.getHeader("ETag")) {
        var val = etag(stat);
        debug("etag %s", val);
        res.setHeader("ETag", val);
      }
    };
    function clearHeaders(res) {
      var headers = getHeaderNames(res);
      for (var i = 0; i < headers.length; i++) {
        res.removeHeader(headers[i]);
      }
    }
    function collapseLeadingSlashes(str) {
      for (var i = 0; i < str.length; i++) {
        if (str[i] !== "/") {
          break;
        }
      }
      return i > 1 ? "/" + str.substr(i) : str;
    }
    function containsDotFile(parts) {
      for (var i = 0; i < parts.length; i++) {
        var part = parts[i];
        if (part.length > 1 && part[0] === ".") {
          return true;
        }
      }
      return false;
    }
    function contentRange(type, size, range) {
      return type + " " + (range ? range.start + "-" + range.end : "*") + "/" + size;
    }
    function createHtmlDocument(title, body) {
      return '<!DOCTYPE html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n<title>' + title + "</title>\n</head>\n<body>\n<pre>" + body + "</pre>\n</body>\n</html>\n";
    }
    function createHttpError(status, err) {
      if (!err) {
        return createError(status);
      }
      return err instanceof Error ? createError(status, err, { expose: false }) : createError(status, err);
    }
    function decode(path5) {
      try {
        return decodeURIComponent(path5);
      } catch (err) {
        return -1;
      }
    }
    function getHeaderNames(res) {
      return typeof res.getHeaderNames !== "function" ? Object.keys(res._headers || {}) : res.getHeaderNames();
    }
    function hasListeners(emitter, type) {
      var count3 = typeof emitter.listenerCount !== "function" ? emitter.listeners(type).length : emitter.listenerCount(type);
      return count3 > 0;
    }
    function headersSent(res) {
      return typeof res.headersSent !== "boolean" ? Boolean(res._header) : res.headersSent;
    }
    function normalizeList(val, name) {
      var list = [].concat(val || []);
      for (var i = 0; i < list.length; i++) {
        if (typeof list[i] !== "string") {
          throw new TypeError(name + " must be array of strings or false");
        }
      }
      return list;
    }
    function parseHttpDate(date6) {
      var timestamp2 = date6 && Date.parse(date6);
      return typeof timestamp2 === "number" ? timestamp2 : NaN;
    }
    function parseTokenList(str) {
      var end = 0;
      var list = [];
      var start = 0;
      for (var i = 0, len = str.length; i < len; i++) {
        switch (str.charCodeAt(i)) {
          case 32:
            if (start === end) {
              start = end = i + 1;
            }
            break;
          case 44:
            if (start !== end) {
              list.push(str.substring(start, end));
            }
            start = end = i + 1;
            break;
          default:
            end = i + 1;
            break;
        }
      }
      if (start !== end) {
        list.push(str.substring(start, end));
      }
      return list;
    }
    function setHeaders(res, headers) {
      var keys = Object.keys(headers);
      for (var i = 0; i < keys.length; i++) {
        var key = keys[i];
        res.setHeader(key, headers[key]);
      }
    }
  }
});

// ../../node_modules/.pnpm/forwarded@0.2.0/node_modules/forwarded/index.js
var require_forwarded = __commonJS({
  "../../node_modules/.pnpm/forwarded@0.2.0/node_modules/forwarded/index.js"(exports, module) {
    "use strict";
    module.exports = forwarded;
    function forwarded(req) {
      if (!req) {
        throw new TypeError("argument req is required");
      }
      var proxyAddrs = parse3(req.headers["x-forwarded-for"] || "");
      var socketAddr = getSocketAddr(req);
      var addrs = [socketAddr].concat(proxyAddrs);
      return addrs;
    }
    function getSocketAddr(req) {
      return req.socket ? req.socket.remoteAddress : req.connection.remoteAddress;
    }
    function parse3(header) {
      var end = header.length;
      var list = [];
      var start = header.length;
      for (var i = header.length - 1; i >= 0; i--) {
        switch (header.charCodeAt(i)) {
          case 32:
            if (start === end) {
              start = end = i;
            }
            break;
          case 44:
            if (start !== end) {
              list.push(header.substring(start, end));
            }
            start = end = i;
            break;
          default:
            start = i;
            break;
        }
      }
      if (start !== end) {
        list.push(header.substring(start, end));
      }
      return list;
    }
  }
});

// ../../node_modules/.pnpm/ipaddr.js@1.9.1/node_modules/ipaddr.js/lib/ipaddr.js
var require_ipaddr = __commonJS({
  "../../node_modules/.pnpm/ipaddr.js@1.9.1/node_modules/ipaddr.js/lib/ipaddr.js"(exports, module) {
    (function() {
      var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root, zoneIndex;
      ipaddr = {};
      root = this;
      if (typeof module !== "undefined" && module !== null && module.exports) {
        module.exports = ipaddr;
      } else {
        root["ipaddr"] = ipaddr;
      }
      matchCIDR = function(first, second, partSize, cidrBits) {
        var part, shift;
        if (first.length !== second.length) {
          throw new Error("ipaddr: cannot match CIDR for objects with different lengths");
        }
        part = 0;
        while (cidrBits > 0) {
          shift = partSize - cidrBits;
          if (shift < 0) {
            shift = 0;
          }
          if (first[part] >> shift !== second[part] >> shift) {
            return false;
          }
          cidrBits -= partSize;
          part += 1;
        }
        return true;
      };
      ipaddr.subnetMatch = function(address, rangeList, defaultName) {
        var k, len, rangeName, rangeSubnets, subnet;
        if (defaultName == null) {
          defaultName = "unicast";
        }
        for (rangeName in rangeList) {
          rangeSubnets = rangeList[rangeName];
          if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) {
            rangeSubnets = [rangeSubnets];
          }
          for (k = 0, len = rangeSubnets.length; k < len; k++) {
            subnet = rangeSubnets[k];
            if (address.kind() === subnet[0].kind()) {
              if (address.match.apply(address, subnet)) {
                return rangeName;
              }
            }
          }
        }
        return defaultName;
      };
      ipaddr.IPv4 = (function() {
        function IPv4(octets) {
          var k, len, octet;
          if (octets.length !== 4) {
            throw new Error("ipaddr: ipv4 octet count should be 4");
          }
          for (k = 0, len = octets.length; k < len; k++) {
            octet = octets[k];
            if (!(0 <= octet && octet <= 255)) {
              throw new Error("ipaddr: ipv4 octet should fit in 8 bits");
            }
          }
          this.octets = octets;
        }
        IPv4.prototype.kind = function() {
          return "ipv4";
        };
        IPv4.prototype.toString = function() {
          return this.octets.join(".");
        };
        IPv4.prototype.toNormalizedString = function() {
          return this.toString();
        };
        IPv4.prototype.toByteArray = function() {
          return this.octets.slice(0);
        };
        IPv4.prototype.match = function(other, cidrRange) {
          var ref;
          if (cidrRange === void 0) {
            ref = other, other = ref[0], cidrRange = ref[1];
          }
          if (other.kind() !== "ipv4") {
            throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");
          }
          return matchCIDR(this.octets, other.octets, 8, cidrRange);
        };
        IPv4.prototype.SpecialRanges = {
          unspecified: [[new IPv4([0, 0, 0, 0]), 8]],
          broadcast: [[new IPv4([255, 255, 255, 255]), 32]],
          multicast: [[new IPv4([224, 0, 0, 0]), 4]],
          linkLocal: [[new IPv4([169, 254, 0, 0]), 16]],
          loopback: [[new IPv4([127, 0, 0, 0]), 8]],
          carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]],
          "private": [[new IPv4([10, 0, 0, 0]), 8], [new IPv4([172, 16, 0, 0]), 12], [new IPv4([192, 168, 0, 0]), 16]],
          reserved: [[new IPv4([192, 0, 0, 0]), 24], [new IPv4([192, 0, 2, 0]), 24], [new IPv4([192, 88, 99, 0]), 24], [new IPv4([198, 51, 100, 0]), 24], [new IPv4([203, 0, 113, 0]), 24], [new IPv4([240, 0, 0, 0]), 4]]
        };
        IPv4.prototype.range = function() {
          return ipaddr.subnetMatch(this, this.SpecialRanges);
        };
        IPv4.prototype.toIPv4MappedAddress = function() {
          return ipaddr.IPv6.parse("::ffff:" + this.toString());
        };
        IPv4.prototype.prefixLengthFromSubnetMask = function() {
          var cidr2, i, k, octet, stop, zeros, zerotable;
          zerotable = {
            0: 8,
            128: 7,
            192: 6,
            224: 5,
            240: 4,
            248: 3,
            252: 2,
            254: 1,
            255: 0
          };
          cidr2 = 0;
          stop = false;
          for (i = k = 3; k >= 0; i = k += -1) {
            octet = this.octets[i];
            if (octet in zerotable) {
              zeros = zerotable[octet];
              if (stop && zeros !== 0) {
                return null;
              }
              if (zeros !== 8) {
                stop = true;
              }
              cidr2 += zeros;
            } else {
              return null;
            }
          }
          return 32 - cidr2;
        };
        return IPv4;
      })();
      ipv4Part = "(0?\\d+|0x[a-f0-9]+)";
      ipv4Regexes = {
        fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", "i"),
        longValue: new RegExp("^" + ipv4Part + "$", "i")
      };
      ipaddr.IPv4.parser = function(string4) {
        var match, parseIntAuto, part, shift, value;
        parseIntAuto = function(string5) {
          if (string5[0] === "0" && string5[1] !== "x") {
            return parseInt(string5, 8);
          } else {
            return parseInt(string5);
          }
        };
        if (match = string4.match(ipv4Regexes.fourOctet)) {
          return (function() {
            var k, len, ref, results;
            ref = match.slice(1, 6);
            results = [];
            for (k = 0, len = ref.length; k < len; k++) {
              part = ref[k];
              results.push(parseIntAuto(part));
            }
            return results;
          })();
        } else if (match = string4.match(ipv4Regexes.longValue)) {
          value = parseIntAuto(match[1]);
          if (value > 4294967295 || value < 0) {
            throw new Error("ipaddr: address outside defined range");
          }
          return (function() {
            var k, results;
            results = [];
            for (shift = k = 0; k <= 24; shift = k += 8) {
              results.push(value >> shift & 255);
            }
            return results;
          })().reverse();
        } else {
          return null;
        }
      };
      ipaddr.IPv6 = (function() {
        function IPv6(parts, zoneId) {
          var i, k, l, len, part, ref;
          if (parts.length === 16) {
            this.parts = [];
            for (i = k = 0; k <= 14; i = k += 2) {
              this.parts.push(parts[i] << 8 | parts[i + 1]);
            }
          } else if (parts.length === 8) {
            this.parts = parts;
          } else {
            throw new Error("ipaddr: ipv6 part count should be 8 or 16");
          }
          ref = this.parts;
          for (l = 0, len = ref.length; l < len; l++) {
            part = ref[l];
            if (!(0 <= part && part <= 65535)) {
              throw new Error("ipaddr: ipv6 part should fit in 16 bits");
            }
          }
          if (zoneId) {
            this.zoneId = zoneId;
          }
        }
        IPv6.prototype.kind = function() {
          return "ipv6";
        };
        IPv6.prototype.toString = function() {
          return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/, "::");
        };
        IPv6.prototype.toRFC5952String = function() {
          var bestMatchIndex, bestMatchLength, match, regex, string4;
          regex = /((^|:)(0(:|$)){2,})/g;
          string4 = this.toNormalizedString();
          bestMatchIndex = 0;
          bestMatchLength = -1;
          while (match = regex.exec(string4)) {
            if (match[0].length > bestMatchLength) {
              bestMatchIndex = match.index;
              bestMatchLength = match[0].length;
            }
          }
          if (bestMatchLength < 0) {
            return string4;
          }
          return string4.substring(0, bestMatchIndex) + "::" + string4.substring(bestMatchIndex + bestMatchLength);
        };
        IPv6.prototype.toByteArray = function() {
          var bytes, k, len, part, ref;
          bytes = [];
          ref = this.parts;
          for (k = 0, len = ref.length; k < len; k++) {
            part = ref[k];
            bytes.push(part >> 8);
            bytes.push(part & 255);
          }
          return bytes;
        };
        IPv6.prototype.toNormalizedString = function() {
          var addr, part, suffix;
          addr = (function() {
            var k, len, ref, results;
            ref = this.parts;
            results = [];
            for (k = 0, len = ref.length; k < len; k++) {
              part = ref[k];
              results.push(part.toString(16));
            }
            return results;
          }).call(this).join(":");
          suffix = "";
          if (this.zoneId) {
            suffix = "%" + this.zoneId;
          }
          return addr + suffix;
        };
        IPv6.prototype.toFixedLengthString = function() {
          var addr, part, suffix;
          addr = (function() {
            var k, len, ref, results;
            ref = this.parts;
            results = [];
            for (k = 0, len = ref.length; k < len; k++) {
              part = ref[k];
              results.push(part.toString(16).padStart(4, "0"));
            }
            return results;
          }).call(this).join(":");
          suffix = "";
          if (this.zoneId) {
            suffix = "%" + this.zoneId;
          }
          return addr + suffix;
        };
        IPv6.prototype.match = function(other, cidrRange) {
          var ref;
          if (cidrRange === void 0) {
            ref = other, other = ref[0], cidrRange = ref[1];
          }
          if (other.kind() !== "ipv6") {
            throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");
          }
          return matchCIDR(this.parts, other.parts, 16, cidrRange);
        };
        IPv6.prototype.SpecialRanges = {
          unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128],
          linkLocal: [new IPv6([65152, 0, 0, 0, 0, 0, 0, 0]), 10],
          multicast: [new IPv6([65280, 0, 0, 0, 0, 0, 0, 0]), 8],
          loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128],
          uniqueLocal: [new IPv6([64512, 0, 0, 0, 0, 0, 0, 0]), 7],
          ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 65535, 0, 0]), 96],
          rfc6145: [new IPv6([0, 0, 0, 0, 65535, 0, 0, 0]), 96],
          rfc6052: [new IPv6([100, 65435, 0, 0, 0, 0, 0, 0]), 96],
          "6to4": [new IPv6([8194, 0, 0, 0, 0, 0, 0, 0]), 16],
          teredo: [new IPv6([8193, 0, 0, 0, 0, 0, 0, 0]), 32],
          reserved: [[new IPv6([8193, 3512, 0, 0, 0, 0, 0, 0]), 32]]
        };
        IPv6.prototype.range = function() {
          return ipaddr.subnetMatch(this, this.SpecialRanges);
        };
        IPv6.prototype.isIPv4MappedAddress = function() {
          return this.range() === "ipv4Mapped";
        };
        IPv6.prototype.toIPv4Address = function() {
          var high, low, ref;
          if (!this.isIPv4MappedAddress()) {
            throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");
          }
          ref = this.parts.slice(-2), high = ref[0], low = ref[1];
          return new ipaddr.IPv4([high >> 8, high & 255, low >> 8, low & 255]);
        };
        IPv6.prototype.prefixLengthFromSubnetMask = function() {
          var cidr2, i, k, part, stop, zeros, zerotable;
          zerotable = {
            0: 16,
            32768: 15,
            49152: 14,
            57344: 13,
            61440: 12,
            63488: 11,
            64512: 10,
            65024: 9,
            65280: 8,
            65408: 7,
            65472: 6,
            65504: 5,
            65520: 4,
            65528: 3,
            65532: 2,
            65534: 1,
            65535: 0
          };
          cidr2 = 0;
          stop = false;
          for (i = k = 7; k >= 0; i = k += -1) {
            part = this.parts[i];
            if (part in zerotable) {
              zeros = zerotable[part];
              if (stop && zeros !== 0) {
                return null;
              }
              if (zeros !== 16) {
                stop = true;
              }
              cidr2 += zeros;
            } else {
              return null;
            }
          }
          return 128 - cidr2;
        };
        return IPv6;
      })();
      ipv6Part = "(?:[0-9a-f]+::?)+";
      zoneIndex = "%[0-9a-z]{1,}";
      ipv6Regexes = {
        zoneIndex: new RegExp(zoneIndex, "i"),
        "native": new RegExp("^(::)?(" + ipv6Part + ")?([0-9a-f]+)?(::)?(" + zoneIndex + ")?$", "i"),
        transitional: new RegExp("^((?:" + ipv6Part + ")|(?:::)(?:" + ipv6Part + ")?)" + (ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part) + ("(" + zoneIndex + ")?$"), "i")
      };
      expandIPv6 = function(string4, parts) {
        var colonCount, lastColon, part, replacement, replacementCount, zoneId;
        if (string4.indexOf("::") !== string4.lastIndexOf("::")) {
          return null;
        }
        zoneId = (string4.match(ipv6Regexes["zoneIndex"]) || [])[0];
        if (zoneId) {
          zoneId = zoneId.substring(1);
          string4 = string4.replace(/%.+$/, "");
        }
        colonCount = 0;
        lastColon = -1;
        while ((lastColon = string4.indexOf(":", lastColon + 1)) >= 0) {
          colonCount++;
        }
        if (string4.substr(0, 2) === "::") {
          colonCount--;
        }
        if (string4.substr(-2, 2) === "::") {
          colonCount--;
        }
        if (colonCount > parts) {
          return null;
        }
        replacementCount = parts - colonCount;
        replacement = ":";
        while (replacementCount--) {
          replacement += "0:";
        }
        string4 = string4.replace("::", replacement);
        if (string4[0] === ":") {
          string4 = string4.slice(1);
        }
        if (string4[string4.length - 1] === ":") {
          string4 = string4.slice(0, -1);
        }
        parts = (function() {
          var k, len, ref, results;
          ref = string4.split(":");
          results = [];
          for (k = 0, len = ref.length; k < len; k++) {
            part = ref[k];
            results.push(parseInt(part, 16));
          }
          return results;
        })();
        return {
          parts,
          zoneId
        };
      };
      ipaddr.IPv6.parser = function(string4) {
        var addr, k, len, match, octet, octets, zoneId;
        if (ipv6Regexes["native"].test(string4)) {
          return expandIPv6(string4, 8);
        } else if (match = string4.match(ipv6Regexes["transitional"])) {
          zoneId = match[6] || "";
          addr = expandIPv6(match[1].slice(0, -1) + zoneId, 6);
          if (addr.parts) {
            octets = [parseInt(match[2]), parseInt(match[3]), parseInt(match[4]), parseInt(match[5])];
            for (k = 0, len = octets.length; k < len; k++) {
              octet = octets[k];
              if (!(0 <= octet && octet <= 255)) {
                return null;
              }
            }
            addr.parts.push(octets[0] << 8 | octets[1]);
            addr.parts.push(octets[2] << 8 | octets[3]);
            return {
              parts: addr.parts,
              zoneId: addr.zoneId
            };
          }
        }
        return null;
      };
      ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string4) {
        return this.parser(string4) !== null;
      };
      ipaddr.IPv4.isValid = function(string4) {
        var e;
        try {
          new this(this.parser(string4));
          return true;
        } catch (error1) {
          e = error1;
          return false;
        }
      };
      ipaddr.IPv4.isValidFourPartDecimal = function(string4) {
        if (ipaddr.IPv4.isValid(string4) && string4.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/)) {
          return true;
        } else {
          return false;
        }
      };
      ipaddr.IPv6.isValid = function(string4) {
        var addr, e;
        if (typeof string4 === "string" && string4.indexOf(":") === -1) {
          return false;
        }
        try {
          addr = this.parser(string4);
          new this(addr.parts, addr.zoneId);
          return true;
        } catch (error1) {
          e = error1;
          return false;
        }
      };
      ipaddr.IPv4.parse = function(string4) {
        var parts;
        parts = this.parser(string4);
        if (parts === null) {
          throw new Error("ipaddr: string is not formatted like ip address");
        }
        return new this(parts);
      };
      ipaddr.IPv6.parse = function(string4) {
        var addr;
        addr = this.parser(string4);
        if (addr.parts === null) {
          throw new Error("ipaddr: string is not formatted like ip address");
        }
        return new this(addr.parts, addr.zoneId);
      };
      ipaddr.IPv4.parseCIDR = function(string4) {
        var maskLength, match, parsed;
        if (match = string4.match(/^(.+)\/(\d+)$/)) {
          maskLength = parseInt(match[2]);
          if (maskLength >= 0 && maskLength <= 32) {
            parsed = [this.parse(match[1]), maskLength];
            Object.defineProperty(parsed, "toString", {
              value: function() {
                return this.join("/");
              }
            });
            return parsed;
          }
        }
        throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range");
      };
      ipaddr.IPv4.subnetMaskFromPrefixLength = function(prefix) {
        var filledOctetCount, j, octets;
        prefix = parseInt(prefix);
        if (prefix < 0 || prefix > 32) {
          throw new Error("ipaddr: invalid IPv4 prefix length");
        }
        octets = [0, 0, 0, 0];
        j = 0;
        filledOctetCount = Math.floor(prefix / 8);
        while (j < filledOctetCount) {
          octets[j] = 255;
          j++;
        }
        if (filledOctetCount < 4) {
          octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - prefix % 8;
        }
        return new this(octets);
      };
      ipaddr.IPv4.broadcastAddressFromCIDR = function(string4) {
        var cidr2, error40, i, ipInterfaceOctets, octets, subnetMaskOctets;
        try {
          cidr2 = this.parseCIDR(string4);
          ipInterfaceOctets = cidr2[0].toByteArray();
          subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr2[1]).toByteArray();
          octets = [];
          i = 0;
          while (i < 4) {
            octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255);
            i++;
          }
          return new this(octets);
        } catch (error1) {
          error40 = error1;
          throw new Error("ipaddr: the address does not have IPv4 CIDR format");
        }
      };
      ipaddr.IPv4.networkAddressFromCIDR = function(string4) {
        var cidr2, error40, i, ipInterfaceOctets, octets, subnetMaskOctets;
        try {
          cidr2 = this.parseCIDR(string4);
          ipInterfaceOctets = cidr2[0].toByteArray();
          subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr2[1]).toByteArray();
          octets = [];
          i = 0;
          while (i < 4) {
            octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10));
            i++;
          }
          return new this(octets);
        } catch (error1) {
          error40 = error1;
          throw new Error("ipaddr: the address does not have IPv4 CIDR format");
        }
      };
      ipaddr.IPv6.parseCIDR = function(string4) {
        var maskLength, match, parsed;
        if (match = string4.match(/^(.+)\/(\d+)$/)) {
          maskLength = parseInt(match[2]);
          if (maskLength >= 0 && maskLength <= 128) {
            parsed = [this.parse(match[1]), maskLength];
            Object.defineProperty(parsed, "toString", {
              value: function() {
                return this.join("/");
              }
            });
            return parsed;
          }
        }
        throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range");
      };
      ipaddr.isValid = function(string4) {
        return ipaddr.IPv6.isValid(string4) || ipaddr.IPv4.isValid(string4);
      };
      ipaddr.parse = function(string4) {
        if (ipaddr.IPv6.isValid(string4)) {
          return ipaddr.IPv6.parse(string4);
        } else if (ipaddr.IPv4.isValid(string4)) {
          return ipaddr.IPv4.parse(string4);
        } else {
          throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format");
        }
      };
      ipaddr.parseCIDR = function(string4) {
        var e;
        try {
          return ipaddr.IPv6.parseCIDR(string4);
        } catch (error1) {
          e = error1;
          try {
            return ipaddr.IPv4.parseCIDR(string4);
          } catch (error110) {
            e = error110;
            throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format");
          }
        }
      };
      ipaddr.fromByteArray = function(bytes) {
        var length;
        length = bytes.length;
        if (length === 4) {
          return new ipaddr.IPv4(bytes);
        } else if (length === 16) {
          return new ipaddr.IPv6(bytes);
        } else {
          throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address");
        }
      };
      ipaddr.process = function(string4) {
        var addr;
        addr = this.parse(string4);
        if (addr.kind() === "ipv6" && addr.isIPv4MappedAddress()) {
          return addr.toIPv4Address();
        } else {
          return addr;
        }
      };
    }).call(exports);
  }
});

// ../../node_modules/.pnpm/proxy-addr@2.0.7/node_modules/proxy-addr/index.js
var require_proxy_addr = __commonJS({
  "../../node_modules/.pnpm/proxy-addr@2.0.7/node_modules/proxy-addr/index.js"(exports, module) {
    "use strict";
    module.exports = proxyaddr;
    module.exports.all = alladdrs;
    module.exports.compile = compile;
    var forwarded = require_forwarded();
    var ipaddr = require_ipaddr();
    var DIGIT_REGEXP = /^[0-9]+$/;
    var isip = ipaddr.isValid;
    var parseip = ipaddr.parse;
    var IP_RANGES = {
      linklocal: ["169.254.0.0/16", "fe80::/10"],
      loopback: ["127.0.0.1/8", "::1/128"],
      uniquelocal: ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7"]
    };
    function alladdrs(req, trust) {
      var addrs = forwarded(req);
      if (!trust) {
        return addrs;
      }
      if (typeof trust !== "function") {
        trust = compile(trust);
      }
      for (var i = 0; i < addrs.length - 1; i++) {
        if (trust(addrs[i], i)) continue;
        addrs.length = i + 1;
      }
      return addrs;
    }
    function compile(val) {
      if (!val) {
        throw new TypeError("argument is required");
      }
      var trust;
      if (typeof val === "string") {
        trust = [val];
      } else if (Array.isArray(val)) {
        trust = val.slice();
      } else {
        throw new TypeError("unsupported trust argument");
      }
      for (var i = 0; i < trust.length; i++) {
        val = trust[i];
        if (!Object.prototype.hasOwnProperty.call(IP_RANGES, val)) {
          continue;
        }
        val = IP_RANGES[val];
        trust.splice.apply(trust, [i, 1].concat(val));
        i += val.length - 1;
      }
      return compileTrust(compileRangeSubnets(trust));
    }
    function compileRangeSubnets(arr) {
      var rangeSubnets = new Array(arr.length);
      for (var i = 0; i < arr.length; i++) {
        rangeSubnets[i] = parseipNotation(arr[i]);
      }
      return rangeSubnets;
    }
    function compileTrust(rangeSubnets) {
      var len = rangeSubnets.length;
      return len === 0 ? trustNone : len === 1 ? trustSingle(rangeSubnets[0]) : trustMulti(rangeSubnets);
    }
    function parseipNotation(note) {
      var pos = note.lastIndexOf("/");
      var str = pos !== -1 ? note.substring(0, pos) : note;
      if (!isip(str)) {
        throw new TypeError("invalid IP address: " + str);
      }
      var ip = parseip(str);
      if (pos === -1 && ip.kind() === "ipv6" && ip.isIPv4MappedAddress()) {
        ip = ip.toIPv4Address();
      }
      var max = ip.kind() === "ipv6" ? 128 : 32;
      var range = pos !== -1 ? note.substring(pos + 1, note.length) : null;
      if (range === null) {
        range = max;
      } else if (DIGIT_REGEXP.test(range)) {
        range = parseInt(range, 10);
      } else if (ip.kind() === "ipv4" && isip(range)) {
        range = parseNetmask(range);
      } else {
        range = null;
      }
      if (range <= 0 || range > max) {
        throw new TypeError("invalid range on address: " + note);
      }
      return [ip, range];
    }
    function parseNetmask(netmask) {
      var ip = parseip(netmask);
      var kind = ip.kind();
      return kind === "ipv4" ? ip.prefixLengthFromSubnetMask() : null;
    }
    function proxyaddr(req, trust) {
      if (!req) {
        throw new TypeError("req argument is required");
      }
      if (!trust) {
        throw new TypeError("trust argument is required");
      }
      var addrs = alladdrs(req, trust);
      var addr = addrs[addrs.length - 1];
      return addr;
    }
    function trustNone() {
      return false;
    }
    function trustMulti(subnets) {
      return function trust(addr) {
        if (!isip(addr)) return false;
        var ip = parseip(addr);
        var ipconv;
        var kind = ip.kind();
        for (var i = 0; i < subnets.length; i++) {
          var subnet = subnets[i];
          var subnetip = subnet[0];
          var subnetkind = subnetip.kind();
          var subnetrange = subnet[1];
          var trusted = ip;
          if (kind !== subnetkind) {
            if (subnetkind === "ipv4" && !ip.isIPv4MappedAddress()) {
              continue;
            }
            if (!ipconv) {
              ipconv = subnetkind === "ipv4" ? ip.toIPv4Address() : ip.toIPv4MappedAddress();
            }
            trusted = ipconv;
          }
          if (trusted.match(subnetip, subnetrange)) {
            return true;
          }
        }
        return false;
      };
    }
    function trustSingle(subnet) {
      var subnetip = subnet[0];
      var subnetkind = subnetip.kind();
      var subnetisipv4 = subnetkind === "ipv4";
      var subnetrange = subnet[1];
      return function trust(addr) {
        if (!isip(addr)) return false;
        var ip = parseip(addr);
        var kind = ip.kind();
        if (kind !== subnetkind) {
          if (subnetisipv4 && !ip.isIPv4MappedAddress()) {
            return false;
          }
          ip = subnetisipv4 ? ip.toIPv4Address() : ip.toIPv4MappedAddress();
        }
        return ip.match(subnetip, subnetrange);
      };
    }
  }
});

// ../../node_modules/.pnpm/express@4.21.2/node_modules/express/lib/utils.js
var require_utils2 = __commonJS({
  "../../node_modules/.pnpm/express@4.21.2/node_modules/express/lib/utils.js"(exports) {
    "use strict";
    var Buffer3 = require_safe_buffer().Buffer;
    var contentDisposition = require_content_disposition();
    var contentType = require_content_type();
    var deprecate = require_depd()("express");
    var flatten = require_array_flatten();
    var mime = require_send().mime;
    var etag = require_etag();
    var proxyaddr = require_proxy_addr();
    var qs = require_lib2();
    var querystring = __require("querystring");
    exports.etag = createETagGenerator({ weak: false });
    exports.wetag = createETagGenerator({ weak: true });
    exports.isAbsolute = function(path4) {
      if ("/" === path4[0]) return true;
      if (":" === path4[1] && ("\\" === path4[2] || "/" === path4[2])) return true;
      if ("\\\\" === path4.substring(0, 2)) return true;
    };
    exports.flatten = deprecate.function(
      flatten,
      "utils.flatten: use array-flatten npm module instead"
    );
    exports.normalizeType = function(type) {
      return ~type.indexOf("/") ? acceptParams(type) : { value: mime.lookup(type), params: {} };
    };
    exports.normalizeTypes = function(types3) {
      var ret = [];
      for (var i = 0; i < types3.length; ++i) {
        ret.push(exports.normalizeType(types3[i]));
      }
      return ret;
    };
    exports.contentDisposition = deprecate.function(
      contentDisposition,
      "utils.contentDisposition: use content-disposition npm module instead"
    );
    function acceptParams(str) {
      var parts = str.split(/ *; */);
      var ret = { value: parts[0], quality: 1, params: {} };
      for (var i = 1; i < parts.length; ++i) {
        var pms = parts[i].split(/ *= */);
        if ("q" === pms[0]) {
          ret.quality = parseFloat(pms[1]);
        } else {
          ret.params[pms[0]] = pms[1];
        }
      }
      return ret;
    }
    exports.compileETag = function(val) {
      var fn;
      if (typeof val === "function") {
        return val;
      }
      switch (val) {
        case true:
        case "weak":
          fn = exports.wetag;
          break;
        case false:
          break;
        case "strong":
          fn = exports.etag;
          break;
        default:
          throw new TypeError("unknown value for etag function: " + val);
      }
      return fn;
    };
    exports.compileQueryParser = function compileQueryParser(val) {
      var fn;
      if (typeof val === "function") {
        return val;
      }
      switch (val) {
        case true:
        case "simple":
          fn = querystring.parse;
          break;
        case false:
          fn = newObject;
          break;
        case "extended":
          fn = parseExtendedQueryString;
          break;
        default:
          throw new TypeError("unknown value for query parser function: " + val);
      }
      return fn;
    };
    exports.compileTrust = function(val) {
      if (typeof val === "function") return val;
      if (val === true) {
        return function() {
          return true;
        };
      }
      if (typeof val === "number") {
        return function(a, i) {
          return i < val;
        };
      }
      if (typeof val === "string") {
        val = val.split(",").map(function(v) {
          return v.trim();
        });
      }
      return proxyaddr.compile(val || []);
    };
    exports.setCharset = function setCharset(type, charset) {
      if (!type || !charset) {
        return type;
      }
      var parsed = contentType.parse(type);
      parsed.parameters.charset = charset;
      return contentType.format(parsed);
    };
    function createETagGenerator(options) {
      return function generateETag(body, encoding) {
        var buf = !Buffer3.isBuffer(body) ? Buffer3.from(body, encoding) : body;
        return etag(buf, options);
      };
    }
    function parseExtendedQueryString(str) {
      return qs.parse(str, {
        allowPrototypes: true
      });
    }
    function newObject() {
      return {};
    }
  }
});

// ../../node_modules/.pnpm/express@4.21.2/node_modules/express/lib/application.js
var require_application = __commonJS({
  "../../node_modules/.pnpm/express@4.21.2/node_modules/express/lib/application.js"(exports, module) {
    "use strict";
    var finalhandler = require_finalhandler();
    var Router16 = require_router();
    var methods = require_methods();
    var middleware = require_init();
    var query = require_query();
    var debug = require_src()("express:application");
    var View2 = require_view();
    var http2 = __require("http");
    var compileETag = require_utils2().compileETag;
    var compileQueryParser = require_utils2().compileQueryParser;
    var compileTrust = require_utils2().compileTrust;
    var deprecate = require_depd()("express");
    var flatten = require_array_flatten();
    var merge2 = require_utils_merge();
    var resolve = __require("path").resolve;
    var setPrototypeOf = require_setprototypeof();
    var hasOwnProperty = Object.prototype.hasOwnProperty;
    var slice = Array.prototype.slice;
    var app3 = exports = module.exports = {};
    var trustProxyDefaultSymbol = "@@symbol:trust_proxy_default";
    app3.init = function init() {
      this.cache = {};
      this.engines = {};
      this.settings = {};
      this.defaultConfiguration();
    };
    app3.defaultConfiguration = function defaultConfiguration() {
      var env = process.env.NODE_ENV || "development";
      this.enable("x-powered-by");
      this.set("etag", "weak");
      this.set("env", env);
      this.set("query parser", "extended");
      this.set("subdomain offset", 2);
      this.set("trust proxy", false);
      Object.defineProperty(this.settings, trustProxyDefaultSymbol, {
        configurable: true,
        value: true
      });
      debug("booting in %s mode", env);
      this.on("mount", function onmount(parent) {
        if (this.settings[trustProxyDefaultSymbol] === true && typeof parent.settings["trust proxy fn"] === "function") {
          delete this.settings["trust proxy"];
          delete this.settings["trust proxy fn"];
        }
        setPrototypeOf(this.request, parent.request);
        setPrototypeOf(this.response, parent.response);
        setPrototypeOf(this.engines, parent.engines);
        setPrototypeOf(this.settings, parent.settings);
      });
      this.locals = /* @__PURE__ */ Object.create(null);
      this.mountpath = "/";
      this.locals.settings = this.settings;
      this.set("view", View2);
      this.set("views", resolve("views"));
      this.set("jsonp callback name", "callback");
      if (env === "production") {
        this.enable("view cache");
      }
      Object.defineProperty(this, "router", {
        get: function() {
          throw new Error("'app.router' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.");
        }
      });
    };
    app3.lazyrouter = function lazyrouter() {
      if (!this._router) {
        this._router = new Router16({
          caseSensitive: this.enabled("case sensitive routing"),
          strict: this.enabled("strict routing")
        });
        this._router.use(query(this.get("query parser fn")));
        this._router.use(middleware.init(this));
      }
    };
    app3.handle = function handle(req, res, callback) {
      var router16 = this._router;
      var done = callback || finalhandler(req, res, {
        env: this.get("env"),
        onerror: logerror.bind(this)
      });
      if (!router16) {
        debug("no routes defined on app");
        done();
        return;
      }
      router16.handle(req, res, done);
    };
    app3.use = function use(fn) {
      var offset = 0;
      var path4 = "/";
      if (typeof fn !== "function") {
        var arg = fn;
        while (Array.isArray(arg) && arg.length !== 0) {
          arg = arg[0];
        }
        if (typeof arg !== "function") {
          offset = 1;
          path4 = fn;
        }
      }
      var fns = flatten(slice.call(arguments, offset));
      if (fns.length === 0) {
        throw new TypeError("app.use() requires a middleware function");
      }
      this.lazyrouter();
      var router16 = this._router;
      fns.forEach(function(fn2) {
        if (!fn2 || !fn2.handle || !fn2.set) {
          return router16.use(path4, fn2);
        }
        debug(".use app under %s", path4);
        fn2.mountpath = path4;
        fn2.parent = this;
        router16.use(path4, function mounted_app(req, res, next) {
          var orig = req.app;
          fn2.handle(req, res, function(err) {
            setPrototypeOf(req, orig.request);
            setPrototypeOf(res, orig.response);
            next(err);
          });
        });
        fn2.emit("mount", this);
      }, this);
      return this;
    };
    app3.route = function route(path4) {
      this.lazyrouter();
      return this._router.route(path4);
    };
    app3.engine = function engine(ext, fn) {
      if (typeof fn !== "function") {
        throw new Error("callback function required");
      }
      var extension = ext[0] !== "." ? "." + ext : ext;
      this.engines[extension] = fn;
      return this;
    };
    app3.param = function param(name, fn) {
      this.lazyrouter();
      if (Array.isArray(name)) {
        for (var i = 0; i < name.length; i++) {
          this.param(name[i], fn);
        }
        return this;
      }
      this._router.param(name, fn);
      return this;
    };
    app3.set = function set2(setting, val) {
      if (arguments.length === 1) {
        var settings = this.settings;
        while (settings && settings !== Object.prototype) {
          if (hasOwnProperty.call(settings, setting)) {
            return settings[setting];
          }
          settings = Object.getPrototypeOf(settings);
        }
        return void 0;
      }
      debug('set "%s" to %o', setting, val);
      this.settings[setting] = val;
      switch (setting) {
        case "etag":
          this.set("etag fn", compileETag(val));
          break;
        case "query parser":
          this.set("query parser fn", compileQueryParser(val));
          break;
        case "trust proxy":
          this.set("trust proxy fn", compileTrust(val));
          Object.defineProperty(this.settings, trustProxyDefaultSymbol, {
            configurable: true,
            value: false
          });
          break;
      }
      return this;
    };
    app3.path = function path4() {
      return this.parent ? this.parent.path() + this.mountpath : "";
    };
    app3.enabled = function enabled2(setting) {
      return Boolean(this.set(setting));
    };
    app3.disabled = function disabled2(setting) {
      return !this.set(setting);
    };
    app3.enable = function enable(setting) {
      return this.set(setting, true);
    };
    app3.disable = function disable(setting) {
      return this.set(setting, false);
    };
    methods.forEach(function(method) {
      app3[method] = function(path4) {
        if (method === "get" && arguments.length === 1) {
          return this.set(path4);
        }
        this.lazyrouter();
        var route = this._router.route(path4);
        route[method].apply(route, slice.call(arguments, 1));
        return this;
      };
    });
    app3.all = function all(path4) {
      this.lazyrouter();
      var route = this._router.route(path4);
      var args = slice.call(arguments, 1);
      for (var i = 0; i < methods.length; i++) {
        route[methods[i]].apply(route, args);
      }
      return this;
    };
    app3.del = deprecate.function(app3.delete, "app.del: Use app.delete instead");
    app3.render = function render(name, options, callback) {
      var cache = this.cache;
      var done = callback;
      var engines = this.engines;
      var opts = options;
      var renderOptions = {};
      var view;
      if (typeof options === "function") {
        done = options;
        opts = {};
      }
      merge2(renderOptions, this.locals);
      if (opts._locals) {
        merge2(renderOptions, opts._locals);
      }
      merge2(renderOptions, opts);
      if (renderOptions.cache == null) {
        renderOptions.cache = this.enabled("view cache");
      }
      if (renderOptions.cache) {
        view = cache[name];
      }
      if (!view) {
        var View3 = this.get("view");
        view = new View3(name, {
          defaultEngine: this.get("view engine"),
          root: this.get("views"),
          engines
        });
        if (!view.path) {
          var dirs = Array.isArray(view.root) && view.root.length > 1 ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"' : 'directory "' + view.root + '"';
          var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs);
          err.view = view;
          return done(err);
        }
        if (renderOptions.cache) {
          cache[name] = view;
        }
      }
      tryRender(view, renderOptions, done);
    };
    app3.listen = function listen() {
      var server2 = http2.createServer(this);
      return server2.listen.apply(server2, arguments);
    };
    function logerror(err) {
      if (this.get("env") !== "test") console.error(err.stack || err.toString());
    }
    function tryRender(view, options, callback) {
      try {
        view.render(options, callback);
      } catch (err) {
        callback(err);
      }
    }
  }
});

// ../../node_modules/.pnpm/negotiator@0.6.3/node_modules/negotiator/lib/charset.js
var require_charset = __commonJS({
  "../../node_modules/.pnpm/negotiator@0.6.3/node_modules/negotiator/lib/charset.js"(exports, module) {
    "use strict";
    module.exports = preferredCharsets;
    module.exports.preferredCharsets = preferredCharsets;
    var simpleCharsetRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/;
    function parseAcceptCharset(accept) {
      var accepts = accept.split(",");
      for (var i = 0, j = 0; i < accepts.length; i++) {
        var charset = parseCharset(accepts[i].trim(), i);
        if (charset) {
          accepts[j++] = charset;
        }
      }
      accepts.length = j;
      return accepts;
    }
    function parseCharset(str, i) {
      var match = simpleCharsetRegExp.exec(str);
      if (!match) return null;
      var charset = match[1];
      var q = 1;
      if (match[2]) {
        var params = match[2].split(";");
        for (var j = 0; j < params.length; j++) {
          var p = params[j].trim().split("=");
          if (p[0] === "q") {
            q = parseFloat(p[1]);
            break;
          }
        }
      }
      return {
        charset,
        q,
        i
      };
    }
    function getCharsetPriority(charset, accepted, index2) {
      var priority = { o: -1, q: 0, s: 0 };
      for (var i = 0; i < accepted.length; i++) {
        var spec = specify(charset, accepted[i], index2);
        if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
          priority = spec;
        }
      }
      return priority;
    }
    function specify(charset, spec, index2) {
      var s = 0;
      if (spec.charset.toLowerCase() === charset.toLowerCase()) {
        s |= 1;
      } else if (spec.charset !== "*") {
        return null;
      }
      return {
        i: index2,
        o: spec.i,
        q: spec.q,
        s
      };
    }
    function preferredCharsets(accept, provided) {
      var accepts = parseAcceptCharset(accept === void 0 ? "*" : accept || "");
      if (!provided) {
        return accepts.filter(isQuality).sort(compareSpecs).map(getFullCharset);
      }
      var priorities = provided.map(function getPriority(type, index2) {
        return getCharsetPriority(type, accepts, index2);
      });
      return priorities.filter(isQuality).sort(compareSpecs).map(function getCharset(priority) {
        return provided[priorities.indexOf(priority)];
      });
    }
    function compareSpecs(a, b) {
      return b.q - a.q || b.s - a.s || a.o - b.o || a.i - b.i || 0;
    }
    function getFullCharset(spec) {
      return spec.charset;
    }
    function isQuality(spec) {
      return spec.q > 0;
    }
  }
});

// ../../node_modules/.pnpm/negotiator@0.6.3/node_modules/negotiator/lib/encoding.js
var require_encoding = __commonJS({
  "../../node_modules/.pnpm/negotiator@0.6.3/node_modules/negotiator/lib/encoding.js"(exports, module) {
    "use strict";
    module.exports = preferredEncodings;
    module.exports.preferredEncodings = preferredEncodings;
    var simpleEncodingRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/;
    function parseAcceptEncoding(accept) {
      var accepts = accept.split(",");
      var hasIdentity = false;
      var minQuality = 1;
      for (var i = 0, j = 0; i < accepts.length; i++) {
        var encoding = parseEncoding(accepts[i].trim(), i);
        if (encoding) {
          accepts[j++] = encoding;
          hasIdentity = hasIdentity || specify("identity", encoding);
          minQuality = Math.min(minQuality, encoding.q || 1);
        }
      }
      if (!hasIdentity) {
        accepts[j++] = {
          encoding: "identity",
          q: minQuality,
          i
        };
      }
      accepts.length = j;
      return accepts;
    }
    function parseEncoding(str, i) {
      var match = simpleEncodingRegExp.exec(str);
      if (!match) return null;
      var encoding = match[1];
      var q = 1;
      if (match[2]) {
        var params = match[2].split(";");
        for (var j = 0; j < params.length; j++) {
          var p = params[j].trim().split("=");
          if (p[0] === "q") {
            q = parseFloat(p[1]);
            break;
          }
        }
      }
      return {
        encoding,
        q,
        i
      };
    }
    function getEncodingPriority(encoding, accepted, index2) {
      var priority = { o: -1, q: 0, s: 0 };
      for (var i = 0; i < accepted.length; i++) {
        var spec = specify(encoding, accepted[i], index2);
        if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
          priority = spec;
        }
      }
      return priority;
    }
    function specify(encoding, spec, index2) {
      var s = 0;
      if (spec.encoding.toLowerCase() === encoding.toLowerCase()) {
        s |= 1;
      } else if (spec.encoding !== "*") {
        return null;
      }
      return {
        i: index2,
        o: spec.i,
        q: spec.q,
        s
      };
    }
    function preferredEncodings(accept, provided) {
      var accepts = parseAcceptEncoding(accept || "");
      if (!provided) {
        return accepts.filter(isQuality).sort(compareSpecs).map(getFullEncoding);
      }
      var priorities = provided.map(function getPriority(type, index2) {
        return getEncodingPriority(type, accepts, index2);
      });
      return priorities.filter(isQuality).sort(compareSpecs).map(function getEncoding(priority) {
        return provided[priorities.indexOf(priority)];
      });
    }
    function compareSpecs(a, b) {
      return b.q - a.q || b.s - a.s || a.o - b.o || a.i - b.i || 0;
    }
    function getFullEncoding(spec) {
      return spec.encoding;
    }
    function isQuality(spec) {
      return spec.q > 0;
    }
  }
});

// ../../node_modules/.pnpm/negotiator@0.6.3/node_modules/negotiator/lib/language.js
var require_language = __commonJS({
  "../../node_modules/.pnpm/negotiator@0.6.3/node_modules/negotiator/lib/language.js"(exports, module) {
    "use strict";
    module.exports = preferredLanguages;
    module.exports.preferredLanguages = preferredLanguages;
    var simpleLanguageRegExp = /^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/;
    function parseAcceptLanguage(accept) {
      var accepts = accept.split(",");
      for (var i = 0, j = 0; i < accepts.length; i++) {
        var language = parseLanguage(accepts[i].trim(), i);
        if (language) {
          accepts[j++] = language;
        }
      }
      accepts.length = j;
      return accepts;
    }
    function parseLanguage(str, i) {
      var match = simpleLanguageRegExp.exec(str);
      if (!match) return null;
      var prefix = match[1];
      var suffix = match[2];
      var full = prefix;
      if (suffix) full += "-" + suffix;
      var q = 1;
      if (match[3]) {
        var params = match[3].split(";");
        for (var j = 0; j < params.length; j++) {
          var p = params[j].split("=");
          if (p[0] === "q") q = parseFloat(p[1]);
        }
      }
      return {
        prefix,
        suffix,
        q,
        i,
        full
      };
    }
    function getLanguagePriority(language, accepted, index2) {
      var priority = { o: -1, q: 0, s: 0 };
      for (var i = 0; i < accepted.length; i++) {
        var spec = specify(language, accepted[i], index2);
        if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
          priority = spec;
        }
      }
      return priority;
    }
    function specify(language, spec, index2) {
      var p = parseLanguage(language);
      if (!p) return null;
      var s = 0;
      if (spec.full.toLowerCase() === p.full.toLowerCase()) {
        s |= 4;
      } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) {
        s |= 2;
      } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) {
        s |= 1;
      } else if (spec.full !== "*") {
        return null;
      }
      return {
        i: index2,
        o: spec.i,
        q: spec.q,
        s
      };
    }
    function preferredLanguages(accept, provided) {
      var accepts = parseAcceptLanguage(accept === void 0 ? "*" : accept || "");
      if (!provided) {
        return accepts.filter(isQuality).sort(compareSpecs).map(getFullLanguage);
      }
      var priorities = provided.map(function getPriority(type, index2) {
        return getLanguagePriority(type, accepts, index2);
      });
      return priorities.filter(isQuality).sort(compareSpecs).map(function getLanguage(priority) {
        return provided[priorities.indexOf(priority)];
      });
    }
    function compareSpecs(a, b) {
      return b.q - a.q || b.s - a.s || a.o - b.o || a.i - b.i || 0;
    }
    function getFullLanguage(spec) {
      return spec.full;
    }
    function isQuality(spec) {
      return spec.q > 0;
    }
  }
});

// ../../node_modules/.pnpm/negotiator@0.6.3/node_modules/negotiator/lib/mediaType.js
var require_mediaType = __commonJS({
  "../../node_modules/.pnpm/negotiator@0.6.3/node_modules/negotiator/lib/mediaType.js"(exports, module) {
    "use strict";
    module.exports = preferredMediaTypes;
    module.exports.preferredMediaTypes = preferredMediaTypes;
    var simpleMediaTypeRegExp = /^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/;
    function parseAccept(accept) {
      var accepts = splitMediaTypes(accept);
      for (var i = 0, j = 0; i < accepts.length; i++) {
        var mediaType = parseMediaType(accepts[i].trim(), i);
        if (mediaType) {
          accepts[j++] = mediaType;
        }
      }
      accepts.length = j;
      return accepts;
    }
    function parseMediaType(str, i) {
      var match = simpleMediaTypeRegExp.exec(str);
      if (!match) return null;
      var params = /* @__PURE__ */ Object.create(null);
      var q = 1;
      var subtype = match[2];
      var type = match[1];
      if (match[3]) {
        var kvps = splitParameters(match[3]).map(splitKeyValuePair);
        for (var j = 0; j < kvps.length; j++) {
          var pair = kvps[j];
          var key = pair[0].toLowerCase();
          var val = pair[1];
          var value = val && val[0] === '"' && val[val.length - 1] === '"' ? val.substr(1, val.length - 2) : val;
          if (key === "q") {
            q = parseFloat(value);
            break;
          }
          params[key] = value;
        }
      }
      return {
        type,
        subtype,
        params,
        q,
        i
      };
    }
    function getMediaTypePriority(type, accepted, index2) {
      var priority = { o: -1, q: 0, s: 0 };
      for (var i = 0; i < accepted.length; i++) {
        var spec = specify(type, accepted[i], index2);
        if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
          priority = spec;
        }
      }
      return priority;
    }
    function specify(type, spec, index2) {
      var p = parseMediaType(type);
      var s = 0;
      if (!p) {
        return null;
      }
      if (spec.type.toLowerCase() == p.type.toLowerCase()) {
        s |= 4;
      } else if (spec.type != "*") {
        return null;
      }
      if (spec.subtype.toLowerCase() == p.subtype.toLowerCase()) {
        s |= 2;
      } else if (spec.subtype != "*") {
        return null;
      }
      var keys = Object.keys(spec.params);
      if (keys.length > 0) {
        if (keys.every(function(k) {
          return spec.params[k] == "*" || (spec.params[k] || "").toLowerCase() == (p.params[k] || "").toLowerCase();
        })) {
          s |= 1;
        } else {
          return null;
        }
      }
      return {
        i: index2,
        o: spec.i,
        q: spec.q,
        s
      };
    }
    function preferredMediaTypes(accept, provided) {
      var accepts = parseAccept(accept === void 0 ? "*/*" : accept || "");
      if (!provided) {
        return accepts.filter(isQuality).sort(compareSpecs).map(getFullType);
      }
      var priorities = provided.map(function getPriority(type, index2) {
        return getMediaTypePriority(type, accepts, index2);
      });
      return priorities.filter(isQuality).sort(compareSpecs).map(function getType(priority) {
        return provided[priorities.indexOf(priority)];
      });
    }
    function compareSpecs(a, b) {
      return b.q - a.q || b.s - a.s || a.o - b.o || a.i - b.i || 0;
    }
    function getFullType(spec) {
      return spec.type + "/" + spec.subtype;
    }
    function isQuality(spec) {
      return spec.q > 0;
    }
    function quoteCount(string4) {
      var count3 = 0;
      var index2 = 0;
      while ((index2 = string4.indexOf('"', index2)) !== -1) {
        count3++;
        index2++;
      }
      return count3;
    }
    function splitKeyValuePair(str) {
      var index2 = str.indexOf("=");
      var key;
      var val;
      if (index2 === -1) {
        key = str;
      } else {
        key = str.substr(0, index2);
        val = str.substr(index2 + 1);
      }
      return [key, val];
    }
    function splitMediaTypes(accept) {
      var accepts = accept.split(",");
      for (var i = 1, j = 0; i < accepts.length; i++) {
        if (quoteCount(accepts[j]) % 2 == 0) {
          accepts[++j] = accepts[i];
        } else {
          accepts[j] += "," + accepts[i];
        }
      }
      accepts.length = j + 1;
      return accepts;
    }
    function splitParameters(str) {
      var parameters = str.split(";");
      for (var i = 1, j = 0; i < parameters.length; i++) {
        if (quoteCount(parameters[j]) % 2 == 0) {
          parameters[++j] = parameters[i];
        } else {
          parameters[j] += ";" + parameters[i];
        }
      }
      parameters.length = j + 1;
      for (var i = 0; i < parameters.length; i++) {
        parameters[i] = parameters[i].trim();
      }
      return parameters;
    }
  }
});

// ../../node_modules/.pnpm/negotiator@0.6.3/node_modules/negotiator/index.js
var require_negotiator = __commonJS({
  "../../node_modules/.pnpm/negotiator@0.6.3/node_modules/negotiator/index.js"(exports, module) {
    "use strict";
    var preferredCharsets = require_charset();
    var preferredEncodings = require_encoding();
    var preferredLanguages = require_language();
    var preferredMediaTypes = require_mediaType();
    module.exports = Negotiator;
    module.exports.Negotiator = Negotiator;
    function Negotiator(request) {
      if (!(this instanceof Negotiator)) {
        return new Negotiator(request);
      }
      this.request = request;
    }
    Negotiator.prototype.charset = function charset(available) {
      var set2 = this.charsets(available);
      return set2 && set2[0];
    };
    Negotiator.prototype.charsets = function charsets(available) {
      return preferredCharsets(this.request.headers["accept-charset"], available);
    };
    Negotiator.prototype.encoding = function encoding(available) {
      var set2 = this.encodings(available);
      return set2 && set2[0];
    };
    Negotiator.prototype.encodings = function encodings(available) {
      return preferredEncodings(this.request.headers["accept-encoding"], available);
    };
    Negotiator.prototype.language = function language(available) {
      var set2 = this.languages(available);
      return set2 && set2[0];
    };
    Negotiator.prototype.languages = function languages(available) {
      return preferredLanguages(this.request.headers["accept-language"], available);
    };
    Negotiator.prototype.mediaType = function mediaType(available) {
      var set2 = this.mediaTypes(available);
      return set2 && set2[0];
    };
    Negotiator.prototype.mediaTypes = function mediaTypes(available) {
      return preferredMediaTypes(this.request.headers.accept, available);
    };
    Negotiator.prototype.preferredCharset = Negotiator.prototype.charset;
    Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets;
    Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding;
    Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings;
    Negotiator.prototype.preferredLanguage = Negotiator.prototype.language;
    Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages;
    Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType;
    Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes;
  }
});

// ../../node_modules/.pnpm/accepts@1.3.8/node_modules/accepts/index.js
var require_accepts = __commonJS({
  "../../node_modules/.pnpm/accepts@1.3.8/node_modules/accepts/index.js"(exports, module) {
    "use strict";
    var Negotiator = require_negotiator();
    var mime = require_mime_types();
    module.exports = Accepts;
    function Accepts(req) {
      if (!(this instanceof Accepts)) {
        return new Accepts(req);
      }
      this.headers = req.headers;
      this.negotiator = new Negotiator(req);
    }
    Accepts.prototype.type = Accepts.prototype.types = function(types_) {
      var types3 = types_;
      if (types3 && !Array.isArray(types3)) {
        types3 = new Array(arguments.length);
        for (var i = 0; i < types3.length; i++) {
          types3[i] = arguments[i];
        }
      }
      if (!types3 || types3.length === 0) {
        return this.negotiator.mediaTypes();
      }
      if (!this.headers.accept) {
        return types3[0];
      }
      var mimes = types3.map(extToMime);
      var accepts = this.negotiator.mediaTypes(mimes.filter(validMime));
      var first = accepts[0];
      return first ? types3[mimes.indexOf(first)] : false;
    };
    Accepts.prototype.encoding = Accepts.prototype.encodings = function(encodings_) {
      var encodings = encodings_;
      if (encodings && !Array.isArray(encodings)) {
        encodings = new Array(arguments.length);
        for (var i = 0; i < encodings.length; i++) {
          encodings[i] = arguments[i];
        }
      }
      if (!encodings || encodings.length === 0) {
        return this.negotiator.encodings();
      }
      return this.negotiator.encodings(encodings)[0] || false;
    };
    Accepts.prototype.charset = Accepts.prototype.charsets = function(charsets_) {
      var charsets = charsets_;
      if (charsets && !Array.isArray(charsets)) {
        charsets = new Array(arguments.length);
        for (var i = 0; i < charsets.length; i++) {
          charsets[i] = arguments[i];
        }
      }
      if (!charsets || charsets.length === 0) {
        return this.negotiator.charsets();
      }
      return this.negotiator.charsets(charsets)[0] || false;
    };
    Accepts.prototype.lang = Accepts.prototype.langs = Accepts.prototype.language = Accepts.prototype.languages = function(languages_) {
      var languages = languages_;
      if (languages && !Array.isArray(languages)) {
        languages = new Array(arguments.length);
        for (var i = 0; i < languages.length; i++) {
          languages[i] = arguments[i];
        }
      }
      if (!languages || languages.length === 0) {
        return this.negotiator.languages();
      }
      return this.negotiator.languages(languages)[0] || false;
    };
    function extToMime(type) {
      return type.indexOf("/") === -1 ? mime.lookup(type) : type;
    }
    function validMime(type) {
      return typeof type === "string";
    }
  }
});

// ../../node_modules/.pnpm/express@4.21.2/node_modules/express/lib/request.js
var require_request = __commonJS({
  "../../node_modules/.pnpm/express@4.21.2/node_modules/express/lib/request.js"(exports, module) {
    "use strict";
    var accepts = require_accepts();
    var deprecate = require_depd()("express");
    var isIP2 = __require("net").isIP;
    var typeis = require_type_is();
    var http2 = __require("http");
    var fresh = require_fresh();
    var parseRange = require_range_parser();
    var parse3 = require_parseurl();
    var proxyaddr = require_proxy_addr();
    var req = Object.create(http2.IncomingMessage.prototype);
    module.exports = req;
    req.get = req.header = function header(name) {
      if (!name) {
        throw new TypeError("name argument is required to req.get");
      }
      if (typeof name !== "string") {
        throw new TypeError("name must be a string to req.get");
      }
      var lc = name.toLowerCase();
      switch (lc) {
        case "referer":
        case "referrer":
          return this.headers.referrer || this.headers.referer;
        default:
          return this.headers[lc];
      }
    };
    req.accepts = function() {
      var accept = accepts(this);
      return accept.types.apply(accept, arguments);
    };
    req.acceptsEncodings = function() {
      var accept = accepts(this);
      return accept.encodings.apply(accept, arguments);
    };
    req.acceptsEncoding = deprecate.function(
      req.acceptsEncodings,
      "req.acceptsEncoding: Use acceptsEncodings instead"
    );
    req.acceptsCharsets = function() {
      var accept = accepts(this);
      return accept.charsets.apply(accept, arguments);
    };
    req.acceptsCharset = deprecate.function(
      req.acceptsCharsets,
      "req.acceptsCharset: Use acceptsCharsets instead"
    );
    req.acceptsLanguages = function() {
      var accept = accepts(this);
      return accept.languages.apply(accept, arguments);
    };
    req.acceptsLanguage = deprecate.function(
      req.acceptsLanguages,
      "req.acceptsLanguage: Use acceptsLanguages instead"
    );
    req.range = function range(size, options) {
      var range2 = this.get("Range");
      if (!range2) return;
      return parseRange(size, range2, options);
    };
    req.param = function param(name, defaultValue) {
      var params = this.params || {};
      var body = this.body || {};
      var query = this.query || {};
      var args = arguments.length === 1 ? "name" : "name, default";
      deprecate("req.param(" + args + "): Use req.params, req.body, or req.query instead");
      if (null != params[name] && params.hasOwnProperty(name)) return params[name];
      if (null != body[name]) return body[name];
      if (null != query[name]) return query[name];
      return defaultValue;
    };
    req.is = function is2(types3) {
      var arr = types3;
      if (!Array.isArray(types3)) {
        arr = new Array(arguments.length);
        for (var i = 0; i < arr.length; i++) {
          arr[i] = arguments[i];
        }
      }
      return typeis(this, arr);
    };
    defineGetter(req, "protocol", function protocol() {
      var proto = this.connection.encrypted ? "https" : "http";
      var trust = this.app.get("trust proxy fn");
      if (!trust(this.connection.remoteAddress, 0)) {
        return proto;
      }
      var header = this.get("X-Forwarded-Proto") || proto;
      var index2 = header.indexOf(",");
      return index2 !== -1 ? header.substring(0, index2).trim() : header.trim();
    });
    defineGetter(req, "secure", function secure() {
      return this.protocol === "https";
    });
    defineGetter(req, "ip", function ip() {
      var trust = this.app.get("trust proxy fn");
      return proxyaddr(this, trust);
    });
    defineGetter(req, "ips", function ips() {
      var trust = this.app.get("trust proxy fn");
      var addrs = proxyaddr.all(this, trust);
      addrs.reverse().pop();
      return addrs;
    });
    defineGetter(req, "subdomains", function subdomains() {
      var hostname2 = this.hostname;
      if (!hostname2) return [];
      var offset = this.app.get("subdomain offset");
      var subdomains2 = !isIP2(hostname2) ? hostname2.split(".").reverse() : [hostname2];
      return subdomains2.slice(offset);
    });
    defineGetter(req, "path", function path4() {
      return parse3(this).pathname;
    });
    defineGetter(req, "hostname", function hostname2() {
      var trust = this.app.get("trust proxy fn");
      var host = this.get("X-Forwarded-Host");
      if (!host || !trust(this.connection.remoteAddress, 0)) {
        host = this.get("Host");
      } else if (host.indexOf(",") !== -1) {
        host = host.substring(0, host.indexOf(",")).trimRight();
      }
      if (!host) return;
      var offset = host[0] === "[" ? host.indexOf("]") + 1 : 0;
      var index2 = host.indexOf(":", offset);
      return index2 !== -1 ? host.substring(0, index2) : host;
    });
    defineGetter(req, "host", deprecate.function(function host() {
      return this.hostname;
    }, "req.host: Use req.hostname instead"));
    defineGetter(req, "fresh", function() {
      var method = this.method;
      var res = this.res;
      var status = res.statusCode;
      if ("GET" !== method && "HEAD" !== method) return false;
      if (status >= 200 && status < 300 || 304 === status) {
        return fresh(this.headers, {
          "etag": res.get("ETag"),
          "last-modified": res.get("Last-Modified")
        });
      }
      return false;
    });
    defineGetter(req, "stale", function stale() {
      return !this.fresh;
    });
    defineGetter(req, "xhr", function xhr() {
      var val = this.get("X-Requested-With") || "";
      return val.toLowerCase() === "xmlhttprequest";
    });
    function defineGetter(obj, name, getter) {
      Object.defineProperty(obj, name, {
        configurable: true,
        enumerable: true,
        get: getter
      });
    }
  }
});

// ../../node_modules/.pnpm/cookie-signature@1.0.6/node_modules/cookie-signature/index.js
var require_cookie_signature = __commonJS({
  "../../node_modules/.pnpm/cookie-signature@1.0.6/node_modules/cookie-signature/index.js"(exports) {
    var crypto4 = __require("crypto");
    exports.sign = function(val, secret) {
      if ("string" != typeof val) throw new TypeError("Cookie value must be provided as a string.");
      if ("string" != typeof secret) throw new TypeError("Secret string must be provided.");
      return val + "." + crypto4.createHmac("sha256", secret).update(val).digest("base64").replace(/\=+$/, "");
    };
    exports.unsign = function(val, secret) {
      if ("string" != typeof val) throw new TypeError("Signed cookie string must be provided.");
      if ("string" != typeof secret) throw new TypeError("Secret string must be provided.");
      var str = val.slice(0, val.lastIndexOf(".")), mac = exports.sign(str, secret);
      return sha1(mac) == sha1(val) ? str : false;
    };
    function sha1(str) {
      return crypto4.createHash("sha1").update(str).digest("hex");
    }
  }
});

// ../../node_modules/.pnpm/cookie@0.7.1/node_modules/cookie/index.js
var require_cookie = __commonJS({
  "../../node_modules/.pnpm/cookie@0.7.1/node_modules/cookie/index.js"(exports) {
    "use strict";
    exports.parse = parse3;
    exports.serialize = serialize;
    var __toString = Object.prototype.toString;
    var cookieNameRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
    var cookieValueRegExp = /^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/;
    var domainValueRegExp = /^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i;
    var pathValueRegExp = /^[\u0020-\u003A\u003D-\u007E]*$/;
    function parse3(str, opt) {
      if (typeof str !== "string") {
        throw new TypeError("argument str must be a string");
      }
      var obj = {};
      var len = str.length;
      if (len < 2) return obj;
      var dec = opt && opt.decode || decode;
      var index2 = 0;
      var eqIdx = 0;
      var endIdx = 0;
      do {
        eqIdx = str.indexOf("=", index2);
        if (eqIdx === -1) break;
        endIdx = str.indexOf(";", index2);
        if (endIdx === -1) {
          endIdx = len;
        } else if (eqIdx > endIdx) {
          index2 = str.lastIndexOf(";", eqIdx - 1) + 1;
          continue;
        }
        var keyStartIdx = startIndex(str, index2, eqIdx);
        var keyEndIdx = endIndex(str, eqIdx, keyStartIdx);
        var key = str.slice(keyStartIdx, keyEndIdx);
        if (!obj.hasOwnProperty(key)) {
          var valStartIdx = startIndex(str, eqIdx + 1, endIdx);
          var valEndIdx = endIndex(str, endIdx, valStartIdx);
          if (str.charCodeAt(valStartIdx) === 34 && str.charCodeAt(valEndIdx - 1) === 34) {
            valStartIdx++;
            valEndIdx--;
          }
          var val = str.slice(valStartIdx, valEndIdx);
          obj[key] = tryDecode(val, dec);
        }
        index2 = endIdx + 1;
      } while (index2 < len);
      return obj;
    }
    function startIndex(str, index2, max) {
      do {
        var code = str.charCodeAt(index2);
        if (code !== 32 && code !== 9) return index2;
      } while (++index2 < max);
      return max;
    }
    function endIndex(str, index2, min) {
      while (index2 > min) {
        var code = str.charCodeAt(--index2);
        if (code !== 32 && code !== 9) return index2 + 1;
      }
      return min;
    }
    function serialize(name, val, opt) {
      var enc = opt && opt.encode || encodeURIComponent;
      if (typeof enc !== "function") {
        throw new TypeError("option encode is invalid");
      }
      if (!cookieNameRegExp.test(name)) {
        throw new TypeError("argument name is invalid");
      }
      var value = enc(val);
      if (!cookieValueRegExp.test(value)) {
        throw new TypeError("argument val is invalid");
      }
      var str = name + "=" + value;
      if (!opt) return str;
      if (null != opt.maxAge) {
        var maxAge = Math.floor(opt.maxAge);
        if (!isFinite(maxAge)) {
          throw new TypeError("option maxAge is invalid");
        }
        str += "; Max-Age=" + maxAge;
      }
      if (opt.domain) {
        if (!domainValueRegExp.test(opt.domain)) {
          throw new TypeError("option domain is invalid");
        }
        str += "; Domain=" + opt.domain;
      }
      if (opt.path) {
        if (!pathValueRegExp.test(opt.path)) {
          throw new TypeError("option path is invalid");
        }
        str += "; Path=" + opt.path;
      }
      if (opt.expires) {
        var expires = opt.expires;
        if (!isDate(expires) || isNaN(expires.valueOf())) {
          throw new TypeError("option expires is invalid");
        }
        str += "; Expires=" + expires.toUTCString();
      }
      if (opt.httpOnly) {
        str += "; HttpOnly";
      }
      if (opt.secure) {
        str += "; Secure";
      }
      if (opt.partitioned) {
        str += "; Partitioned";
      }
      if (opt.priority) {
        var priority = typeof opt.priority === "string" ? opt.priority.toLowerCase() : opt.priority;
        switch (priority) {
          case "low":
            str += "; Priority=Low";
            break;
          case "medium":
            str += "; Priority=Medium";
            break;
          case "high":
            str += "; Priority=High";
            break;
          default:
            throw new TypeError("option priority is invalid");
        }
      }
      if (opt.sameSite) {
        var sameSite = typeof opt.sameSite === "string" ? opt.sameSite.toLowerCase() : opt.sameSite;
        switch (sameSite) {
          case true:
            str += "; SameSite=Strict";
            break;
          case "lax":
            str += "; SameSite=Lax";
            break;
          case "strict":
            str += "; SameSite=Strict";
            break;
          case "none":
            str += "; SameSite=None";
            break;
          default:
            throw new TypeError("option sameSite is invalid");
        }
      }
      return str;
    }
    function decode(str) {
      return str.indexOf("%") !== -1 ? decodeURIComponent(str) : str;
    }
    function isDate(val) {
      return __toString.call(val) === "[object Date]";
    }
    function tryDecode(str, decode2) {
      try {
        return decode2(str);
      } catch (e) {
        return str;
      }
    }
  }
});

// ../../node_modules/.pnpm/vary@1.1.2/node_modules/vary/index.js
var require_vary = __commonJS({
  "../../node_modules/.pnpm/vary@1.1.2/node_modules/vary/index.js"(exports, module) {
    "use strict";
    module.exports = vary;
    module.exports.append = append;
    var FIELD_NAME_REGEXP = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
    function append(header, field) {
      if (typeof header !== "string") {
        throw new TypeError("header argument is required");
      }
      if (!field) {
        throw new TypeError("field argument is required");
      }
      var fields = !Array.isArray(field) ? parse3(String(field)) : field;
      for (var j = 0; j < fields.length; j++) {
        if (!FIELD_NAME_REGEXP.test(fields[j])) {
          throw new TypeError("field argument contains an invalid header name");
        }
      }
      if (header === "*") {
        return header;
      }
      var val = header;
      var vals = parse3(header.toLowerCase());
      if (fields.indexOf("*") !== -1 || vals.indexOf("*") !== -1) {
        return "*";
      }
      for (var i = 0; i < fields.length; i++) {
        var fld = fields[i].toLowerCase();
        if (vals.indexOf(fld) === -1) {
          vals.push(fld);
          val = val ? val + ", " + fields[i] : fields[i];
        }
      }
      return val;
    }
    function parse3(header) {
      var end = 0;
      var list = [];
      var start = 0;
      for (var i = 0, len = header.length; i < len; i++) {
        switch (header.charCodeAt(i)) {
          case 32:
            if (start === end) {
              start = end = i + 1;
            }
            break;
          case 44:
            list.push(header.substring(start, end));
            start = end = i + 1;
            break;
          default:
            end = i + 1;
            break;
        }
      }
      list.push(header.substring(start, end));
      return list;
    }
    function vary(res, field) {
      if (!res || !res.getHeader || !res.setHeader) {
        throw new TypeError("res argument is required");
      }
      var val = res.getHeader("Vary") || "";
      var header = Array.isArray(val) ? val.join(", ") : String(val);
      if (val = append(header, field)) {
        res.setHeader("Vary", val);
      }
    }
  }
});

// ../../node_modules/.pnpm/express@4.21.2/node_modules/express/lib/response.js
var require_response = __commonJS({
  "../../node_modules/.pnpm/express@4.21.2/node_modules/express/lib/response.js"(exports, module) {
    "use strict";
    var Buffer3 = require_safe_buffer().Buffer;
    var contentDisposition = require_content_disposition();
    var createError = require_http_errors();
    var deprecate = require_depd()("express");
    var encodeUrl = require_encodeurl();
    var escapeHtml2 = require_escape_html();
    var http2 = __require("http");
    var isAbsolute = require_utils2().isAbsolute;
    var onFinished = require_on_finished();
    var path4 = __require("path");
    var statuses = require_statuses();
    var merge2 = require_utils_merge();
    var sign = require_cookie_signature().sign;
    var normalizeType = require_utils2().normalizeType;
    var normalizeTypes = require_utils2().normalizeTypes;
    var setCharset = require_utils2().setCharset;
    var cookie = require_cookie();
    var send = require_send();
    var extname = path4.extname;
    var mime = send.mime;
    var resolve = path4.resolve;
    var vary = require_vary();
    var res = Object.create(http2.ServerResponse.prototype);
    module.exports = res;
    var charsetRegExp = /;\s*charset\s*=/;
    res.status = function status(code) {
      if ((typeof code === "string" || Math.floor(code) !== code) && code > 99 && code < 1e3) {
        deprecate("res.status(" + JSON.stringify(code) + "): use res.status(" + Math.floor(code) + ") instead");
      }
      this.statusCode = code;
      return this;
    };
    res.links = function(links) {
      var link = this.get("Link") || "";
      if (link) link += ", ";
      return this.set("Link", link + Object.keys(links).map(function(rel) {
        return "<" + links[rel] + '>; rel="' + rel + '"';
      }).join(", "));
    };
    res.send = function send2(body) {
      var chunk2 = body;
      var encoding;
      var req = this.req;
      var type;
      var app3 = this.app;
      if (arguments.length === 2) {
        if (typeof arguments[0] !== "number" && typeof arguments[1] === "number") {
          deprecate("res.send(body, status): Use res.status(status).send(body) instead");
          this.statusCode = arguments[1];
        } else {
          deprecate("res.send(status, body): Use res.status(status).send(body) instead");
          this.statusCode = arguments[0];
          chunk2 = arguments[1];
        }
      }
      if (typeof chunk2 === "number" && arguments.length === 1) {
        if (!this.get("Content-Type")) {
          this.type("txt");
        }
        deprecate("res.send(status): Use res.sendStatus(status) instead");
        this.statusCode = chunk2;
        chunk2 = statuses.message[chunk2];
      }
      switch (typeof chunk2) {
        // string defaulting to html
        case "string":
          if (!this.get("Content-Type")) {
            this.type("html");
          }
          break;
        case "boolean":
        case "number":
        case "object":
          if (chunk2 === null) {
            chunk2 = "";
          } else if (Buffer3.isBuffer(chunk2)) {
            if (!this.get("Content-Type")) {
              this.type("bin");
            }
          } else {
            return this.json(chunk2);
          }
          break;
      }
      if (typeof chunk2 === "string") {
        encoding = "utf8";
        type = this.get("Content-Type");
        if (typeof type === "string") {
          this.set("Content-Type", setCharset(type, "utf-8"));
        }
      }
      var etagFn = app3.get("etag fn");
      var generateETag = !this.get("ETag") && typeof etagFn === "function";
      var len;
      if (chunk2 !== void 0) {
        if (Buffer3.isBuffer(chunk2)) {
          len = chunk2.length;
        } else if (!generateETag && chunk2.length < 1e3) {
          len = Buffer3.byteLength(chunk2, encoding);
        } else {
          chunk2 = Buffer3.from(chunk2, encoding);
          encoding = void 0;
          len = chunk2.length;
        }
        this.set("Content-Length", len);
      }
      var etag;
      if (generateETag && len !== void 0) {
        if (etag = etagFn(chunk2, encoding)) {
          this.set("ETag", etag);
        }
      }
      if (req.fresh) this.statusCode = 304;
      if (204 === this.statusCode || 304 === this.statusCode) {
        this.removeHeader("Content-Type");
        this.removeHeader("Content-Length");
        this.removeHeader("Transfer-Encoding");
        chunk2 = "";
      }
      if (this.statusCode === 205) {
        this.set("Content-Length", "0");
        this.removeHeader("Transfer-Encoding");
        chunk2 = "";
      }
      if (req.method === "HEAD") {
        this.end();
      } else {
        this.end(chunk2, encoding);
      }
      return this;
    };
    res.json = function json3(obj) {
      var val = obj;
      if (arguments.length === 2) {
        if (typeof arguments[1] === "number") {
          deprecate("res.json(obj, status): Use res.status(status).json(obj) instead");
          this.statusCode = arguments[1];
        } else {
          deprecate("res.json(status, obj): Use res.status(status).json(obj) instead");
          this.statusCode = arguments[0];
          val = arguments[1];
        }
      }
      var app3 = this.app;
      var escape2 = app3.get("json escape");
      var replacer = app3.get("json replacer");
      var spaces = app3.get("json spaces");
      var body = stringify(val, replacer, spaces, escape2);
      if (!this.get("Content-Type")) {
        this.set("Content-Type", "application/json");
      }
      return this.send(body);
    };
    res.jsonp = function jsonp(obj) {
      var val = obj;
      if (arguments.length === 2) {
        if (typeof arguments[1] === "number") {
          deprecate("res.jsonp(obj, status): Use res.status(status).jsonp(obj) instead");
          this.statusCode = arguments[1];
        } else {
          deprecate("res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead");
          this.statusCode = arguments[0];
          val = arguments[1];
        }
      }
      var app3 = this.app;
      var escape2 = app3.get("json escape");
      var replacer = app3.get("json replacer");
      var spaces = app3.get("json spaces");
      var body = stringify(val, replacer, spaces, escape2);
      var callback = this.req.query[app3.get("jsonp callback name")];
      if (!this.get("Content-Type")) {
        this.set("X-Content-Type-Options", "nosniff");
        this.set("Content-Type", "application/json");
      }
      if (Array.isArray(callback)) {
        callback = callback[0];
      }
      if (typeof callback === "string" && callback.length !== 0) {
        this.set("X-Content-Type-Options", "nosniff");
        this.set("Content-Type", "text/javascript");
        callback = callback.replace(/[^\[\]\w$.]/g, "");
        if (body === void 0) {
          body = "";
        } else if (typeof body === "string") {
          body = body.replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
        }
        body = "/**/ typeof " + callback + " === 'function' && " + callback + "(" + body + ");";
      }
      return this.send(body);
    };
    res.sendStatus = function sendStatus(statusCode) {
      var body = statuses.message[statusCode] || String(statusCode);
      this.statusCode = statusCode;
      this.type("txt");
      return this.send(body);
    };
    res.sendFile = function sendFile(path5, options, callback) {
      var done = callback;
      var req = this.req;
      var res2 = this;
      var next = req.next;
      var opts = options || {};
      if (!path5) {
        throw new TypeError("path argument is required to res.sendFile");
      }
      if (typeof path5 !== "string") {
        throw new TypeError("path must be a string to res.sendFile");
      }
      if (typeof options === "function") {
        done = options;
        opts = {};
      }
      if (!opts.root && !isAbsolute(path5)) {
        throw new TypeError("path must be absolute or specify root to res.sendFile");
      }
      var pathname = encodeURI(path5);
      var file2 = send(req, pathname, opts);
      sendfile(res2, file2, opts, function(err) {
        if (done) return done(err);
        if (err && err.code === "EISDIR") return next();
        if (err && err.code !== "ECONNABORTED" && err.syscall !== "write") {
          next(err);
        }
      });
    };
    res.sendfile = function(path5, options, callback) {
      var done = callback;
      var req = this.req;
      var res2 = this;
      var next = req.next;
      var opts = options || {};
      if (typeof options === "function") {
        done = options;
        opts = {};
      }
      var file2 = send(req, path5, opts);
      sendfile(res2, file2, opts, function(err) {
        if (done) return done(err);
        if (err && err.code === "EISDIR") return next();
        if (err && err.code !== "ECONNABORTED" && err.syscall !== "write") {
          next(err);
        }
      });
    };
    res.sendfile = deprecate.function(
      res.sendfile,
      "res.sendfile: Use res.sendFile instead"
    );
    res.download = function download(path5, filename, options, callback) {
      var done = callback;
      var name = filename;
      var opts = options || null;
      if (typeof filename === "function") {
        done = filename;
        name = null;
        opts = null;
      } else if (typeof options === "function") {
        done = options;
        opts = null;
      }
      if (typeof filename === "object" && (typeof options === "function" || options === void 0)) {
        name = null;
        opts = filename;
      }
      var headers = {
        "Content-Disposition": contentDisposition(name || path5)
      };
      if (opts && opts.headers) {
        var keys = Object.keys(opts.headers);
        for (var i = 0; i < keys.length; i++) {
          var key = keys[i];
          if (key.toLowerCase() !== "content-disposition") {
            headers[key] = opts.headers[key];
          }
        }
      }
      opts = Object.create(opts);
      opts.headers = headers;
      var fullPath = !opts.root ? resolve(path5) : path5;
      return this.sendFile(fullPath, opts, done);
    };
    res.contentType = res.type = function contentType(type) {
      var ct = type.indexOf("/") === -1 ? mime.lookup(type) : type;
      return this.set("Content-Type", ct);
    };
    res.format = function(obj) {
      var req = this.req;
      var next = req.next;
      var keys = Object.keys(obj).filter(function(v) {
        return v !== "default";
      });
      var key = keys.length > 0 ? req.accepts(keys) : false;
      this.vary("Accept");
      if (key) {
        this.set("Content-Type", normalizeType(key).value);
        obj[key](req, this, next);
      } else if (obj.default) {
        obj.default(req, this, next);
      } else {
        next(createError(406, {
          types: normalizeTypes(keys).map(function(o) {
            return o.value;
          })
        }));
      }
      return this;
    };
    res.attachment = function attachment(filename) {
      if (filename) {
        this.type(extname(filename));
      }
      this.set("Content-Disposition", contentDisposition(filename));
      return this;
    };
    res.append = function append(field, val) {
      var prev = this.get(field);
      var value = val;
      if (prev) {
        value = Array.isArray(prev) ? prev.concat(val) : Array.isArray(val) ? [prev].concat(val) : [prev, val];
      }
      return this.set(field, value);
    };
    res.set = res.header = function header(field, val) {
      if (arguments.length === 2) {
        var value = Array.isArray(val) ? val.map(String) : String(val);
        if (field.toLowerCase() === "content-type") {
          if (Array.isArray(value)) {
            throw new TypeError("Content-Type cannot be set to an Array");
          }
          if (!charsetRegExp.test(value)) {
            var charset = mime.charsets.lookup(value.split(";")[0]);
            if (charset) value += "; charset=" + charset.toLowerCase();
          }
        }
        this.setHeader(field, value);
      } else {
        for (var key in field) {
          this.set(key, field[key]);
        }
      }
      return this;
    };
    res.get = function(field) {
      return this.getHeader(field);
    };
    res.clearCookie = function clearCookie(name, options) {
      if (options) {
        if (options.maxAge) {
          deprecate('res.clearCookie: Passing "options.maxAge" is deprecated. In v5.0.0 of Express, this option will be ignored, as res.clearCookie will automatically set cookies to expire immediately. Please update your code to omit this option.');
        }
        if (options.expires) {
          deprecate('res.clearCookie: Passing "options.expires" is deprecated. In v5.0.0 of Express, this option will be ignored, as res.clearCookie will automatically set cookies to expire immediately. Please update your code to omit this option.');
        }
      }
      var opts = merge2({ expires: /* @__PURE__ */ new Date(1), path: "/" }, options);
      return this.cookie(name, "", opts);
    };
    res.cookie = function(name, value, options) {
      var opts = merge2({}, options);
      var secret = this.req.secret;
      var signed = opts.signed;
      if (signed && !secret) {
        throw new Error('cookieParser("secret") required for signed cookies');
      }
      var val = typeof value === "object" ? "j:" + JSON.stringify(value) : String(value);
      if (signed) {
        val = "s:" + sign(val, secret);
      }
      if (opts.maxAge != null) {
        var maxAge = opts.maxAge - 0;
        if (!isNaN(maxAge)) {
          opts.expires = new Date(Date.now() + maxAge);
          opts.maxAge = Math.floor(maxAge / 1e3);
        }
      }
      if (opts.path == null) {
        opts.path = "/";
      }
      this.append("Set-Cookie", cookie.serialize(name, String(val), opts));
      return this;
    };
    res.location = function location(url2) {
      var loc;
      if (url2 === "back") {
        deprecate('res.location("back"): use res.location(req.get("Referrer") || "/") and refer to https://dub.sh/security-redirect for best practices');
        loc = this.req.get("Referrer") || "/";
      } else {
        loc = String(url2);
      }
      return this.set("Location", encodeUrl(loc));
    };
    res.redirect = function redirect(url2) {
      var address = url2;
      var body;
      var status = 302;
      if (arguments.length === 2) {
        if (typeof arguments[0] === "number") {
          status = arguments[0];
          address = arguments[1];
        } else {
          deprecate("res.redirect(url, status): Use res.redirect(status, url) instead");
          status = arguments[1];
        }
      }
      address = this.location(address).get("Location");
      this.format({
        text: function() {
          body = statuses.message[status] + ". Redirecting to " + address;
        },
        html: function() {
          var u = escapeHtml2(address);
          body = "<p>" + statuses.message[status] + ". Redirecting to " + u + "</p>";
        },
        default: function() {
          body = "";
        }
      });
      this.statusCode = status;
      this.set("Content-Length", Buffer3.byteLength(body));
      if (this.req.method === "HEAD") {
        this.end();
      } else {
        this.end(body);
      }
    };
    res.vary = function(field) {
      if (!field || Array.isArray(field) && !field.length) {
        deprecate("res.vary(): Provide a field name");
        return this;
      }
      vary(this, field);
      return this;
    };
    res.render = function render(view, options, callback) {
      var app3 = this.req.app;
      var done = callback;
      var opts = options || {};
      var req = this.req;
      var self = this;
      if (typeof options === "function") {
        done = options;
        opts = {};
      }
      opts._locals = self.locals;
      done = done || function(err, str) {
        if (err) return req.next(err);
        self.send(str);
      };
      app3.render(view, opts, done);
    };
    function sendfile(res2, file2, options, callback) {
      var done = false;
      var streaming;
      function onaborted() {
        if (done) return;
        done = true;
        var err = new Error("Request aborted");
        err.code = "ECONNABORTED";
        callback(err);
      }
      function ondirectory() {
        if (done) return;
        done = true;
        var err = new Error("EISDIR, read");
        err.code = "EISDIR";
        callback(err);
      }
      function onerror(err) {
        if (done) return;
        done = true;
        callback(err);
      }
      function onend() {
        if (done) return;
        done = true;
        callback();
      }
      function onfile() {
        streaming = false;
      }
      function onfinish(err) {
        if (err && err.code === "ECONNRESET") return onaborted();
        if (err) return onerror(err);
        if (done) return;
        setImmediate(function() {
          if (streaming !== false && !done) {
            onaborted();
            return;
          }
          if (done) return;
          done = true;
          callback();
        });
      }
      function onstream() {
        streaming = true;
      }
      file2.on("directory", ondirectory);
      file2.on("end", onend);
      file2.on("error", onerror);
      file2.on("file", onfile);
      file2.on("stream", onstream);
      onFinished(res2, onfinish);
      if (options.headers) {
        file2.on("headers", function headers(res3) {
          var obj = options.headers;
          var keys = Object.keys(obj);
          for (var i = 0; i < keys.length; i++) {
            var k = keys[i];
            res3.setHeader(k, obj[k]);
          }
        });
      }
      file2.pipe(res2);
    }
    function stringify(value, replacer, spaces, escape2) {
      var json3 = replacer || spaces ? JSON.stringify(value, replacer, spaces) : JSON.stringify(value);
      if (escape2 && typeof json3 === "string") {
        json3 = json3.replace(/[<>&]/g, function(c) {
          switch (c.charCodeAt(0)) {
            case 60:
              return "\\u003c";
            case 62:
              return "\\u003e";
            case 38:
              return "\\u0026";
            /* istanbul ignore next: unreachable default */
            default:
              return c;
          }
        });
      }
      return json3;
    }
  }
});

// ../../node_modules/.pnpm/serve-static@1.16.2/node_modules/serve-static/index.js
var require_serve_static = __commonJS({
  "../../node_modules/.pnpm/serve-static@1.16.2/node_modules/serve-static/index.js"(exports, module) {
    "use strict";
    var encodeUrl = require_encodeurl();
    var escapeHtml2 = require_escape_html();
    var parseUrl = require_parseurl();
    var resolve = __require("path").resolve;
    var send = require_send();
    var url2 = __require("url");
    module.exports = serveStatic;
    module.exports.mime = send.mime;
    function serveStatic(root, options) {
      if (!root) {
        throw new TypeError("root path required");
      }
      if (typeof root !== "string") {
        throw new TypeError("root path must be a string");
      }
      var opts = Object.create(options || null);
      var fallthrough = opts.fallthrough !== false;
      var redirect = opts.redirect !== false;
      var setHeaders = opts.setHeaders;
      if (setHeaders && typeof setHeaders !== "function") {
        throw new TypeError("option setHeaders must be function");
      }
      opts.maxage = opts.maxage || opts.maxAge || 0;
      opts.root = resolve(root);
      var onDirectory = redirect ? createRedirectDirectoryListener() : createNotFoundDirectoryListener();
      return function serveStatic2(req, res, next) {
        if (req.method !== "GET" && req.method !== "HEAD") {
          if (fallthrough) {
            return next();
          }
          res.statusCode = 405;
          res.setHeader("Allow", "GET, HEAD");
          res.setHeader("Content-Length", "0");
          res.end();
          return;
        }
        var forwardError = !fallthrough;
        var originalUrl = parseUrl.original(req);
        var path4 = parseUrl(req).pathname;
        if (path4 === "/" && originalUrl.pathname.substr(-1) !== "/") {
          path4 = "";
        }
        var stream = send(req, path4, opts);
        stream.on("directory", onDirectory);
        if (setHeaders) {
          stream.on("headers", setHeaders);
        }
        if (fallthrough) {
          stream.on("file", function onFile() {
            forwardError = true;
          });
        }
        stream.on("error", function error40(err) {
          if (forwardError || !(err.statusCode < 500)) {
            next(err);
            return;
          }
          next();
        });
        stream.pipe(res);
      };
    }
    function collapseLeadingSlashes(str) {
      for (var i = 0; i < str.length; i++) {
        if (str.charCodeAt(i) !== 47) {
          break;
        }
      }
      return i > 1 ? "/" + str.substr(i) : str;
    }
    function createHtmlDocument(title, body) {
      return '<!DOCTYPE html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n<title>' + title + "</title>\n</head>\n<body>\n<pre>" + body + "</pre>\n</body>\n</html>\n";
    }
    function createNotFoundDirectoryListener() {
      return function notFound() {
        this.error(404);
      };
    }
    function createRedirectDirectoryListener() {
      return function redirect(res) {
        if (this.hasTrailingSlash()) {
          this.error(404);
          return;
        }
        var originalUrl = parseUrl.original(this.req);
        originalUrl.path = null;
        originalUrl.pathname = collapseLeadingSlashes(originalUrl.pathname + "/");
        var loc = encodeUrl(url2.format(originalUrl));
        var doc = createHtmlDocument("Redirecting", "Redirecting to " + escapeHtml2(loc));
        res.statusCode = 301;
        res.setHeader("Content-Type", "text/html; charset=UTF-8");
        res.setHeader("Content-Length", Buffer.byteLength(doc));
        res.setHeader("Content-Security-Policy", "default-src 'none'");
        res.setHeader("X-Content-Type-Options", "nosniff");
        res.setHeader("Location", loc);
        res.end(doc);
      };
    }
  }
});

// ../../node_modules/.pnpm/express@4.21.2/node_modules/express/lib/express.js
var require_express = __commonJS({
  "../../node_modules/.pnpm/express@4.21.2/node_modules/express/lib/express.js"(exports, module) {
    "use strict";
    var bodyParser = require_body_parser();
    var EventEmitter2 = __require("events").EventEmitter;
    var mixin = require_merge_descriptors();
    var proto = require_application();
    var Route = require_route();
    var Router16 = require_router();
    var req = require_request();
    var res = require_response();
    exports = module.exports = createApplication;
    function createApplication() {
      var app3 = function(req2, res2, next) {
        app3.handle(req2, res2, next);
      };
      mixin(app3, EventEmitter2.prototype, false);
      mixin(app3, proto, false);
      app3.request = Object.create(req, {
        app: { configurable: true, enumerable: true, writable: true, value: app3 }
      });
      app3.response = Object.create(res, {
        app: { configurable: true, enumerable: true, writable: true, value: app3 }
      });
      app3.init();
      return app3;
    }
    exports.application = proto;
    exports.request = req;
    exports.response = res;
    exports.Route = Route;
    exports.Router = Router16;
    exports.json = bodyParser.json;
    exports.query = require_query();
    exports.raw = bodyParser.raw;
    exports.static = require_serve_static();
    exports.text = bodyParser.text;
    exports.urlencoded = bodyParser.urlencoded;
    var removedMiddlewares = [
      "bodyParser",
      "compress",
      "cookieSession",
      "session",
      "logger",
      "cookieParser",
      "favicon",
      "responseTime",
      "errorHandler",
      "timeout",
      "methodOverride",
      "vhost",
      "csrf",
      "directory",
      "limit",
      "multipart",
      "staticCache"
    ];
    removedMiddlewares.forEach(function(name) {
      Object.defineProperty(exports, name, {
        get: function() {
          throw new Error("Most middleware (like " + name + ") is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.");
        },
        configurable: true
      });
    });
  }
});

// ../../node_modules/.pnpm/express@4.21.2/node_modules/express/index.js
var require_express2 = __commonJS({
  "../../node_modules/.pnpm/express@4.21.2/node_modules/express/index.js"(exports, module) {
    "use strict";
    module.exports = require_express();
  }
});

// ../../node_modules/.pnpm/object-assign@4.1.1/node_modules/object-assign/index.js
var require_object_assign = __commonJS({
  "../../node_modules/.pnpm/object-assign@4.1.1/node_modules/object-assign/index.js"(exports, module) {
    "use strict";
    var getOwnPropertySymbols = Object.getOwnPropertySymbols;
    var hasOwnProperty = Object.prototype.hasOwnProperty;
    var propIsEnumerable = Object.prototype.propertyIsEnumerable;
    function toObject(val) {
      if (val === null || val === void 0) {
        throw new TypeError("Object.assign cannot be called with null or undefined");
      }
      return Object(val);
    }
    function shouldUseNative() {
      try {
        if (!Object.assign) {
          return false;
        }
        var test1 = new String("abc");
        test1[5] = "de";
        if (Object.getOwnPropertyNames(test1)[0] === "5") {
          return false;
        }
        var test2 = {};
        for (var i = 0; i < 10; i++) {
          test2["_" + String.fromCharCode(i)] = i;
        }
        var order2 = Object.getOwnPropertyNames(test2).map(function(n) {
          return test2[n];
        });
        if (order2.join("") !== "0123456789") {
          return false;
        }
        var test3 = {};
        "abcdefghijklmnopqrst".split("").forEach(function(letter) {
          test3[letter] = letter;
        });
        if (Object.keys(Object.assign({}, test3)).join("") !== "abcdefghijklmnopqrst") {
          return false;
        }
        return true;
      } catch (err) {
        return false;
      }
    }
    module.exports = shouldUseNative() ? Object.assign : function(target, source) {
      var from;
      var to = toObject(target);
      var symbols;
      for (var s = 1; s < arguments.length; s++) {
        from = Object(arguments[s]);
        for (var key in from) {
          if (hasOwnProperty.call(from, key)) {
            to[key] = from[key];
          }
        }
        if (getOwnPropertySymbols) {
          symbols = getOwnPropertySymbols(from);
          for (var i = 0; i < symbols.length; i++) {
            if (propIsEnumerable.call(from, symbols[i])) {
              to[symbols[i]] = from[symbols[i]];
            }
          }
        }
      }
      return to;
    };
  }
});

// ../../node_modules/.pnpm/cors@2.8.6/node_modules/cors/lib/index.js
var require_lib3 = __commonJS({
  "../../node_modules/.pnpm/cors@2.8.6/node_modules/cors/lib/index.js"(exports, module) {
    (function() {
      "use strict";
      var assign = require_object_assign();
      var vary = require_vary();
      var defaults2 = {
        origin: "*",
        methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
        preflightContinue: false,
        optionsSuccessStatus: 204
      };
      function isString(s) {
        return typeof s === "string" || s instanceof String;
      }
      function isOriginAllowed(origin, allowedOrigin) {
        if (Array.isArray(allowedOrigin)) {
          for (var i = 0; i < allowedOrigin.length; ++i) {
            if (isOriginAllowed(origin, allowedOrigin[i])) {
              return true;
            }
          }
          return false;
        } else if (isString(allowedOrigin)) {
          return origin === allowedOrigin;
        } else if (allowedOrigin instanceof RegExp) {
          return allowedOrigin.test(origin);
        } else {
          return !!allowedOrigin;
        }
      }
      function configureOrigin(options, req) {
        var requestOrigin = req.headers.origin, headers = [], isAllowed;
        if (!options.origin || options.origin === "*") {
          headers.push([{
            key: "Access-Control-Allow-Origin",
            value: "*"
          }]);
        } else if (isString(options.origin)) {
          headers.push([{
            key: "Access-Control-Allow-Origin",
            value: options.origin
          }]);
          headers.push([{
            key: "Vary",
            value: "Origin"
          }]);
        } else {
          isAllowed = isOriginAllowed(requestOrigin, options.origin);
          headers.push([{
            key: "Access-Control-Allow-Origin",
            value: isAllowed ? requestOrigin : false
          }]);
          headers.push([{
            key: "Vary",
            value: "Origin"
          }]);
        }
        return headers;
      }
      function configureMethods(options) {
        var methods = options.methods;
        if (methods.join) {
          methods = options.methods.join(",");
        }
        return {
          key: "Access-Control-Allow-Methods",
          value: methods
        };
      }
      function configureCredentials(options) {
        if (options.credentials === true) {
          return {
            key: "Access-Control-Allow-Credentials",
            value: "true"
          };
        }
        return null;
      }
      function configureAllowedHeaders(options, req) {
        var allowedHeaders = options.allowedHeaders || options.headers;
        var headers = [];
        if (!allowedHeaders) {
          allowedHeaders = req.headers["access-control-request-headers"];
          headers.push([{
            key: "Vary",
            value: "Access-Control-Request-Headers"
          }]);
        } else if (allowedHeaders.join) {
          allowedHeaders = allowedHeaders.join(",");
        }
        if (allowedHeaders && allowedHeaders.length) {
          headers.push([{
            key: "Access-Control-Allow-Headers",
            value: allowedHeaders
          }]);
        }
        return headers;
      }
      function configureExposedHeaders(options) {
        var headers = options.exposedHeaders;
        if (!headers) {
          return null;
        } else if (headers.join) {
          headers = headers.join(",");
        }
        if (headers && headers.length) {
          return {
            key: "Access-Control-Expose-Headers",
            value: headers
          };
        }
        return null;
      }
      function configureMaxAge(options) {
        var maxAge = (typeof options.maxAge === "number" || options.maxAge) && options.maxAge.toString();
        if (maxAge && maxAge.length) {
          return {
            key: "Access-Control-Max-Age",
            value: maxAge
          };
        }
        return null;
      }
      function applyHeaders(headers, res) {
        for (var i = 0, n = headers.length; i < n; i++) {
          var header = headers[i];
          if (header) {
            if (Array.isArray(header)) {
              applyHeaders(header, res);
            } else if (header.key === "Vary" && header.value) {
              vary(res, header.value);
            } else if (header.value) {
              res.setHeader(header.key, header.value);
            }
          }
        }
      }
      function cors2(options, req, res, next) {
        var headers = [], method = req.method && req.method.toUpperCase && req.method.toUpperCase();
        if (method === "OPTIONS") {
          headers.push(configureOrigin(options, req));
          headers.push(configureCredentials(options));
          headers.push(configureMethods(options));
          headers.push(configureAllowedHeaders(options, req));
          headers.push(configureMaxAge(options));
          headers.push(configureExposedHeaders(options));
          applyHeaders(headers, res);
          if (options.preflightContinue) {
            next();
          } else {
            res.statusCode = options.optionsSuccessStatus;
            res.setHeader("Content-Length", "0");
            res.end();
          }
        } else {
          headers.push(configureOrigin(options, req));
          headers.push(configureCredentials(options));
          headers.push(configureExposedHeaders(options));
          applyHeaders(headers, res);
          next();
        }
      }
      function middlewareWrapper(o) {
        var optionsCallback = null;
        if (typeof o === "function") {
          optionsCallback = o;
        } else {
          optionsCallback = function(req, cb) {
            cb(null, o);
          };
        }
        return function corsMiddleware(req, res, next) {
          optionsCallback(req, function(err, options) {
            if (err) {
              next(err);
            } else {
              var corsOptions = assign({}, defaults2, options);
              var originCallback = null;
              if (corsOptions.origin && typeof corsOptions.origin === "function") {
                originCallback = corsOptions.origin;
              } else if (corsOptions.origin) {
                originCallback = function(origin, cb) {
                  cb(null, corsOptions.origin);
                };
              }
              if (originCallback) {
                originCallback(req.headers.origin, function(err2, origin) {
                  if (err2 || !origin) {
                    next(err2);
                  } else {
                    corsOptions.origin = origin;
                    cors2(corsOptions, req, res, next);
                  }
                });
              } else {
                next();
              }
            }
          });
        };
      }
      module.exports = middlewareWrapper;
    })();
  }
});

// ../../node_modules/.pnpm/cookie@0.7.2/node_modules/cookie/index.js
var require_cookie2 = __commonJS({
  "../../node_modules/.pnpm/cookie@0.7.2/node_modules/cookie/index.js"(exports) {
    "use strict";
    exports.parse = parse3;
    exports.serialize = serialize;
    var __toString = Object.prototype.toString;
    var __hasOwnProperty = Object.prototype.hasOwnProperty;
    var cookieNameRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
    var cookieValueRegExp = /^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/;
    var domainValueRegExp = /^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i;
    var pathValueRegExp = /^[\u0020-\u003A\u003D-\u007E]*$/;
    function parse3(str, opt) {
      if (typeof str !== "string") {
        throw new TypeError("argument str must be a string");
      }
      var obj = {};
      var len = str.length;
      if (len < 2) return obj;
      var dec = opt && opt.decode || decode;
      var index2 = 0;
      var eqIdx = 0;
      var endIdx = 0;
      do {
        eqIdx = str.indexOf("=", index2);
        if (eqIdx === -1) break;
        endIdx = str.indexOf(";", index2);
        if (endIdx === -1) {
          endIdx = len;
        } else if (eqIdx > endIdx) {
          index2 = str.lastIndexOf(";", eqIdx - 1) + 1;
          continue;
        }
        var keyStartIdx = startIndex(str, index2, eqIdx);
        var keyEndIdx = endIndex(str, eqIdx, keyStartIdx);
        var key = str.slice(keyStartIdx, keyEndIdx);
        if (!__hasOwnProperty.call(obj, key)) {
          var valStartIdx = startIndex(str, eqIdx + 1, endIdx);
          var valEndIdx = endIndex(str, endIdx, valStartIdx);
          if (str.charCodeAt(valStartIdx) === 34 && str.charCodeAt(valEndIdx - 1) === 34) {
            valStartIdx++;
            valEndIdx--;
          }
          var val = str.slice(valStartIdx, valEndIdx);
          obj[key] = tryDecode(val, dec);
        }
        index2 = endIdx + 1;
      } while (index2 < len);
      return obj;
    }
    function startIndex(str, index2, max) {
      do {
        var code = str.charCodeAt(index2);
        if (code !== 32 && code !== 9) return index2;
      } while (++index2 < max);
      return max;
    }
    function endIndex(str, index2, min) {
      while (index2 > min) {
        var code = str.charCodeAt(--index2);
        if (code !== 32 && code !== 9) return index2 + 1;
      }
      return min;
    }
    function serialize(name, val, opt) {
      var enc = opt && opt.encode || encodeURIComponent;
      if (typeof enc !== "function") {
        throw new TypeError("option encode is invalid");
      }
      if (!cookieNameRegExp.test(name)) {
        throw new TypeError("argument name is invalid");
      }
      var value = enc(val);
      if (!cookieValueRegExp.test(value)) {
        throw new TypeError("argument val is invalid");
      }
      var str = name + "=" + value;
      if (!opt) return str;
      if (null != opt.maxAge) {
        var maxAge = Math.floor(opt.maxAge);
        if (!isFinite(maxAge)) {
          throw new TypeError("option maxAge is invalid");
        }
        str += "; Max-Age=" + maxAge;
      }
      if (opt.domain) {
        if (!domainValueRegExp.test(opt.domain)) {
          throw new TypeError("option domain is invalid");
        }
        str += "; Domain=" + opt.domain;
      }
      if (opt.path) {
        if (!pathValueRegExp.test(opt.path)) {
          throw new TypeError("option path is invalid");
        }
        str += "; Path=" + opt.path;
      }
      if (opt.expires) {
        var expires = opt.expires;
        if (!isDate(expires) || isNaN(expires.valueOf())) {
          throw new TypeError("option expires is invalid");
        }
        str += "; Expires=" + expires.toUTCString();
      }
      if (opt.httpOnly) {
        str += "; HttpOnly";
      }
      if (opt.secure) {
        str += "; Secure";
      }
      if (opt.partitioned) {
        str += "; Partitioned";
      }
      if (opt.priority) {
        var priority = typeof opt.priority === "string" ? opt.priority.toLowerCase() : opt.priority;
        switch (priority) {
          case "low":
            str += "; Priority=Low";
            break;
          case "medium":
            str += "; Priority=Medium";
            break;
          case "high":
            str += "; Priority=High";
            break;
          default:
            throw new TypeError("option priority is invalid");
        }
      }
      if (opt.sameSite) {
        var sameSite = typeof opt.sameSite === "string" ? opt.sameSite.toLowerCase() : opt.sameSite;
        switch (sameSite) {
          case true:
            str += "; SameSite=Strict";
            break;
          case "lax":
            str += "; SameSite=Lax";
            break;
          case "strict":
            str += "; SameSite=Strict";
            break;
          case "none":
            str += "; SameSite=None";
            break;
          default:
            throw new TypeError("option sameSite is invalid");
        }
      }
      return str;
    }
    function decode(str) {
      return str.indexOf("%") !== -1 ? decodeURIComponent(str) : str;
    }
    function isDate(val) {
      return __toString.call(val) === "[object Date]";
    }
    function tryDecode(str, decode2) {
      try {
        return decode2(str);
      } catch (e) {
        return str;
      }
    }
  }
});

// ../../node_modules/.pnpm/cookie-parser@1.4.7/node_modules/cookie-parser/index.js
var require_cookie_parser = __commonJS({
  "../../node_modules/.pnpm/cookie-parser@1.4.7/node_modules/cookie-parser/index.js"(exports, module) {
    "use strict";
    var cookie = require_cookie2();
    var signature = require_cookie_signature();
    module.exports = cookieParser2;
    module.exports.JSONCookie = JSONCookie;
    module.exports.JSONCookies = JSONCookies;
    module.exports.signedCookie = signedCookie;
    module.exports.signedCookies = signedCookies;
    function cookieParser2(secret, options) {
      var secrets = !secret || Array.isArray(secret) ? secret || [] : [secret];
      return function cookieParser3(req, res, next) {
        if (req.cookies) {
          return next();
        }
        var cookies = req.headers.cookie;
        req.secret = secrets[0];
        req.cookies = /* @__PURE__ */ Object.create(null);
        req.signedCookies = /* @__PURE__ */ Object.create(null);
        if (!cookies) {
          return next();
        }
        req.cookies = cookie.parse(cookies, options);
        if (secrets.length !== 0) {
          req.signedCookies = signedCookies(req.cookies, secrets);
          req.signedCookies = JSONCookies(req.signedCookies);
        }
        req.cookies = JSONCookies(req.cookies);
        next();
      };
    }
    function JSONCookie(str) {
      if (typeof str !== "string" || str.substr(0, 2) !== "j:") {
        return void 0;
      }
      try {
        return JSON.parse(str.slice(2));
      } catch (err) {
        return void 0;
      }
    }
    function JSONCookies(obj) {
      var cookies = Object.keys(obj);
      var key;
      var val;
      for (var i = 0; i < cookies.length; i++) {
        key = cookies[i];
        val = JSONCookie(obj[key]);
        if (val) {
          obj[key] = val;
        }
      }
      return obj;
    }
    function signedCookie(str, secret) {
      if (typeof str !== "string") {
        return void 0;
      }
      if (str.substr(0, 2) !== "s:") {
        return str;
      }
      var secrets = !secret || Array.isArray(secret) ? secret || [] : [secret];
      for (var i = 0; i < secrets.length; i++) {
        var val = signature.unsign(str.slice(2), secrets[i]);
        if (val !== false) {
          return val;
        }
      }
      return false;
    }
    function signedCookies(obj, secret) {
      var cookies = Object.keys(obj);
      var dec;
      var key;
      var ret = /* @__PURE__ */ Object.create(null);
      var val;
      for (var i = 0; i < cookies.length; i++) {
        key = cookies[i];
        val = obj[key];
        dec = signedCookie(val, secret);
        if (val !== dec) {
          ret[key] = dec;
          delete obj[key];
        }
      }
      return ret;
    }
  }
});

// ../../node_modules/.pnpm/get-caller-file@2.0.5/node_modules/get-caller-file/index.js
var require_get_caller_file = __commonJS({
  "../../node_modules/.pnpm/get-caller-file@2.0.5/node_modules/get-caller-file/index.js"(exports, module) {
    "use strict";
    module.exports = function getCallerFile(position) {
      if (position === void 0) {
        position = 2;
      }
      if (position >= Error.stackTraceLimit) {
        throw new TypeError("getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `" + position + "` and Error.stackTraceLimit was: `" + Error.stackTraceLimit + "`");
      }
      var oldPrepareStackTrace = Error.prepareStackTrace;
      Error.prepareStackTrace = function(_, stack2) {
        return stack2;
      };
      var stack = new Error().stack;
      Error.prepareStackTrace = oldPrepareStackTrace;
      if (stack !== null && typeof stack === "object") {
        return stack[position] ? stack[position].getFileName() : void 0;
      }
    };
  }
});

// ../../node_modules/.pnpm/pino-http@10.5.0/node_modules/pino-http/logger.js
var require_logger = __commonJS({
  "../../node_modules/.pnpm/pino-http@10.5.0/node_modules/pino-http/logger.js"(exports, module) {
    "use strict";
    var { pino: pino2, symbols: { stringifySym, chindingsSym } } = require_pino();
    var serializers = require_pino_std_serializers();
    var getCallerFile = require_get_caller_file();
    var startTime = /* @__PURE__ */ Symbol("startTime");
    var reqObject = /* @__PURE__ */ Symbol("reqObject");
    function pinoLogger(opts, stream) {
      if (opts && opts._writableState) {
        stream = opts;
        opts = null;
      }
      opts = Object.assign({}, opts);
      opts.customAttributeKeys = opts.customAttributeKeys || {};
      const reqKey = opts.customAttributeKeys.req || "req";
      const resKey = opts.customAttributeKeys.res || "res";
      const errKey = opts.customAttributeKeys.err || "err";
      const requestIdKey = opts.customAttributeKeys.reqId || "reqId";
      const responseTimeKey = opts.customAttributeKeys.responseTime || "responseTime";
      delete opts.customAttributeKeys;
      const customProps = opts.customProps || void 0;
      opts.wrapSerializers = "wrapSerializers" in opts ? opts.wrapSerializers : true;
      if (opts.wrapSerializers) {
        opts.serializers = Object.assign({}, opts.serializers);
        const requestSerializer = opts.serializers[reqKey] || opts.serializers.req || serializers.req;
        const responseSerializer = opts.serializers[resKey] || opts.serializers.res || serializers.res;
        const errorSerializer = opts.serializers[errKey] || opts.serializers.err || serializers.err;
        opts.serializers[reqKey] = serializers.wrapRequestSerializer(requestSerializer);
        opts.serializers[resKey] = serializers.wrapResponseSerializer(responseSerializer);
        opts.serializers[errKey] = serializers.wrapErrorSerializer(errorSerializer);
      }
      delete opts.wrapSerializers;
      if (opts.useLevel && opts.customLogLevel) {
        throw new Error("You can't pass 'useLevel' and 'customLogLevel' together");
      }
      function getValidLogLevel(level, defaultValue = "info") {
        if (level && typeof level === "string") {
          const logLevel = level.trim();
          if (validLogLevels.includes(logLevel) === true) {
            return logLevel;
          }
        }
        return defaultValue;
      }
      function getLogLevelFromCustomLogLevel(customLogLevel2, useLevel2, res, err, req) {
        return customLogLevel2 ? getValidLogLevel(customLogLevel2(req, res, err), useLevel2) : useLevel2;
      }
      const customLogLevel = opts.customLogLevel;
      delete opts.customLogLevel;
      const theStream = opts.stream || stream;
      delete opts.stream;
      const autoLogging = opts.autoLogging !== false;
      const autoLoggingIgnore = opts.autoLogging && opts.autoLogging.ignore ? opts.autoLogging.ignore : null;
      delete opts.autoLogging;
      const onRequestReceivedObject = getFunctionOrDefault(opts.customReceivedObject, void 0);
      const receivedMessage = getFunctionOrDefault(opts.customReceivedMessage, void 0);
      const onRequestSuccessObject = getFunctionOrDefault(opts.customSuccessObject, defaultSuccessfulRequestObjectProvider);
      const successMessage = getFunctionOrDefault(opts.customSuccessMessage, defaultSuccessfulRequestMessageProvider);
      const onRequestErrorObject = getFunctionOrDefault(opts.customErrorObject, defaultFailedRequestObjectProvider);
      const errorMessage = getFunctionOrDefault(opts.customErrorMessage, defaultFailedRequestMessageProvider);
      delete opts.customSuccessfulMessage;
      delete opts.customErroredMessage;
      const quietReqLogger = !!opts.quietReqLogger;
      const quietResLogger = !!opts.quietResLogger;
      const logger2 = wrapChild(opts, theStream);
      const validLogLevels = Object.keys(logger2.levels.values).concat("silent");
      const useLevel = getValidLogLevel(opts.useLevel);
      delete opts.useLevel;
      const genReqId = reqIdGenFactory(opts.genReqId);
      const result = (req, res, next) => {
        return loggingMiddleware(logger2, req, res, next);
      };
      result.logger = logger2;
      return result;
      function onResFinished(res, logger3, err) {
        let log = logger3;
        const responseTime = Date.now() - res[startTime];
        const req = res[reqObject];
        const level = getLogLevelFromCustomLogLevel(customLogLevel, useLevel, res, err, req);
        if (level === "silent") {
          return;
        }
        const customPropBindings = typeof customProps === "function" ? customProps(req, res) : customProps;
        if (customPropBindings) {
          const customPropBindingStr = logger3[stringifySym](customPropBindings).replace(/[{}]/g, "");
          const customPropBindingsStr = logger3[chindingsSym];
          if (!customPropBindingsStr.includes(customPropBindingStr)) {
            log = logger3.child(customPropBindings);
          }
        }
        if (err || res.err || res.statusCode >= 500) {
          const error40 = err || res.err || new Error("failed with status code " + res.statusCode);
          log[level](
            onRequestErrorObject(req, res, error40, {
              [resKey]: res,
              [errKey]: error40,
              [responseTimeKey]: responseTime
            }),
            errorMessage(req, res, error40, responseTime)
          );
          return;
        }
        log[level](
          onRequestSuccessObject(req, res, {
            [resKey]: res,
            [responseTimeKey]: responseTime
          }),
          successMessage(req, res, responseTime)
        );
      }
      function loggingMiddleware(logger3, req, res, next) {
        let shouldLogSuccess = true;
        req.id = req.id || genReqId(req, res);
        const log = quietReqLogger ? logger3.child({ [requestIdKey]: req.id }) : logger3;
        let fullReqLogger = log.child({ [reqKey]: req });
        const customPropBindings = typeof customProps === "function" ? customProps(req, res) : customProps;
        if (customPropBindings) {
          fullReqLogger = fullReqLogger.child(customPropBindings);
        }
        const responseLogger = quietResLogger ? log : fullReqLogger;
        const requestLogger = quietReqLogger ? log : fullReqLogger;
        if (!res.log) {
          res.log = responseLogger;
        }
        if (Array.isArray(res.allLogs) === false) {
          res.allLogs = [];
        }
        res.allLogs.push(responseLogger);
        if (!req.log) {
          req.log = requestLogger;
        }
        if (!req.allLogs) {
          req.allLogs = [];
        }
        req.allLogs.push(requestLogger);
        res[startTime] = res[startTime] || Date.now();
        res[reqObject] = req;
        const onResponseComplete = (err) => {
          res.removeListener("close", onResponseComplete);
          res.removeListener("finish", onResponseComplete);
          res.removeListener("error", onResponseComplete);
          return onResFinished(res, responseLogger, err);
        };
        if (autoLogging) {
          if (autoLoggingIgnore !== null && shouldLogSuccess === true) {
            const isIgnored = autoLoggingIgnore(req);
            shouldLogSuccess = !isIgnored;
          }
          if (shouldLogSuccess) {
            const shouldLogReceived = receivedMessage !== void 0 || onRequestReceivedObject !== void 0;
            if (shouldLogReceived) {
              const level = getLogLevelFromCustomLogLevel(customLogLevel, useLevel, res, void 0, req);
              const receivedObjectResult = onRequestReceivedObject !== void 0 ? onRequestReceivedObject(req, res, void 0) : {};
              const receivedStringResult = receivedMessage !== void 0 ? receivedMessage(req, res) : void 0;
              requestLogger[level](receivedObjectResult, receivedStringResult);
            }
            res.on("close", onResponseComplete);
            res.on("finish", onResponseComplete);
          }
          res.on("error", onResponseComplete);
        }
        if (next) {
          next();
        }
      }
    }
    function wrapChild(opts, stream) {
      const prevLogger = opts.logger;
      const prevGenReqId = opts.genReqId;
      let logger2 = null;
      if (prevLogger) {
        opts.logger = void 0;
        opts.genReqId = void 0;
        logger2 = prevLogger.child({}, opts);
        opts.logger = prevLogger;
        opts.genReqId = prevGenReqId;
      } else {
        if (opts.transport && !opts.transport.caller) {
          opts.transport.caller = getCallerFile();
        }
        logger2 = pino2(opts, stream);
      }
      return logger2;
    }
    function reqIdGenFactory(func) {
      if (typeof func === "function") return func;
      const maxInt = 2147483647;
      let nextReqId = 0;
      return function genReqId(req, res) {
        return req.id || (nextReqId = nextReqId + 1 & maxInt);
      };
    }
    function getFunctionOrDefault(value, defaultValue) {
      if (value && typeof value === "function") {
        return value;
      }
      return defaultValue;
    }
    function defaultSuccessfulRequestObjectProvider(req, res, successObject) {
      return successObject;
    }
    function defaultFailedRequestObjectProvider(req, res, error40, errorObject) {
      return errorObject;
    }
    function defaultFailedRequestMessageProvider() {
      return "request errored";
    }
    function defaultSuccessfulRequestMessageProvider(req, res) {
      return !req.readableAborted && res.writableEnded ? "request completed" : "request aborted";
    }
    module.exports = pinoLogger;
    module.exports.stdSerializers = {
      err: serializers.err,
      req: serializers.req,
      res: serializers.res
    };
    module.exports.startTime = startTime;
    module.exports.default = pinoLogger;
    module.exports.pinoHttp = pinoLogger;
  }
});

// ../../node_modules/.pnpm/helmet@8.2.0/node_modules/helmet/index.mjs
function normalizeDirectives(options) {
  const defaultDirectives = getDefaultDirectives();
  const { useDefaults = true, directives: rawDirectives = defaultDirectives } = options;
  const result = /* @__PURE__ */ new Map();
  const directiveNamesSeen = /* @__PURE__ */ new Set();
  const directivesExplicitlyDisabled = /* @__PURE__ */ new Set();
  for (const rawDirectiveName in rawDirectives) {
    if (!Object.hasOwn(rawDirectives, rawDirectiveName)) {
      continue;
    }
    if (rawDirectiveName.length === 0 || /[^a-zA-Z0-9-]/.test(rawDirectiveName)) {
      throw new Error(`Content-Security-Policy received an invalid directive name ${JSON.stringify(rawDirectiveName)}`);
    }
    const directiveName = dashify(rawDirectiveName);
    if (directiveNamesSeen.has(directiveName)) {
      throw new Error(`Content-Security-Policy received a duplicate directive ${JSON.stringify(directiveName)}`);
    }
    directiveNamesSeen.add(directiveName);
    const rawDirectiveValue = rawDirectives[rawDirectiveName];
    let directiveValue;
    if (rawDirectiveValue === null) {
      if (directiveName === "default-src") {
        throw new Error("Content-Security-Policy needs a default-src but it was set to `null`. If you really want to disable it, set it to `contentSecurityPolicy.dangerouslyDisableDefaultSrc`.");
      }
      directivesExplicitlyDisabled.add(directiveName);
      continue;
    } else if (typeof rawDirectiveValue === "string") {
      directiveValue = [rawDirectiveValue];
    } else if (!rawDirectiveValue) {
      throw new Error(`Content-Security-Policy received an invalid directive value for ${JSON.stringify(directiveName)}`);
    } else if (rawDirectiveValue === dangerouslyDisableDefaultSrc) {
      if (directiveName === "default-src") {
        directivesExplicitlyDisabled.add("default-src");
        continue;
      } else {
        throw new Error(`Content-Security-Policy: tried to disable ${JSON.stringify(directiveName)} as if it were default-src; simply omit the key`);
      }
    } else {
      directiveValue = rawDirectiveValue;
    }
    for (const element of directiveValue) {
      if (typeof element !== "string") continue;
      assertDirectiveValueIsValid(directiveName, element);
      assertDirectiveValueEntryIsValid(directiveName, element);
    }
    result.set(directiveName, directiveValue);
  }
  if (useDefaults) {
    Object.entries(defaultDirectives).forEach(([defaultDirectiveName, defaultDirectiveValue]) => {
      if (!result.has(defaultDirectiveName) && !directivesExplicitlyDisabled.has(defaultDirectiveName)) {
        result.set(defaultDirectiveName, defaultDirectiveValue);
      }
    });
  }
  if (!result.size) {
    throw new Error("Content-Security-Policy has no directives. Either set some or disable the header");
  }
  if (!result.has("default-src") && !directivesExplicitlyDisabled.has("default-src")) {
    throw new Error("Content-Security-Policy needs a default-src but none was provided. If you really want to disable it, set it to `contentSecurityPolicy.dangerouslyDisableDefaultSrc`.");
  }
  return result;
}
function getHeaderValue(req, res, normalizedDirectives) {
  const result = [];
  for (const [directiveName, rawDirectiveValue] of normalizedDirectives) {
    let directiveValue = "";
    for (const element of rawDirectiveValue) {
      if (typeof element === "function") {
        const newElement = element(req, res);
        assertDirectiveValueEntryIsValid(directiveName, newElement);
        directiveValue += " " + newElement;
      } else {
        directiveValue += " " + element;
      }
    }
    if (directiveValue) {
      assertDirectiveValueIsValid(directiveName, directiveValue);
      result.push(`${directiveName}${directiveValue}`);
    } else {
      result.push(directiveName);
    }
  }
  return result.join(";");
}
function getHeaderValueFromOptions$6({ policy = "require-corp" }) {
  if (ALLOWED_POLICIES$2.has(policy)) {
    return policy;
  } else {
    throw new Error(`Cross-Origin-Embedder-Policy does not support the ${JSON.stringify(policy)} policy`);
  }
}
function crossOriginEmbedderPolicy(options = {}) {
  const headerValue = getHeaderValueFromOptions$6(options);
  return function crossOriginEmbedderPolicyMiddleware(_req, res, next) {
    res.setHeader("Cross-Origin-Embedder-Policy", headerValue);
    next();
  };
}
function getHeaderValueFromOptions$5({ policy = "same-origin" }) {
  if (ALLOWED_POLICIES$1.has(policy)) {
    return policy;
  } else {
    throw new Error(`Cross-Origin-Opener-Policy does not support the ${JSON.stringify(policy)} policy`);
  }
}
function crossOriginOpenerPolicy(options = {}) {
  const headerValue = getHeaderValueFromOptions$5(options);
  return function crossOriginOpenerPolicyMiddleware(_req, res, next) {
    res.setHeader("Cross-Origin-Opener-Policy", headerValue);
    next();
  };
}
function getHeaderValueFromOptions$4({ policy = "same-origin" }) {
  if (ALLOWED_POLICIES.has(policy)) {
    return policy;
  } else {
    throw new Error(`Cross-Origin-Resource-Policy does not support the ${JSON.stringify(policy)} policy`);
  }
}
function crossOriginResourcePolicy(options = {}) {
  const headerValue = getHeaderValueFromOptions$4(options);
  return function crossOriginResourcePolicyMiddleware(_req, res, next) {
    res.setHeader("Cross-Origin-Resource-Policy", headerValue);
    next();
  };
}
function originAgentCluster() {
  return function originAgentClusterMiddleware(_req, res, next) {
    res.setHeader("Origin-Agent-Cluster", "?1");
    next();
  };
}
function getHeaderValueFromOptions$3({ policy = ["no-referrer"] }) {
  const tokens = typeof policy === "string" ? [policy] : policy;
  if (tokens.length === 0) {
    throw new Error("Referrer-Policy received no policy tokens");
  }
  const tokensSeen = /* @__PURE__ */ new Set();
  tokens.forEach((token) => {
    if (!ALLOWED_TOKENS.has(token)) {
      throw new Error(`Referrer-Policy received an unexpected policy token ${JSON.stringify(token)}`);
    } else if (tokensSeen.has(token)) {
      throw new Error(`Referrer-Policy received a duplicate policy token ${JSON.stringify(token)}`);
    }
    tokensSeen.add(token);
  });
  return tokens.join(",");
}
function referrerPolicy(options = {}) {
  const headerValue = getHeaderValueFromOptions$3(options);
  return function referrerPolicyMiddleware(_req, res, next) {
    res.setHeader("Referrer-Policy", headerValue);
    next();
  };
}
function parseMaxAge(value = DEFAULT_MAX_AGE) {
  if (value >= 0 && Number.isFinite(value)) {
    return Math.floor(value);
  } else {
    throw new Error(`Strict-Transport-Security: ${JSON.stringify(value)} is not a valid value for maxAge. Please choose a positive integer.`);
  }
}
function getHeaderValueFromOptions$2(options) {
  if ("maxage" in options) {
    throw new Error("Strict-Transport-Security received an unsupported property, `maxage`. Did you mean to pass `maxAge`?");
  }
  if ("includeSubdomains" in options) {
    throw new Error('Strict-Transport-Security middleware should use `includeSubDomains` instead of `includeSubdomains`. (The correct one has an uppercase "D".)');
  }
  const directives = [`max-age=${parseMaxAge(options.maxAge)}`];
  if (options.includeSubDomains === void 0 || options.includeSubDomains) {
    directives.push("includeSubDomains");
  }
  if (options.preload) {
    directives.push("preload");
  }
  return directives.join("; ");
}
function strictTransportSecurity(options = {}) {
  const headerValue = getHeaderValueFromOptions$2(options);
  return function strictTransportSecurityMiddleware(_req, res, next) {
    res.setHeader("Strict-Transport-Security", headerValue);
    next();
  };
}
function xContentTypeOptions() {
  return function xContentTypeOptionsMiddleware(_req, res, next) {
    res.setHeader("X-Content-Type-Options", "nosniff");
    next();
  };
}
function xDnsPrefetchControl(options = {}) {
  const headerValue = options.allow ? "on" : "off";
  return function xDnsPrefetchControlMiddleware(_req, res, next) {
    res.setHeader("X-DNS-Prefetch-Control", headerValue);
    next();
  };
}
function xDownloadOptions() {
  return function xDownloadOptionsMiddleware(_req, res, next) {
    res.setHeader("X-Download-Options", "noopen");
    next();
  };
}
function getHeaderValueFromOptions$1({ action = "sameorigin" }) {
  const normalizedAction = typeof action === "string" ? action.toUpperCase() : action;
  switch (normalizedAction) {
    case "SAME-ORIGIN":
      return "SAMEORIGIN";
    case "DENY":
    case "SAMEORIGIN":
      return normalizedAction;
    default:
      throw new Error(`X-Frame-Options received an invalid action ${JSON.stringify(action)}`);
  }
}
function xFrameOptions(options = {}) {
  const headerValue = getHeaderValueFromOptions$1(options);
  return function xFrameOptionsMiddleware(_req, res, next) {
    res.setHeader("X-Frame-Options", headerValue);
    next();
  };
}
function getHeaderValueFromOptions({ permittedPolicies = "none" }) {
  if (ALLOWED_PERMITTED_POLICIES.has(permittedPolicies)) {
    return permittedPolicies;
  } else {
    throw new Error(`X-Permitted-Cross-Domain-Policies does not support ${JSON.stringify(permittedPolicies)}`);
  }
}
function xPermittedCrossDomainPolicies(options = {}) {
  const headerValue = getHeaderValueFromOptions(options);
  return function xPermittedCrossDomainPoliciesMiddleware(_req, res, next) {
    res.setHeader("X-Permitted-Cross-Domain-Policies", headerValue);
    next();
  };
}
function xPoweredBy() {
  return function xPoweredByMiddleware(_req, res, next) {
    res.removeHeader("X-Powered-By");
    next();
  };
}
function xXssProtection() {
  return function xXssProtectionMiddleware(_req, res, next) {
    res.setHeader("X-XSS-Protection", "0");
    next();
  };
}
function getMiddlewareFunctionsFromOptions(options) {
  const result = [];
  switch (options.contentSecurityPolicy) {
    case void 0:
    case true:
      result.push(contentSecurityPolicy());
      break;
    case false:
      break;
    default:
      result.push(contentSecurityPolicy(options.contentSecurityPolicy));
      break;
  }
  switch (options.crossOriginEmbedderPolicy) {
    case void 0:
    case false:
      break;
    case true:
      result.push(crossOriginEmbedderPolicy());
      break;
    default:
      result.push(crossOriginEmbedderPolicy(options.crossOriginEmbedderPolicy));
      break;
  }
  switch (options.crossOriginOpenerPolicy) {
    case void 0:
    case true:
      result.push(crossOriginOpenerPolicy());
      break;
    case false:
      break;
    default:
      result.push(crossOriginOpenerPolicy(options.crossOriginOpenerPolicy));
      break;
  }
  switch (options.crossOriginResourcePolicy) {
    case void 0:
    case true:
      result.push(crossOriginResourcePolicy());
      break;
    case false:
      break;
    default:
      result.push(crossOriginResourcePolicy(options.crossOriginResourcePolicy));
      break;
  }
  switch (options.originAgentCluster) {
    case void 0:
    case true:
      result.push(originAgentCluster());
      break;
    case false:
      break;
    default:
      console.warn("Origin-Agent-Cluster does not take options. Remove the property to silence this warning.");
      result.push(originAgentCluster());
      break;
  }
  switch (options.referrerPolicy) {
    case void 0:
    case true:
      result.push(referrerPolicy());
      break;
    case false:
      break;
    default:
      result.push(referrerPolicy(options.referrerPolicy));
      break;
  }
  if ("strictTransportSecurity" in options && "hsts" in options) {
    throw new Error("Strict-Transport-Security option was specified twice. Remove the `hsts` option to fix this error.");
  }
  const strictTransportSecurityOption = options.strictTransportSecurity ?? options.hsts;
  switch (strictTransportSecurityOption) {
    case void 0:
    case true:
      result.push(strictTransportSecurity());
      break;
    case false:
      break;
    default:
      result.push(strictTransportSecurity(strictTransportSecurityOption));
      break;
  }
  if ("xContentTypeOptions" in options && "noSniff" in options) {
    throw new Error("X-Content-Type-Options option was specified twice. Remove the `noSniff` option to fix this error.");
  }
  const xContentTypeOptionsOption = options.xContentTypeOptions ?? options.noSniff;
  switch (xContentTypeOptionsOption) {
    case void 0:
    case true:
      result.push(xContentTypeOptions());
      break;
    case false:
      break;
    default:
      console.warn("X-Content-Type-Options does not take options. Remove the property to silence this warning.");
      result.push(xContentTypeOptions());
      break;
  }
  if ("xDnsPrefetchControl" in options && "dnsPrefetchControl" in options) {
    throw new Error("X-DNS-Prefetch-Control option was specified twice. Remove the `dnsPrefetchControl` option to fix this error.");
  }
  const xDnsPrefetchControlOption = options.xDnsPrefetchControl ?? options.dnsPrefetchControl;
  switch (xDnsPrefetchControlOption) {
    case void 0:
    case true:
      result.push(xDnsPrefetchControl());
      break;
    case false:
      break;
    default:
      result.push(xDnsPrefetchControl(xDnsPrefetchControlOption));
      break;
  }
  if ("xDownloadOptions" in options && "ieNoOpen" in options) {
    throw new Error("X-Download-Options option was specified twice. Remove the `ieNoOpen` option to fix this error.");
  }
  const xDownloadOptionsOption = options.xDownloadOptions ?? options.ieNoOpen;
  switch (xDownloadOptionsOption) {
    case void 0:
    case true:
      result.push(xDownloadOptions());
      break;
    case false:
      break;
    default:
      console.warn("X-Download-Options does not take options. Remove the property to silence this warning.");
      result.push(xDownloadOptions());
      break;
  }
  if ("xFrameOptions" in options && "frameguard" in options) {
    throw new Error("X-Frame-Options option was specified twice. Remove the `frameguard` option to fix this error.");
  }
  const xFrameOptionsOption = options.xFrameOptions ?? options.frameguard;
  switch (xFrameOptionsOption) {
    case void 0:
    case true:
      result.push(xFrameOptions());
      break;
    case false:
      break;
    default:
      result.push(xFrameOptions(xFrameOptionsOption));
      break;
  }
  if ("xPermittedCrossDomainPolicies" in options && "permittedCrossDomainPolicies" in options) {
    throw new Error("X-Permitted-Cross-Domain-Policies option was specified twice. Remove the `permittedCrossDomainPolicies` option to fix this error.");
  }
  const xPermittedCrossDomainPoliciesOption = options.xPermittedCrossDomainPolicies ?? options.permittedCrossDomainPolicies;
  switch (xPermittedCrossDomainPoliciesOption) {
    case void 0:
    case true:
      result.push(xPermittedCrossDomainPolicies());
      break;
    case false:
      break;
    default:
      result.push(xPermittedCrossDomainPolicies(xPermittedCrossDomainPoliciesOption));
      break;
  }
  if ("xPoweredBy" in options && "hidePoweredBy" in options) {
    throw new Error("X-Powered-By option was specified twice. Remove the `hidePoweredBy` option to fix this error.");
  }
  const xPoweredByOption = options.xPoweredBy ?? options.hidePoweredBy;
  switch (xPoweredByOption) {
    case void 0:
    case true:
      result.push(xPoweredBy());
      break;
    case false:
      break;
    default:
      console.warn("X-Powered-By does not take options. Remove the property to silence this warning.");
      result.push(xPoweredBy());
      break;
  }
  if ("xXssProtection" in options && "xssFilter" in options) {
    throw new Error("X-XSS-Protection option was specified twice. Remove the `xssFilter` option to fix this error.");
  }
  const xXssProtectionOption = options.xXssProtection ?? options.xssFilter;
  switch (xXssProtectionOption) {
    case void 0:
    case true:
      result.push(xXssProtection());
      break;
    case false:
      break;
    default:
      console.warn("X-XSS-Protection does not take options. Remove the property to silence this warning.");
      result.push(xXssProtection());
      break;
  }
  return result;
}
var dangerouslyDisableDefaultSrc, SHOULD_BE_QUOTED, getDefaultDirectives, dashify, assertDirectiveValueIsValid, assertDirectiveValueEntryIsValid, contentSecurityPolicy, ALLOWED_POLICIES$2, ALLOWED_POLICIES$1, ALLOWED_POLICIES, ALLOWED_TOKENS, DEFAULT_MAX_AGE, ALLOWED_PERMITTED_POLICIES, helmet;
var init_helmet = __esm({
  "../../node_modules/.pnpm/helmet@8.2.0/node_modules/helmet/index.mjs"() {
    dangerouslyDisableDefaultSrc = /* @__PURE__ */ Symbol("dangerouslyDisableDefaultSrc");
    SHOULD_BE_QUOTED = /* @__PURE__ */ new Set(["none", "self", "strict-dynamic", "report-sample", "inline-speculation-rules", "unsafe-inline", "unsafe-eval", "unsafe-hashes", "wasm-unsafe-eval"]);
    getDefaultDirectives = () => ({
      "default-src": ["'self'"],
      "base-uri": ["'self'"],
      "font-src": ["'self'", "https:", "data:"],
      "form-action": ["'self'"],
      "frame-ancestors": ["'self'"],
      "img-src": ["'self'", "data:"],
      "object-src": ["'none'"],
      "script-src": ["'self'"],
      "script-src-attr": ["'none'"],
      "style-src": ["'self'", "https:", "'unsafe-inline'"],
      "upgrade-insecure-requests": []
    });
    dashify = (str) => str.replace(/[A-Z]/g, (capitalLetter) => "-" + capitalLetter.toLowerCase());
    assertDirectiveValueIsValid = (directiveName, directiveValue) => {
      if (/;|,/.test(directiveValue)) {
        throw new Error(`Content-Security-Policy received an invalid directive value for ${JSON.stringify(directiveName)}`);
      }
    };
    assertDirectiveValueEntryIsValid = (directiveName, directiveValueEntry) => {
      if (SHOULD_BE_QUOTED.has(directiveValueEntry) || directiveValueEntry.startsWith("nonce-") || directiveValueEntry.startsWith("sha256-") || directiveValueEntry.startsWith("sha384-") || directiveValueEntry.startsWith("sha512-")) {
        throw new Error(`Content-Security-Policy received an invalid directive value for ${JSON.stringify(directiveName)}. ${JSON.stringify(directiveValueEntry)} should be quoted`);
      }
    };
    contentSecurityPolicy = function contentSecurityPolicy2(options = {}) {
      const headerName = options.reportOnly ? "Content-Security-Policy-Report-Only" : "Content-Security-Policy";
      const normalizedDirectives = normalizeDirectives(options);
      return function contentSecurityPolicyMiddleware(req, res, next) {
        const result = getHeaderValue(req, res, normalizedDirectives);
        if (result instanceof Error) {
          next(result);
        } else {
          res.setHeader(headerName, result);
          next();
        }
      };
    };
    contentSecurityPolicy.getDefaultDirectives = getDefaultDirectives;
    contentSecurityPolicy.dangerouslyDisableDefaultSrc = dangerouslyDisableDefaultSrc;
    ALLOWED_POLICIES$2 = /* @__PURE__ */ new Set(["require-corp", "credentialless", "unsafe-none"]);
    ALLOWED_POLICIES$1 = /* @__PURE__ */ new Set(["same-origin", "same-origin-allow-popups", "noopener-allow-popups", "unsafe-none"]);
    ALLOWED_POLICIES = /* @__PURE__ */ new Set(["same-origin", "same-site", "cross-origin"]);
    ALLOWED_TOKENS = /* @__PURE__ */ new Set(["no-referrer", "no-referrer-when-downgrade", "same-origin", "origin", "strict-origin", "origin-when-cross-origin", "strict-origin-when-cross-origin", "unsafe-url", ""]);
    DEFAULT_MAX_AGE = 365 * 24 * 60 * 60;
    ALLOWED_PERMITTED_POLICIES = /* @__PURE__ */ new Set(["none", "master-only", "by-content-type", "all"]);
    helmet = Object.assign(
      function helmet2(options = {}) {
        if (options.constructor?.name === "IncomingMessage") {
          throw new Error("It appears you have done something like `app.use(helmet)`, but it should be `app.use(helmet())`.");
        }
        const middlewareFunctions = getMiddlewareFunctionsFromOptions(options);
        return function helmetMiddleware(req, res, next) {
          let middlewareIndex = 0;
          (function internalNext(err) {
            if (err) {
              next(err);
              return;
            }
            const middlewareFunction = middlewareFunctions[middlewareIndex];
            if (middlewareFunction) {
              middlewareIndex++;
              middlewareFunction(req, res, internalNext);
            } else {
              next();
            }
          })();
        };
      },
      {
        contentSecurityPolicy,
        crossOriginEmbedderPolicy,
        crossOriginOpenerPolicy,
        crossOriginResourcePolicy,
        originAgentCluster,
        referrerPolicy,
        strictTransportSecurity,
        xContentTypeOptions,
        xDnsPrefetchControl,
        xDownloadOptions,
        xFrameOptions,
        xPermittedCrossDomainPolicies,
        xPoweredBy,
        xXssProtection,
        // Legacy aliases
        dnsPrefetchControl: xDnsPrefetchControl,
        xssFilter: xXssProtection,
        permittedCrossDomainPolicies: xPermittedCrossDomainPolicies,
        ieNoOpen: xDownloadOptions,
        noSniff: xContentTypeOptions,
        frameguard: xFrameOptions,
        hidePoweredBy: xPoweredBy,
        hsts: strictTransportSecurity
      }
    );
  }
});

// ../../node_modules/.pnpm/ip-address@10.2.0/node_modules/ip-address/dist/address-error.js
var require_address_error = __commonJS({
  "../../node_modules/.pnpm/ip-address@10.2.0/node_modules/ip-address/dist/address-error.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AddressError = void 0;
    var AddressError = class extends Error {
      constructor(message, parseMessage) {
        super(message);
        this.name = "AddressError";
        this.parseMessage = parseMessage;
      }
    };
    exports.AddressError = AddressError;
  }
});

// ../../node_modules/.pnpm/ip-address@10.2.0/node_modules/ip-address/dist/common.js
var require_common = __commonJS({
  "../../node_modules/.pnpm/ip-address@10.2.0/node_modules/ip-address/dist/common.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.isInSubnet = isInSubnet;
    exports.isCorrect = isCorrect;
    exports.prefixLengthFromMask = prefixLengthFromMask;
    exports.numberToPaddedHex = numberToPaddedHex;
    exports.stringToPaddedHex = stringToPaddedHex;
    exports.testBit = testBit;
    var address_error_1 = require_address_error();
    function isInSubnet(address) {
      if (this.subnetMask < address.subnetMask) {
        return false;
      }
      if (this.mask(address.subnetMask) === address.mask()) {
        return true;
      }
      return false;
    }
    function isCorrect(defaultBits) {
      return function() {
        if (this.addressMinusSuffix !== this.correctForm()) {
          return false;
        }
        if (this.subnetMask === defaultBits && !this.parsedSubnet) {
          return true;
        }
        return this.parsedSubnet === String(this.subnetMask);
      };
    }
    function prefixLengthFromMask(value, totalBits) {
      const binary = value.toString(2).padStart(totalBits, "0");
      if (binary.length > totalBits) {
        throw new address_error_1.AddressError("Invalid subnet mask.");
      }
      const firstZero = binary.indexOf("0");
      if (firstZero === -1) {
        return totalBits;
      }
      if (binary.slice(firstZero).includes("1")) {
        throw new address_error_1.AddressError("Invalid subnet mask.");
      }
      return firstZero;
    }
    function numberToPaddedHex(number4) {
      return number4.toString(16).padStart(2, "0");
    }
    function stringToPaddedHex(numberString) {
      return numberToPaddedHex(parseInt(numberString, 10));
    }
    function testBit(binaryValue, position) {
      const { length } = binaryValue;
      if (position > length) {
        return false;
      }
      const positionInString = length - position;
      return binaryValue.substring(positionInString, positionInString + 1) === "1";
    }
  }
});

// ../../node_modules/.pnpm/ip-address@10.2.0/node_modules/ip-address/dist/v4/constants.js
var require_constants2 = __commonJS({
  "../../node_modules/.pnpm/ip-address@10.2.0/node_modules/ip-address/dist/v4/constants.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RE_SUBNET_STRING = exports.RE_ADDRESS = exports.GROUPS = exports.BITS = void 0;
    exports.BITS = 32;
    exports.GROUPS = 4;
    exports.RE_ADDRESS = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g;
    exports.RE_SUBNET_STRING = /\/\d{1,2}$/;
  }
});

// ../../node_modules/.pnpm/ip-address@10.2.0/node_modules/ip-address/dist/ipv4.js
var require_ipv4 = __commonJS({
  "../../node_modules/.pnpm/ip-address@10.2.0/node_modules/ip-address/dist/ipv4.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc2 = Object.getOwnPropertyDescriptor(m, k);
      if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc2);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
      }
      __setModuleDefault(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Address4 = void 0;
    var common = __importStar(require_common());
    var constants = __importStar(require_constants2());
    var address_error_1 = require_address_error();
    var isCorrect4 = common.isCorrect(constants.BITS);
    var Address4 = class _Address4 {
      constructor(address) {
        this.groups = constants.GROUPS;
        this.parsedAddress = [];
        this.parsedSubnet = "";
        this.subnet = "/32";
        this.subnetMask = 32;
        this.v4 = true;
        this.isCorrect = isCorrect4;
        this.isInSubnet = common.isInSubnet;
        this.address = address;
        const subnet = constants.RE_SUBNET_STRING.exec(address);
        if (subnet) {
          this.parsedSubnet = subnet[0].replace("/", "");
          this.subnetMask = parseInt(this.parsedSubnet, 10);
          this.subnet = `/${this.subnetMask}`;
          if (this.subnetMask < 0 || this.subnetMask > constants.BITS) {
            throw new address_error_1.AddressError("Invalid subnet mask.");
          }
          address = address.replace(constants.RE_SUBNET_STRING, "");
        }
        this.addressMinusSuffix = address;
        this.parsedAddress = this.parse(address);
      }
      /**
       * Returns true if the given string is a valid IPv4 address (with optional
       * CIDR subnet), false otherwise. Host bits in the subnet portion are
       * allowed (e.g. `192.168.1.5/24` is valid); for strict network-address
       * validation compare `correctForm()` to `startAddress().correctForm()`,
       * or use `networkForm()`.
       */
      static isValid(address) {
        try {
          new _Address4(address);
          return true;
        } catch (e) {
          return false;
        }
      }
      /**
       * Parses an IPv4 address string into its four octet groups and stores the
       * result on `this.parsedAddress`. Called automatically by the constructor;
       * you typically don't need to call it directly. Throws `AddressError` if
       * the input is not a valid IPv4 address.
       */
      parse(address) {
        const groups = address.split(".");
        if (!address.match(constants.RE_ADDRESS)) {
          throw new address_error_1.AddressError("Invalid IPv4 address.");
        }
        return groups;
      }
      /**
       * Returns the address in correct form: octets joined with `.` and any
       * leading zeros stripped (e.g. `192.168.1.1`). For IPv4 this matches the
       * canonical dotted-decimal representation.
       */
      correctForm() {
        return this.parsedAddress.map((part) => parseInt(part, 10)).join(".");
      }
      /**
       * Construct an `Address4` from an address and a dotted-decimal subnet
       * mask given as separate strings (e.g. as returned by Node's
       * `os.networkInterfaces()`). Throws `AddressError` if the mask is
       * non-contiguous (e.g. `255.0.255.0`).
       * @example
       * var address = Address4.fromAddressAndMask('192.168.1.1', '255.255.255.0');
       * address.subnetMask; // 24
       */
      static fromAddressAndMask(address, mask) {
        const bits = common.prefixLengthFromMask(new _Address4(mask).bigInt(), constants.BITS);
        return new _Address4(`${address}/${bits}`);
      }
      /**
       * Construct an `Address4` from an address and a Cisco-style wildcard mask
       * given as separate strings (e.g. `0.0.0.255` for a `/24`). The wildcard
       * mask is the bitwise inverse of the subnet mask. Throws `AddressError`
       * if the mask is non-contiguous (e.g. `0.255.0.255`).
       * @example
       * var address = Address4.fromAddressAndWildcardMask('10.0.0.1', '0.0.0.255');
       * address.subnetMask; // 24
       */
      static fromAddressAndWildcardMask(address, wildcardMask) {
        const wildcard = new _Address4(wildcardMask).bigInt();
        const allOnes = (BigInt(1) << BigInt(constants.BITS)) - BigInt(1);
        const mask = wildcard ^ allOnes;
        const bits = common.prefixLengthFromMask(mask, constants.BITS);
        return new _Address4(`${address}/${bits}`);
      }
      /**
       * Construct an `Address4` from a wildcard pattern with trailing `*`
       * octets. The number of trailing wildcards determines the prefix
       * length: each `*` represents 8 bits.
       *
       * Only trailing whole-octet wildcards are supported. Partial-octet
       * wildcards (e.g. `192.168.0.1*`) and interior wildcards (e.g.
       * `192.*.0.1`) throw `AddressError`.
       * @example
       * Address4.fromWildcard('192.168.0.*').subnet;   // '/24'
       * Address4.fromWildcard('192.168.*.*').subnet;   // '/16'
       * Address4.fromWildcard('*.*.*.*').subnet;       // '/0'
       */
      static fromWildcard(input) {
        const groups = input.split(".");
        if (groups.length !== constants.GROUPS) {
          throw new address_error_1.AddressError("Wildcard pattern must have 4 octets");
        }
        let firstWildcard = -1;
        for (let i = 0; i < groups.length; i++) {
          if (groups[i] === "*") {
            if (firstWildcard === -1) {
              firstWildcard = i;
            }
          } else if (firstWildcard !== -1) {
            throw new address_error_1.AddressError("Wildcard `*` must only appear in trailing octets (e.g. `192.168.0.*`)");
          }
        }
        const trailing = firstWildcard === -1 ? 0 : groups.length - firstWildcard;
        const replaced = groups.map((g) => g === "*" ? "0" : g);
        const subnetBits = constants.BITS - trailing * 8;
        return new _Address4(`${replaced.join(".")}/${subnetBits}`);
      }
      /**
       * Converts a hex string to an IPv4 address object. Accepts 8 hex digits
       * with optional `:` separators (e.g. `'7f000001'` or `'7f:00:00:01'`).
       * Throws `AddressError` for any other length or for non-hex characters.
       * @param {string} hex - a hex string to convert
       * @returns {Address4}
       */
      static fromHex(hex) {
        const stripped = hex.replace(/:/g, "");
        if (!/^[0-9a-fA-F]{8}$/.test(stripped)) {
          throw new address_error_1.AddressError("IPv4 hex must be exactly 8 hex digits");
        }
        const groups = [];
        for (let i = 0; i < 8; i += 2) {
          groups.push(parseInt(stripped.slice(i, i + 2), 16));
        }
        return new _Address4(groups.join("."));
      }
      /**
       * Converts an integer into a IPv4 address object. The integer must be a
       * non-negative safe integer in the range `[0, 2**32 - 1]`; otherwise
       * `AddressError` is thrown.
       * @param {integer} integer - a number to convert
       * @returns {Address4}
       */
      static fromInteger(integer3) {
        if (!Number.isInteger(integer3) || integer3 < 0 || integer3 > 4294967295) {
          throw new address_error_1.AddressError("IPv4 integer must be in the range 0 to 2**32 - 1");
        }
        return _Address4.fromHex(integer3.toString(16).padStart(8, "0"));
      }
      /**
       * Return an address from in-addr.arpa form
       * @param {string} arpaFormAddress - an 'in-addr.arpa' form ipv4 address
       * @returns {Adress4}
       * @example
       * var address = Address4.fromArpa(42.2.0.192.in-addr.arpa.)
       * address.correctForm(); // '192.0.2.42'
       */
      static fromArpa(arpaFormAddress) {
        const leader = arpaFormAddress.replace(/(\.in-addr\.arpa)?\.$/, "");
        const address = leader.split(".").reverse().join(".");
        return new _Address4(address);
      }
      /**
       * Converts an IPv4 address object to a hex string
       * @returns {String}
       */
      toHex() {
        return this.parsedAddress.map((part) => common.stringToPaddedHex(part)).join(":");
      }
      /**
       * Converts an IPv4 address object to an array of bytes.
       *
       * To get a Node.js `Buffer`, wrap the result: `Buffer.from(address.toArray())`.
       * @returns {Array}
       */
      toArray() {
        return this.parsedAddress.map((part) => parseInt(part, 10));
      }
      /**
       * Converts an IPv4 address object to an IPv6 address group
       * @returns {String}
       */
      toGroup6() {
        const output = [];
        let i;
        for (i = 0; i < constants.GROUPS; i += 2) {
          output.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i + 1])}`);
        }
        return output.join(":");
      }
      /**
       * Returns the address as a `bigint`
       * @returns {bigint}
       */
      bigInt() {
        return BigInt(`0x${this.parsedAddress.map((n) => common.stringToPaddedHex(n)).join("")}`);
      }
      /**
       * Helper function getting start address.
       * @returns {bigint}
       */
      _startAddress() {
        return BigInt(`0b${this.mask() + "0".repeat(constants.BITS - this.subnetMask)}`);
      }
      /**
       * The first address in the range given by this address' subnet.
       * Often referred to as the Network Address.
       * @returns {Address4}
       */
      startAddress() {
        return _Address4.fromBigInt(this._startAddress());
      }
      /**
       * The first host address in the range given by this address's subnet ie
       * the first address after the Network Address
       * @returns {Address4}
       */
      startAddressExclusive() {
        const adjust = BigInt("1");
        return _Address4.fromBigInt(this._startAddress() + adjust);
      }
      /**
       * Helper function getting end address.
       * @returns {bigint}
       */
      _endAddress() {
        return BigInt(`0b${this.mask() + "1".repeat(constants.BITS - this.subnetMask)}`);
      }
      /**
       * The last address in the range given by this address' subnet
       * Often referred to as the Broadcast
       * @returns {Address4}
       */
      endAddress() {
        return _Address4.fromBigInt(this._endAddress());
      }
      /**
       * The last host address in the range given by this address's subnet ie
       * the last address prior to the Broadcast Address
       * @returns {Address4}
       */
      endAddressExclusive() {
        const adjust = BigInt("1");
        return _Address4.fromBigInt(this._endAddress() - adjust);
      }
      /**
       * The dotted-decimal form of the subnet mask, e.g. `255.255.240.0` for
       * a `/20`. Returns an `Address4`; call `.correctForm()` for the string.
       * @returns {Address4}
       */
      subnetMaskAddress() {
        return _Address4.fromBigInt(BigInt(`0b${"1".repeat(this.subnetMask)}${"0".repeat(constants.BITS - this.subnetMask)}`));
      }
      /**
       * The Cisco-style wildcard mask, e.g. `0.0.0.255` for a `/24`. This is
       * the bitwise inverse of `subnetMaskAddress()`. Returns an `Address4`;
       * call `.correctForm()` for the string.
       * @returns {Address4}
       */
      wildcardMask() {
        return _Address4.fromBigInt(BigInt(`0b${"0".repeat(this.subnetMask)}${"1".repeat(constants.BITS - this.subnetMask)}`));
      }
      /**
       * The network address in CIDR string form, e.g. `192.168.1.0/24` for
       * `192.168.1.5/24`. For an address with no explicit subnet the prefix is
       * `/32`, e.g. `networkForm()` on `192.168.1.5` returns `192.168.1.5/32`.
       * @returns {string}
       */
      networkForm() {
        return `${this.startAddress().correctForm()}/${this.subnetMask}`;
      }
      /**
       * Converts a BigInt to a v4 address object. The value must be in the
       * range `[0, 2**32 - 1]`; otherwise `AddressError` is thrown.
       * @param {bigint} bigInt - a BigInt to convert
       * @returns {Address4}
       */
      static fromBigInt(bigInt) {
        if (bigInt < 0n || bigInt > 0xffffffffn) {
          throw new address_error_1.AddressError("IPv4 BigInt must be in the range 0 to 2**32 - 1");
        }
        return _Address4.fromHex(bigInt.toString(16).padStart(8, "0"));
      }
      /**
       * Convert a byte array to an Address4 object.
       *
       * To convert from a Node.js `Buffer`, spread it: `Address4.fromByteArray([...buf])`.
       * @param {Array<number>} bytes - an array of 4 bytes (0-255)
       * @returns {Address4}
       */
      static fromByteArray(bytes) {
        if (bytes.length !== 4) {
          throw new address_error_1.AddressError("IPv4 addresses require exactly 4 bytes");
        }
        for (let i = 0; i < bytes.length; i++) {
          if (!Number.isInteger(bytes[i]) || bytes[i] < 0 || bytes[i] > 255) {
            throw new address_error_1.AddressError("All bytes must be integers between 0 and 255");
          }
        }
        return this.fromUnsignedByteArray(bytes);
      }
      /**
       * Convert an unsigned byte array to an Address4 object
       * @param {Array<number>} bytes - an array of 4 unsigned bytes (0-255)
       * @returns {Address4}
       */
      static fromUnsignedByteArray(bytes) {
        if (bytes.length !== 4) {
          throw new address_error_1.AddressError("IPv4 addresses require exactly 4 bytes");
        }
        const address = bytes.join(".");
        return new _Address4(address);
      }
      /**
       * Returns the first n bits of the address, defaulting to the
       * subnet mask
       * @returns {String}
       */
      mask(mask) {
        if (mask === void 0) {
          mask = this.subnetMask;
        }
        return this.getBitsBase2(0, mask);
      }
      /**
       * Returns the bits in the given range as a base-2 string
       * @returns {string}
       */
      getBitsBase2(start, end) {
        return this.binaryZeroPad().slice(start, end);
      }
      /**
       * Return the reversed ip6.arpa form of the address
       * @param {Object} options
       * @param {boolean} options.omitSuffix - omit the "in-addr.arpa" suffix
       * @returns {String}
       */
      reverseForm(options) {
        if (!options) {
          options = {};
        }
        const reversed = this.correctForm().split(".").reverse().join(".");
        if (options.omitSuffix) {
          return reversed;
        }
        return `${reversed}.in-addr.arpa.`;
      }
      /**
       * Returns true if the given address is a multicast address
       * @returns {boolean}
       */
      isMulticast() {
        return this.isInSubnet(MULTICAST_V4);
      }
      /**
       * Returns true if the address is in one of the [RFC 1918](https://datatracker.ietf.org/doc/html/rfc1918) private address ranges (`10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`).
       * @returns {boolean}
       */
      isPrivate() {
        return PRIVATE_V4.some((subnet) => this.isInSubnet(subnet));
      }
      /**
       * Returns true if the address is in the loopback range `127.0.0.0/8` ([RFC 1122](https://datatracker.ietf.org/doc/html/rfc1122)).
       * @returns {boolean}
       */
      isLoopback() {
        return this.isInSubnet(LOOPBACK_V4);
      }
      /**
       * Returns true if the address is in the link-local range `169.254.0.0/16` ([RFC 3927](https://datatracker.ietf.org/doc/html/rfc3927)).
       * @returns {boolean}
       */
      isLinkLocal() {
        return this.isInSubnet(LINK_LOCAL_V4);
      }
      /**
       * Returns true if the address is the unspecified address `0.0.0.0`.
       * @returns {boolean}
       */
      isUnspecified() {
        return this.isInSubnet(UNSPECIFIED_V4);
      }
      /**
       * Returns true if the address is the limited broadcast address `255.255.255.255` ([RFC 919](https://datatracker.ietf.org/doc/html/rfc919)).
       * @returns {boolean}
       */
      isBroadcast() {
        return this.isInSubnet(BROADCAST_V4);
      }
      /**
       * Returns true if the address is in the carrier-grade NAT range `100.64.0.0/10` ([RFC 6598](https://datatracker.ietf.org/doc/html/rfc6598)).
       * @returns {boolean}
       */
      isCGNAT() {
        return this.isInSubnet(CGNAT_V4);
      }
      /**
       * Returns a zero-padded base-2 string representation of the address
       * @returns {string}
       */
      binaryZeroPad() {
        if (this._binaryZeroPad === void 0) {
          this._binaryZeroPad = this.bigInt().toString(2).padStart(constants.BITS, "0");
        }
        return this._binaryZeroPad;
      }
      /**
       * Groups an IPv4 address for inclusion at the end of an IPv6 address
       * @returns {String}
       */
      groupForV6() {
        const segments = this.parsedAddress;
        return this.address.replace(constants.RE_ADDRESS, `<span class="hover-group group-v4 group-6">${segments.slice(0, 2).join(".")}</span>.<span class="hover-group group-v4 group-7">${segments.slice(2, 4).join(".")}</span>`);
      }
    };
    exports.Address4 = Address4;
    var MULTICAST_V4 = new Address4("224.0.0.0/4");
    var PRIVATE_V4 = [
      new Address4("10.0.0.0/8"),
      new Address4("172.16.0.0/12"),
      new Address4("192.168.0.0/16")
    ];
    var LOOPBACK_V4 = new Address4("127.0.0.0/8");
    var LINK_LOCAL_V4 = new Address4("169.254.0.0/16");
    var UNSPECIFIED_V4 = new Address4("0.0.0.0/32");
    var BROADCAST_V4 = new Address4("255.255.255.255/32");
    var CGNAT_V4 = new Address4("100.64.0.0/10");
  }
});

// ../../node_modules/.pnpm/ip-address@10.2.0/node_modules/ip-address/dist/v6/constants.js
var require_constants3 = __commonJS({
  "../../node_modules/.pnpm/ip-address@10.2.0/node_modules/ip-address/dist/v6/constants.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RE_URL_WITH_PORT = exports.RE_URL = exports.RE_ZONE_STRING = exports.RE_SUBNET_STRING = exports.RE_BAD_ADDRESS = exports.RE_BAD_CHARACTERS = exports.TYPES = exports.SCOPES = exports.GROUPS = exports.BITS = void 0;
    exports.BITS = 128;
    exports.GROUPS = 8;
    exports.SCOPES = {
      0: "Reserved",
      1: "Interface local",
      2: "Link local",
      4: "Admin local",
      5: "Site local",
      8: "Organization local",
      14: "Global",
      15: "Reserved"
    };
    exports.TYPES = {
      "ff01::1/128": "Multicast (All nodes on this interface)",
      "ff01::2/128": "Multicast (All routers on this interface)",
      "ff02::1/128": "Multicast (All nodes on this link)",
      "ff02::2/128": "Multicast (All routers on this link)",
      "ff05::2/128": "Multicast (All routers in this site)",
      "ff02::5/128": "Multicast (OSPFv3 AllSPF routers)",
      "ff02::6/128": "Multicast (OSPFv3 AllDR routers)",
      "ff02::9/128": "Multicast (RIP routers)",
      "ff02::a/128": "Multicast (EIGRP routers)",
      "ff02::d/128": "Multicast (PIM routers)",
      "ff02::16/128": "Multicast (MLDv2 reports)",
      "ff01::fb/128": "Multicast (mDNSv6)",
      "ff02::fb/128": "Multicast (mDNSv6)",
      "ff05::fb/128": "Multicast (mDNSv6)",
      "ff02::1:2/128": "Multicast (All DHCP servers and relay agents on this link)",
      "ff05::1:2/128": "Multicast (All DHCP servers and relay agents in this site)",
      "ff02::1:3/128": "Multicast (All DHCP servers on this link)",
      "ff05::1:3/128": "Multicast (All DHCP servers in this site)",
      "::/128": "Unspecified",
      "::1/128": "Loopback",
      "ff00::/8": "Multicast",
      "fe80::/10": "Link-local unicast",
      "fc00::/7": "Unique local",
      "2002::/16": "6to4",
      "2001:db8::/32": "Documentation",
      "64:ff9b::/96": "NAT64 (well-known)",
      "64:ff9b:1::/48": "NAT64 (local-use)"
    };
    exports.RE_BAD_CHARACTERS = /([^0-9a-f:/%])/gi;
    exports.RE_BAD_ADDRESS = /([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi;
    exports.RE_SUBNET_STRING = /\/\d{1,3}(?=%|$)/;
    exports.RE_ZONE_STRING = /%.*$/;
    exports.RE_URL = /^\[{0,1}([0-9a-f:]+)\]{0,1}/;
    exports.RE_URL_WITH_PORT = /\[([0-9a-f:]+)\]:([0-9]{1,5})/;
  }
});

// ../../node_modules/.pnpm/ip-address@10.2.0/node_modules/ip-address/dist/v6/helpers.js
var require_helpers = __commonJS({
  "../../node_modules/.pnpm/ip-address@10.2.0/node_modules/ip-address/dist/v6/helpers.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.escapeHtml = escapeHtml2;
    exports.spanAllZeroes = spanAllZeroes;
    exports.spanAll = spanAll;
    exports.spanLeadingZeroes = spanLeadingZeroes;
    exports.simpleGroup = simpleGroup;
    function escapeHtml2(s) {
      return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
    }
    function spanAllZeroes(s) {
      return escapeHtml2(s).replace(/(0+)/g, '<span class="zero">$1</span>');
    }
    function spanAll(s, offset = 0) {
      const letters = s.split("");
      return letters.map((n, i) => `<span class="digit value-${escapeHtml2(n)} position-${i + offset}">${spanAllZeroes(n)}</span>`).join("");
    }
    function spanLeadingZeroesSimple(group) {
      return escapeHtml2(group).replace(/^(0+)/, '<span class="zero">$1</span>');
    }
    function spanLeadingZeroes(address) {
      const groups = address.split(":");
      return groups.map((g) => spanLeadingZeroesSimple(g)).join(":");
    }
    function simpleGroup(addressString, offset = 0) {
      const groups = addressString.split(":");
      return groups.map((g, i) => {
        if (/group-v4/.test(g)) {
          return g;
        }
        return `<span class="hover-group group-${i + offset}">${spanLeadingZeroesSimple(g)}</span>`;
      });
    }
  }
});

// ../../node_modules/.pnpm/ip-address@10.2.0/node_modules/ip-address/dist/v6/regular-expressions.js
var require_regular_expressions = __commonJS({
  "../../node_modules/.pnpm/ip-address@10.2.0/node_modules/ip-address/dist/v6/regular-expressions.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc2 = Object.getOwnPropertyDescriptor(m, k);
      if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc2);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
      }
      __setModuleDefault(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ADDRESS_BOUNDARY = void 0;
    exports.groupPossibilities = groupPossibilities;
    exports.padGroup = padGroup;
    exports.simpleRegularExpression = simpleRegularExpression;
    exports.possibleElisions = possibleElisions;
    var v6 = __importStar(require_constants3());
    function groupPossibilities(possibilities) {
      return `(${possibilities.join("|")})`;
    }
    function padGroup(group) {
      if (group.length < 4) {
        return `0{0,${4 - group.length}}${group}`;
      }
      return group;
    }
    exports.ADDRESS_BOUNDARY = "[^A-Fa-f0-9:]";
    function simpleRegularExpression(groups) {
      const zeroIndexes = [];
      groups.forEach((group, i) => {
        const groupInteger = parseInt(group, 16);
        if (groupInteger === 0) {
          zeroIndexes.push(i);
        }
      });
      const possibilities = zeroIndexes.map((zeroIndex) => groups.map((group, i) => {
        if (i === zeroIndex) {
          const elision = i === 0 || i === v6.GROUPS - 1 ? ":" : "";
          return groupPossibilities([padGroup(group), elision]);
        }
        return padGroup(group);
      }).join(":"));
      possibilities.push(groups.map(padGroup).join(":"));
      return groupPossibilities(possibilities);
    }
    function possibleElisions(elidedGroups, moreLeft, moreRight) {
      const left = moreLeft ? "" : ":";
      const right = moreRight ? "" : ":";
      const possibilities = [];
      if (!moreLeft && !moreRight) {
        possibilities.push("::");
      }
      if (moreLeft && moreRight) {
        possibilities.push("");
      }
      if (moreRight && !moreLeft || !moreRight && moreLeft) {
        possibilities.push(":");
      }
      possibilities.push(`${left}(:0{1,4}){1,${elidedGroups - 1}}`);
      possibilities.push(`(0{1,4}:){1,${elidedGroups - 1}}${right}`);
      possibilities.push(`(0{1,4}:){${elidedGroups - 1}}0{1,4}`);
      for (let groups = 1; groups < elidedGroups - 1; groups++) {
        for (let position = 1; position < elidedGroups - groups; position++) {
          possibilities.push(`(0{1,4}:){${position}}:(0{1,4}:){${elidedGroups - position - groups - 1}}0{1,4}`);
        }
      }
      return groupPossibilities(possibilities);
    }
  }
});

// ../../node_modules/.pnpm/ip-address@10.2.0/node_modules/ip-address/dist/ipv6.js
var require_ipv6 = __commonJS({
  "../../node_modules/.pnpm/ip-address@10.2.0/node_modules/ip-address/dist/ipv6.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc2 = Object.getOwnPropertyDescriptor(m, k);
      if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc2);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
      }
      __setModuleDefault(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Address6 = void 0;
    var common = __importStar(require_common());
    var constants4 = __importStar(require_constants2());
    var constants6 = __importStar(require_constants3());
    var helpers = __importStar(require_helpers());
    var ipv4_1 = require_ipv4();
    var regular_expressions_1 = require_regular_expressions();
    var address_error_1 = require_address_error();
    var common_1 = require_common();
    var isCorrect6 = common.isCorrect(constants6.BITS);
    function assert2(condition) {
      if (!condition) {
        throw new Error("Assertion failed.");
      }
    }
    function addCommas(number4) {
      const r = /(\d+)(\d{3})/;
      while (r.test(number4)) {
        number4 = number4.replace(r, "$1,$2");
      }
      return number4;
    }
    function spanLeadingZeroes4(n) {
      n = n.replace(/^(0{1,})([1-9]+)$/, '<span class="parse-error">$1</span>$2');
      n = n.replace(/^(0{1,})(0)$/, '<span class="parse-error">$1</span>$2');
      return n;
    }
    function compact(address, slice) {
      const s1 = [];
      const s2 = [];
      let i;
      for (i = 0; i < address.length; i++) {
        if (i < slice[0]) {
          s1.push(address[i]);
        } else if (i > slice[1]) {
          s2.push(address[i]);
        }
      }
      return s1.concat(["compact"]).concat(s2);
    }
    function paddedHex(octet) {
      return parseInt(octet, 16).toString(16).padStart(4, "0");
    }
    function unsignByte(b) {
      return b & 255;
    }
    var Address62 = class _Address6 {
      constructor(address, optionalGroups) {
        this.addressMinusSuffix = "";
        this.parsedSubnet = "";
        this.subnet = "/128";
        this.subnetMask = 128;
        this.v4 = false;
        this.zone = "";
        this.isInSubnet = common.isInSubnet;
        this.isCorrect = isCorrect6;
        if (optionalGroups === void 0) {
          this.groups = constants6.GROUPS;
        } else {
          this.groups = optionalGroups;
        }
        this.address = address;
        const subnet = constants6.RE_SUBNET_STRING.exec(address);
        if (subnet) {
          this.parsedSubnet = subnet[0].replace("/", "");
          this.subnetMask = parseInt(this.parsedSubnet, 10);
          this.subnet = `/${this.subnetMask}`;
          if (Number.isNaN(this.subnetMask) || this.subnetMask < 0 || this.subnetMask > constants6.BITS) {
            throw new address_error_1.AddressError("Invalid subnet mask.");
          }
          address = address.replace(constants6.RE_SUBNET_STRING, "");
        } else if (/\//.test(address)) {
          throw new address_error_1.AddressError("Invalid subnet mask.");
        }
        const zone = constants6.RE_ZONE_STRING.exec(address);
        if (zone) {
          this.zone = zone[0];
          address = address.replace(constants6.RE_ZONE_STRING, "");
        }
        this.addressMinusSuffix = address;
        this.parsedAddress = this.parse(this.addressMinusSuffix);
      }
      /**
       * Returns true if the given string is a valid IPv6 address (with optional
       * CIDR subnet and zone identifier), false otherwise. Host bits in the
       * subnet portion are allowed (e.g. `2001:db8::1/32` is valid); for strict
       * network-address validation compare `correctForm()` to
       * `startAddress().correctForm()`, or use `networkForm()`.
       */
      static isValid(address) {
        try {
          new _Address6(address);
          return true;
        } catch (e) {
          return false;
        }
      }
      /**
       * Convert a BigInt to a v6 address object. The value must be in the
       * range `[0, 2**128 - 1]`; otherwise `AddressError` is thrown.
       * @param {bigint} bigInt - a BigInt to convert
       * @returns {Address6}
       * @example
       * var bigInt = BigInt('1000000000000');
       * var address = Address6.fromBigInt(bigInt);
       * address.correctForm(); // '::e8:d4a5:1000'
       */
      static fromBigInt(bigInt) {
        if (bigInt < 0n || bigInt > (1n << BigInt(constants6.BITS)) - 1n) {
          throw new address_error_1.AddressError("IPv6 BigInt must be in the range 0 to 2**128 - 1");
        }
        const hex = bigInt.toString(16).padStart(32, "0");
        const groups = [];
        for (let i = 0; i < constants6.GROUPS; i++) {
          groups.push(hex.slice(i * 4, (i + 1) * 4));
        }
        return new _Address6(groups.join(":"));
      }
      /**
       * Parse a URL (with optional bracketed host and port) into an address and
       * port. Returns either `{ address, port }` on success or
       * `{ error, address: null, port: null }` if the URL could not be parsed.
       * Ports are returned as numbers (or `null` if absent or out of range).
       * @example
       * var addressAndPort = Address6.fromURL('http://[ffff::]:8080/foo/');
       * addressAndPort.address.correctForm(); // 'ffff::'
       * addressAndPort.port; // 8080
       */
      static fromURL(url2) {
        let host;
        let port2 = null;
        let result;
        if (url2.indexOf("[") !== -1 && url2.indexOf("]:") !== -1) {
          result = constants6.RE_URL_WITH_PORT.exec(url2);
          if (result === null) {
            return {
              error: "failed to parse address with port",
              address: null,
              port: null
            };
          }
          host = result[1];
          port2 = result[2];
        } else if (url2.indexOf("/") !== -1) {
          url2 = url2.replace(/^[a-z0-9]+:\/\//, "");
          result = constants6.RE_URL.exec(url2);
          if (result === null) {
            return {
              error: "failed to parse address from URL",
              address: null,
              port: null
            };
          }
          host = result[1];
        } else {
          host = url2;
        }
        if (port2) {
          port2 = parseInt(port2, 10);
          if (port2 < 0 || port2 > 65536) {
            port2 = null;
          }
        } else {
          port2 = null;
        }
        return {
          address: new _Address6(host),
          port: port2
        };
      }
      /**
       * Construct an `Address6` from an address and a hex subnet mask given as
       * separate strings (e.g. as returned by Node's `os.networkInterfaces()`).
       * Throws `AddressError` if the mask is non-contiguous (e.g.
       * `ffff::ffff`).
       * @example
       * var address = Address6.fromAddressAndMask('fe80::1', 'ffff:ffff:ffff:ffff::');
       * address.subnetMask; // 64
       */
      static fromAddressAndMask(address, mask) {
        const bits = common.prefixLengthFromMask(new _Address6(mask).bigInt(), constants6.BITS);
        return new _Address6(`${address}/${bits}`);
      }
      /**
       * Construct an `Address6` from an address and a Cisco-style wildcard mask
       * given as separate strings (e.g. `::ffff:ffff:ffff:ffff` for a `/64`).
       * The wildcard mask is the bitwise inverse of the subnet mask. Throws
       * `AddressError` if the mask is non-contiguous.
       * @example
       * var address = Address6.fromAddressAndWildcardMask('fe80::1', '::ffff:ffff:ffff:ffff');
       * address.subnetMask; // 64
       */
      static fromAddressAndWildcardMask(address, wildcardMask) {
        const wildcard = new _Address6(wildcardMask).bigInt();
        const allOnes = (BigInt(1) << BigInt(constants6.BITS)) - BigInt(1);
        const mask = wildcard ^ allOnes;
        const bits = common.prefixLengthFromMask(mask, constants6.BITS);
        return new _Address6(`${address}/${bits}`);
      }
      /**
       * Construct an `Address6` from a wildcard pattern with trailing `*`
       * groups. The number of trailing wildcards determines the prefix
       * length: each `*` represents 16 bits. `::` is expanded to zero groups
       * (not wildcards) before evaluating trailing wildcards.
       *
       * Only trailing whole-group wildcards are supported. Partial-group
       * wildcards (e.g. `2001:db8::0*`) and interior wildcards (e.g.
       * `*::1`) throw `AddressError`.
       * @example
       * Address6.fromWildcard('2001:db8:*:*:*:*:*:*').subnet;  // '/32'
       * Address6.fromWildcard('2001:db8::*').subnet;           // '/112'
       * Address6.fromWildcard('*:*:*:*:*:*:*:*').subnet;       // '/0'
       */
      static fromWildcard(input) {
        if (input.includes("%") || input.includes("/")) {
          throw new address_error_1.AddressError("Wildcard pattern must not include a zone or CIDR suffix");
        }
        const halves = input.split("::");
        if (halves.length > 2) {
          throw new address_error_1.AddressError("Wildcard pattern cannot contain more than one '::'");
        }
        let groups;
        if (halves.length === 2) {
          const left = halves[0] === "" ? [] : halves[0].split(":");
          const right = halves[1] === "" ? [] : halves[1].split(":");
          const remaining = constants6.GROUPS - left.length - right.length;
          if (remaining < 1) {
            throw new address_error_1.AddressError("Wildcard pattern with '::' has too many groups");
          }
          groups = [...left, ...new Array(remaining).fill("0"), ...right];
        } else {
          groups = input.split(":");
        }
        if (groups.length !== constants6.GROUPS) {
          throw new address_error_1.AddressError("Wildcard pattern must have 8 groups");
        }
        let firstWildcard = -1;
        for (let i = 0; i < groups.length; i++) {
          if (groups[i] === "*") {
            if (firstWildcard === -1) {
              firstWildcard = i;
            }
          } else if (firstWildcard !== -1) {
            throw new address_error_1.AddressError("Wildcard `*` must only appear in trailing groups (e.g. `2001:db8:*:*:*:*:*:*`)");
          }
        }
        const trailing = firstWildcard === -1 ? 0 : groups.length - firstWildcard;
        const replaced = groups.map((g) => g === "*" ? "0" : g);
        const subnetBits = constants6.BITS - trailing * 16;
        return new _Address6(`${replaced.join(":")}/${subnetBits}`);
      }
      /**
       * Create an IPv6-mapped address given an IPv4 address
       * @param {string} address - An IPv4 address string
       * @returns {Address6}
       * @example
       * var address = Address6.fromAddress4('192.168.0.1');
       * address.correctForm(); // '::ffff:c0a8:1'
       * address.to4in6(); // '::ffff:192.168.0.1'
       */
      static fromAddress4(address) {
        const address4 = new ipv4_1.Address4(address);
        const mask6 = constants6.BITS - (constants4.BITS - address4.subnetMask);
        return new _Address6(`::ffff:${address4.correctForm()}/${mask6}`);
      }
      /**
       * Return an address from ip6.arpa form
       * @param {string} arpaFormAddress - an 'ip6.arpa' form address
       * @returns {Adress6}
       * @example
       * var address = Address6.fromArpa(e.f.f.f.3.c.2.6.f.f.f.e.6.6.8.e.1.0.6.7.9.4.e.c.0.0.0.0.1.0.0.2.ip6.arpa.)
       * address.correctForm(); // '2001:0:ce49:7601:e866:efff:62c3:fffe'
       */
      static fromArpa(arpaFormAddress) {
        let address = arpaFormAddress.replace(/(\.ip6\.arpa)?\.$/, "");
        const semicolonAmount = 7;
        if (address.length !== 63) {
          throw new address_error_1.AddressError("Invalid 'ip6.arpa' form.");
        }
        const parts = address.split(".").reverse();
        for (let i = semicolonAmount; i > 0; i--) {
          const insertIndex = i * 4;
          parts.splice(insertIndex, 0, ":");
        }
        address = parts.join("");
        return new _Address6(address);
      }
      /**
       * Return the Microsoft UNC transcription of the address
       * @returns {String} the Microsoft UNC transcription of the address
       */
      microsoftTranscription() {
        return `${this.correctForm().replace(/:/g, "-")}.ipv6-literal.net`;
      }
      /**
       * Return the first n bits of the address, defaulting to the subnet mask
       * @param {number} [mask=subnet] - the number of bits to mask
       * @returns {String} the first n bits of the address as a string
       */
      mask(mask = this.subnetMask) {
        return this.getBitsBase2(0, mask);
      }
      /**
       * Return the number of possible subnets of a given size in the address
       * @param {number} [subnetSize=128] - the subnet size
       * @returns {String}
       */
      // TODO: probably useful to have a numeric version of this too
      possibleSubnets(subnetSize = 128) {
        const availableBits = constants6.BITS - this.subnetMask;
        const subnetBits = Math.abs(subnetSize - constants6.BITS);
        const subnetPowers = availableBits - subnetBits;
        if (subnetPowers < 0) {
          return "0";
        }
        return addCommas((BigInt("2") ** BigInt(subnetPowers)).toString(10));
      }
      /**
       * Helper function getting start address.
       * @returns {bigint}
       */
      _startAddress() {
        return BigInt(`0b${this.mask() + "0".repeat(constants6.BITS - this.subnetMask)}`);
      }
      /**
       * The first address in the range given by this address' subnet
       * Often referred to as the Network Address.
       * @returns {Address6}
       */
      startAddress() {
        return _Address6.fromBigInt(this._startAddress());
      }
      /**
       * The first host address in the range given by this address's subnet ie
       * the first address after the Network Address
       * @returns {Address6}
       */
      startAddressExclusive() {
        const adjust = BigInt("1");
        return _Address6.fromBigInt(this._startAddress() + adjust);
      }
      /**
       * Helper function getting end address.
       * @returns {bigint}
       */
      _endAddress() {
        return BigInt(`0b${this.mask() + "1".repeat(constants6.BITS - this.subnetMask)}`);
      }
      /**
       * The last address in the range given by this address' subnet
       * Often referred to as the Broadcast
       * @returns {Address6}
       */
      endAddress() {
        return _Address6.fromBigInt(this._endAddress());
      }
      /**
       * The last host address in the range given by this address's subnet ie
       * the last address prior to the Broadcast Address
       * @returns {Address6}
       */
      endAddressExclusive() {
        const adjust = BigInt("1");
        return _Address6.fromBigInt(this._endAddress() - adjust);
      }
      /**
       * The hex form of the subnet mask, e.g. `ffff:ffff:ffff:ffff::` for a
       * `/64`. Returns an `Address6`; call `.correctForm()` for the string.
       * @returns {Address6}
       */
      subnetMaskAddress() {
        return _Address6.fromBigInt(BigInt(`0b${"1".repeat(this.subnetMask)}${"0".repeat(constants6.BITS - this.subnetMask)}`));
      }
      /**
       * The Cisco-style wildcard mask, e.g. `::ffff:ffff:ffff:ffff` for a
       * `/64`. This is the bitwise inverse of `subnetMaskAddress()`. Returns
       * an `Address6`; call `.correctForm()` for the string.
       * @returns {Address6}
       */
      wildcardMask() {
        return _Address6.fromBigInt(BigInt(`0b${"0".repeat(this.subnetMask)}${"1".repeat(constants6.BITS - this.subnetMask)}`));
      }
      /**
       * The network address in CIDR string form, e.g. `2001:db8::/32` for
       * `2001:db8::1/32`. For an address with no explicit subnet the prefix
       * is `/128`, e.g. `networkForm()` on `2001:db8::1` returns
       * `2001:db8::1/128`.
       * @returns {string}
       */
      networkForm() {
        return `${this.startAddress().correctForm()}/${this.subnetMask}`;
      }
      /**
       * Return the scope of the address. The 4-bit scope field
       * ([RFC 4291 §2.7](https://datatracker.ietf.org/doc/html/rfc4291#section-2.7))
       * is only defined for multicast addresses; for unicast addresses the scope
       * is derived from the address type per
       * [RFC 4007 §6](https://datatracker.ietf.org/doc/html/rfc4007#section-6).
       * @returns {String}
       */
      getScope() {
        const type = this.getType();
        if (type === "Multicast" || type.startsWith("Multicast ")) {
          const scope = constants6.SCOPES[parseInt(this.getBits(12, 16).toString(10), 10)];
          return scope || "Unknown";
        }
        if (type === "Link-local unicast" || type === "Loopback") {
          return "Link local";
        }
        if (type === "Unspecified") {
          return "Unknown";
        }
        return "Global";
      }
      /**
       * Return the type of the address
       * @returns {String}
       */
      getType() {
        for (let i = 0; i < TYPE_SUBNETS.length; i++) {
          const entry = TYPE_SUBNETS[i];
          if (this.isInSubnet(entry[0])) {
            return entry[1];
          }
        }
        return "Global unicast";
      }
      /**
       * Return the bits in the given range as a BigInt
       * @returns {bigint}
       */
      getBits(start, end) {
        return BigInt(`0b${this.getBitsBase2(start, end)}`);
      }
      /**
       * Return the bits in the given range as a base-2 string
       * @returns {String}
       */
      getBitsBase2(start, end) {
        return this.binaryZeroPad().slice(start, end);
      }
      /**
       * Return the bits in the given range as a base-16 string
       * @returns {String}
       */
      getBitsBase16(start, end) {
        const length = end - start;
        if (length % 4 !== 0) {
          throw new Error("Length of bits to retrieve must be divisible by four");
        }
        return this.getBits(start, end).toString(16).padStart(length / 4, "0");
      }
      /**
       * Return the bits that are set past the subnet mask length
       * @returns {String}
       */
      getBitsPastSubnet() {
        return this.getBitsBase2(this.subnetMask, constants6.BITS);
      }
      /**
       * Return the reversed ip6.arpa form of the address
       * @param {Object} options
       * @param {boolean} options.omitSuffix - omit the "ip6.arpa" suffix
       * @returns {String}
       */
      reverseForm(options) {
        if (!options) {
          options = {};
        }
        const characters = Math.floor(this.subnetMask / 4);
        const reversed = this.canonicalForm().replace(/:/g, "").split("").slice(0, characters).reverse().join(".");
        if (characters > 0) {
          if (options.omitSuffix) {
            return reversed;
          }
          return `${reversed}.ip6.arpa.`;
        }
        if (options.omitSuffix) {
          return "";
        }
        return "ip6.arpa.";
      }
      /**
       * Returns the address in correct form, per
       * [RFC 5952](https://datatracker.ietf.org/doc/html/rfc5952): leading zeros
       * stripped, the longest run of zero groups collapsed to `::`, and hex digits
       * lowercased (e.g. `2001:db8::1`). This is the recommended form for display.
       */
      correctForm() {
        let i;
        let groups = [];
        let zeroCounter = 0;
        const zeroes = [];
        for (i = 0; i < this.parsedAddress.length; i++) {
          const value = parseInt(this.parsedAddress[i], 16);
          if (value === 0) {
            zeroCounter++;
          }
          if (value !== 0 && zeroCounter > 0) {
            if (zeroCounter > 1) {
              zeroes.push([i - zeroCounter, i - 1]);
            }
            zeroCounter = 0;
          }
        }
        if (zeroCounter > 1) {
          zeroes.push([this.parsedAddress.length - zeroCounter, this.parsedAddress.length - 1]);
        }
        const zeroLengths = zeroes.map((n) => n[1] - n[0] + 1);
        if (zeroes.length > 0) {
          const index2 = zeroLengths.indexOf(Math.max(...zeroLengths));
          groups = compact(this.parsedAddress, zeroes[index2]);
        } else {
          groups = this.parsedAddress;
        }
        for (i = 0; i < groups.length; i++) {
          if (groups[i] !== "compact") {
            groups[i] = parseInt(groups[i], 16).toString(16);
          }
        }
        let correct = groups.join(":");
        correct = correct.replace(/^compact$/, "::");
        correct = correct.replace(/(^compact)|(compact$)/, ":");
        correct = correct.replace(/compact/, "");
        return correct;
      }
      /**
       * Return a zero-padded base-2 string representation of the address
       * @returns {String}
       * @example
       * var address = new Address6('2001:4860:4001:803::1011');
       * address.binaryZeroPad();
       * // '0010000000000001010010000110000001000000000000010000100000000011
       * //  0000000000000000000000000000000000000000000000000001000000010001'
       */
      binaryZeroPad() {
        if (this._binaryZeroPad === void 0) {
          this._binaryZeroPad = this.bigInt().toString(2).padStart(constants6.BITS, "0");
        }
        return this._binaryZeroPad;
      }
      /**
       * Parses a v4-in-v6 string (e.g. `::ffff:192.168.0.1`) by extracting the
       * trailing IPv4 address into `this.address4` / `this.parsedAddress4` and
       * returning the address with the v4 portion converted to two v6 groups.
       * Used internally by `parse()`.
       */
      // TODO: Improve the semantics of this helper function
      parse4in6(address) {
        if (address.indexOf(".") === -1) {
          return address;
        }
        const groups = address.split(":");
        const lastGroup = groups.slice(-1)[0];
        const address4 = lastGroup.match(constants4.RE_ADDRESS);
        if (address4) {
          this.parsedAddress4 = address4[0];
          this.address4 = new ipv4_1.Address4(this.parsedAddress4);
          for (let i = 0; i < this.address4.groups; i++) {
            if (/^0[0-9]+/.test(this.address4.parsedAddress[i])) {
              const highlighted = this.address4.parsedAddress.map(spanLeadingZeroes4).join(".");
              const prefix = groups.slice(0, -1).map(helpers.escapeHtml).join(":");
              const separator = groups.length > 1 ? ":" : "";
              throw new address_error_1.AddressError("IPv4 addresses can't have leading zeroes.", `${prefix}${separator}${highlighted}`);
            }
          }
          this.v4 = true;
          groups[groups.length - 1] = this.address4.toGroup6();
          address = groups.join(":");
        }
        return address;
      }
      /**
       * Parses an IPv6 address string into its 8 hexadecimal groups (expanding
       * any `::` elision and any trailing v4-in-v6 portion) and stores the result
       * on `this.parsedAddress`. Called automatically by the constructor; you
       * typically don't need to call it directly. Throws `AddressError` if the
       * input is malformed.
       */
      // TODO: Make private?
      parse(address) {
        address = this.parse4in6(address);
        const badCharacters = address.match(constants6.RE_BAD_CHARACTERS);
        if (badCharacters) {
          throw new address_error_1.AddressError(`Bad character${badCharacters.length > 1 ? "s" : ""} detected in address: ${badCharacters.join("")}`, address.replace(constants6.RE_BAD_CHARACTERS, '<span class="parse-error">$1</span>'));
        }
        const badAddress = address.match(constants6.RE_BAD_ADDRESS);
        if (badAddress) {
          throw new address_error_1.AddressError(`Address failed regex: ${badAddress.join("")}`, address.replace(constants6.RE_BAD_ADDRESS, '<span class="parse-error">$1</span>'));
        }
        let groups = [];
        const halves = address.split("::");
        if (halves.length === 2) {
          let first = halves[0].split(":");
          let last = halves[1].split(":");
          if (first.length === 1 && first[0] === "") {
            first = [];
          }
          if (last.length === 1 && last[0] === "") {
            last = [];
          }
          const remaining = this.groups - (first.length + last.length);
          if (!remaining) {
            throw new address_error_1.AddressError("Error parsing groups");
          }
          this.elidedGroups = remaining;
          this.elisionBegin = first.length;
          this.elisionEnd = first.length + this.elidedGroups;
          groups = groups.concat(first);
          for (let i = 0; i < remaining; i++) {
            groups.push("0");
          }
          groups = groups.concat(last);
        } else if (halves.length === 1) {
          groups = address.split(":");
          this.elidedGroups = 0;
        } else {
          throw new address_error_1.AddressError("Too many :: groups found");
        }
        groups = groups.map((group) => parseInt(group, 16).toString(16));
        if (groups.length !== this.groups) {
          throw new address_error_1.AddressError("Incorrect number of groups found");
        }
        return groups;
      }
      /**
       * Returns the canonical (fully expanded) form of the address: all 8 groups,
       * each padded to 4 hex digits, with no `::` collapsing
       * (e.g. `2001:0db8:0000:0000:0000:0000:0000:0001`). Useful for sorting and
       * byte-exact comparison.
       */
      canonicalForm() {
        return this.parsedAddress.map(paddedHex).join(":");
      }
      /**
       * Return the decimal form of the address
       * @returns {String}
       */
      decimal() {
        return this.parsedAddress.map((n) => parseInt(n, 16).toString(10).padStart(5, "0")).join(":");
      }
      /**
       * Return the address as a BigInt
       * @returns {bigint}
       */
      bigInt() {
        return BigInt(`0x${this.parsedAddress.map(paddedHex).join("")}`);
      }
      /**
       * Return the last two groups of this address as an IPv4 address string
       * @returns {Address4}
       * @example
       * var address = new Address6('2001:4860:4001::1825:bf11');
       * address.to4().correctForm(); // '24.37.191.17'
       */
      to4() {
        const binary = this.binaryZeroPad().split("");
        return ipv4_1.Address4.fromHex(BigInt(`0b${binary.slice(96, 128).join("")}`).toString(16).padStart(8, "0"));
      }
      /**
       * Return the v4-in-v6 form of the address
       * @returns {String}
       */
      to4in6() {
        const address4 = this.to4();
        const address6 = new _Address6(this.parsedAddress.slice(0, 6).join(":"), 6);
        const correct = address6.correctForm();
        let infix = "";
        if (!/:$/.test(correct)) {
          infix = ":";
        }
        return correct + infix + address4.address;
      }
      /**
       * Decodes the Teredo tunneling fields embedded in this address. Returns the
       * Teredo prefix, server IPv4, client IPv4, raw flag bits, cone-NAT flag,
       * UDP port, and Microsoft-format flag breakdown (reserved, universal/local,
       * group/individual, nonce). Only meaningful for addresses in `2001::/32`.
       */
      inspectTeredo() {
        const prefix = this.getBitsBase16(0, 32);
        const bitsForUdpPort = this.getBits(80, 96);
        const udpPort = (bitsForUdpPort ^ BigInt("0xffff")).toString();
        const server4 = ipv4_1.Address4.fromHex(this.getBitsBase16(32, 64));
        const bitsForClient4 = this.getBits(96, 128);
        const client4 = ipv4_1.Address4.fromHex((bitsForClient4 ^ BigInt("0xffffffff")).toString(16).padStart(8, "0"));
        const flagsBase2 = this.getBitsBase2(64, 80);
        const coneNat = (0, common_1.testBit)(flagsBase2, 15);
        const reserved = (0, common_1.testBit)(flagsBase2, 14);
        const groupIndividual = (0, common_1.testBit)(flagsBase2, 8);
        const universalLocal = (0, common_1.testBit)(flagsBase2, 9);
        const nonce = BigInt(`0b${flagsBase2.slice(2, 6) + flagsBase2.slice(8, 16)}`).toString(10);
        return {
          prefix: `${prefix.slice(0, 4)}:${prefix.slice(4, 8)}`,
          server4: server4.address,
          client4: client4.address,
          flags: flagsBase2,
          coneNat,
          microsoft: {
            reserved,
            universalLocal,
            groupIndividual,
            nonce
          },
          udpPort
        };
      }
      /**
       * Decodes the 6to4 tunneling fields embedded in this address. Returns the
       * 6to4 prefix and the embedded IPv4 gateway address. Only meaningful for
       * addresses in `2002::/16`.
       */
      inspect6to4() {
        const prefix = this.getBitsBase16(0, 16);
        const gateway = ipv4_1.Address4.fromHex(this.getBitsBase16(16, 48));
        return {
          prefix: prefix.slice(0, 4),
          gateway: gateway.address
        };
      }
      /**
       * Return a v6 6to4 address from a v6 v4inv6 address
       * @returns {Address6}
       */
      to6to4() {
        if (!this.is4()) {
          return null;
        }
        const addr6to4 = [
          "2002",
          this.getBitsBase16(96, 112),
          this.getBitsBase16(112, 128),
          "",
          "/16"
        ].join(":");
        return new _Address6(addr6to4);
      }
      /**
       * Embed an IPv4 address into a NAT64 IPv6 address using the encoding
       * defined by [RFC 6052](https://datatracker.ietf.org/doc/html/rfc6052).
       * The default prefix is the well-known prefix `64:ff9b::/96`. The prefix
       * length must be one of 32, 40, 48, 56, 64, or 96; for prefixes shorter
       * than /64 the IPv4 octets are split around the reserved bits 64–71.
       * @example
       * Address6.fromAddress4Nat64('192.0.2.33').correctForm(); // '64:ff9b::c000:221'
       * Address6.fromAddress4Nat64('192.0.2.33', '2001:db8::/32').correctForm(); // '2001:db8:c000:221::'
       */
      static fromAddress4Nat64(address, prefix = "64:ff9b::/96") {
        const v4 = new ipv4_1.Address4(address);
        const prefix6 = new _Address6(prefix);
        const pl = prefix6.subnetMask;
        if (pl !== 32 && pl !== 40 && pl !== 48 && pl !== 56 && pl !== 64 && pl !== 96) {
          throw new address_error_1.AddressError("NAT64 prefix length must be 32, 40, 48, 56, 64, or 96");
        }
        const prefixBits = prefix6.binaryZeroPad();
        const v4Bits = v4.binaryZeroPad();
        let bits;
        if (pl === 96) {
          bits = prefixBits.slice(0, 96) + v4Bits;
        } else {
          const beforeU = 64 - pl;
          bits = prefixBits.slice(0, pl) + v4Bits.slice(0, beforeU) + "00000000" + v4Bits.slice(beforeU) + "0".repeat(128 - 72 - (32 - beforeU));
        }
        const hex = BigInt(`0b${bits}`).toString(16).padStart(32, "0");
        const groups = [];
        for (let i = 0; i < 8; i++) {
          groups.push(hex.slice(i * 4, (i + 1) * 4));
        }
        return new _Address6(groups.join(":"));
      }
      /**
       * Extract the embedded IPv4 address from a NAT64 IPv6 address using the
       * encoding defined by [RFC 6052](https://datatracker.ietf.org/doc/html/rfc6052).
       * The default prefix is the well-known prefix `64:ff9b::/96`. Returns
       * `null` if this address is not contained within the given prefix.
       * @example
       * new Address6('64:ff9b::c000:221').toAddress4Nat64()!.correctForm(); // '192.0.2.33'
       */
      toAddress4Nat64(prefix = "64:ff9b::/96") {
        const prefix6 = new _Address6(prefix);
        const pl = prefix6.subnetMask;
        if (pl !== 32 && pl !== 40 && pl !== 48 && pl !== 56 && pl !== 64 && pl !== 96) {
          throw new address_error_1.AddressError("NAT64 prefix length must be 32, 40, 48, 56, 64, or 96");
        }
        if (!this.isInSubnet(prefix6)) {
          return null;
        }
        const bits = this.binaryZeroPad();
        let v4Bits;
        if (pl === 96) {
          v4Bits = bits.slice(96, 128);
        } else {
          const beforeU = 64 - pl;
          v4Bits = bits.slice(pl, pl + beforeU) + bits.slice(72, 72 + (32 - beforeU));
        }
        const octets = [];
        for (let i = 0; i < 4; i++) {
          octets.push(parseInt(v4Bits.slice(i * 8, (i + 1) * 8), 2).toString());
        }
        return new ipv4_1.Address4(octets.join("."));
      }
      /**
       * Return a byte array.
       *
       * To get a Node.js `Buffer`, wrap the result: `Buffer.from(address.toByteArray())`.
       * @returns {Array}
       */
      toByteArray() {
        const valueWithoutPadding = this.bigInt().toString(16);
        const leadingPad = "0".repeat(valueWithoutPadding.length % 2);
        const value = `${leadingPad}${valueWithoutPadding}`;
        const bytes = [];
        for (let i = 0, length = value.length; i < length; i += 2) {
          bytes.push(parseInt(value.substring(i, i + 2), 16));
        }
        return bytes;
      }
      /**
       * Return an unsigned byte array.
       *
       * To get a Node.js `Buffer`, wrap the result: `Buffer.from(address.toUnsignedByteArray())`.
       * @returns {Array}
       */
      toUnsignedByteArray() {
        return this.toByteArray().map(unsignByte);
      }
      /**
       * Convert a byte array to an Address6 object.
       *
       * To convert from a Node.js `Buffer`, spread it: `Address6.fromByteArray([...buf])`.
       * @returns {Address6}
       */
      static fromByteArray(bytes) {
        return this.fromUnsignedByteArray(bytes.map(unsignByte));
      }
      /**
       * Convert an unsigned byte array to an Address6 object.
       *
       * To convert from a Node.js `Buffer`, spread it: `Address6.fromUnsignedByteArray([...buf])`.
       * @returns {Address6}
       */
      static fromUnsignedByteArray(bytes) {
        const BYTE_MAX = BigInt("256");
        let result = BigInt("0");
        let multiplier = BigInt("1");
        for (let i = bytes.length - 1; i >= 0; i--) {
          result += multiplier * BigInt(bytes[i].toString(10));
          multiplier *= BYTE_MAX;
        }
        return _Address6.fromBigInt(result);
      }
      /**
       * Returns true if the address is in the canonical form, false otherwise
       * @returns {boolean}
       */
      isCanonical() {
        return this.addressMinusSuffix === this.canonicalForm();
      }
      /**
       * Returns true if the address is a link local address, false otherwise
       * @returns {boolean}
       */
      isLinkLocal() {
        if (this.getBitsBase2(0, 64) === "1111111010000000000000000000000000000000000000000000000000000000") {
          return true;
        }
        return false;
      }
      /**
       * Returns true if the address is a multicast address, false otherwise
       * @returns {boolean}
       */
      isMulticast() {
        const type = this.getType();
        return type === "Multicast" || type.startsWith("Multicast ");
      }
      /**
       * Returns true if the address was written in v4-in-v6 dotted-quad notation
       * (e.g. `::ffff:127.0.0.1`), false otherwise. This is a notation-level flag
       * and does not reflect whether the address bits lie in the IPv4-mapped
       * (`::ffff:0:0/96`) subnet — for that, see {@link isMapped4}.
       * @returns {boolean}
       */
      is4() {
        return this.v4;
      }
      /**
       * Returns true if the address is an IPv4-mapped IPv6 address in
       * `::ffff:0:0/96` ([RFC 4291 §2.5.5.2](https://datatracker.ietf.org/doc/html/rfc4291#section-2.5.5.2)),
       * false otherwise. Unlike {@link is4}, this checks the underlying address
       * bits rather than the textual notation, so `::ffff:127.0.0.1` and
       * `::ffff:7f00:1` both return true.
       * @returns {boolean}
       */
      isMapped4() {
        return this.isInSubnet(IPV4_MAPPED_SUBNET);
      }
      /**
       * Returns true if the address is a Teredo address, false otherwise
       * @returns {boolean}
       */
      isTeredo() {
        return this.isInSubnet(TEREDO_SUBNET);
      }
      /**
       * Returns true if the address is a 6to4 address, false otherwise
       * @returns {boolean}
       */
      is6to4() {
        return this.isInSubnet(SIX_TO_FOUR_SUBNET);
      }
      /**
       * Returns true if the address is a loopback address, false otherwise
       * @returns {boolean}
       */
      isLoopback() {
        return this.getType() === "Loopback";
      }
      /**
       * Returns true if the address is a Unique Local Address in `fc00::/7` ([RFC 4193](https://datatracker.ietf.org/doc/html/rfc4193)). ULAs are the IPv6 equivalent of IPv4 [RFC 1918](https://datatracker.ietf.org/doc/html/rfc1918) private addresses.
       * @returns {boolean}
       */
      isULA() {
        return this.isInSubnet(ULA_SUBNET);
      }
      /**
       * Returns true if the address is the unspecified address `::`.
       * @returns {boolean}
       */
      isUnspecified() {
        return this.getType() === "Unspecified";
      }
      /**
       * Returns true if the address is in the documentation prefix `2001:db8::/32` ([RFC 3849](https://datatracker.ietf.org/doc/html/rfc3849)).
       * @returns {boolean}
       */
      isDocumentation() {
        return this.isInSubnet(DOCUMENTATION_SUBNET);
      }
      // #endregion
      // #region HTML
      /**
       * Returns the address as an HTTP URL with the host bracketed, e.g.
       * `http://[2001:db8::1]/`. If `optionalPort` is provided it is appended,
       * e.g. `http://[2001:db8::1]:8080/`.
       */
      href(optionalPort) {
        if (optionalPort === void 0) {
          optionalPort = "";
        } else {
          optionalPort = `:${optionalPort}`;
        }
        return `http://[${this.correctForm()}]${optionalPort}/`;
      }
      /**
       * Returns an HTML `<a>` element whose `href` encodes the address in a URL
       * hash fragment (default prefix `/#address=`). Useful for linking between
       * pages of an address-inspector UI.
       * @param options.className - CSS class for the rendered `<a>` element
       * @param options.prefix - hash prefix prepended to the address (default `/#address=`)
       * @param options.v4 - when true, render the address in v4-in-v6 form
       */
      link(options) {
        if (!options) {
          options = {};
        }
        if (options.className === void 0) {
          options.className = "";
        }
        if (options.prefix === void 0) {
          options.prefix = "/#address=";
        }
        if (options.v4 === void 0) {
          options.v4 = false;
        }
        let formFunction = this.correctForm;
        if (options.v4) {
          formFunction = this.to4in6;
        }
        const form = formFunction.call(this);
        const safeHref = helpers.escapeHtml(`${options.prefix}${form}`);
        const safeForm = helpers.escapeHtml(form);
        if (options.className) {
          const safeClass = helpers.escapeHtml(options.className);
          return `<a href="${safeHref}" class="${safeClass}">${safeForm}</a>`;
        }
        return `<a href="${safeHref}">${safeForm}</a>`;
      }
      /**
       * Groups an address
       * @returns {String}
       */
      group() {
        if (this.elidedGroups === 0) {
          return helpers.simpleGroup(this.addressMinusSuffix).join(":");
        }
        assert2(typeof this.elidedGroups === "number");
        assert2(typeof this.elisionBegin === "number");
        const output = [];
        const [left, right] = this.addressMinusSuffix.split("::");
        if (left.length) {
          output.push(...helpers.simpleGroup(left));
        } else {
          output.push("");
        }
        const classes = ["hover-group"];
        for (let i = this.elisionBegin; i < this.elisionBegin + this.elidedGroups; i++) {
          classes.push(`group-${i}`);
        }
        output.push(`<span class="${classes.join(" ")}"></span>`);
        if (right.length) {
          output.push(...helpers.simpleGroup(right, this.elisionEnd));
        } else {
          output.push("");
        }
        if (this.is4()) {
          assert2(this.address4 instanceof ipv4_1.Address4);
          output.pop();
          output.push(this.address4.groupForV6());
        }
        return output.join(":");
      }
      // #endregion
      // #region Regular expressions
      /**
       * Generate a regular expression string that can be used to find or validate
       * all variations of this address
       * @param {boolean} substringSearch
       * @returns {string}
       */
      regularExpressionString(substringSearch = false) {
        let output = [];
        const address6 = new _Address6(this.correctForm());
        if (address6.elidedGroups === 0) {
          output.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress));
        } else if (address6.elidedGroups === constants6.GROUPS) {
          output.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS));
        } else {
          const halves = address6.address.split("::");
          if (halves[0].length) {
            output.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(":")));
          }
          assert2(typeof address6.elidedGroups === "number");
          output.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0));
          if (halves[1].length) {
            output.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(":")));
          }
          output = [output.join(":")];
        }
        if (!substringSearch) {
          output = [
            "(?=^|",
            regular_expressions_1.ADDRESS_BOUNDARY,
            "|[^\\w\\:])(",
            ...output,
            ")(?=[^\\w\\:]|",
            regular_expressions_1.ADDRESS_BOUNDARY,
            "|$)"
          ];
        }
        return output.join("");
      }
      /**
       * Generate a regular expression that can be used to find or validate all
       * variations of this address.
       * @param {boolean} substringSearch
       * @returns {RegExp}
       */
      regularExpression(substringSearch = false) {
        return new RegExp(this.regularExpressionString(substringSearch), "i");
      }
    };
    exports.Address6 = Address62;
    var TYPE_SUBNETS = Object.keys(constants6.TYPES).map((subnet) => [
      new Address62(subnet),
      constants6.TYPES[subnet]
    ]);
    var TEREDO_SUBNET = new Address62("2001::/32");
    var SIX_TO_FOUR_SUBNET = new Address62("2002::/16");
    var ULA_SUBNET = new Address62("fc00::/7");
    var DOCUMENTATION_SUBNET = new Address62("2001:db8::/32");
    var IPV4_MAPPED_SUBNET = new Address62("::ffff:0:0/96");
  }
});

// ../../node_modules/.pnpm/ip-address@10.2.0/node_modules/ip-address/dist/ip-address.js
var require_ip_address = __commonJS({
  "../../node_modules/.pnpm/ip-address@10.2.0/node_modules/ip-address/dist/ip-address.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc2 = Object.getOwnPropertyDescriptor(m, k);
      if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc2);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
      }
      __setModuleDefault(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.v6 = exports.AddressError = exports.Address6 = exports.Address4 = void 0;
    var ipv4_1 = require_ipv4();
    Object.defineProperty(exports, "Address4", { enumerable: true, get: function() {
      return ipv4_1.Address4;
    } });
    var ipv6_1 = require_ipv6();
    Object.defineProperty(exports, "Address6", { enumerable: true, get: function() {
      return ipv6_1.Address6;
    } });
    var address_error_1 = require_address_error();
    Object.defineProperty(exports, "AddressError", { enumerable: true, get: function() {
      return address_error_1.AddressError;
    } });
    var helpers = __importStar(require_helpers());
    exports.v6 = { helpers };
  }
});

// ../../node_modules/.pnpm/express-rate-limit@8.5.2_express@4.21.2/node_modules/express-rate-limit/dist/index.mjs
import { isIPv6 } from "node:net";
import { isIPv6 as isIPv62 } from "node:net";
import { Buffer as Buffer2 } from "node:buffer";
import { createHash } from "node:crypto";
import { isIP } from "node:net";
function ipKeyGenerator(ip, ipv6Subnet = 56) {
  if (isIPv6(ip)) {
    const address = new import_ip_address.Address6(ip);
    if (address.is4()) return address.to4().correctForm();
    if (ipv6Subnet) {
      const subnet = new import_ip_address.Address6(`${ip}/${ipv6Subnet}`);
      return subnet.networkForm();
    }
  }
  return ip;
}
function validateLogger(logger2) {
  if (typeof logger2 !== "object" || typeof logger2.error !== "function" || typeof logger2.warn !== "function") {
    throw new TypeError(
      "Provided logger does not implement the Logger interface"
    );
  }
}
var import_ip_address, MemoryStore, ConsoleLogger, SUPPORTED_DRAFT_VERSIONS, getResetSeconds, getPartitionKey, setLegacyHeaders, setDraft6Headers, setDraft7Headers, setDraft8Headers, setRetryAfterHeader, omitUndefinedProperties, ValidationError, ChangeWarning, usedStores, singleCountKeys, validations, getValidations, isLegacyStore, promisifyStore, getOptionsFromConfig, parseOptions, handleAsyncErrors, rateLimit, rate_limit_default;
var init_dist = __esm({
  "../../node_modules/.pnpm/express-rate-limit@8.5.2_express@4.21.2/node_modules/express-rate-limit/dist/index.mjs"() {
    import_ip_address = __toESM(require_ip_address(), 1);
    MemoryStore = class {
      constructor(validations2) {
        this.validations = validations2;
        this.previous = /* @__PURE__ */ new Map();
        this.current = /* @__PURE__ */ new Map();
        this.localKeys = true;
      }
      /**
       * Method that initializes the store.
       *
       * @param options {Options} - The options used to setup the middleware.
       */
      init(options) {
        this.windowMs = options.windowMs;
        this.validations?.windowMs(this.windowMs);
        if (this.interval) clearInterval(this.interval);
        this.interval = setInterval(() => {
          this.clearExpired();
        }, this.windowMs);
        this.interval.unref?.();
      }
      /**
       * Method to fetch a client's hit count and reset time.
       *
       * @param key {string} - The identifier for a client.
       *
       * @returns {ClientRateLimitInfo | undefined} - The number of hits and reset time for that client.
       *
       * @public
       */
      async get(key) {
        return this.current.get(key) ?? this.previous.get(key);
      }
      /**
       * Method to increment a client's hit counter.
       *
       * @param key {string} - The identifier for a client.
       *
       * @returns {ClientRateLimitInfo} - The number of hits and reset time for that client.
       *
       * @public
       */
      async increment(key) {
        const client = this.getClient(key);
        const now = Date.now();
        if (client.resetTime.getTime() <= now) {
          this.resetClient(client, now);
        }
        client.totalHits++;
        return client;
      }
      /**
       * Method to decrement a client's hit counter.
       *
       * @param key {string} - The identifier for a client.
       *
       * @public
       */
      async decrement(key) {
        const client = this.getClient(key);
        if (client.totalHits > 0) client.totalHits--;
      }
      /**
       * Method to reset a client's hit counter.
       *
       * @param key {string} - The identifier for a client.
       *
       * @public
       */
      async resetKey(key) {
        this.current.delete(key);
        this.previous.delete(key);
      }
      /**
       * Method to reset everyone's hit counter.
       *
       * @public
       */
      async resetAll() {
        this.current.clear();
        this.previous.clear();
      }
      /**
       * Method to stop the timer (if currently running) and prevent any memory
       * leaks.
       *
       * @public
       */
      shutdown() {
        clearInterval(this.interval);
        void this.resetAll();
      }
      /**
       * Recycles a client by setting its hit count to zero, and reset time to
       * `windowMs` milliseconds from now.
       *
       * NOT to be confused with `#resetKey()`, which removes a client from both the
       * `current` and `previous` maps.
       *
       * @param client {Client} - The client to recycle.
       * @param now {number} - The current time, to which the `windowMs` is added to get the `resetTime` for the client.
       *
       * @return {Client} - The modified client that was passed in, to allow for chaining.
       */
      resetClient(client, now = Date.now()) {
        client.totalHits = 0;
        client.resetTime.setTime(now + this.windowMs);
        return client;
      }
      /**
       * Retrieves or creates a client, given a key. Also ensures that the client being
       * returned is in the `current` map.
       *
       * @param key {string} - The key under which the client is (or is to be) stored.
       *
       * @returns {Client} - The requested client.
       */
      getClient(key) {
        if (this.current.has(key)) return this.current.get(key);
        let client;
        if (this.previous.has(key)) {
          client = this.previous.get(key);
          this.previous.delete(key);
        } else {
          client = { totalHits: 0, resetTime: /* @__PURE__ */ new Date() };
          this.resetClient(client);
        }
        this.current.set(key, client);
        return client;
      }
      /**
       * Move current clients to previous, create a new map for current.
       *
       * This function is called every `windowMs`.
       */
      clearExpired() {
        this.previous = this.current;
        this.current = /* @__PURE__ */ new Map();
      }
    };
    ConsoleLogger = {
      warn(...args) {
        console.warn(...args.reverse());
      },
      error(...args) {
        console.error(...args.reverse());
      }
    };
    SUPPORTED_DRAFT_VERSIONS = [
      "draft-6",
      "draft-7",
      "draft-8"
    ];
    getResetSeconds = (windowMs, resetTime) => {
      let resetSeconds;
      if (resetTime) {
        const deltaSeconds = Math.ceil((resetTime.getTime() - Date.now()) / 1e3);
        resetSeconds = Math.max(0, deltaSeconds);
      } else {
        resetSeconds = Math.ceil(windowMs / 1e3);
      }
      return resetSeconds;
    };
    getPartitionKey = (key) => {
      const hash2 = createHash("sha256");
      hash2.update(key);
      const partitionKey = hash2.digest("hex").slice(0, 12);
      return Buffer2.from(partitionKey).toString("base64");
    };
    setLegacyHeaders = (response, info) => {
      if (response.headersSent) return;
      response.setHeader("X-RateLimit-Limit", info.limit.toString());
      response.setHeader("X-RateLimit-Remaining", info.remaining.toString());
      if (info.resetTime instanceof Date) {
        response.setHeader("Date", (/* @__PURE__ */ new Date()).toUTCString());
        response.setHeader(
          "X-RateLimit-Reset",
          Math.ceil(info.resetTime.getTime() / 1e3).toString()
        );
      }
    };
    setDraft6Headers = (response, info, windowMs) => {
      if (response.headersSent) return;
      const windowSeconds = Math.ceil(windowMs / 1e3);
      const resetSeconds = getResetSeconds(windowMs, info.resetTime);
      response.setHeader("RateLimit-Policy", `${info.limit};w=${windowSeconds}`);
      response.setHeader("RateLimit-Limit", info.limit.toString());
      response.setHeader("RateLimit-Remaining", info.remaining.toString());
      if (typeof resetSeconds === "number")
        response.setHeader("RateLimit-Reset", resetSeconds.toString());
    };
    setDraft7Headers = (response, info, windowMs) => {
      if (response.headersSent) return;
      const windowSeconds = Math.ceil(windowMs / 1e3);
      const resetSeconds = getResetSeconds(windowMs, info.resetTime);
      response.setHeader("RateLimit-Policy", `${info.limit};w=${windowSeconds}`);
      response.setHeader(
        "RateLimit",
        `limit=${info.limit}, remaining=${info.remaining}, reset=${resetSeconds}`
      );
    };
    setDraft8Headers = (response, info, windowMs, name, key) => {
      if (response.headersSent) return;
      const windowSeconds = Math.ceil(windowMs / 1e3);
      const resetSeconds = getResetSeconds(windowMs, info.resetTime);
      const partitionKey = getPartitionKey(key);
      const header = `r=${info.remaining}; t=${resetSeconds}`;
      const policy = `q=${info.limit}; w=${windowSeconds}; pk=:${partitionKey}:`;
      response.append("RateLimit", `"${name}"; ${header}`);
      response.append("RateLimit-Policy", `"${name}"; ${policy}`);
    };
    setRetryAfterHeader = (response, info, windowMs) => {
      if (response.headersSent) return;
      const resetSeconds = getResetSeconds(windowMs, info.resetTime);
      response.setHeader("Retry-After", resetSeconds.toString());
    };
    omitUndefinedProperties = (passedOptions) => {
      const omittedOptions = {};
      for (const k of Object.keys(passedOptions)) {
        const key = k;
        if (passedOptions[key] !== void 0) {
          omittedOptions[key] = passedOptions[key];
        }
      }
      return omittedOptions;
    };
    ValidationError = class extends Error {
      /**
       * The code must be a string, in snake case and all capital, that starts with
       * the substring `ERR_ERL_`.
       *
       * The message must be a string, starting with an uppercase character,
       * describing the issue in detail.
       */
      constructor(code, message) {
        const url2 = `https://express-rate-limit.github.io/${code}/`;
        super(`${message} See ${url2} for more information.`);
        this.name = this.constructor.name;
        this.code = code;
        this.help = url2;
      }
    };
    ChangeWarning = class extends ValidationError {
    };
    usedStores = /* @__PURE__ */ new Set();
    singleCountKeys = /* @__PURE__ */ new WeakMap();
    validations = {
      enabled: {
        default: true
      },
      // Should be EnabledValidations type, but that's a circular reference
      disable() {
        for (const k of Object.keys(this.enabled)) this.enabled[k] = false;
      },
      /**
       * Checks whether the IP address is valid, and that it does not have a port
       * number in it.
       *
       * See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_invalid_ip_address.
       *
       * @param ip {string | undefined} - The IP address provided by Express as request.ip.
       *
       * @returns {void}
       */
      ip(ip) {
        if (ip === void 0) {
          throw new ValidationError(
            "ERR_ERL_UNDEFINED_IP_ADDRESS",
            `An undefined 'request.ip' was detected. This might indicate a misconfiguration or the connection being destroyed prematurely.`
          );
        }
        if (!isIP(ip)) {
          throw new ValidationError(
            "ERR_ERL_INVALID_IP_ADDRESS",
            `An invalid 'request.ip' (${ip}) was detected. Consider passing a custom 'keyGenerator' function to the rate limiter.`
          );
        }
      },
      /**
       * Makes sure the trust proxy setting is not set to `true`.
       *
       * See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_permissive_trust_proxy.
       *
       * @param request {Request} - The Express request object.
       *
       * @returns {void}
       */
      trustProxy(request) {
        if (request.app.get("trust proxy") === true) {
          throw new ValidationError(
            "ERR_ERL_PERMISSIVE_TRUST_PROXY",
            `The Express 'trust proxy' setting is true, which allows anyone to trivially bypass IP-based rate limiting.`
          );
        }
      },
      /**
       * Makes sure the trust proxy setting is set in case the `X-Forwarded-For`
       * header is present.
       *
       * See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_unset_trust_proxy.
       *
       * @param request {Request} - The Express request object.
       *
       * @returns {void}
       */
      xForwardedForHeader(request) {
        if (request.headers["x-forwarded-for"] && request.app.get("trust proxy") === false) {
          throw new ValidationError(
            "ERR_ERL_UNEXPECTED_X_FORWARDED_FOR",
            `The 'X-Forwarded-For' header is set but the Express 'trust proxy' setting is false (default). This could indicate a misconfiguration which would prevent express-rate-limit from accurately identifying users.`
          );
        }
      },
      /**
       * Alert the user if the Forwarded header is set (standardized version of X-Forwarded-For - not supported by express as of version 5.1.0)
       *
       * @param request {Request} - The Express request object.
       *
       * @returns {void}
       */
      forwardedHeader(request) {
        if (request.headers.forwarded && request.ip === request.socket?.remoteAddress) {
          throw new ValidationError(
            "ERR_ERL_FORWARDED_HEADER",
            `The 'Forwarded' header (standardized X-Forwarded-For) is set but currently being ignored. Add a custom keyGenerator to use a value from this header.`
          );
        }
      },
      /**
       * Ensures totalHits value from store is a positive integer.
       *
       * @param hits {any} - The `totalHits` returned by the store.
       */
      positiveHits(hits) {
        if (typeof hits !== "number" || hits < 1 || hits !== Math.round(hits)) {
          throw new ValidationError(
            "ERR_ERL_INVALID_HITS",
            `The totalHits value returned from the store must be a positive integer, got ${hits}`
          );
        }
      },
      /**
       * Ensures a single store instance is not used with multiple express-rate-limit instances
       */
      unsharedStore(store) {
        if (usedStores.has(store)) {
          const maybeUniquePrefix = store?.localKeys ? "" : " (with a unique prefix)";
          throw new ValidationError(
            "ERR_ERL_STORE_REUSE",
            `A Store instance must not be shared across multiple rate limiters. Create a new instance of ${store.constructor.name}${maybeUniquePrefix} for each limiter instead.`
          );
        }
        usedStores.add(store);
      },
      /**
       * Ensures a given key is incremented only once per request.
       *
       * @param request {Request} - The Express request object.
       * @param store {Store} - The store class.
       * @param key {string} - The key used to store the client's hit count.
       *
       * @returns {void}
       */
      singleCount(request, store, key) {
        let storeKeys = singleCountKeys.get(request);
        if (!storeKeys) {
          storeKeys = /* @__PURE__ */ new Map();
          singleCountKeys.set(request, storeKeys);
        }
        const storeKey = store.localKeys ? store : store.constructor.name;
        let keys = storeKeys.get(storeKey);
        if (!keys) {
          keys = [];
          storeKeys.set(storeKey, keys);
        }
        const prefixedKey = `${store.prefix ?? ""}${key}`;
        if (keys.includes(prefixedKey)) {
          throw new ValidationError(
            "ERR_ERL_DOUBLE_COUNT",
            `The hit count for ${key} was incremented more than once for a single request.`
          );
        }
        keys.push(prefixedKey);
      },
      /**
       * Warns the user that the behaviour for `max: 0` / `limit: 0` is
       * changing in the next major release.
       *
       * @param limit {number} - The maximum number of hits per client.
       *
       * @returns {void}
       */
      limit(limit) {
        if (limit === 0) {
          throw new ChangeWarning(
            "WRN_ERL_MAX_ZERO",
            "Setting limit or max to 0 disables rate limiting in express-rate-limit v6 and older, but will cause all requests to be blocked in v7"
          );
        }
      },
      /**
       * Warns the user that the `draft_polli_ratelimit_headers` option is deprecated
       * and will be removed in the next major release.
       *
       * @param draft_polli_ratelimit_headers {any | undefined} - The now-deprecated setting that was used to enable standard headers.
       *
       * @returns {void}
       */
      draftPolliHeaders(draft_polli_ratelimit_headers) {
        if (draft_polli_ratelimit_headers) {
          throw new ChangeWarning(
            "WRN_ERL_DEPRECATED_DRAFT_POLLI_HEADERS",
            `The draft_polli_ratelimit_headers configuration option is deprecated and has been removed in express-rate-limit v7, please set standardHeaders: 'draft-6' instead.`
          );
        }
      },
      /**
       * Warns the user that the `onLimitReached` option is deprecated and
       * will be removed in the next major release.
       *
       * @param onLimitReached {any | undefined} - The maximum number of hits per client.
       *
       * @returns {void}
       */
      onLimitReached(onLimitReached) {
        if (onLimitReached) {
          throw new ChangeWarning(
            "WRN_ERL_DEPRECATED_ON_LIMIT_REACHED",
            "The onLimitReached configuration option is deprecated and has been removed in express-rate-limit v7."
          );
        }
      },
      /**
       * Warns the user when an invalid/unsupported version of the draft spec is passed.
       *
       * @param version {any | undefined} - The version passed by the user.
       *
       * @returns {void}
       */
      headersDraftVersion(version3) {
        if (typeof version3 !== "string" || // @ts-expect-error This is fine. If version is not in the array, it will just return false.
        !SUPPORTED_DRAFT_VERSIONS.includes(version3)) {
          const versionString = SUPPORTED_DRAFT_VERSIONS.join(", ");
          throw new ValidationError(
            "ERR_ERL_HEADERS_UNSUPPORTED_DRAFT_VERSION",
            `standardHeaders: only the following versions of the IETF draft specification are supported: ${versionString}.`
          );
        }
      },
      /**
       * Warns the user when the selected headers option requires a reset time but
       * the store does not provide one.
       *
       * @param resetTime {Date | undefined} - The timestamp when the client's hit count will be reset.
       *
       * @returns {void}
       */
      headersResetTime(resetTime) {
        if (!resetTime) {
          throw new ValidationError(
            "ERR_ERL_HEADERS_NO_RESET",
            `standardHeaders:  'draft-7' requires a 'resetTime', but the store did not provide one. The 'windowMs' value will be used instead, which may cause clients to wait longer than necessary.`
          );
        }
      },
      knownOptions(passedOptions) {
        if (!passedOptions) return;
        const optionsMap = {
          windowMs: true,
          limit: true,
          message: true,
          statusCode: true,
          legacyHeaders: true,
          standardHeaders: true,
          identifier: true,
          requestPropertyName: true,
          skipFailedRequests: true,
          skipSuccessfulRequests: true,
          keyGenerator: true,
          ipv6Subnet: true,
          handler: true,
          skip: true,
          requestWasSuccessful: true,
          store: true,
          validate: true,
          headers: true,
          max: true,
          passOnStoreError: true,
          logger: true
        };
        const validOptions = Object.keys(optionsMap).concat(
          "draft_polli_ratelimit_headers",
          // not a valid option anymore, but we have a more specific check for this one, so don't warn for it here
          // from express-slow-down - https://github.com/express-rate-limit/express-slow-down/blob/main/source/types.ts#L65
          "delayAfter",
          "delayMs",
          "maxDelayMs"
        );
        for (const key of Object.keys(passedOptions)) {
          if (!validOptions.includes(key)) {
            throw new ValidationError(
              "ERR_ERL_UNKNOWN_OPTION",
              `Unexpected configuration option: ${key}`
              // todo: suggest a valid option with a short levenstein distance?
            );
          }
        }
      },
      /**
       * Checks the options.validate setting to ensure that only recognized
       * validations are enabled or disabled.
       *
       * If any unrecognized values are found, an error is logged that
       * includes the list of supported validations.
       */
      validationsConfig() {
        const supportedValidations = Object.keys(this).filter(
          (k) => !["enabled", "disable"].includes(k)
        );
        supportedValidations.push("default");
        for (const key of Object.keys(this.enabled)) {
          if (!supportedValidations.includes(key)) {
            throw new ValidationError(
              "ERR_ERL_UNKNOWN_VALIDATION",
              `options.validate.${key} is not recognized. Supported validate options are: ${supportedValidations.join(
                ", "
              )}.`
            );
          }
        }
      },
      /**
       * Checks to see if the instance was created inside of a request handler,
       * which would prevent it from working correctly, with the default memory
       * store (or any other store with localKeys.)
       */
      creationStack(store) {
        const { stack } = new Error(
          "express-rate-limit validation check (set options.validate.creationStack=false to disable)"
        );
        if (stack?.includes("Layer.handle [as handle_request]") || // express v4
        stack?.includes("Layer.handleRequest")) {
          if (!store.localKeys) {
            throw new ValidationError(
              "ERR_ERL_CREATED_IN_REQUEST_HANDLER",
              "express-rate-limit instance should *usually* be created at app initialization, not when responding to a request."
            );
          }
          throw new ValidationError(
            "ERR_ERL_CREATED_IN_REQUEST_HANDLER",
            "express-rate-limit instance should be created at app initialization, not when responding to a request."
          );
        }
      },
      ipv6Subnet(ipv6Subnet) {
        if (ipv6Subnet === false) {
          return;
        }
        if (!Number.isInteger(ipv6Subnet) || ipv6Subnet < 32 || ipv6Subnet > 64) {
          throw new ValidationError(
            "ERR_ERL_IPV6_SUBNET",
            `Unexpected ipv6Subnet value: ${ipv6Subnet}. Expected an integer between 32 and 64 (usually 48-64).`
          );
        }
      },
      ipv6SubnetOrKeyGenerator(options) {
        if (options.ipv6Subnet !== void 0 && options.keyGenerator) {
          throw new ValidationError(
            "ERR_ERL_IPV6SUBNET_OR_KEYGENERATOR",
            `Incompatible options: the 'ipv6Subnet' option is ignored when a custom 'keyGenerator' function is also set.`
          );
        }
      },
      keyGeneratorIpFallback(keyGenerator) {
        if (!keyGenerator) {
          return;
        }
        const src = keyGenerator.toString();
        if ((src.includes("req.ip") || src.includes("request.ip")) && !src.includes("ipKeyGenerator")) {
          throw new ValidationError(
            "ERR_ERL_KEY_GEN_IPV6",
            "Custom keyGenerator appears to use request IP without calling the ipKeyGenerator helper function for IPv6 addresses. This could allow IPv6 users to bypass limits."
          );
        }
      },
      /**
       * Checks to see if the window duration is greater than 2^32 - 1. This is only
       * called by the default MemoryStore, since it uses Node's setInterval method.
       *
       * See https://nodejs.org/api/timers.html#setintervalcallback-delay-args.
       */
      windowMs(windowMs) {
        const SET_TIMEOUT_MAX = 2 ** 31 - 1;
        if (typeof windowMs !== "number" || Number.isNaN(windowMs) || windowMs < 1 || windowMs > SET_TIMEOUT_MAX) {
          throw new ValidationError(
            "ERR_ERL_WINDOW_MS",
            `Invalid windowMs value: ${windowMs}${typeof windowMs !== "number" ? ` (${typeof windowMs})` : ""}, must be a number between 1 and ${SET_TIMEOUT_MAX} when using the default MemoryStore`
          );
        }
      }
    };
    getValidations = (_enabled, logger2) => {
      validateLogger(logger2);
      let enabled2;
      if (typeof _enabled === "boolean") {
        enabled2 = {
          default: _enabled
        };
      } else {
        enabled2 = {
          default: true,
          ..._enabled
        };
      }
      const wrappedValidations = { enabled: enabled2 };
      for (const [name, validation] of Object.entries(validations)) {
        if (typeof validation === "function")
          wrappedValidations[name] = (...args) => {
            if (!(enabled2[name] ?? enabled2.default)) {
              return;
            }
            try {
              ;
              validation.apply(
                wrappedValidations,
                args
              );
            } catch (error40) {
              if (error40 instanceof ChangeWarning) logger2.warn(error40);
              else logger2.error(error40);
            }
          };
      }
      return wrappedValidations;
    };
    isLegacyStore = (store) => (
      // Check that `incr` exists but `increment` does not - store authors might want
      // to keep both around for backwards compatibility.
      typeof store.incr === "function" && typeof store.increment !== "function"
    );
    promisifyStore = (passedStore) => {
      if (!isLegacyStore(passedStore)) {
        return passedStore;
      }
      const legacyStore = passedStore;
      class PromisifiedStore {
        async increment(key) {
          return new Promise((resolve, reject) => {
            legacyStore.incr(
              key,
              (error40, totalHits, resetTime) => {
                if (error40) reject(error40);
                resolve({ totalHits, resetTime });
              }
            );
          });
        }
        async decrement(key) {
          return legacyStore.decrement(key);
        }
        async resetKey(key) {
          return legacyStore.resetKey(key);
        }
        /* istanbul ignore next */
        async resetAll() {
          if (typeof legacyStore.resetAll === "function")
            return legacyStore.resetAll();
        }
      }
      return new PromisifiedStore();
    };
    getOptionsFromConfig = (config2) => {
      const { validations: validations2, ...directlyPassableEntries } = config2;
      return {
        ...directlyPassableEntries,
        validate: validations2.enabled
      };
    };
    parseOptions = (passedOptions) => {
      const notUndefinedOptions = omitUndefinedProperties(passedOptions);
      const logger2 = passedOptions.logger ?? ConsoleLogger;
      const validations2 = getValidations(
        notUndefinedOptions?.validate ?? true,
        logger2
      );
      validations2.validationsConfig();
      validations2.knownOptions(passedOptions);
      validations2.draftPolliHeaders(
        // @ts-expect-error see the note above.
        notUndefinedOptions.draft_polli_ratelimit_headers
      );
      validations2.onLimitReached(notUndefinedOptions.onLimitReached);
      if (notUndefinedOptions.ipv6Subnet !== void 0 && typeof notUndefinedOptions.ipv6Subnet !== "function") {
        validations2.ipv6Subnet(notUndefinedOptions.ipv6Subnet);
      }
      validations2.keyGeneratorIpFallback(notUndefinedOptions.keyGenerator);
      validations2.ipv6SubnetOrKeyGenerator(notUndefinedOptions);
      let standardHeaders = notUndefinedOptions.standardHeaders ?? false;
      if (standardHeaders === true) standardHeaders = "draft-6";
      const config2 = {
        windowMs: 60 * 1e3,
        limit: passedOptions.max ?? 5,
        // `max` is deprecated, but support it anyways.
        message: "Too many requests, please try again later.",
        statusCode: 429,
        legacyHeaders: passedOptions.headers ?? true,
        identifier(request, _response) {
          let duration3 = "";
          const property = config2.requestPropertyName;
          const { limit } = request[property];
          const seconds = config2.windowMs / 1e3;
          const minutes = config2.windowMs / (1e3 * 60);
          const hours = config2.windowMs / (1e3 * 60 * 60);
          const days = config2.windowMs / (1e3 * 60 * 60 * 24);
          if (seconds < 60) duration3 = `${seconds}sec`;
          else if (minutes < 60) duration3 = `${minutes}min`;
          else if (hours < 24) duration3 = `${hours}hr${hours > 1 ? "s" : ""}`;
          else duration3 = `${days}day${days > 1 ? "s" : ""}`;
          return `${limit}-in-${duration3}`;
        },
        requestPropertyName: "rateLimit",
        skipFailedRequests: false,
        skipSuccessfulRequests: false,
        requestWasSuccessful: (_request, response) => response.statusCode < 400,
        skip: (_request, _response) => false,
        async keyGenerator(request, response) {
          validations2.ip(request.ip);
          validations2.trustProxy(request);
          validations2.xForwardedForHeader(request);
          validations2.forwardedHeader(request);
          const ip = request.ip;
          let subnet = 56;
          if (isIPv62(ip)) {
            subnet = typeof config2.ipv6Subnet === "function" ? await config2.ipv6Subnet(request, response) : config2.ipv6Subnet;
            if (typeof config2.ipv6Subnet === "function")
              validations2.ipv6Subnet(subnet);
          }
          return ipKeyGenerator(ip, subnet);
        },
        ipv6Subnet: 56,
        async handler(request, response, _next, _optionsUsed) {
          response.status(config2.statusCode);
          const message = typeof config2.message === "function" ? await config2.message(
            request,
            response
          ) : config2.message;
          if (!response.writableEnded) response.send(message);
        },
        passOnStoreError: false,
        // Allow the default options to be overridden by the passed options.
        ...notUndefinedOptions,
        // `standardHeaders` is resolved into a draft version above, use that.
        standardHeaders,
        // Note that this field is declared after the user's options are spread in,
        // so that this field doesn't get overridden with an un-promisified store!
        store: promisifyStore(
          notUndefinedOptions.store ?? new MemoryStore(validations2)
        ),
        // Print an error to the console if a few known misconfigurations are detected.
        validations: validations2,
        logger: logger2
      };
      if (typeof config2.store.increment !== "function" || typeof config2.store.decrement !== "function" || typeof config2.store.resetKey !== "function" || config2.store.resetAll !== void 0 && typeof config2.store.resetAll !== "function" || config2.store.init !== void 0 && typeof config2.store.init !== "function") {
        throw new TypeError(
          "An invalid store was passed. Please ensure that the store is a class that implements the `Store` interface."
        );
      }
      return config2;
    };
    handleAsyncErrors = (fn) => async (request, response, next) => {
      try {
        await Promise.resolve(fn(request, response, next)).catch(next);
      } catch (error40) {
        next(error40);
      }
    };
    rateLimit = (passedOptions) => {
      const config2 = parseOptions(passedOptions ?? {});
      const options = getOptionsFromConfig(config2);
      config2.validations.creationStack(config2.store);
      config2.validations.unsharedStore(config2.store);
      if (typeof config2.store.init === "function") {
        try {
          const storeInit = config2.store.init(options);
          if (storeInit instanceof Promise) {
            storeInit.catch(
              (error40) => config2.logger.error(
                error40,
                "express-rate-limit: async error during store initialization."
              )
            );
          }
        } catch (error40) {
          config2.logger.error(
            error40,
            "express-rate-limit: error during store initialization."
          );
        }
      }
      const middleware = handleAsyncErrors(
        async (request, response, next) => {
          const closePromise = config2.skipFailedRequests && new Promise((resolve) => response.once("close", resolve));
          const finishPromise = (config2.skipFailedRequests || config2.skipSuccessfulRequests) && new Promise((resolve) => response.once("finish", resolve));
          const errorPromise = config2.skipFailedRequests && new Promise((resolve) => response.once("error", resolve));
          const skip = await config2.skip(request, response);
          if (skip) {
            next();
            return;
          }
          const augmentedRequest = request;
          const key = await config2.keyGenerator(request, response);
          let totalHits = 0;
          let resetTime;
          try {
            const incrementResult = await config2.store.increment(key);
            totalHits = incrementResult.totalHits;
            resetTime = incrementResult.resetTime;
          } catch (error40) {
            if (config2.passOnStoreError) {
              config2.logger.error(
                error40,
                "express-rate-limit: error from store, allowing request without rate-limiting."
              );
              next();
              return;
            }
            throw error40;
          }
          config2.validations.positiveHits(totalHits);
          config2.validations.singleCount(request, config2.store, key);
          const retrieveLimit = typeof config2.limit === "function" ? config2.limit(request, response) : config2.limit;
          const limit = await retrieveLimit;
          config2.validations.limit(limit);
          const info = {
            limit,
            used: totalHits,
            remaining: Math.max(limit - totalHits, 0),
            resetTime,
            key
          };
          Object.defineProperty(info, "current", {
            configurable: false,
            enumerable: false,
            value: totalHits
          });
          augmentedRequest[config2.requestPropertyName] = info;
          if (config2.legacyHeaders && !response.headersSent) {
            setLegacyHeaders(response, info);
          }
          if (config2.standardHeaders && !response.headersSent) {
            switch (config2.standardHeaders) {
              case "draft-6": {
                setDraft6Headers(response, info, config2.windowMs);
                break;
              }
              case "draft-7": {
                config2.validations.headersResetTime(info.resetTime);
                setDraft7Headers(response, info, config2.windowMs);
                break;
              }
              case "draft-8": {
                const retrieveName = typeof config2.identifier === "function" ? config2.identifier(request, response) : config2.identifier;
                const name = await retrieveName;
                config2.validations.headersResetTime(info.resetTime);
                setDraft8Headers(response, info, config2.windowMs, name, key);
                break;
              }
              default: {
                config2.validations.headersDraftVersion(config2.standardHeaders);
                break;
              }
            }
          }
          if (config2.skipFailedRequests || config2.skipSuccessfulRequests) {
            let decremented = false;
            const decrementKey = async () => {
              if (!decremented) {
                await config2.store.decrement(key);
                decremented = true;
              }
            };
            if (config2.skipFailedRequests) {
              if (finishPromise) {
                void finishPromise.then(async () => {
                  if (!await config2.requestWasSuccessful(request, response))
                    await decrementKey();
                });
              }
              if (closePromise) {
                void closePromise.then(async () => {
                  if (!response.writableEnded) await decrementKey();
                });
              }
              if (errorPromise) {
                void errorPromise.then(async () => {
                  await decrementKey();
                });
              }
            }
            if (config2.skipSuccessfulRequests) {
              if (finishPromise) {
                void finishPromise.then(async () => {
                  if (await config2.requestWasSuccessful(request, response))
                    await decrementKey();
                });
              }
            }
          }
          config2.validations.disable();
          if (totalHits > limit) {
            if (config2.legacyHeaders || config2.standardHeaders) {
              setRetryAfterHeader(response, info, config2.windowMs);
            }
            config2.handler(request, response, next, options);
            return;
          }
          next();
        }
      );
      const getThrowFn = () => {
        throw new Error("The current store does not support the get/getKey method");
      };
      middleware.resetKey = config2.store.resetKey.bind(config2.store);
      middleware.getKey = typeof config2.store.get === "function" ? config2.store.get.bind(config2.store) : getThrowFn;
      return middleware;
    };
    rate_limit_default = rateLimit;
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js
var util, objectUtil, ZodParsedType, getParsedType;
var init_util = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js"() {
    (function(util2) {
      util2.assertEqual = (_) => {
      };
      function assertIs2(_arg) {
      }
      util2.assertIs = assertIs2;
      function assertNever2(_x) {
        throw new Error();
      }
      util2.assertNever = assertNever2;
      util2.arrayToEnum = (items) => {
        const obj = {};
        for (const item of items) {
          obj[item] = item;
        }
        return obj;
      };
      util2.getValidEnumValues = (obj) => {
        const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
        const filtered = {};
        for (const k of validKeys) {
          filtered[k] = obj[k];
        }
        return util2.objectValues(filtered);
      };
      util2.objectValues = (obj) => {
        return util2.objectKeys(obj).map(function(e) {
          return obj[e];
        });
      };
      util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object2) => {
        const keys = [];
        for (const key in object2) {
          if (Object.prototype.hasOwnProperty.call(object2, key)) {
            keys.push(key);
          }
        }
        return keys;
      };
      util2.find = (arr, checker) => {
        for (const item of arr) {
          if (checker(item))
            return item;
        }
        return void 0;
      };
      util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
      function joinValues2(array2, separator = " | ") {
        return array2.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
      }
      util2.joinValues = joinValues2;
      util2.jsonStringifyReplacer = (_, value) => {
        if (typeof value === "bigint") {
          return value.toString();
        }
        return value;
      };
    })(util || (util = {}));
    (function(objectUtil2) {
      objectUtil2.mergeShapes = (first, second) => {
        return {
          ...first,
          ...second
          // second overwrites first
        };
      };
    })(objectUtil || (objectUtil = {}));
    ZodParsedType = util.arrayToEnum([
      "string",
      "nan",
      "number",
      "integer",
      "float",
      "boolean",
      "date",
      "bigint",
      "symbol",
      "function",
      "undefined",
      "null",
      "array",
      "object",
      "unknown",
      "promise",
      "void",
      "never",
      "map",
      "set"
    ]);
    getParsedType = (data) => {
      const t = typeof data;
      switch (t) {
        case "undefined":
          return ZodParsedType.undefined;
        case "string":
          return ZodParsedType.string;
        case "number":
          return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
        case "boolean":
          return ZodParsedType.boolean;
        case "function":
          return ZodParsedType.function;
        case "bigint":
          return ZodParsedType.bigint;
        case "symbol":
          return ZodParsedType.symbol;
        case "object":
          if (Array.isArray(data)) {
            return ZodParsedType.array;
          }
          if (data === null) {
            return ZodParsedType.null;
          }
          if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
            return ZodParsedType.promise;
          }
          if (typeof Map !== "undefined" && data instanceof Map) {
            return ZodParsedType.map;
          }
          if (typeof Set !== "undefined" && data instanceof Set) {
            return ZodParsedType.set;
          }
          if (typeof Date !== "undefined" && data instanceof Date) {
            return ZodParsedType.date;
          }
          return ZodParsedType.object;
        default:
          return ZodParsedType.unknown;
      }
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js
var ZodIssueCode, quotelessJson, ZodError;
var init_ZodError = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js"() {
    init_util();
    ZodIssueCode = util.arrayToEnum([
      "invalid_type",
      "invalid_literal",
      "custom",
      "invalid_union",
      "invalid_union_discriminator",
      "invalid_enum_value",
      "unrecognized_keys",
      "invalid_arguments",
      "invalid_return_type",
      "invalid_date",
      "invalid_string",
      "too_small",
      "too_big",
      "invalid_intersection_types",
      "not_multiple_of",
      "not_finite"
    ]);
    quotelessJson = (obj) => {
      const json3 = JSON.stringify(obj, null, 2);
      return json3.replace(/"([^"]+)":/g, "$1:");
    };
    ZodError = class _ZodError extends Error {
      get errors() {
        return this.issues;
      }
      constructor(issues) {
        super();
        this.issues = [];
        this.addIssue = (sub) => {
          this.issues = [...this.issues, sub];
        };
        this.addIssues = (subs = []) => {
          this.issues = [...this.issues, ...subs];
        };
        const actualProto = new.target.prototype;
        if (Object.setPrototypeOf) {
          Object.setPrototypeOf(this, actualProto);
        } else {
          this.__proto__ = actualProto;
        }
        this.name = "ZodError";
        this.issues = issues;
      }
      format(_mapper) {
        const mapper = _mapper || function(issue2) {
          return issue2.message;
        };
        const fieldErrors = { _errors: [] };
        const processError = (error40) => {
          for (const issue2 of error40.issues) {
            if (issue2.code === "invalid_union") {
              issue2.unionErrors.map(processError);
            } else if (issue2.code === "invalid_return_type") {
              processError(issue2.returnTypeError);
            } else if (issue2.code === "invalid_arguments") {
              processError(issue2.argumentsError);
            } else if (issue2.path.length === 0) {
              fieldErrors._errors.push(mapper(issue2));
            } else {
              let curr = fieldErrors;
              let i = 0;
              while (i < issue2.path.length) {
                const el = issue2.path[i];
                const terminal = i === issue2.path.length - 1;
                if (!terminal) {
                  curr[el] = curr[el] || { _errors: [] };
                } else {
                  curr[el] = curr[el] || { _errors: [] };
                  curr[el]._errors.push(mapper(issue2));
                }
                curr = curr[el];
                i++;
              }
            }
          }
        };
        processError(this);
        return fieldErrors;
      }
      static assert(value) {
        if (!(value instanceof _ZodError)) {
          throw new Error(`Not a ZodError: ${value}`);
        }
      }
      toString() {
        return this.message;
      }
      get message() {
        return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
      }
      get isEmpty() {
        return this.issues.length === 0;
      }
      flatten(mapper = (issue2) => issue2.message) {
        const fieldErrors = {};
        const formErrors = [];
        for (const sub of this.issues) {
          if (sub.path.length > 0) {
            const firstEl = sub.path[0];
            fieldErrors[firstEl] = fieldErrors[firstEl] || [];
            fieldErrors[firstEl].push(mapper(sub));
          } else {
            formErrors.push(mapper(sub));
          }
        }
        return { formErrors, fieldErrors };
      }
      get formErrors() {
        return this.flatten();
      }
    };
    ZodError.create = (issues) => {
      const error40 = new ZodError(issues);
      return error40;
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js
var errorMap, en_default;
var init_en = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js"() {
    init_ZodError();
    init_util();
    errorMap = (issue2, _ctx) => {
      let message;
      switch (issue2.code) {
        case ZodIssueCode.invalid_type:
          if (issue2.received === ZodParsedType.undefined) {
            message = "Required";
          } else {
            message = `Expected ${issue2.expected}, received ${issue2.received}`;
          }
          break;
        case ZodIssueCode.invalid_literal:
          message = `Invalid literal value, expected ${JSON.stringify(issue2.expected, util.jsonStringifyReplacer)}`;
          break;
        case ZodIssueCode.unrecognized_keys:
          message = `Unrecognized key(s) in object: ${util.joinValues(issue2.keys, ", ")}`;
          break;
        case ZodIssueCode.invalid_union:
          message = `Invalid input`;
          break;
        case ZodIssueCode.invalid_union_discriminator:
          message = `Invalid discriminator value. Expected ${util.joinValues(issue2.options)}`;
          break;
        case ZodIssueCode.invalid_enum_value:
          message = `Invalid enum value. Expected ${util.joinValues(issue2.options)}, received '${issue2.received}'`;
          break;
        case ZodIssueCode.invalid_arguments:
          message = `Invalid function arguments`;
          break;
        case ZodIssueCode.invalid_return_type:
          message = `Invalid function return type`;
          break;
        case ZodIssueCode.invalid_date:
          message = `Invalid date`;
          break;
        case ZodIssueCode.invalid_string:
          if (typeof issue2.validation === "object") {
            if ("includes" in issue2.validation) {
              message = `Invalid input: must include "${issue2.validation.includes}"`;
              if (typeof issue2.validation.position === "number") {
                message = `${message} at one or more positions greater than or equal to ${issue2.validation.position}`;
              }
            } else if ("startsWith" in issue2.validation) {
              message = `Invalid input: must start with "${issue2.validation.startsWith}"`;
            } else if ("endsWith" in issue2.validation) {
              message = `Invalid input: must end with "${issue2.validation.endsWith}"`;
            } else {
              util.assertNever(issue2.validation);
            }
          } else if (issue2.validation !== "regex") {
            message = `Invalid ${issue2.validation}`;
          } else {
            message = "Invalid";
          }
          break;
        case ZodIssueCode.too_small:
          if (issue2.type === "array")
            message = `Array must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `more than`} ${issue2.minimum} element(s)`;
          else if (issue2.type === "string")
            message = `String must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `over`} ${issue2.minimum} character(s)`;
          else if (issue2.type === "number")
            message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`;
          else if (issue2.type === "bigint")
            message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`;
          else if (issue2.type === "date")
            message = `Date must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue2.minimum))}`;
          else
            message = "Invalid input";
          break;
        case ZodIssueCode.too_big:
          if (issue2.type === "array")
            message = `Array must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `less than`} ${issue2.maximum} element(s)`;
          else if (issue2.type === "string")
            message = `String must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `under`} ${issue2.maximum} character(s)`;
          else if (issue2.type === "number")
            message = `Number must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`;
          else if (issue2.type === "bigint")
            message = `BigInt must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`;
          else if (issue2.type === "date")
            message = `Date must be ${issue2.exact ? `exactly` : issue2.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue2.maximum))}`;
          else
            message = "Invalid input";
          break;
        case ZodIssueCode.custom:
          message = `Invalid input`;
          break;
        case ZodIssueCode.invalid_intersection_types:
          message = `Intersection results could not be merged`;
          break;
        case ZodIssueCode.not_multiple_of:
          message = `Number must be a multiple of ${issue2.multipleOf}`;
          break;
        case ZodIssueCode.not_finite:
          message = "Number must be finite";
          break;
        default:
          message = _ctx.defaultError;
          util.assertNever(issue2);
      }
      return { message };
    };
    en_default = errorMap;
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js
function setErrorMap(map2) {
  overrideErrorMap = map2;
}
function getErrorMap() {
  return overrideErrorMap;
}
var overrideErrorMap;
var init_errors = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js"() {
    init_en();
    overrideErrorMap = en_default;
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js
function addIssueToContext(ctx, issueData) {
  const overrideMap = getErrorMap();
  const issue2 = makeIssue({
    issueData,
    data: ctx.data,
    path: ctx.path,
    errorMaps: [
      ctx.common.contextualErrorMap,
      // contextual error map is first priority
      ctx.schemaErrorMap,
      // then schema-bound map if available
      overrideMap,
      // then global override map
      overrideMap === en_default ? void 0 : en_default
      // then global default map
    ].filter((x) => !!x)
  });
  ctx.common.issues.push(issue2);
}
var makeIssue, EMPTY_PATH, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync;
var init_parseUtil = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js"() {
    init_errors();
    init_en();
    makeIssue = (params) => {
      const { data, path: path4, errorMaps, issueData } = params;
      const fullPath = [...path4, ...issueData.path || []];
      const fullIssue = {
        ...issueData,
        path: fullPath
      };
      if (issueData.message !== void 0) {
        return {
          ...issueData,
          path: fullPath,
          message: issueData.message
        };
      }
      let errorMessage = "";
      const maps = errorMaps.filter((m) => !!m).slice().reverse();
      for (const map2 of maps) {
        errorMessage = map2(fullIssue, { data, defaultError: errorMessage }).message;
      }
      return {
        ...issueData,
        path: fullPath,
        message: errorMessage
      };
    };
    EMPTY_PATH = [];
    ParseStatus = class _ParseStatus {
      constructor() {
        this.value = "valid";
      }
      dirty() {
        if (this.value === "valid")
          this.value = "dirty";
      }
      abort() {
        if (this.value !== "aborted")
          this.value = "aborted";
      }
      static mergeArray(status, results) {
        const arrayValue = [];
        for (const s of results) {
          if (s.status === "aborted")
            return INVALID;
          if (s.status === "dirty")
            status.dirty();
          arrayValue.push(s.value);
        }
        return { status: status.value, value: arrayValue };
      }
      static async mergeObjectAsync(status, pairs) {
        const syncPairs = [];
        for (const pair of pairs) {
          const key = await pair.key;
          const value = await pair.value;
          syncPairs.push({
            key,
            value
          });
        }
        return _ParseStatus.mergeObjectSync(status, syncPairs);
      }
      static mergeObjectSync(status, pairs) {
        const finalObject = {};
        for (const pair of pairs) {
          const { key, value } = pair;
          if (key.status === "aborted")
            return INVALID;
          if (value.status === "aborted")
            return INVALID;
          if (key.status === "dirty")
            status.dirty();
          if (value.status === "dirty")
            status.dirty();
          if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
            finalObject[key.value] = value.value;
          }
        }
        return { status: status.value, value: finalObject };
      }
    };
    INVALID = Object.freeze({
      status: "aborted"
    });
    DIRTY = (value) => ({ status: "dirty", value });
    OK = (value) => ({ status: "valid", value });
    isAborted = (x) => x.status === "aborted";
    isDirty = (x) => x.status === "dirty";
    isValid = (x) => x.status === "valid";
    isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/typeAliases.js
var init_typeAliases = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/typeAliases.js"() {
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js
var errorUtil;
var init_errorUtil = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js"() {
    (function(errorUtil2) {
      errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
      errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
    })(errorUtil || (errorUtil = {}));
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js
function processCreateParams(params) {
  if (!params)
    return {};
  const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
  if (errorMap2 && (invalid_type_error || required_error)) {
    throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  }
  if (errorMap2)
    return { errorMap: errorMap2, description };
  const customMap = (iss, ctx) => {
    const { message } = params;
    if (iss.code === "invalid_enum_value") {
      return { message: message ?? ctx.defaultError };
    }
    if (typeof ctx.data === "undefined") {
      return { message: message ?? required_error ?? ctx.defaultError };
    }
    if (iss.code !== "invalid_type")
      return { message: ctx.defaultError };
    return { message: message ?? invalid_type_error ?? ctx.defaultError };
  };
  return { errorMap: customMap, description };
}
function timeRegexSource(args) {
  let secondsRegexSource = `[0-5]\\d`;
  if (args.precision) {
    secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
  } else if (args.precision == null) {
    secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
  }
  const secondsQuantifier = args.precision ? "+" : "?";
  return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
}
function timeRegex(args) {
  return new RegExp(`^${timeRegexSource(args)}$`);
}
function datetimeRegex(args) {
  let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
  const opts = [];
  opts.push(args.local ? `Z?` : `Z`);
  if (args.offset)
    opts.push(`([+-]\\d{2}:?\\d{2})`);
  regex = `${regex}(${opts.join("|")})`;
  return new RegExp(`^${regex}$`);
}
function isValidIP(ip, version3) {
  if ((version3 === "v4" || !version3) && ipv4Regex.test(ip)) {
    return true;
  }
  if ((version3 === "v6" || !version3) && ipv6Regex.test(ip)) {
    return true;
  }
  return false;
}
function isValidJWT(jwt3, alg) {
  if (!jwtRegex.test(jwt3))
    return false;
  try {
    const [header] = jwt3.split(".");
    if (!header)
      return false;
    const base643 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
    const decoded = JSON.parse(atob(base643));
    if (typeof decoded !== "object" || decoded === null)
      return false;
    if ("typ" in decoded && decoded?.typ !== "JWT")
      return false;
    if (!decoded.alg)
      return false;
    if (alg && decoded.alg !== alg)
      return false;
    return true;
  } catch {
    return false;
  }
}
function isValidCidr(ip, version3) {
  if ((version3 === "v4" || !version3) && ipv4CidrRegex.test(ip)) {
    return true;
  }
  if ((version3 === "v6" || !version3) && ipv6CidrRegex.test(ip)) {
    return true;
  }
  return false;
}
function floatSafeRemainder(val, step) {
  const valDecCount = (val.toString().split(".")[1] || "").length;
  const stepDecCount = (step.toString().split(".")[1] || "").length;
  const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
  const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
  return valInt % stepInt / 10 ** decCount;
}
function deepPartialify(schema) {
  if (schema instanceof ZodObject) {
    const newShape = {};
    for (const key in schema.shape) {
      const fieldSchema = schema.shape[key];
      newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
    }
    return new ZodObject({
      ...schema._def,
      shape: () => newShape
    });
  } else if (schema instanceof ZodArray) {
    return new ZodArray({
      ...schema._def,
      type: deepPartialify(schema.element)
    });
  } else if (schema instanceof ZodOptional) {
    return ZodOptional.create(deepPartialify(schema.unwrap()));
  } else if (schema instanceof ZodNullable) {
    return ZodNullable.create(deepPartialify(schema.unwrap()));
  } else if (schema instanceof ZodTuple) {
    return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
  } else {
    return schema;
  }
}
function mergeValues(a, b) {
  const aType = getParsedType(a);
  const bType = getParsedType(b);
  if (a === b) {
    return { valid: true, data: a };
  } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
    const bKeys = util.objectKeys(b);
    const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
    const newObj = { ...a, ...b };
    for (const key of sharedKeys) {
      const sharedValue = mergeValues(a[key], b[key]);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newObj[key] = sharedValue.data;
    }
    return { valid: true, data: newObj };
  } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
    if (a.length !== b.length) {
      return { valid: false };
    }
    const newArray = [];
    for (let index2 = 0; index2 < a.length; index2++) {
      const itemA = a[index2];
      const itemB = b[index2];
      const sharedValue = mergeValues(itemA, itemB);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newArray.push(sharedValue.data);
    }
    return { valid: true, data: newArray };
  } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
    return { valid: true, data: a };
  } else {
    return { valid: false };
  }
}
function createZodEnum(values, params) {
  return new ZodEnum({
    values,
    typeName: ZodFirstPartyTypeKind.ZodEnum,
    ...processCreateParams(params)
  });
}
function cleanParams(params, data) {
  const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
  const p2 = typeof p === "string" ? { message: p } : p;
  return p2;
}
function custom(check2, _params = {}, fatal) {
  if (check2)
    return ZodAny.create().superRefine((data, ctx) => {
      const r = check2(data);
      if (r instanceof Promise) {
        return r.then((r2) => {
          if (!r2) {
            const params = cleanParams(_params, data);
            const _fatal = params.fatal ?? fatal ?? true;
            ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
          }
        });
      }
      if (!r) {
        const params = cleanParams(_params, data);
        const _fatal = params.fatal ?? fatal ?? true;
        ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
      }
      return;
    });
  return ZodAny.create();
}
var ParseInputLazyPath, handleResult, ZodType, cuidRegex, cuid2Regex, ulidRegex, uuidRegex, nanoidRegex, jwtRegex, durationRegex, emailRegex, _emojiRegex, emojiRegex, ipv4Regex, ipv4CidrRegex, ipv6Regex, ipv6CidrRegex, base64Regex, base64urlRegex, dateRegexSource, dateRegex, ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodArray, ZodObject, ZodUnion, getDiscriminator, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodNativeEnum, ZodPromise, ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodCatch, ZodNaN, BRAND, ZodBranded, ZodPipeline, ZodReadonly, late, ZodFirstPartyTypeKind, instanceOfType, stringType, numberType, nanType, bigIntType, booleanType, dateType, symbolType, undefinedType, nullType, anyType, unknownType, neverType, voidType, arrayType, objectType, strictObjectType, unionType, discriminatedUnionType, intersectionType, tupleType, recordType, mapType, setType, functionType, lazyType, literalType, enumType, nativeEnumType, promiseType, effectsType, optionalType, nullableType, preprocessType, pipelineType, ostring, onumber, oboolean, coerce, NEVER;
var init_types = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js"() {
    init_ZodError();
    init_errors();
    init_errorUtil();
    init_parseUtil();
    init_util();
    ParseInputLazyPath = class {
      constructor(parent, value, path4, key) {
        this._cachedPath = [];
        this.parent = parent;
        this.data = value;
        this._path = path4;
        this._key = key;
      }
      get path() {
        if (!this._cachedPath.length) {
          if (Array.isArray(this._key)) {
            this._cachedPath.push(...this._path, ...this._key);
          } else {
            this._cachedPath.push(...this._path, this._key);
          }
        }
        return this._cachedPath;
      }
    };
    handleResult = (ctx, result) => {
      if (isValid(result)) {
        return { success: true, data: result.value };
      } else {
        if (!ctx.common.issues.length) {
          throw new Error("Validation failed but no issues detected.");
        }
        return {
          success: false,
          get error() {
            if (this._error)
              return this._error;
            const error40 = new ZodError(ctx.common.issues);
            this._error = error40;
            return this._error;
          }
        };
      }
    };
    ZodType = class {
      get description() {
        return this._def.description;
      }
      _getType(input) {
        return getParsedType(input.data);
      }
      _getOrReturnCtx(input, ctx) {
        return ctx || {
          common: input.parent.common,
          data: input.data,
          parsedType: getParsedType(input.data),
          schemaErrorMap: this._def.errorMap,
          path: input.path,
          parent: input.parent
        };
      }
      _processInputParams(input) {
        return {
          status: new ParseStatus(),
          ctx: {
            common: input.parent.common,
            data: input.data,
            parsedType: getParsedType(input.data),
            schemaErrorMap: this._def.errorMap,
            path: input.path,
            parent: input.parent
          }
        };
      }
      _parseSync(input) {
        const result = this._parse(input);
        if (isAsync(result)) {
          throw new Error("Synchronous parse encountered promise.");
        }
        return result;
      }
      _parseAsync(input) {
        const result = this._parse(input);
        return Promise.resolve(result);
      }
      parse(data, params) {
        const result = this.safeParse(data, params);
        if (result.success)
          return result.data;
        throw result.error;
      }
      safeParse(data, params) {
        const ctx = {
          common: {
            issues: [],
            async: params?.async ?? false,
            contextualErrorMap: params?.errorMap
          },
          path: params?.path || [],
          schemaErrorMap: this._def.errorMap,
          parent: null,
          data,
          parsedType: getParsedType(data)
        };
        const result = this._parseSync({ data, path: ctx.path, parent: ctx });
        return handleResult(ctx, result);
      }
      "~validate"(data) {
        const ctx = {
          common: {
            issues: [],
            async: !!this["~standard"].async
          },
          path: [],
          schemaErrorMap: this._def.errorMap,
          parent: null,
          data,
          parsedType: getParsedType(data)
        };
        if (!this["~standard"].async) {
          try {
            const result = this._parseSync({ data, path: [], parent: ctx });
            return isValid(result) ? {
              value: result.value
            } : {
              issues: ctx.common.issues
            };
          } catch (err) {
            if (err?.message?.toLowerCase()?.includes("encountered")) {
              this["~standard"].async = true;
            }
            ctx.common = {
              issues: [],
              async: true
            };
          }
        }
        return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
          value: result.value
        } : {
          issues: ctx.common.issues
        });
      }
      async parseAsync(data, params) {
        const result = await this.safeParseAsync(data, params);
        if (result.success)
          return result.data;
        throw result.error;
      }
      async safeParseAsync(data, params) {
        const ctx = {
          common: {
            issues: [],
            contextualErrorMap: params?.errorMap,
            async: true
          },
          path: params?.path || [],
          schemaErrorMap: this._def.errorMap,
          parent: null,
          data,
          parsedType: getParsedType(data)
        };
        const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
        const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
        return handleResult(ctx, result);
      }
      refine(check2, message) {
        const getIssueProperties = (val) => {
          if (typeof message === "string" || typeof message === "undefined") {
            return { message };
          } else if (typeof message === "function") {
            return message(val);
          } else {
            return message;
          }
        };
        return this._refinement((val, ctx) => {
          const result = check2(val);
          const setError = () => ctx.addIssue({
            code: ZodIssueCode.custom,
            ...getIssueProperties(val)
          });
          if (typeof Promise !== "undefined" && result instanceof Promise) {
            return result.then((data) => {
              if (!data) {
                setError();
                return false;
              } else {
                return true;
              }
            });
          }
          if (!result) {
            setError();
            return false;
          } else {
            return true;
          }
        });
      }
      refinement(check2, refinementData) {
        return this._refinement((val, ctx) => {
          if (!check2(val)) {
            ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
            return false;
          } else {
            return true;
          }
        });
      }
      _refinement(refinement) {
        return new ZodEffects({
          schema: this,
          typeName: ZodFirstPartyTypeKind.ZodEffects,
          effect: { type: "refinement", refinement }
        });
      }
      superRefine(refinement) {
        return this._refinement(refinement);
      }
      constructor(def) {
        this.spa = this.safeParseAsync;
        this._def = def;
        this.parse = this.parse.bind(this);
        this.safeParse = this.safeParse.bind(this);
        this.parseAsync = this.parseAsync.bind(this);
        this.safeParseAsync = this.safeParseAsync.bind(this);
        this.spa = this.spa.bind(this);
        this.refine = this.refine.bind(this);
        this.refinement = this.refinement.bind(this);
        this.superRefine = this.superRefine.bind(this);
        this.optional = this.optional.bind(this);
        this.nullable = this.nullable.bind(this);
        this.nullish = this.nullish.bind(this);
        this.array = this.array.bind(this);
        this.promise = this.promise.bind(this);
        this.or = this.or.bind(this);
        this.and = this.and.bind(this);
        this.transform = this.transform.bind(this);
        this.brand = this.brand.bind(this);
        this.default = this.default.bind(this);
        this.catch = this.catch.bind(this);
        this.describe = this.describe.bind(this);
        this.pipe = this.pipe.bind(this);
        this.readonly = this.readonly.bind(this);
        this.isNullable = this.isNullable.bind(this);
        this.isOptional = this.isOptional.bind(this);
        this["~standard"] = {
          version: 1,
          vendor: "zod",
          validate: (data) => this["~validate"](data)
        };
      }
      optional() {
        return ZodOptional.create(this, this._def);
      }
      nullable() {
        return ZodNullable.create(this, this._def);
      }
      nullish() {
        return this.nullable().optional();
      }
      array() {
        return ZodArray.create(this);
      }
      promise() {
        return ZodPromise.create(this, this._def);
      }
      or(option) {
        return ZodUnion.create([this, option], this._def);
      }
      and(incoming) {
        return ZodIntersection.create(this, incoming, this._def);
      }
      transform(transform2) {
        return new ZodEffects({
          ...processCreateParams(this._def),
          schema: this,
          typeName: ZodFirstPartyTypeKind.ZodEffects,
          effect: { type: "transform", transform: transform2 }
        });
      }
      default(def) {
        const defaultValueFunc = typeof def === "function" ? def : () => def;
        return new ZodDefault({
          ...processCreateParams(this._def),
          innerType: this,
          defaultValue: defaultValueFunc,
          typeName: ZodFirstPartyTypeKind.ZodDefault
        });
      }
      brand() {
        return new ZodBranded({
          typeName: ZodFirstPartyTypeKind.ZodBranded,
          type: this,
          ...processCreateParams(this._def)
        });
      }
      catch(def) {
        const catchValueFunc = typeof def === "function" ? def : () => def;
        return new ZodCatch({
          ...processCreateParams(this._def),
          innerType: this,
          catchValue: catchValueFunc,
          typeName: ZodFirstPartyTypeKind.ZodCatch
        });
      }
      describe(description) {
        const This = this.constructor;
        return new This({
          ...this._def,
          description
        });
      }
      pipe(target) {
        return ZodPipeline.create(this, target);
      }
      readonly() {
        return ZodReadonly.create(this);
      }
      isOptional() {
        return this.safeParse(void 0).success;
      }
      isNullable() {
        return this.safeParse(null).success;
      }
    };
    cuidRegex = /^c[^\s-]{8,}$/i;
    cuid2Regex = /^[0-9a-z]+$/;
    ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
    uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
    nanoidRegex = /^[a-z0-9_-]{21}$/i;
    jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
    durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
    emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
    _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
    ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
    ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
    ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
    ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
    base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
    base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
    dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
    dateRegex = new RegExp(`^${dateRegexSource}$`);
    ZodString = class _ZodString2 extends ZodType {
      _parse(input) {
        if (this._def.coerce) {
          input.data = String(input.data);
        }
        const parsedType4 = this._getType(input);
        if (parsedType4 !== ZodParsedType.string) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.string,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        const status = new ParseStatus();
        let ctx = void 0;
        for (const check2 of this._def.checks) {
          if (check2.kind === "min") {
            if (input.data.length < check2.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                minimum: check2.value,
                type: "string",
                inclusive: true,
                exact: false,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "max") {
            if (input.data.length > check2.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                maximum: check2.value,
                type: "string",
                inclusive: true,
                exact: false,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "length") {
            const tooBig = input.data.length > check2.value;
            const tooSmall = input.data.length < check2.value;
            if (tooBig || tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              if (tooBig) {
                addIssueToContext(ctx, {
                  code: ZodIssueCode.too_big,
                  maximum: check2.value,
                  type: "string",
                  inclusive: true,
                  exact: true,
                  message: check2.message
                });
              } else if (tooSmall) {
                addIssueToContext(ctx, {
                  code: ZodIssueCode.too_small,
                  minimum: check2.value,
                  type: "string",
                  inclusive: true,
                  exact: true,
                  message: check2.message
                });
              }
              status.dirty();
            }
          } else if (check2.kind === "email") {
            if (!emailRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "email",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "emoji") {
            if (!emojiRegex) {
              emojiRegex = new RegExp(_emojiRegex, "u");
            }
            if (!emojiRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "emoji",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "uuid") {
            if (!uuidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "uuid",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "nanoid") {
            if (!nanoidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "nanoid",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "cuid") {
            if (!cuidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cuid",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "cuid2") {
            if (!cuid2Regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cuid2",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "ulid") {
            if (!ulidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "ulid",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "url") {
            try {
              new URL(input.data);
            } catch {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "url",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "regex") {
            check2.regex.lastIndex = 0;
            const testResult = check2.regex.test(input.data);
            if (!testResult) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "regex",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "trim") {
            input.data = input.data.trim();
          } else if (check2.kind === "includes") {
            if (!input.data.includes(check2.value, check2.position)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { includes: check2.value, position: check2.position },
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "toLowerCase") {
            input.data = input.data.toLowerCase();
          } else if (check2.kind === "toUpperCase") {
            input.data = input.data.toUpperCase();
          } else if (check2.kind === "startsWith") {
            if (!input.data.startsWith(check2.value)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { startsWith: check2.value },
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "endsWith") {
            if (!input.data.endsWith(check2.value)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { endsWith: check2.value },
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "datetime") {
            const regex = datetimeRegex(check2);
            if (!regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "datetime",
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "date") {
            const regex = dateRegex;
            if (!regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "date",
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "time") {
            const regex = timeRegex(check2);
            if (!regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "time",
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "duration") {
            if (!durationRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "duration",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "ip") {
            if (!isValidIP(input.data, check2.version)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "ip",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "jwt") {
            if (!isValidJWT(input.data, check2.alg)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "jwt",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "cidr") {
            if (!isValidCidr(input.data, check2.version)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cidr",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "base64") {
            if (!base64Regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "base64",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "base64url") {
            if (!base64urlRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "base64url",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else {
            util.assertNever(check2);
          }
        }
        return { status: status.value, value: input.data };
      }
      _regex(regex, validation, message) {
        return this.refinement((data) => regex.test(data), {
          validation,
          code: ZodIssueCode.invalid_string,
          ...errorUtil.errToObj(message)
        });
      }
      _addCheck(check2) {
        return new _ZodString2({
          ...this._def,
          checks: [...this._def.checks, check2]
        });
      }
      email(message) {
        return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
      }
      url(message) {
        return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
      }
      emoji(message) {
        return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
      }
      uuid(message) {
        return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
      }
      nanoid(message) {
        return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
      }
      cuid(message) {
        return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
      }
      cuid2(message) {
        return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
      }
      ulid(message) {
        return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
      }
      base64(message) {
        return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
      }
      base64url(message) {
        return this._addCheck({
          kind: "base64url",
          ...errorUtil.errToObj(message)
        });
      }
      jwt(options) {
        return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
      }
      ip(options) {
        return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
      }
      cidr(options) {
        return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
      }
      datetime(options) {
        if (typeof options === "string") {
          return this._addCheck({
            kind: "datetime",
            precision: null,
            offset: false,
            local: false,
            message: options
          });
        }
        return this._addCheck({
          kind: "datetime",
          precision: typeof options?.precision === "undefined" ? null : options?.precision,
          offset: options?.offset ?? false,
          local: options?.local ?? false,
          ...errorUtil.errToObj(options?.message)
        });
      }
      date(message) {
        return this._addCheck({ kind: "date", message });
      }
      time(options) {
        if (typeof options === "string") {
          return this._addCheck({
            kind: "time",
            precision: null,
            message: options
          });
        }
        return this._addCheck({
          kind: "time",
          precision: typeof options?.precision === "undefined" ? null : options?.precision,
          ...errorUtil.errToObj(options?.message)
        });
      }
      duration(message) {
        return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
      }
      regex(regex, message) {
        return this._addCheck({
          kind: "regex",
          regex,
          ...errorUtil.errToObj(message)
        });
      }
      includes(value, options) {
        return this._addCheck({
          kind: "includes",
          value,
          position: options?.position,
          ...errorUtil.errToObj(options?.message)
        });
      }
      startsWith(value, message) {
        return this._addCheck({
          kind: "startsWith",
          value,
          ...errorUtil.errToObj(message)
        });
      }
      endsWith(value, message) {
        return this._addCheck({
          kind: "endsWith",
          value,
          ...errorUtil.errToObj(message)
        });
      }
      min(minLength, message) {
        return this._addCheck({
          kind: "min",
          value: minLength,
          ...errorUtil.errToObj(message)
        });
      }
      max(maxLength, message) {
        return this._addCheck({
          kind: "max",
          value: maxLength,
          ...errorUtil.errToObj(message)
        });
      }
      length(len, message) {
        return this._addCheck({
          kind: "length",
          value: len,
          ...errorUtil.errToObj(message)
        });
      }
      /**
       * Equivalent to `.min(1)`
       */
      nonempty(message) {
        return this.min(1, errorUtil.errToObj(message));
      }
      trim() {
        return new _ZodString2({
          ...this._def,
          checks: [...this._def.checks, { kind: "trim" }]
        });
      }
      toLowerCase() {
        return new _ZodString2({
          ...this._def,
          checks: [...this._def.checks, { kind: "toLowerCase" }]
        });
      }
      toUpperCase() {
        return new _ZodString2({
          ...this._def,
          checks: [...this._def.checks, { kind: "toUpperCase" }]
        });
      }
      get isDatetime() {
        return !!this._def.checks.find((ch) => ch.kind === "datetime");
      }
      get isDate() {
        return !!this._def.checks.find((ch) => ch.kind === "date");
      }
      get isTime() {
        return !!this._def.checks.find((ch) => ch.kind === "time");
      }
      get isDuration() {
        return !!this._def.checks.find((ch) => ch.kind === "duration");
      }
      get isEmail() {
        return !!this._def.checks.find((ch) => ch.kind === "email");
      }
      get isURL() {
        return !!this._def.checks.find((ch) => ch.kind === "url");
      }
      get isEmoji() {
        return !!this._def.checks.find((ch) => ch.kind === "emoji");
      }
      get isUUID() {
        return !!this._def.checks.find((ch) => ch.kind === "uuid");
      }
      get isNANOID() {
        return !!this._def.checks.find((ch) => ch.kind === "nanoid");
      }
      get isCUID() {
        return !!this._def.checks.find((ch) => ch.kind === "cuid");
      }
      get isCUID2() {
        return !!this._def.checks.find((ch) => ch.kind === "cuid2");
      }
      get isULID() {
        return !!this._def.checks.find((ch) => ch.kind === "ulid");
      }
      get isIP() {
        return !!this._def.checks.find((ch) => ch.kind === "ip");
      }
      get isCIDR() {
        return !!this._def.checks.find((ch) => ch.kind === "cidr");
      }
      get isBase64() {
        return !!this._def.checks.find((ch) => ch.kind === "base64");
      }
      get isBase64url() {
        return !!this._def.checks.find((ch) => ch.kind === "base64url");
      }
      get minLength() {
        let min = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min === null || ch.value > min)
              min = ch.value;
          }
        }
        return min;
      }
      get maxLength() {
        let max = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return max;
      }
    };
    ZodString.create = (params) => {
      return new ZodString({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodString,
        coerce: params?.coerce ?? false,
        ...processCreateParams(params)
      });
    };
    ZodNumber = class _ZodNumber extends ZodType {
      constructor() {
        super(...arguments);
        this.min = this.gte;
        this.max = this.lte;
        this.step = this.multipleOf;
      }
      _parse(input) {
        if (this._def.coerce) {
          input.data = Number(input.data);
        }
        const parsedType4 = this._getType(input);
        if (parsedType4 !== ZodParsedType.number) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.number,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        let ctx = void 0;
        const status = new ParseStatus();
        for (const check2 of this._def.checks) {
          if (check2.kind === "int") {
            if (!util.isInteger(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: "integer",
                received: "float",
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "min") {
            const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value;
            if (tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                minimum: check2.value,
                type: "number",
                inclusive: check2.inclusive,
                exact: false,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "max") {
            const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value;
            if (tooBig) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                maximum: check2.value,
                type: "number",
                inclusive: check2.inclusive,
                exact: false,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "multipleOf") {
            if (floatSafeRemainder(input.data, check2.value) !== 0) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_multiple_of,
                multipleOf: check2.value,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "finite") {
            if (!Number.isFinite(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_finite,
                message: check2.message
              });
              status.dirty();
            }
          } else {
            util.assertNever(check2);
          }
        }
        return { status: status.value, value: input.data };
      }
      gte(value, message) {
        return this.setLimit("min", value, true, errorUtil.toString(message));
      }
      gt(value, message) {
        return this.setLimit("min", value, false, errorUtil.toString(message));
      }
      lte(value, message) {
        return this.setLimit("max", value, true, errorUtil.toString(message));
      }
      lt(value, message) {
        return this.setLimit("max", value, false, errorUtil.toString(message));
      }
      setLimit(kind, value, inclusive, message) {
        return new _ZodNumber({
          ...this._def,
          checks: [
            ...this._def.checks,
            {
              kind,
              value,
              inclusive,
              message: errorUtil.toString(message)
            }
          ]
        });
      }
      _addCheck(check2) {
        return new _ZodNumber({
          ...this._def,
          checks: [...this._def.checks, check2]
        });
      }
      int(message) {
        return this._addCheck({
          kind: "int",
          message: errorUtil.toString(message)
        });
      }
      positive(message) {
        return this._addCheck({
          kind: "min",
          value: 0,
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      negative(message) {
        return this._addCheck({
          kind: "max",
          value: 0,
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      nonpositive(message) {
        return this._addCheck({
          kind: "max",
          value: 0,
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      nonnegative(message) {
        return this._addCheck({
          kind: "min",
          value: 0,
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      multipleOf(value, message) {
        return this._addCheck({
          kind: "multipleOf",
          value,
          message: errorUtil.toString(message)
        });
      }
      finite(message) {
        return this._addCheck({
          kind: "finite",
          message: errorUtil.toString(message)
        });
      }
      safe(message) {
        return this._addCheck({
          kind: "min",
          inclusive: true,
          value: Number.MIN_SAFE_INTEGER,
          message: errorUtil.toString(message)
        })._addCheck({
          kind: "max",
          inclusive: true,
          value: Number.MAX_SAFE_INTEGER,
          message: errorUtil.toString(message)
        });
      }
      get minValue() {
        let min = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min === null || ch.value > min)
              min = ch.value;
          }
        }
        return min;
      }
      get maxValue() {
        let max = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return max;
      }
      get isInt() {
        return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
      }
      get isFinite() {
        let max = null;
        let min = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
            return true;
          } else if (ch.kind === "min") {
            if (min === null || ch.value > min)
              min = ch.value;
          } else if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return Number.isFinite(min) && Number.isFinite(max);
      }
    };
    ZodNumber.create = (params) => {
      return new ZodNumber({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodNumber,
        coerce: params?.coerce || false,
        ...processCreateParams(params)
      });
    };
    ZodBigInt = class _ZodBigInt extends ZodType {
      constructor() {
        super(...arguments);
        this.min = this.gte;
        this.max = this.lte;
      }
      _parse(input) {
        if (this._def.coerce) {
          try {
            input.data = BigInt(input.data);
          } catch {
            return this._getInvalidInput(input);
          }
        }
        const parsedType4 = this._getType(input);
        if (parsedType4 !== ZodParsedType.bigint) {
          return this._getInvalidInput(input);
        }
        let ctx = void 0;
        const status = new ParseStatus();
        for (const check2 of this._def.checks) {
          if (check2.kind === "min") {
            const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value;
            if (tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                type: "bigint",
                minimum: check2.value,
                inclusive: check2.inclusive,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "max") {
            const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value;
            if (tooBig) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                type: "bigint",
                maximum: check2.value,
                inclusive: check2.inclusive,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "multipleOf") {
            if (input.data % check2.value !== BigInt(0)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_multiple_of,
                multipleOf: check2.value,
                message: check2.message
              });
              status.dirty();
            }
          } else {
            util.assertNever(check2);
          }
        }
        return { status: status.value, value: input.data };
      }
      _getInvalidInput(input) {
        const ctx = this._getOrReturnCtx(input);
        addIssueToContext(ctx, {
          code: ZodIssueCode.invalid_type,
          expected: ZodParsedType.bigint,
          received: ctx.parsedType
        });
        return INVALID;
      }
      gte(value, message) {
        return this.setLimit("min", value, true, errorUtil.toString(message));
      }
      gt(value, message) {
        return this.setLimit("min", value, false, errorUtil.toString(message));
      }
      lte(value, message) {
        return this.setLimit("max", value, true, errorUtil.toString(message));
      }
      lt(value, message) {
        return this.setLimit("max", value, false, errorUtil.toString(message));
      }
      setLimit(kind, value, inclusive, message) {
        return new _ZodBigInt({
          ...this._def,
          checks: [
            ...this._def.checks,
            {
              kind,
              value,
              inclusive,
              message: errorUtil.toString(message)
            }
          ]
        });
      }
      _addCheck(check2) {
        return new _ZodBigInt({
          ...this._def,
          checks: [...this._def.checks, check2]
        });
      }
      positive(message) {
        return this._addCheck({
          kind: "min",
          value: BigInt(0),
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      negative(message) {
        return this._addCheck({
          kind: "max",
          value: BigInt(0),
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      nonpositive(message) {
        return this._addCheck({
          kind: "max",
          value: BigInt(0),
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      nonnegative(message) {
        return this._addCheck({
          kind: "min",
          value: BigInt(0),
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      multipleOf(value, message) {
        return this._addCheck({
          kind: "multipleOf",
          value,
          message: errorUtil.toString(message)
        });
      }
      get minValue() {
        let min = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min === null || ch.value > min)
              min = ch.value;
          }
        }
        return min;
      }
      get maxValue() {
        let max = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return max;
      }
    };
    ZodBigInt.create = (params) => {
      return new ZodBigInt({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodBigInt,
        coerce: params?.coerce ?? false,
        ...processCreateParams(params)
      });
    };
    ZodBoolean = class extends ZodType {
      _parse(input) {
        if (this._def.coerce) {
          input.data = Boolean(input.data);
        }
        const parsedType4 = this._getType(input);
        if (parsedType4 !== ZodParsedType.boolean) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.boolean,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodBoolean.create = (params) => {
      return new ZodBoolean({
        typeName: ZodFirstPartyTypeKind.ZodBoolean,
        coerce: params?.coerce || false,
        ...processCreateParams(params)
      });
    };
    ZodDate = class _ZodDate extends ZodType {
      _parse(input) {
        if (this._def.coerce) {
          input.data = new Date(input.data);
        }
        const parsedType4 = this._getType(input);
        if (parsedType4 !== ZodParsedType.date) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.date,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        if (Number.isNaN(input.data.getTime())) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_date
          });
          return INVALID;
        }
        const status = new ParseStatus();
        let ctx = void 0;
        for (const check2 of this._def.checks) {
          if (check2.kind === "min") {
            if (input.data.getTime() < check2.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                message: check2.message,
                inclusive: true,
                exact: false,
                minimum: check2.value,
                type: "date"
              });
              status.dirty();
            }
          } else if (check2.kind === "max") {
            if (input.data.getTime() > check2.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                message: check2.message,
                inclusive: true,
                exact: false,
                maximum: check2.value,
                type: "date"
              });
              status.dirty();
            }
          } else {
            util.assertNever(check2);
          }
        }
        return {
          status: status.value,
          value: new Date(input.data.getTime())
        };
      }
      _addCheck(check2) {
        return new _ZodDate({
          ...this._def,
          checks: [...this._def.checks, check2]
        });
      }
      min(minDate, message) {
        return this._addCheck({
          kind: "min",
          value: minDate.getTime(),
          message: errorUtil.toString(message)
        });
      }
      max(maxDate, message) {
        return this._addCheck({
          kind: "max",
          value: maxDate.getTime(),
          message: errorUtil.toString(message)
        });
      }
      get minDate() {
        let min = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min === null || ch.value > min)
              min = ch.value;
          }
        }
        return min != null ? new Date(min) : null;
      }
      get maxDate() {
        let max = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return max != null ? new Date(max) : null;
      }
    };
    ZodDate.create = (params) => {
      return new ZodDate({
        checks: [],
        coerce: params?.coerce || false,
        typeName: ZodFirstPartyTypeKind.ZodDate,
        ...processCreateParams(params)
      });
    };
    ZodSymbol = class extends ZodType {
      _parse(input) {
        const parsedType4 = this._getType(input);
        if (parsedType4 !== ZodParsedType.symbol) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.symbol,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodSymbol.create = (params) => {
      return new ZodSymbol({
        typeName: ZodFirstPartyTypeKind.ZodSymbol,
        ...processCreateParams(params)
      });
    };
    ZodUndefined = class extends ZodType {
      _parse(input) {
        const parsedType4 = this._getType(input);
        if (parsedType4 !== ZodParsedType.undefined) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.undefined,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodUndefined.create = (params) => {
      return new ZodUndefined({
        typeName: ZodFirstPartyTypeKind.ZodUndefined,
        ...processCreateParams(params)
      });
    };
    ZodNull = class extends ZodType {
      _parse(input) {
        const parsedType4 = this._getType(input);
        if (parsedType4 !== ZodParsedType.null) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.null,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodNull.create = (params) => {
      return new ZodNull({
        typeName: ZodFirstPartyTypeKind.ZodNull,
        ...processCreateParams(params)
      });
    };
    ZodAny = class extends ZodType {
      constructor() {
        super(...arguments);
        this._any = true;
      }
      _parse(input) {
        return OK(input.data);
      }
    };
    ZodAny.create = (params) => {
      return new ZodAny({
        typeName: ZodFirstPartyTypeKind.ZodAny,
        ...processCreateParams(params)
      });
    };
    ZodUnknown = class extends ZodType {
      constructor() {
        super(...arguments);
        this._unknown = true;
      }
      _parse(input) {
        return OK(input.data);
      }
    };
    ZodUnknown.create = (params) => {
      return new ZodUnknown({
        typeName: ZodFirstPartyTypeKind.ZodUnknown,
        ...processCreateParams(params)
      });
    };
    ZodNever = class extends ZodType {
      _parse(input) {
        const ctx = this._getOrReturnCtx(input);
        addIssueToContext(ctx, {
          code: ZodIssueCode.invalid_type,
          expected: ZodParsedType.never,
          received: ctx.parsedType
        });
        return INVALID;
      }
    };
    ZodNever.create = (params) => {
      return new ZodNever({
        typeName: ZodFirstPartyTypeKind.ZodNever,
        ...processCreateParams(params)
      });
    };
    ZodVoid = class extends ZodType {
      _parse(input) {
        const parsedType4 = this._getType(input);
        if (parsedType4 !== ZodParsedType.undefined) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.void,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodVoid.create = (params) => {
      return new ZodVoid({
        typeName: ZodFirstPartyTypeKind.ZodVoid,
        ...processCreateParams(params)
      });
    };
    ZodArray = class _ZodArray extends ZodType {
      _parse(input) {
        const { ctx, status } = this._processInputParams(input);
        const def = this._def;
        if (ctx.parsedType !== ZodParsedType.array) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.array,
            received: ctx.parsedType
          });
          return INVALID;
        }
        if (def.exactLength !== null) {
          const tooBig = ctx.data.length > def.exactLength.value;
          const tooSmall = ctx.data.length < def.exactLength.value;
          if (tooBig || tooSmall) {
            addIssueToContext(ctx, {
              code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
              minimum: tooSmall ? def.exactLength.value : void 0,
              maximum: tooBig ? def.exactLength.value : void 0,
              type: "array",
              inclusive: true,
              exact: true,
              message: def.exactLength.message
            });
            status.dirty();
          }
        }
        if (def.minLength !== null) {
          if (ctx.data.length < def.minLength.value) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_small,
              minimum: def.minLength.value,
              type: "array",
              inclusive: true,
              exact: false,
              message: def.minLength.message
            });
            status.dirty();
          }
        }
        if (def.maxLength !== null) {
          if (ctx.data.length > def.maxLength.value) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_big,
              maximum: def.maxLength.value,
              type: "array",
              inclusive: true,
              exact: false,
              message: def.maxLength.message
            });
            status.dirty();
          }
        }
        if (ctx.common.async) {
          return Promise.all([...ctx.data].map((item, i) => {
            return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
          })).then((result2) => {
            return ParseStatus.mergeArray(status, result2);
          });
        }
        const result = [...ctx.data].map((item, i) => {
          return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
        });
        return ParseStatus.mergeArray(status, result);
      }
      get element() {
        return this._def.type;
      }
      min(minLength, message) {
        return new _ZodArray({
          ...this._def,
          minLength: { value: minLength, message: errorUtil.toString(message) }
        });
      }
      max(maxLength, message) {
        return new _ZodArray({
          ...this._def,
          maxLength: { value: maxLength, message: errorUtil.toString(message) }
        });
      }
      length(len, message) {
        return new _ZodArray({
          ...this._def,
          exactLength: { value: len, message: errorUtil.toString(message) }
        });
      }
      nonempty(message) {
        return this.min(1, message);
      }
    };
    ZodArray.create = (schema, params) => {
      return new ZodArray({
        type: schema,
        minLength: null,
        maxLength: null,
        exactLength: null,
        typeName: ZodFirstPartyTypeKind.ZodArray,
        ...processCreateParams(params)
      });
    };
    ZodObject = class _ZodObject extends ZodType {
      constructor() {
        super(...arguments);
        this._cached = null;
        this.nonstrict = this.passthrough;
        this.augment = this.extend;
      }
      _getCached() {
        if (this._cached !== null)
          return this._cached;
        const shape = this._def.shape();
        const keys = util.objectKeys(shape);
        this._cached = { shape, keys };
        return this._cached;
      }
      _parse(input) {
        const parsedType4 = this._getType(input);
        if (parsedType4 !== ZodParsedType.object) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.object,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        const { status, ctx } = this._processInputParams(input);
        const { shape, keys: shapeKeys } = this._getCached();
        const extraKeys = [];
        if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
          for (const key in ctx.data) {
            if (!shapeKeys.includes(key)) {
              extraKeys.push(key);
            }
          }
        }
        const pairs = [];
        for (const key of shapeKeys) {
          const keyValidator = shape[key];
          const value = ctx.data[key];
          pairs.push({
            key: { status: "valid", value: key },
            value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
            alwaysSet: key in ctx.data
          });
        }
        if (this._def.catchall instanceof ZodNever) {
          const unknownKeys = this._def.unknownKeys;
          if (unknownKeys === "passthrough") {
            for (const key of extraKeys) {
              pairs.push({
                key: { status: "valid", value: key },
                value: { status: "valid", value: ctx.data[key] }
              });
            }
          } else if (unknownKeys === "strict") {
            if (extraKeys.length > 0) {
              addIssueToContext(ctx, {
                code: ZodIssueCode.unrecognized_keys,
                keys: extraKeys
              });
              status.dirty();
            }
          } else if (unknownKeys === "strip") {
          } else {
            throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
          }
        } else {
          const catchall = this._def.catchall;
          for (const key of extraKeys) {
            const value = ctx.data[key];
            pairs.push({
              key: { status: "valid", value: key },
              value: catchall._parse(
                new ParseInputLazyPath(ctx, value, ctx.path, key)
                //, ctx.child(key), value, getParsedType(value)
              ),
              alwaysSet: key in ctx.data
            });
          }
        }
        if (ctx.common.async) {
          return Promise.resolve().then(async () => {
            const syncPairs = [];
            for (const pair of pairs) {
              const key = await pair.key;
              const value = await pair.value;
              syncPairs.push({
                key,
                value,
                alwaysSet: pair.alwaysSet
              });
            }
            return syncPairs;
          }).then((syncPairs) => {
            return ParseStatus.mergeObjectSync(status, syncPairs);
          });
        } else {
          return ParseStatus.mergeObjectSync(status, pairs);
        }
      }
      get shape() {
        return this._def.shape();
      }
      strict(message) {
        errorUtil.errToObj;
        return new _ZodObject({
          ...this._def,
          unknownKeys: "strict",
          ...message !== void 0 ? {
            errorMap: (issue2, ctx) => {
              const defaultError = this._def.errorMap?.(issue2, ctx).message ?? ctx.defaultError;
              if (issue2.code === "unrecognized_keys")
                return {
                  message: errorUtil.errToObj(message).message ?? defaultError
                };
              return {
                message: defaultError
              };
            }
          } : {}
        });
      }
      strip() {
        return new _ZodObject({
          ...this._def,
          unknownKeys: "strip"
        });
      }
      passthrough() {
        return new _ZodObject({
          ...this._def,
          unknownKeys: "passthrough"
        });
      }
      // const AugmentFactory =
      //   <Def extends ZodObjectDef>(def: Def) =>
      //   <Augmentation extends ZodRawShape>(
      //     augmentation: Augmentation
      //   ): ZodObject<
      //     extendShape<ReturnType<Def["shape"]>, Augmentation>,
      //     Def["unknownKeys"],
      //     Def["catchall"]
      //   > => {
      //     return new ZodObject({
      //       ...def,
      //       shape: () => ({
      //         ...def.shape(),
      //         ...augmentation,
      //       }),
      //     }) as any;
      //   };
      extend(augmentation) {
        return new _ZodObject({
          ...this._def,
          shape: () => ({
            ...this._def.shape(),
            ...augmentation
          })
        });
      }
      /**
       * Prior to zod@1.0.12 there was a bug in the
       * inferred type of merged objects. Please
       * upgrade if you are experiencing issues.
       */
      merge(merging) {
        const merged = new _ZodObject({
          unknownKeys: merging._def.unknownKeys,
          catchall: merging._def.catchall,
          shape: () => ({
            ...this._def.shape(),
            ...merging._def.shape()
          }),
          typeName: ZodFirstPartyTypeKind.ZodObject
        });
        return merged;
      }
      // merge<
      //   Incoming extends AnyZodObject,
      //   Augmentation extends Incoming["shape"],
      //   NewOutput extends {
      //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
      //       ? Augmentation[k]["_output"]
      //       : k extends keyof Output
      //       ? Output[k]
      //       : never;
      //   },
      //   NewInput extends {
      //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
      //       ? Augmentation[k]["_input"]
      //       : k extends keyof Input
      //       ? Input[k]
      //       : never;
      //   }
      // >(
      //   merging: Incoming
      // ): ZodObject<
      //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
      //   Incoming["_def"]["unknownKeys"],
      //   Incoming["_def"]["catchall"],
      //   NewOutput,
      //   NewInput
      // > {
      //   const merged: any = new ZodObject({
      //     unknownKeys: merging._def.unknownKeys,
      //     catchall: merging._def.catchall,
      //     shape: () =>
      //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
      //     typeName: ZodFirstPartyTypeKind.ZodObject,
      //   }) as any;
      //   return merged;
      // }
      setKey(key, schema) {
        return this.augment({ [key]: schema });
      }
      // merge<Incoming extends AnyZodObject>(
      //   merging: Incoming
      // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
      // ZodObject<
      //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
      //   Incoming["_def"]["unknownKeys"],
      //   Incoming["_def"]["catchall"]
      // > {
      //   // const mergedShape = objectUtil.mergeShapes(
      //   //   this._def.shape(),
      //   //   merging._def.shape()
      //   // );
      //   const merged: any = new ZodObject({
      //     unknownKeys: merging._def.unknownKeys,
      //     catchall: merging._def.catchall,
      //     shape: () =>
      //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
      //     typeName: ZodFirstPartyTypeKind.ZodObject,
      //   }) as any;
      //   return merged;
      // }
      catchall(index2) {
        return new _ZodObject({
          ...this._def,
          catchall: index2
        });
      }
      pick(mask) {
        const shape = {};
        for (const key of util.objectKeys(mask)) {
          if (mask[key] && this.shape[key]) {
            shape[key] = this.shape[key];
          }
        }
        return new _ZodObject({
          ...this._def,
          shape: () => shape
        });
      }
      omit(mask) {
        const shape = {};
        for (const key of util.objectKeys(this.shape)) {
          if (!mask[key]) {
            shape[key] = this.shape[key];
          }
        }
        return new _ZodObject({
          ...this._def,
          shape: () => shape
        });
      }
      /**
       * @deprecated
       */
      deepPartial() {
        return deepPartialify(this);
      }
      partial(mask) {
        const newShape = {};
        for (const key of util.objectKeys(this.shape)) {
          const fieldSchema = this.shape[key];
          if (mask && !mask[key]) {
            newShape[key] = fieldSchema;
          } else {
            newShape[key] = fieldSchema.optional();
          }
        }
        return new _ZodObject({
          ...this._def,
          shape: () => newShape
        });
      }
      required(mask) {
        const newShape = {};
        for (const key of util.objectKeys(this.shape)) {
          if (mask && !mask[key]) {
            newShape[key] = this.shape[key];
          } else {
            const fieldSchema = this.shape[key];
            let newField = fieldSchema;
            while (newField instanceof ZodOptional) {
              newField = newField._def.innerType;
            }
            newShape[key] = newField;
          }
        }
        return new _ZodObject({
          ...this._def,
          shape: () => newShape
        });
      }
      keyof() {
        return createZodEnum(util.objectKeys(this.shape));
      }
    };
    ZodObject.create = (shape, params) => {
      return new ZodObject({
        shape: () => shape,
        unknownKeys: "strip",
        catchall: ZodNever.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params)
      });
    };
    ZodObject.strictCreate = (shape, params) => {
      return new ZodObject({
        shape: () => shape,
        unknownKeys: "strict",
        catchall: ZodNever.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params)
      });
    };
    ZodObject.lazycreate = (shape, params) => {
      return new ZodObject({
        shape,
        unknownKeys: "strip",
        catchall: ZodNever.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params)
      });
    };
    ZodUnion = class extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const options = this._def.options;
        function handleResults(results) {
          for (const result of results) {
            if (result.result.status === "valid") {
              return result.result;
            }
          }
          for (const result of results) {
            if (result.result.status === "dirty") {
              ctx.common.issues.push(...result.ctx.common.issues);
              return result.result;
            }
          }
          const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_union,
            unionErrors
          });
          return INVALID;
        }
        if (ctx.common.async) {
          return Promise.all(options.map(async (option) => {
            const childCtx = {
              ...ctx,
              common: {
                ...ctx.common,
                issues: []
              },
              parent: null
            };
            return {
              result: await option._parseAsync({
                data: ctx.data,
                path: ctx.path,
                parent: childCtx
              }),
              ctx: childCtx
            };
          })).then(handleResults);
        } else {
          let dirty = void 0;
          const issues = [];
          for (const option of options) {
            const childCtx = {
              ...ctx,
              common: {
                ...ctx.common,
                issues: []
              },
              parent: null
            };
            const result = option._parseSync({
              data: ctx.data,
              path: ctx.path,
              parent: childCtx
            });
            if (result.status === "valid") {
              return result;
            } else if (result.status === "dirty" && !dirty) {
              dirty = { result, ctx: childCtx };
            }
            if (childCtx.common.issues.length) {
              issues.push(childCtx.common.issues);
            }
          }
          if (dirty) {
            ctx.common.issues.push(...dirty.ctx.common.issues);
            return dirty.result;
          }
          const unionErrors = issues.map((issues2) => new ZodError(issues2));
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_union,
            unionErrors
          });
          return INVALID;
        }
      }
      get options() {
        return this._def.options;
      }
    };
    ZodUnion.create = (types3, params) => {
      return new ZodUnion({
        options: types3,
        typeName: ZodFirstPartyTypeKind.ZodUnion,
        ...processCreateParams(params)
      });
    };
    getDiscriminator = (type) => {
      if (type instanceof ZodLazy) {
        return getDiscriminator(type.schema);
      } else if (type instanceof ZodEffects) {
        return getDiscriminator(type.innerType());
      } else if (type instanceof ZodLiteral) {
        return [type.value];
      } else if (type instanceof ZodEnum) {
        return type.options;
      } else if (type instanceof ZodNativeEnum) {
        return util.objectValues(type.enum);
      } else if (type instanceof ZodDefault) {
        return getDiscriminator(type._def.innerType);
      } else if (type instanceof ZodUndefined) {
        return [void 0];
      } else if (type instanceof ZodNull) {
        return [null];
      } else if (type instanceof ZodOptional) {
        return [void 0, ...getDiscriminator(type.unwrap())];
      } else if (type instanceof ZodNullable) {
        return [null, ...getDiscriminator(type.unwrap())];
      } else if (type instanceof ZodBranded) {
        return getDiscriminator(type.unwrap());
      } else if (type instanceof ZodReadonly) {
        return getDiscriminator(type.unwrap());
      } else if (type instanceof ZodCatch) {
        return getDiscriminator(type._def.innerType);
      } else {
        return [];
      }
    };
    ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.object) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.object,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const discriminator = this.discriminator;
        const discriminatorValue = ctx.data[discriminator];
        const option = this.optionsMap.get(discriminatorValue);
        if (!option) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_union_discriminator,
            options: Array.from(this.optionsMap.keys()),
            path: [discriminator]
          });
          return INVALID;
        }
        if (ctx.common.async) {
          return option._parseAsync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          });
        } else {
          return option._parseSync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          });
        }
      }
      get discriminator() {
        return this._def.discriminator;
      }
      get options() {
        return this._def.options;
      }
      get optionsMap() {
        return this._def.optionsMap;
      }
      /**
       * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
       * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
       * have a different value for each object in the union.
       * @param discriminator the name of the discriminator property
       * @param types an array of object schemas
       * @param params
       */
      static create(discriminator, options, params) {
        const optionsMap = /* @__PURE__ */ new Map();
        for (const type of options) {
          const discriminatorValues = getDiscriminator(type.shape[discriminator]);
          if (!discriminatorValues.length) {
            throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
          }
          for (const value of discriminatorValues) {
            if (optionsMap.has(value)) {
              throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
            }
            optionsMap.set(value, type);
          }
        }
        return new _ZodDiscriminatedUnion({
          typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
          discriminator,
          options,
          optionsMap,
          ...processCreateParams(params)
        });
      }
    };
    ZodIntersection = class extends ZodType {
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        const handleParsed = (parsedLeft, parsedRight) => {
          if (isAborted(parsedLeft) || isAborted(parsedRight)) {
            return INVALID;
          }
          const merged = mergeValues(parsedLeft.value, parsedRight.value);
          if (!merged.valid) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.invalid_intersection_types
            });
            return INVALID;
          }
          if (isDirty(parsedLeft) || isDirty(parsedRight)) {
            status.dirty();
          }
          return { status: status.value, value: merged.data };
        };
        if (ctx.common.async) {
          return Promise.all([
            this._def.left._parseAsync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            }),
            this._def.right._parseAsync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            })
          ]).then(([left, right]) => handleParsed(left, right));
        } else {
          return handleParsed(this._def.left._parseSync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          }), this._def.right._parseSync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          }));
        }
      }
    };
    ZodIntersection.create = (left, right, params) => {
      return new ZodIntersection({
        left,
        right,
        typeName: ZodFirstPartyTypeKind.ZodIntersection,
        ...processCreateParams(params)
      });
    };
    ZodTuple = class _ZodTuple extends ZodType {
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.array) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.array,
            received: ctx.parsedType
          });
          return INVALID;
        }
        if (ctx.data.length < this._def.items.length) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            minimum: this._def.items.length,
            inclusive: true,
            exact: false,
            type: "array"
          });
          return INVALID;
        }
        const rest = this._def.rest;
        if (!rest && ctx.data.length > this._def.items.length) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            maximum: this._def.items.length,
            inclusive: true,
            exact: false,
            type: "array"
          });
          status.dirty();
        }
        const items = [...ctx.data].map((item, itemIndex) => {
          const schema = this._def.items[itemIndex] || this._def.rest;
          if (!schema)
            return null;
          return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
        }).filter((x) => !!x);
        if (ctx.common.async) {
          return Promise.all(items).then((results) => {
            return ParseStatus.mergeArray(status, results);
          });
        } else {
          return ParseStatus.mergeArray(status, items);
        }
      }
      get items() {
        return this._def.items;
      }
      rest(rest) {
        return new _ZodTuple({
          ...this._def,
          rest
        });
      }
    };
    ZodTuple.create = (schemas, params) => {
      if (!Array.isArray(schemas)) {
        throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
      }
      return new ZodTuple({
        items: schemas,
        typeName: ZodFirstPartyTypeKind.ZodTuple,
        rest: null,
        ...processCreateParams(params)
      });
    };
    ZodRecord = class _ZodRecord extends ZodType {
      get keySchema() {
        return this._def.keyType;
      }
      get valueSchema() {
        return this._def.valueType;
      }
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.object) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.object,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const pairs = [];
        const keyType = this._def.keyType;
        const valueType = this._def.valueType;
        for (const key in ctx.data) {
          pairs.push({
            key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
            value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
            alwaysSet: key in ctx.data
          });
        }
        if (ctx.common.async) {
          return ParseStatus.mergeObjectAsync(status, pairs);
        } else {
          return ParseStatus.mergeObjectSync(status, pairs);
        }
      }
      get element() {
        return this._def.valueType;
      }
      static create(first, second, third) {
        if (second instanceof ZodType) {
          return new _ZodRecord({
            keyType: first,
            valueType: second,
            typeName: ZodFirstPartyTypeKind.ZodRecord,
            ...processCreateParams(third)
          });
        }
        return new _ZodRecord({
          keyType: ZodString.create(),
          valueType: first,
          typeName: ZodFirstPartyTypeKind.ZodRecord,
          ...processCreateParams(second)
        });
      }
    };
    ZodMap = class extends ZodType {
      get keySchema() {
        return this._def.keyType;
      }
      get valueSchema() {
        return this._def.valueType;
      }
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.map) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.map,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const keyType = this._def.keyType;
        const valueType = this._def.valueType;
        const pairs = [...ctx.data.entries()].map(([key, value], index2) => {
          return {
            key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index2, "key"])),
            value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index2, "value"]))
          };
        });
        if (ctx.common.async) {
          const finalMap = /* @__PURE__ */ new Map();
          return Promise.resolve().then(async () => {
            for (const pair of pairs) {
              const key = await pair.key;
              const value = await pair.value;
              if (key.status === "aborted" || value.status === "aborted") {
                return INVALID;
              }
              if (key.status === "dirty" || value.status === "dirty") {
                status.dirty();
              }
              finalMap.set(key.value, value.value);
            }
            return { status: status.value, value: finalMap };
          });
        } else {
          const finalMap = /* @__PURE__ */ new Map();
          for (const pair of pairs) {
            const key = pair.key;
            const value = pair.value;
            if (key.status === "aborted" || value.status === "aborted") {
              return INVALID;
            }
            if (key.status === "dirty" || value.status === "dirty") {
              status.dirty();
            }
            finalMap.set(key.value, value.value);
          }
          return { status: status.value, value: finalMap };
        }
      }
    };
    ZodMap.create = (keyType, valueType, params) => {
      return new ZodMap({
        valueType,
        keyType,
        typeName: ZodFirstPartyTypeKind.ZodMap,
        ...processCreateParams(params)
      });
    };
    ZodSet = class _ZodSet extends ZodType {
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.set) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.set,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const def = this._def;
        if (def.minSize !== null) {
          if (ctx.data.size < def.minSize.value) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_small,
              minimum: def.minSize.value,
              type: "set",
              inclusive: true,
              exact: false,
              message: def.minSize.message
            });
            status.dirty();
          }
        }
        if (def.maxSize !== null) {
          if (ctx.data.size > def.maxSize.value) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_big,
              maximum: def.maxSize.value,
              type: "set",
              inclusive: true,
              exact: false,
              message: def.maxSize.message
            });
            status.dirty();
          }
        }
        const valueType = this._def.valueType;
        function finalizeSet(elements2) {
          const parsedSet = /* @__PURE__ */ new Set();
          for (const element of elements2) {
            if (element.status === "aborted")
              return INVALID;
            if (element.status === "dirty")
              status.dirty();
            parsedSet.add(element.value);
          }
          return { status: status.value, value: parsedSet };
        }
        const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
        if (ctx.common.async) {
          return Promise.all(elements).then((elements2) => finalizeSet(elements2));
        } else {
          return finalizeSet(elements);
        }
      }
      min(minSize, message) {
        return new _ZodSet({
          ...this._def,
          minSize: { value: minSize, message: errorUtil.toString(message) }
        });
      }
      max(maxSize, message) {
        return new _ZodSet({
          ...this._def,
          maxSize: { value: maxSize, message: errorUtil.toString(message) }
        });
      }
      size(size, message) {
        return this.min(size, message).max(size, message);
      }
      nonempty(message) {
        return this.min(1, message);
      }
    };
    ZodSet.create = (valueType, params) => {
      return new ZodSet({
        valueType,
        minSize: null,
        maxSize: null,
        typeName: ZodFirstPartyTypeKind.ZodSet,
        ...processCreateParams(params)
      });
    };
    ZodFunction = class _ZodFunction extends ZodType {
      constructor() {
        super(...arguments);
        this.validate = this.implement;
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.function) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.function,
            received: ctx.parsedType
          });
          return INVALID;
        }
        function makeArgsIssue(args, error40) {
          return makeIssue({
            data: args,
            path: ctx.path,
            errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
            issueData: {
              code: ZodIssueCode.invalid_arguments,
              argumentsError: error40
            }
          });
        }
        function makeReturnsIssue(returns, error40) {
          return makeIssue({
            data: returns,
            path: ctx.path,
            errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
            issueData: {
              code: ZodIssueCode.invalid_return_type,
              returnTypeError: error40
            }
          });
        }
        const params = { errorMap: ctx.common.contextualErrorMap };
        const fn = ctx.data;
        if (this._def.returns instanceof ZodPromise) {
          const me = this;
          return OK(async function(...args) {
            const error40 = new ZodError([]);
            const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
              error40.addIssue(makeArgsIssue(args, e));
              throw error40;
            });
            const result = await Reflect.apply(fn, this, parsedArgs);
            const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
              error40.addIssue(makeReturnsIssue(result, e));
              throw error40;
            });
            return parsedReturns;
          });
        } else {
          const me = this;
          return OK(function(...args) {
            const parsedArgs = me._def.args.safeParse(args, params);
            if (!parsedArgs.success) {
              throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
            }
            const result = Reflect.apply(fn, this, parsedArgs.data);
            const parsedReturns = me._def.returns.safeParse(result, params);
            if (!parsedReturns.success) {
              throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
            }
            return parsedReturns.data;
          });
        }
      }
      parameters() {
        return this._def.args;
      }
      returnType() {
        return this._def.returns;
      }
      args(...items) {
        return new _ZodFunction({
          ...this._def,
          args: ZodTuple.create(items).rest(ZodUnknown.create())
        });
      }
      returns(returnType) {
        return new _ZodFunction({
          ...this._def,
          returns: returnType
        });
      }
      implement(func) {
        const validatedFunc = this.parse(func);
        return validatedFunc;
      }
      strictImplement(func) {
        const validatedFunc = this.parse(func);
        return validatedFunc;
      }
      static create(args, returns, params) {
        return new _ZodFunction({
          args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
          returns: returns || ZodUnknown.create(),
          typeName: ZodFirstPartyTypeKind.ZodFunction,
          ...processCreateParams(params)
        });
      }
    };
    ZodLazy = class extends ZodType {
      get schema() {
        return this._def.getter();
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const lazySchema = this._def.getter();
        return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
      }
    };
    ZodLazy.create = (getter, params) => {
      return new ZodLazy({
        getter,
        typeName: ZodFirstPartyTypeKind.ZodLazy,
        ...processCreateParams(params)
      });
    };
    ZodLiteral = class extends ZodType {
      _parse(input) {
        if (input.data !== this._def.value) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            received: ctx.data,
            code: ZodIssueCode.invalid_literal,
            expected: this._def.value
          });
          return INVALID;
        }
        return { status: "valid", value: input.data };
      }
      get value() {
        return this._def.value;
      }
    };
    ZodLiteral.create = (value, params) => {
      return new ZodLiteral({
        value,
        typeName: ZodFirstPartyTypeKind.ZodLiteral,
        ...processCreateParams(params)
      });
    };
    ZodEnum = class _ZodEnum extends ZodType {
      _parse(input) {
        if (typeof input.data !== "string") {
          const ctx = this._getOrReturnCtx(input);
          const expectedValues = this._def.values;
          addIssueToContext(ctx, {
            expected: util.joinValues(expectedValues),
            received: ctx.parsedType,
            code: ZodIssueCode.invalid_type
          });
          return INVALID;
        }
        if (!this._cache) {
          this._cache = new Set(this._def.values);
        }
        if (!this._cache.has(input.data)) {
          const ctx = this._getOrReturnCtx(input);
          const expectedValues = this._def.values;
          addIssueToContext(ctx, {
            received: ctx.data,
            code: ZodIssueCode.invalid_enum_value,
            options: expectedValues
          });
          return INVALID;
        }
        return OK(input.data);
      }
      get options() {
        return this._def.values;
      }
      get enum() {
        const enumValues = {};
        for (const val of this._def.values) {
          enumValues[val] = val;
        }
        return enumValues;
      }
      get Values() {
        const enumValues = {};
        for (const val of this._def.values) {
          enumValues[val] = val;
        }
        return enumValues;
      }
      get Enum() {
        const enumValues = {};
        for (const val of this._def.values) {
          enumValues[val] = val;
        }
        return enumValues;
      }
      extract(values, newDef = this._def) {
        return _ZodEnum.create(values, {
          ...this._def,
          ...newDef
        });
      }
      exclude(values, newDef = this._def) {
        return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
          ...this._def,
          ...newDef
        });
      }
    };
    ZodEnum.create = createZodEnum;
    ZodNativeEnum = class extends ZodType {
      _parse(input) {
        const nativeEnumValues = util.getValidEnumValues(this._def.values);
        const ctx = this._getOrReturnCtx(input);
        if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
          const expectedValues = util.objectValues(nativeEnumValues);
          addIssueToContext(ctx, {
            expected: util.joinValues(expectedValues),
            received: ctx.parsedType,
            code: ZodIssueCode.invalid_type
          });
          return INVALID;
        }
        if (!this._cache) {
          this._cache = new Set(util.getValidEnumValues(this._def.values));
        }
        if (!this._cache.has(input.data)) {
          const expectedValues = util.objectValues(nativeEnumValues);
          addIssueToContext(ctx, {
            received: ctx.data,
            code: ZodIssueCode.invalid_enum_value,
            options: expectedValues
          });
          return INVALID;
        }
        return OK(input.data);
      }
      get enum() {
        return this._def.values;
      }
    };
    ZodNativeEnum.create = (values, params) => {
      return new ZodNativeEnum({
        values,
        typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
        ...processCreateParams(params)
      });
    };
    ZodPromise = class extends ZodType {
      unwrap() {
        return this._def.type;
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.promise,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
        return OK(promisified.then((data) => {
          return this._def.type.parseAsync(data, {
            path: ctx.path,
            errorMap: ctx.common.contextualErrorMap
          });
        }));
      }
    };
    ZodPromise.create = (schema, params) => {
      return new ZodPromise({
        type: schema,
        typeName: ZodFirstPartyTypeKind.ZodPromise,
        ...processCreateParams(params)
      });
    };
    ZodEffects = class extends ZodType {
      innerType() {
        return this._def.schema;
      }
      sourceType() {
        return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
      }
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        const effect = this._def.effect || null;
        const checkCtx = {
          addIssue: (arg) => {
            addIssueToContext(ctx, arg);
            if (arg.fatal) {
              status.abort();
            } else {
              status.dirty();
            }
          },
          get path() {
            return ctx.path;
          }
        };
        checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
        if (effect.type === "preprocess") {
          const processed = effect.transform(ctx.data, checkCtx);
          if (ctx.common.async) {
            return Promise.resolve(processed).then(async (processed2) => {
              if (status.value === "aborted")
                return INVALID;
              const result = await this._def.schema._parseAsync({
                data: processed2,
                path: ctx.path,
                parent: ctx
              });
              if (result.status === "aborted")
                return INVALID;
              if (result.status === "dirty")
                return DIRTY(result.value);
              if (status.value === "dirty")
                return DIRTY(result.value);
              return result;
            });
          } else {
            if (status.value === "aborted")
              return INVALID;
            const result = this._def.schema._parseSync({
              data: processed,
              path: ctx.path,
              parent: ctx
            });
            if (result.status === "aborted")
              return INVALID;
            if (result.status === "dirty")
              return DIRTY(result.value);
            if (status.value === "dirty")
              return DIRTY(result.value);
            return result;
          }
        }
        if (effect.type === "refinement") {
          const executeRefinement = (acc) => {
            const result = effect.refinement(acc, checkCtx);
            if (ctx.common.async) {
              return Promise.resolve(result);
            }
            if (result instanceof Promise) {
              throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
            }
            return acc;
          };
          if (ctx.common.async === false) {
            const inner = this._def.schema._parseSync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            });
            if (inner.status === "aborted")
              return INVALID;
            if (inner.status === "dirty")
              status.dirty();
            executeRefinement(inner.value);
            return { status: status.value, value: inner.value };
          } else {
            return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
              if (inner.status === "aborted")
                return INVALID;
              if (inner.status === "dirty")
                status.dirty();
              return executeRefinement(inner.value).then(() => {
                return { status: status.value, value: inner.value };
              });
            });
          }
        }
        if (effect.type === "transform") {
          if (ctx.common.async === false) {
            const base = this._def.schema._parseSync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            });
            if (!isValid(base))
              return INVALID;
            const result = effect.transform(base.value, checkCtx);
            if (result instanceof Promise) {
              throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
            }
            return { status: status.value, value: result };
          } else {
            return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
              if (!isValid(base))
                return INVALID;
              return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
                status: status.value,
                value: result
              }));
            });
          }
        }
        util.assertNever(effect);
      }
    };
    ZodEffects.create = (schema, effect, params) => {
      return new ZodEffects({
        schema,
        typeName: ZodFirstPartyTypeKind.ZodEffects,
        effect,
        ...processCreateParams(params)
      });
    };
    ZodEffects.createWithPreprocess = (preprocess2, schema, params) => {
      return new ZodEffects({
        schema,
        effect: { type: "preprocess", transform: preprocess2 },
        typeName: ZodFirstPartyTypeKind.ZodEffects,
        ...processCreateParams(params)
      });
    };
    ZodOptional = class extends ZodType {
      _parse(input) {
        const parsedType4 = this._getType(input);
        if (parsedType4 === ZodParsedType.undefined) {
          return OK(void 0);
        }
        return this._def.innerType._parse(input);
      }
      unwrap() {
        return this._def.innerType;
      }
    };
    ZodOptional.create = (type, params) => {
      return new ZodOptional({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodOptional,
        ...processCreateParams(params)
      });
    };
    ZodNullable = class extends ZodType {
      _parse(input) {
        const parsedType4 = this._getType(input);
        if (parsedType4 === ZodParsedType.null) {
          return OK(null);
        }
        return this._def.innerType._parse(input);
      }
      unwrap() {
        return this._def.innerType;
      }
    };
    ZodNullable.create = (type, params) => {
      return new ZodNullable({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodNullable,
        ...processCreateParams(params)
      });
    };
    ZodDefault = class extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        let data = ctx.data;
        if (ctx.parsedType === ZodParsedType.undefined) {
          data = this._def.defaultValue();
        }
        return this._def.innerType._parse({
          data,
          path: ctx.path,
          parent: ctx
        });
      }
      removeDefault() {
        return this._def.innerType;
      }
    };
    ZodDefault.create = (type, params) => {
      return new ZodDefault({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodDefault,
        defaultValue: typeof params.default === "function" ? params.default : () => params.default,
        ...processCreateParams(params)
      });
    };
    ZodCatch = class extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const newCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          }
        };
        const result = this._def.innerType._parse({
          data: newCtx.data,
          path: newCtx.path,
          parent: {
            ...newCtx
          }
        });
        if (isAsync(result)) {
          return result.then((result2) => {
            return {
              status: "valid",
              value: result2.status === "valid" ? result2.value : this._def.catchValue({
                get error() {
                  return new ZodError(newCtx.common.issues);
                },
                input: newCtx.data
              })
            };
          });
        } else {
          return {
            status: "valid",
            value: result.status === "valid" ? result.value : this._def.catchValue({
              get error() {
                return new ZodError(newCtx.common.issues);
              },
              input: newCtx.data
            })
          };
        }
      }
      removeCatch() {
        return this._def.innerType;
      }
    };
    ZodCatch.create = (type, params) => {
      return new ZodCatch({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodCatch,
        catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
        ...processCreateParams(params)
      });
    };
    ZodNaN = class extends ZodType {
      _parse(input) {
        const parsedType4 = this._getType(input);
        if (parsedType4 !== ZodParsedType.nan) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.nan,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return { status: "valid", value: input.data };
      }
    };
    ZodNaN.create = (params) => {
      return new ZodNaN({
        typeName: ZodFirstPartyTypeKind.ZodNaN,
        ...processCreateParams(params)
      });
    };
    BRAND = /* @__PURE__ */ Symbol("zod_brand");
    ZodBranded = class extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const data = ctx.data;
        return this._def.type._parse({
          data,
          path: ctx.path,
          parent: ctx
        });
      }
      unwrap() {
        return this._def.type;
      }
    };
    ZodPipeline = class _ZodPipeline extends ZodType {
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.common.async) {
          const handleAsync = async () => {
            const inResult = await this._def.in._parseAsync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            });
            if (inResult.status === "aborted")
              return INVALID;
            if (inResult.status === "dirty") {
              status.dirty();
              return DIRTY(inResult.value);
            } else {
              return this._def.out._parseAsync({
                data: inResult.value,
                path: ctx.path,
                parent: ctx
              });
            }
          };
          return handleAsync();
        } else {
          const inResult = this._def.in._parseSync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          });
          if (inResult.status === "aborted")
            return INVALID;
          if (inResult.status === "dirty") {
            status.dirty();
            return {
              status: "dirty",
              value: inResult.value
            };
          } else {
            return this._def.out._parseSync({
              data: inResult.value,
              path: ctx.path,
              parent: ctx
            });
          }
        }
      }
      static create(a, b) {
        return new _ZodPipeline({
          in: a,
          out: b,
          typeName: ZodFirstPartyTypeKind.ZodPipeline
        });
      }
    };
    ZodReadonly = class extends ZodType {
      _parse(input) {
        const result = this._def.innerType._parse(input);
        const freeze = (data) => {
          if (isValid(data)) {
            data.value = Object.freeze(data.value);
          }
          return data;
        };
        return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
      }
      unwrap() {
        return this._def.innerType;
      }
    };
    ZodReadonly.create = (type, params) => {
      return new ZodReadonly({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodReadonly,
        ...processCreateParams(params)
      });
    };
    late = {
      object: ZodObject.lazycreate
    };
    (function(ZodFirstPartyTypeKind2) {
      ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
      ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
      ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
      ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
      ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
      ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
      ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
      ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
      ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
      ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
      ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
      ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
      ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
      ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
      ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
      ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
      ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
      ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
      ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
      ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
      ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
      ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
      ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
      ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
      ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
      ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
      ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
      ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
      ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
      ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
      ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
      ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
      ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
      ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
      ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
      ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
    })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
    instanceOfType = (cls, params = {
      message: `Input not instance of ${cls.name}`
    }) => custom((data) => data instanceof cls, params);
    stringType = ZodString.create;
    numberType = ZodNumber.create;
    nanType = ZodNaN.create;
    bigIntType = ZodBigInt.create;
    booleanType = ZodBoolean.create;
    dateType = ZodDate.create;
    symbolType = ZodSymbol.create;
    undefinedType = ZodUndefined.create;
    nullType = ZodNull.create;
    anyType = ZodAny.create;
    unknownType = ZodUnknown.create;
    neverType = ZodNever.create;
    voidType = ZodVoid.create;
    arrayType = ZodArray.create;
    objectType = ZodObject.create;
    strictObjectType = ZodObject.strictCreate;
    unionType = ZodUnion.create;
    discriminatedUnionType = ZodDiscriminatedUnion.create;
    intersectionType = ZodIntersection.create;
    tupleType = ZodTuple.create;
    recordType = ZodRecord.create;
    mapType = ZodMap.create;
    setType = ZodSet.create;
    functionType = ZodFunction.create;
    lazyType = ZodLazy.create;
    literalType = ZodLiteral.create;
    enumType = ZodEnum.create;
    nativeEnumType = ZodNativeEnum.create;
    promiseType = ZodPromise.create;
    effectsType = ZodEffects.create;
    optionalType = ZodOptional.create;
    nullableType = ZodNullable.create;
    preprocessType = ZodEffects.createWithPreprocess;
    pipelineType = ZodPipeline.create;
    ostring = () => stringType().optional();
    onumber = () => numberType().optional();
    oboolean = () => booleanType().optional();
    coerce = {
      string: ((arg) => ZodString.create({ ...arg, coerce: true })),
      number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
      boolean: ((arg) => ZodBoolean.create({
        ...arg,
        coerce: true
      })),
      bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
      date: ((arg) => ZodDate.create({ ...arg, coerce: true }))
    };
    NEVER = INVALID;
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js
var external_exports = {};
__export(external_exports, {
  BRAND: () => BRAND,
  DIRTY: () => DIRTY,
  EMPTY_PATH: () => EMPTY_PATH,
  INVALID: () => INVALID,
  NEVER: () => NEVER,
  OK: () => OK,
  ParseStatus: () => ParseStatus,
  Schema: () => ZodType,
  ZodAny: () => ZodAny,
  ZodArray: () => ZodArray,
  ZodBigInt: () => ZodBigInt,
  ZodBoolean: () => ZodBoolean,
  ZodBranded: () => ZodBranded,
  ZodCatch: () => ZodCatch,
  ZodDate: () => ZodDate,
  ZodDefault: () => ZodDefault,
  ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
  ZodEffects: () => ZodEffects,
  ZodEnum: () => ZodEnum,
  ZodError: () => ZodError,
  ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
  ZodFunction: () => ZodFunction,
  ZodIntersection: () => ZodIntersection,
  ZodIssueCode: () => ZodIssueCode,
  ZodLazy: () => ZodLazy,
  ZodLiteral: () => ZodLiteral,
  ZodMap: () => ZodMap,
  ZodNaN: () => ZodNaN,
  ZodNativeEnum: () => ZodNativeEnum,
  ZodNever: () => ZodNever,
  ZodNull: () => ZodNull,
  ZodNullable: () => ZodNullable,
  ZodNumber: () => ZodNumber,
  ZodObject: () => ZodObject,
  ZodOptional: () => ZodOptional,
  ZodParsedType: () => ZodParsedType,
  ZodPipeline: () => ZodPipeline,
  ZodPromise: () => ZodPromise,
  ZodReadonly: () => ZodReadonly,
  ZodRecord: () => ZodRecord,
  ZodSchema: () => ZodType,
  ZodSet: () => ZodSet,
  ZodString: () => ZodString,
  ZodSymbol: () => ZodSymbol,
  ZodTransformer: () => ZodEffects,
  ZodTuple: () => ZodTuple,
  ZodType: () => ZodType,
  ZodUndefined: () => ZodUndefined,
  ZodUnion: () => ZodUnion,
  ZodUnknown: () => ZodUnknown,
  ZodVoid: () => ZodVoid,
  addIssueToContext: () => addIssueToContext,
  any: () => anyType,
  array: () => arrayType,
  bigint: () => bigIntType,
  boolean: () => booleanType,
  coerce: () => coerce,
  custom: () => custom,
  date: () => dateType,
  datetimeRegex: () => datetimeRegex,
  defaultErrorMap: () => en_default,
  discriminatedUnion: () => discriminatedUnionType,
  effect: () => effectsType,
  enum: () => enumType,
  function: () => functionType,
  getErrorMap: () => getErrorMap,
  getParsedType: () => getParsedType,
  instanceof: () => instanceOfType,
  intersection: () => intersectionType,
  isAborted: () => isAborted,
  isAsync: () => isAsync,
  isDirty: () => isDirty,
  isValid: () => isValid,
  late: () => late,
  lazy: () => lazyType,
  literal: () => literalType,
  makeIssue: () => makeIssue,
  map: () => mapType,
  nan: () => nanType,
  nativeEnum: () => nativeEnumType,
  never: () => neverType,
  null: () => nullType,
  nullable: () => nullableType,
  number: () => numberType,
  object: () => objectType,
  objectUtil: () => objectUtil,
  oboolean: () => oboolean,
  onumber: () => onumber,
  optional: () => optionalType,
  ostring: () => ostring,
  pipeline: () => pipelineType,
  preprocess: () => preprocessType,
  promise: () => promiseType,
  quotelessJson: () => quotelessJson,
  record: () => recordType,
  set: () => setType,
  setErrorMap: () => setErrorMap,
  strictObject: () => strictObjectType,
  string: () => stringType,
  symbol: () => symbolType,
  transformer: () => effectsType,
  tuple: () => tupleType,
  undefined: () => undefinedType,
  union: () => unionType,
  unknown: () => unknownType,
  util: () => util,
  void: () => voidType
});
var init_external = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js"() {
    init_errors();
    init_parseUtil();
    init_typeAliases();
    init_util();
    init_types();
    init_ZodError();
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/index.js
var init_zod = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/index.js"() {
    init_external();
    init_external();
  }
});

// ../../lib/api-zod/src/generated/api.ts
var HealthCheckResponse;
var init_api = __esm({
  "../../lib/api-zod/src/generated/api.ts"() {
    "use strict";
    init_zod();
    HealthCheckResponse = objectType({
      status: stringType()
    });
  }
});

// ../../lib/api-zod/src/generated/types/healthStatus.ts
var init_healthStatus = __esm({
  "../../lib/api-zod/src/generated/types/healthStatus.ts"() {
    "use strict";
  }
});

// ../../lib/api-zod/src/generated/types/index.ts
var init_types2 = __esm({
  "../../lib/api-zod/src/generated/types/index.ts"() {
    "use strict";
    init_healthStatus();
  }
});

// ../../lib/api-zod/src/index.ts
var init_src = __esm({
  "../../lib/api-zod/src/index.ts"() {
    "use strict";
    init_api();
    init_types2();
  }
});

// src/routes/health.ts
var import_express, router, health_default;
var init_health = __esm({
  "src/routes/health.ts"() {
    "use strict";
    import_express = __toESM(require_express2(), 1);
    init_src();
    router = (0, import_express.Router)();
    router.get("/healthz", (_req, res) => {
      const data = HealthCheckResponse.parse({ status: "ok" });
      res.json(data);
    });
    health_default = router;
  }
});

// ../../node_modules/.pnpm/bcryptjs@3.0.3/node_modules/bcryptjs/index.js
import nodeCrypto from "crypto";
function randomBytes(len) {
  try {
    return crypto.getRandomValues(new Uint8Array(len));
  } catch {
  }
  try {
    return nodeCrypto.randomBytes(len);
  } catch {
  }
  if (!randomFallback) {
    throw Error(
      "Neither WebCryptoAPI nor a crypto module is available. Use bcrypt.setRandomFallback to set an alternative"
    );
  }
  return randomFallback(len);
}
function setRandomFallback(random) {
  randomFallback = random;
}
function genSaltSync(rounds, seed_length) {
  rounds = rounds || GENSALT_DEFAULT_LOG2_ROUNDS;
  if (typeof rounds !== "number")
    throw Error(
      "Illegal arguments: " + typeof rounds + ", " + typeof seed_length
    );
  if (rounds < 4) rounds = 4;
  else if (rounds > 31) rounds = 31;
  var salt = [];
  salt.push("$2b$");
  if (rounds < 10) salt.push("0");
  salt.push(rounds.toString());
  salt.push("$");
  salt.push(base64_encode(randomBytes(BCRYPT_SALT_LEN), BCRYPT_SALT_LEN));
  return salt.join("");
}
function genSalt(rounds, seed_length, callback) {
  if (typeof seed_length === "function")
    callback = seed_length, seed_length = void 0;
  if (typeof rounds === "function") callback = rounds, rounds = void 0;
  if (typeof rounds === "undefined") rounds = GENSALT_DEFAULT_LOG2_ROUNDS;
  else if (typeof rounds !== "number")
    throw Error("illegal arguments: " + typeof rounds);
  function _async(callback2) {
    nextTick(function() {
      try {
        callback2(null, genSaltSync(rounds));
      } catch (err) {
        callback2(err);
      }
    });
  }
  if (callback) {
    if (typeof callback !== "function")
      throw Error("Illegal callback: " + typeof callback);
    _async(callback);
  } else
    return new Promise(function(resolve, reject) {
      _async(function(err, res) {
        if (err) {
          reject(err);
          return;
        }
        resolve(res);
      });
    });
}
function hashSync(password, salt) {
  if (typeof salt === "undefined") salt = GENSALT_DEFAULT_LOG2_ROUNDS;
  if (typeof salt === "number") salt = genSaltSync(salt);
  if (typeof password !== "string" || typeof salt !== "string")
    throw Error("Illegal arguments: " + typeof password + ", " + typeof salt);
  return _hash(password, salt);
}
function hash(password, salt, callback, progressCallback) {
  function _async(callback2) {
    if (typeof password === "string" && typeof salt === "number")
      genSalt(salt, function(err, salt2) {
        _hash(password, salt2, callback2, progressCallback);
      });
    else if (typeof password === "string" && typeof salt === "string")
      _hash(password, salt, callback2, progressCallback);
    else
      nextTick(
        callback2.bind(
          this,
          Error("Illegal arguments: " + typeof password + ", " + typeof salt)
        )
      );
  }
  if (callback) {
    if (typeof callback !== "function")
      throw Error("Illegal callback: " + typeof callback);
    _async(callback);
  } else
    return new Promise(function(resolve, reject) {
      _async(function(err, res) {
        if (err) {
          reject(err);
          return;
        }
        resolve(res);
      });
    });
}
function safeStringCompare(known, unknown2) {
  var diff = known.length ^ unknown2.length;
  for (var i = 0; i < known.length; ++i) {
    diff |= known.charCodeAt(i) ^ unknown2.charCodeAt(i);
  }
  return diff === 0;
}
function compareSync(password, hash2) {
  if (typeof password !== "string" || typeof hash2 !== "string")
    throw Error("Illegal arguments: " + typeof password + ", " + typeof hash2);
  if (hash2.length !== 60) return false;
  return safeStringCompare(
    hashSync(password, hash2.substring(0, hash2.length - 31)),
    hash2
  );
}
function compare(password, hashValue, callback, progressCallback) {
  function _async(callback2) {
    if (typeof password !== "string" || typeof hashValue !== "string") {
      nextTick(
        callback2.bind(
          this,
          Error(
            "Illegal arguments: " + typeof password + ", " + typeof hashValue
          )
        )
      );
      return;
    }
    if (hashValue.length !== 60) {
      nextTick(callback2.bind(this, null, false));
      return;
    }
    hash(
      password,
      hashValue.substring(0, 29),
      function(err, comp) {
        if (err) callback2(err);
        else callback2(null, safeStringCompare(comp, hashValue));
      },
      progressCallback
    );
  }
  if (callback) {
    if (typeof callback !== "function")
      throw Error("Illegal callback: " + typeof callback);
    _async(callback);
  } else
    return new Promise(function(resolve, reject) {
      _async(function(err, res) {
        if (err) {
          reject(err);
          return;
        }
        resolve(res);
      });
    });
}
function getRounds(hash2) {
  if (typeof hash2 !== "string")
    throw Error("Illegal arguments: " + typeof hash2);
  return parseInt(hash2.split("$")[2], 10);
}
function getSalt(hash2) {
  if (typeof hash2 !== "string")
    throw Error("Illegal arguments: " + typeof hash2);
  if (hash2.length !== 60)
    throw Error("Illegal hash length: " + hash2.length + " != 60");
  return hash2.substring(0, 29);
}
function truncates(password) {
  if (typeof password !== "string")
    throw Error("Illegal arguments: " + typeof password);
  return utf8Length(password) > 72;
}
function utf8Length(string4) {
  var len = 0, c = 0;
  for (var i = 0; i < string4.length; ++i) {
    c = string4.charCodeAt(i);
    if (c < 128) len += 1;
    else if (c < 2048) len += 2;
    else if ((c & 64512) === 55296 && (string4.charCodeAt(i + 1) & 64512) === 56320) {
      ++i;
      len += 4;
    } else len += 3;
  }
  return len;
}
function utf8Array(string4) {
  var offset = 0, c1, c2;
  var buffer = new Array(utf8Length(string4));
  for (var i = 0, k = string4.length; i < k; ++i) {
    c1 = string4.charCodeAt(i);
    if (c1 < 128) {
      buffer[offset++] = c1;
    } else if (c1 < 2048) {
      buffer[offset++] = c1 >> 6 | 192;
      buffer[offset++] = c1 & 63 | 128;
    } else if ((c1 & 64512) === 55296 && ((c2 = string4.charCodeAt(i + 1)) & 64512) === 56320) {
      c1 = 65536 + ((c1 & 1023) << 10) + (c2 & 1023);
      ++i;
      buffer[offset++] = c1 >> 18 | 240;
      buffer[offset++] = c1 >> 12 & 63 | 128;
      buffer[offset++] = c1 >> 6 & 63 | 128;
      buffer[offset++] = c1 & 63 | 128;
    } else {
      buffer[offset++] = c1 >> 12 | 224;
      buffer[offset++] = c1 >> 6 & 63 | 128;
      buffer[offset++] = c1 & 63 | 128;
    }
  }
  return buffer;
}
function base64_encode(b, len) {
  var off = 0, rs = [], c1, c2;
  if (len <= 0 || len > b.length) throw Error("Illegal len: " + len);
  while (off < len) {
    c1 = b[off++] & 255;
    rs.push(BASE64_CODE[c1 >> 2 & 63]);
    c1 = (c1 & 3) << 4;
    if (off >= len) {
      rs.push(BASE64_CODE[c1 & 63]);
      break;
    }
    c2 = b[off++] & 255;
    c1 |= c2 >> 4 & 15;
    rs.push(BASE64_CODE[c1 & 63]);
    c1 = (c2 & 15) << 2;
    if (off >= len) {
      rs.push(BASE64_CODE[c1 & 63]);
      break;
    }
    c2 = b[off++] & 255;
    c1 |= c2 >> 6 & 3;
    rs.push(BASE64_CODE[c1 & 63]);
    rs.push(BASE64_CODE[c2 & 63]);
  }
  return rs.join("");
}
function base64_decode(s, len) {
  var off = 0, slen = s.length, olen = 0, rs = [], c1, c2, c3, c4, o, code;
  if (len <= 0) throw Error("Illegal len: " + len);
  while (off < slen - 1 && olen < len) {
    code = s.charCodeAt(off++);
    c1 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1;
    code = s.charCodeAt(off++);
    c2 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1;
    if (c1 == -1 || c2 == -1) break;
    o = c1 << 2 >>> 0;
    o |= (c2 & 48) >> 4;
    rs.push(String.fromCharCode(o));
    if (++olen >= len || off >= slen) break;
    code = s.charCodeAt(off++);
    c3 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1;
    if (c3 == -1) break;
    o = (c2 & 15) << 4 >>> 0;
    o |= (c3 & 60) >> 2;
    rs.push(String.fromCharCode(o));
    if (++olen >= len || off >= slen) break;
    code = s.charCodeAt(off++);
    c4 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1;
    o = (c3 & 3) << 6 >>> 0;
    o |= c4;
    rs.push(String.fromCharCode(o));
    ++olen;
  }
  var res = [];
  for (off = 0; off < olen; off++) res.push(rs[off].charCodeAt(0));
  return res;
}
function _encipher(lr, off, P, S) {
  var n, l = lr[off], r = lr[off + 1];
  l ^= P[0];
  n = S[l >>> 24];
  n += S[256 | l >> 16 & 255];
  n ^= S[512 | l >> 8 & 255];
  n += S[768 | l & 255];
  r ^= n ^ P[1];
  n = S[r >>> 24];
  n += S[256 | r >> 16 & 255];
  n ^= S[512 | r >> 8 & 255];
  n += S[768 | r & 255];
  l ^= n ^ P[2];
  n = S[l >>> 24];
  n += S[256 | l >> 16 & 255];
  n ^= S[512 | l >> 8 & 255];
  n += S[768 | l & 255];
  r ^= n ^ P[3];
  n = S[r >>> 24];
  n += S[256 | r >> 16 & 255];
  n ^= S[512 | r >> 8 & 255];
  n += S[768 | r & 255];
  l ^= n ^ P[4];
  n = S[l >>> 24];
  n += S[256 | l >> 16 & 255];
  n ^= S[512 | l >> 8 & 255];
  n += S[768 | l & 255];
  r ^= n ^ P[5];
  n = S[r >>> 24];
  n += S[256 | r >> 16 & 255];
  n ^= S[512 | r >> 8 & 255];
  n += S[768 | r & 255];
  l ^= n ^ P[6];
  n = S[l >>> 24];
  n += S[256 | l >> 16 & 255];
  n ^= S[512 | l >> 8 & 255];
  n += S[768 | l & 255];
  r ^= n ^ P[7];
  n = S[r >>> 24];
  n += S[256 | r >> 16 & 255];
  n ^= S[512 | r >> 8 & 255];
  n += S[768 | r & 255];
  l ^= n ^ P[8];
  n = S[l >>> 24];
  n += S[256 | l >> 16 & 255];
  n ^= S[512 | l >> 8 & 255];
  n += S[768 | l & 255];
  r ^= n ^ P[9];
  n = S[r >>> 24];
  n += S[256 | r >> 16 & 255];
  n ^= S[512 | r >> 8 & 255];
  n += S[768 | r & 255];
  l ^= n ^ P[10];
  n = S[l >>> 24];
  n += S[256 | l >> 16 & 255];
  n ^= S[512 | l >> 8 & 255];
  n += S[768 | l & 255];
  r ^= n ^ P[11];
  n = S[r >>> 24];
  n += S[256 | r >> 16 & 255];
  n ^= S[512 | r >> 8 & 255];
  n += S[768 | r & 255];
  l ^= n ^ P[12];
  n = S[l >>> 24];
  n += S[256 | l >> 16 & 255];
  n ^= S[512 | l >> 8 & 255];
  n += S[768 | l & 255];
  r ^= n ^ P[13];
  n = S[r >>> 24];
  n += S[256 | r >> 16 & 255];
  n ^= S[512 | r >> 8 & 255];
  n += S[768 | r & 255];
  l ^= n ^ P[14];
  n = S[l >>> 24];
  n += S[256 | l >> 16 & 255];
  n ^= S[512 | l >> 8 & 255];
  n += S[768 | l & 255];
  r ^= n ^ P[15];
  n = S[r >>> 24];
  n += S[256 | r >> 16 & 255];
  n ^= S[512 | r >> 8 & 255];
  n += S[768 | r & 255];
  l ^= n ^ P[16];
  lr[off] = r ^ P[BLOWFISH_NUM_ROUNDS + 1];
  lr[off + 1] = l;
  return lr;
}
function _streamtoword(data, offp) {
  for (var i = 0, word = 0; i < 4; ++i)
    word = word << 8 | data[offp] & 255, offp = (offp + 1) % data.length;
  return { key: word, offp };
}
function _key(key, P, S) {
  var offset = 0, lr = [0, 0], plen = P.length, slen = S.length, sw;
  for (var i = 0; i < plen; i++)
    sw = _streamtoword(key, offset), offset = sw.offp, P[i] = P[i] ^ sw.key;
  for (i = 0; i < plen; i += 2)
    lr = _encipher(lr, 0, P, S), P[i] = lr[0], P[i + 1] = lr[1];
  for (i = 0; i < slen; i += 2)
    lr = _encipher(lr, 0, P, S), S[i] = lr[0], S[i + 1] = lr[1];
}
function _ekskey(data, key, P, S) {
  var offp = 0, lr = [0, 0], plen = P.length, slen = S.length, sw;
  for (var i = 0; i < plen; i++)
    sw = _streamtoword(key, offp), offp = sw.offp, P[i] = P[i] ^ sw.key;
  offp = 0;
  for (i = 0; i < plen; i += 2)
    sw = _streamtoword(data, offp), offp = sw.offp, lr[0] ^= sw.key, sw = _streamtoword(data, offp), offp = sw.offp, lr[1] ^= sw.key, lr = _encipher(lr, 0, P, S), P[i] = lr[0], P[i + 1] = lr[1];
  for (i = 0; i < slen; i += 2)
    sw = _streamtoword(data, offp), offp = sw.offp, lr[0] ^= sw.key, sw = _streamtoword(data, offp), offp = sw.offp, lr[1] ^= sw.key, lr = _encipher(lr, 0, P, S), S[i] = lr[0], S[i + 1] = lr[1];
}
function _crypt(b, salt, rounds, callback, progressCallback) {
  var cdata = C_ORIG.slice(), clen = cdata.length, err;
  if (rounds < 4 || rounds > 31) {
    err = Error("Illegal number of rounds (4-31): " + rounds);
    if (callback) {
      nextTick(callback.bind(this, err));
      return;
    } else throw err;
  }
  if (salt.length !== BCRYPT_SALT_LEN) {
    err = Error(
      "Illegal salt length: " + salt.length + " != " + BCRYPT_SALT_LEN
    );
    if (callback) {
      nextTick(callback.bind(this, err));
      return;
    } else throw err;
  }
  rounds = 1 << rounds >>> 0;
  var P, S, i = 0, j;
  if (typeof Int32Array === "function") {
    P = new Int32Array(P_ORIG);
    S = new Int32Array(S_ORIG);
  } else {
    P = P_ORIG.slice();
    S = S_ORIG.slice();
  }
  _ekskey(salt, b, P, S);
  function next() {
    if (progressCallback) progressCallback(i / rounds);
    if (i < rounds) {
      var start = Date.now();
      for (; i < rounds; ) {
        i = i + 1;
        _key(b, P, S);
        _key(salt, P, S);
        if (Date.now() - start > MAX_EXECUTION_TIME) break;
      }
    } else {
      for (i = 0; i < 64; i++)
        for (j = 0; j < clen >> 1; j++) _encipher(cdata, j << 1, P, S);
      var ret = [];
      for (i = 0; i < clen; i++)
        ret.push((cdata[i] >> 24 & 255) >>> 0), ret.push((cdata[i] >> 16 & 255) >>> 0), ret.push((cdata[i] >> 8 & 255) >>> 0), ret.push((cdata[i] & 255) >>> 0);
      if (callback) {
        callback(null, ret);
        return;
      } else return ret;
    }
    if (callback) nextTick(next);
  }
  if (typeof callback !== "undefined") {
    next();
  } else {
    var res;
    while (true) if (typeof (res = next()) !== "undefined") return res || [];
  }
}
function _hash(password, salt, callback, progressCallback) {
  var err;
  if (typeof password !== "string" || typeof salt !== "string") {
    err = Error("Invalid string / salt: Not a string");
    if (callback) {
      nextTick(callback.bind(this, err));
      return;
    } else throw err;
  }
  var minor, offset;
  if (salt.charAt(0) !== "$" || salt.charAt(1) !== "2") {
    err = Error("Invalid salt version: " + salt.substring(0, 2));
    if (callback) {
      nextTick(callback.bind(this, err));
      return;
    } else throw err;
  }
  if (salt.charAt(2) === "$") minor = String.fromCharCode(0), offset = 3;
  else {
    minor = salt.charAt(2);
    if (minor !== "a" && minor !== "b" && minor !== "y" || salt.charAt(3) !== "$") {
      err = Error("Invalid salt revision: " + salt.substring(2, 4));
      if (callback) {
        nextTick(callback.bind(this, err));
        return;
      } else throw err;
    }
    offset = 4;
  }
  if (salt.charAt(offset + 2) > "$") {
    err = Error("Missing salt rounds");
    if (callback) {
      nextTick(callback.bind(this, err));
      return;
    } else throw err;
  }
  var r1 = parseInt(salt.substring(offset, offset + 1), 10) * 10, r2 = parseInt(salt.substring(offset + 1, offset + 2), 10), rounds = r1 + r2, real_salt = salt.substring(offset + 3, offset + 25);
  password += minor >= "a" ? "\0" : "";
  var passwordb = utf8Array(password), saltb = base64_decode(real_salt, BCRYPT_SALT_LEN);
  function finish(bytes) {
    var res = [];
    res.push("$2");
    if (minor >= "a") res.push(minor);
    res.push("$");
    if (rounds < 10) res.push("0");
    res.push(rounds.toString());
    res.push("$");
    res.push(base64_encode(saltb, saltb.length));
    res.push(base64_encode(bytes, C_ORIG.length * 4 - 1));
    return res.join("");
  }
  if (typeof callback == "undefined")
    return finish(_crypt(passwordb, saltb, rounds));
  else {
    _crypt(
      passwordb,
      saltb,
      rounds,
      function(err2, bytes) {
        if (err2) callback(err2, null);
        else callback(null, finish(bytes));
      },
      progressCallback
    );
  }
}
function encodeBase64(bytes, length) {
  return base64_encode(bytes, length);
}
function decodeBase64(string4, length) {
  return base64_decode(string4, length);
}
var randomFallback, nextTick, BASE64_CODE, BASE64_INDEX, BCRYPT_SALT_LEN, GENSALT_DEFAULT_LOG2_ROUNDS, BLOWFISH_NUM_ROUNDS, MAX_EXECUTION_TIME, P_ORIG, S_ORIG, C_ORIG, bcryptjs_default;
var init_bcryptjs = __esm({
  "../../node_modules/.pnpm/bcryptjs@3.0.3/node_modules/bcryptjs/index.js"() {
    randomFallback = null;
    nextTick = typeof setImmediate === "function" ? setImmediate : typeof scheduler === "object" && typeof scheduler.postTask === "function" ? scheduler.postTask.bind(scheduler) : setTimeout;
    BASE64_CODE = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split("");
    BASE64_INDEX = [
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      0,
      1,
      54,
      55,
      56,
      57,
      58,
      59,
      60,
      61,
      62,
      63,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      2,
      3,
      4,
      5,
      6,
      7,
      8,
      9,
      10,
      11,
      12,
      13,
      14,
      15,
      16,
      17,
      18,
      19,
      20,
      21,
      22,
      23,
      24,
      25,
      26,
      27,
      -1,
      -1,
      -1,
      -1,
      -1,
      -1,
      28,
      29,
      30,
      31,
      32,
      33,
      34,
      35,
      36,
      37,
      38,
      39,
      40,
      41,
      42,
      43,
      44,
      45,
      46,
      47,
      48,
      49,
      50,
      51,
      52,
      53,
      -1,
      -1,
      -1,
      -1,
      -1
    ];
    BCRYPT_SALT_LEN = 16;
    GENSALT_DEFAULT_LOG2_ROUNDS = 10;
    BLOWFISH_NUM_ROUNDS = 16;
    MAX_EXECUTION_TIME = 100;
    P_ORIG = [
      608135816,
      2242054355,
      320440878,
      57701188,
      2752067618,
      698298832,
      137296536,
      3964562569,
      1160258022,
      953160567,
      3193202383,
      887688300,
      3232508343,
      3380367581,
      1065670069,
      3041331479,
      2450970073,
      2306472731
    ];
    S_ORIG = [
      3509652390,
      2564797868,
      805139163,
      3491422135,
      3101798381,
      1780907670,
      3128725573,
      4046225305,
      614570311,
      3012652279,
      134345442,
      2240740374,
      1667834072,
      1901547113,
      2757295779,
      4103290238,
      227898511,
      1921955416,
      1904987480,
      2182433518,
      2069144605,
      3260701109,
      2620446009,
      720527379,
      3318853667,
      677414384,
      3393288472,
      3101374703,
      2390351024,
      1614419982,
      1822297739,
      2954791486,
      3608508353,
      3174124327,
      2024746970,
      1432378464,
      3864339955,
      2857741204,
      1464375394,
      1676153920,
      1439316330,
      715854006,
      3033291828,
      289532110,
      2706671279,
      2087905683,
      3018724369,
      1668267050,
      732546397,
      1947742710,
      3462151702,
      2609353502,
      2950085171,
      1814351708,
      2050118529,
      680887927,
      999245976,
      1800124847,
      3300911131,
      1713906067,
      1641548236,
      4213287313,
      1216130144,
      1575780402,
      4018429277,
      3917837745,
      3693486850,
      3949271944,
      596196993,
      3549867205,
      258830323,
      2213823033,
      772490370,
      2760122372,
      1774776394,
      2652871518,
      566650946,
      4142492826,
      1728879713,
      2882767088,
      1783734482,
      3629395816,
      2517608232,
      2874225571,
      1861159788,
      326777828,
      3124490320,
      2130389656,
      2716951837,
      967770486,
      1724537150,
      2185432712,
      2364442137,
      1164943284,
      2105845187,
      998989502,
      3765401048,
      2244026483,
      1075463327,
      1455516326,
      1322494562,
      910128902,
      469688178,
      1117454909,
      936433444,
      3490320968,
      3675253459,
      1240580251,
      122909385,
      2157517691,
      634681816,
      4142456567,
      3825094682,
      3061402683,
      2540495037,
      79693498,
      3249098678,
      1084186820,
      1583128258,
      426386531,
      1761308591,
      1047286709,
      322548459,
      995290223,
      1845252383,
      2603652396,
      3431023940,
      2942221577,
      3202600964,
      3727903485,
      1712269319,
      422464435,
      3234572375,
      1170764815,
      3523960633,
      3117677531,
      1434042557,
      442511882,
      3600875718,
      1076654713,
      1738483198,
      4213154764,
      2393238008,
      3677496056,
      1014306527,
      4251020053,
      793779912,
      2902807211,
      842905082,
      4246964064,
      1395751752,
      1040244610,
      2656851899,
      3396308128,
      445077038,
      3742853595,
      3577915638,
      679411651,
      2892444358,
      2354009459,
      1767581616,
      3150600392,
      3791627101,
      3102740896,
      284835224,
      4246832056,
      1258075500,
      768725851,
      2589189241,
      3069724005,
      3532540348,
      1274779536,
      3789419226,
      2764799539,
      1660621633,
      3471099624,
      4011903706,
      913787905,
      3497959166,
      737222580,
      2514213453,
      2928710040,
      3937242737,
      1804850592,
      3499020752,
      2949064160,
      2386320175,
      2390070455,
      2415321851,
      4061277028,
      2290661394,
      2416832540,
      1336762016,
      1754252060,
      3520065937,
      3014181293,
      791618072,
      3188594551,
      3933548030,
      2332172193,
      3852520463,
      3043980520,
      413987798,
      3465142937,
      3030929376,
      4245938359,
      2093235073,
      3534596313,
      375366246,
      2157278981,
      2479649556,
      555357303,
      3870105701,
      2008414854,
      3344188149,
      4221384143,
      3956125452,
      2067696032,
      3594591187,
      2921233993,
      2428461,
      544322398,
      577241275,
      1471733935,
      610547355,
      4027169054,
      1432588573,
      1507829418,
      2025931657,
      3646575487,
      545086370,
      48609733,
      2200306550,
      1653985193,
      298326376,
      1316178497,
      3007786442,
      2064951626,
      458293330,
      2589141269,
      3591329599,
      3164325604,
      727753846,
      2179363840,
      146436021,
      1461446943,
      4069977195,
      705550613,
      3059967265,
      3887724982,
      4281599278,
      3313849956,
      1404054877,
      2845806497,
      146425753,
      1854211946,
      1266315497,
      3048417604,
      3681880366,
      3289982499,
      290971e4,
      1235738493,
      2632868024,
      2414719590,
      3970600049,
      1771706367,
      1449415276,
      3266420449,
      422970021,
      1963543593,
      2690192192,
      3826793022,
      1062508698,
      1531092325,
      1804592342,
      2583117782,
      2714934279,
      4024971509,
      1294809318,
      4028980673,
      1289560198,
      2221992742,
      1669523910,
      35572830,
      157838143,
      1052438473,
      1016535060,
      1802137761,
      1753167236,
      1386275462,
      3080475397,
      2857371447,
      1040679964,
      2145300060,
      2390574316,
      1461121720,
      2956646967,
      4031777805,
      4028374788,
      33600511,
      2920084762,
      1018524850,
      629373528,
      3691585981,
      3515945977,
      2091462646,
      2486323059,
      586499841,
      988145025,
      935516892,
      3367335476,
      2599673255,
      2839830854,
      265290510,
      3972581182,
      2759138881,
      3795373465,
      1005194799,
      847297441,
      406762289,
      1314163512,
      1332590856,
      1866599683,
      4127851711,
      750260880,
      613907577,
      1450815602,
      3165620655,
      3734664991,
      3650291728,
      3012275730,
      3704569646,
      1427272223,
      778793252,
      1343938022,
      2676280711,
      2052605720,
      1946737175,
      3164576444,
      3914038668,
      3967478842,
      3682934266,
      1661551462,
      3294938066,
      4011595847,
      840292616,
      3712170807,
      616741398,
      312560963,
      711312465,
      1351876610,
      322626781,
      1910503582,
      271666773,
      2175563734,
      1594956187,
      70604529,
      3617834859,
      1007753275,
      1495573769,
      4069517037,
      2549218298,
      2663038764,
      504708206,
      2263041392,
      3941167025,
      2249088522,
      1514023603,
      1998579484,
      1312622330,
      694541497,
      2582060303,
      2151582166,
      1382467621,
      776784248,
      2618340202,
      3323268794,
      2497899128,
      2784771155,
      503983604,
      4076293799,
      907881277,
      423175695,
      432175456,
      1378068232,
      4145222326,
      3954048622,
      3938656102,
      3820766613,
      2793130115,
      2977904593,
      26017576,
      3274890735,
      3194772133,
      1700274565,
      1756076034,
      4006520079,
      3677328699,
      720338349,
      1533947780,
      354530856,
      688349552,
      3973924725,
      1637815568,
      332179504,
      3949051286,
      53804574,
      2852348879,
      3044236432,
      1282449977,
      3583942155,
      3416972820,
      4006381244,
      1617046695,
      2628476075,
      3002303598,
      1686838959,
      431878346,
      2686675385,
      1700445008,
      1080580658,
      1009431731,
      832498133,
      3223435511,
      2605976345,
      2271191193,
      2516031870,
      1648197032,
      4164389018,
      2548247927,
      300782431,
      375919233,
      238389289,
      3353747414,
      2531188641,
      2019080857,
      1475708069,
      455242339,
      2609103871,
      448939670,
      3451063019,
      1395535956,
      2413381860,
      1841049896,
      1491858159,
      885456874,
      4264095073,
      4001119347,
      1565136089,
      3898914787,
      1108368660,
      540939232,
      1173283510,
      2745871338,
      3681308437,
      4207628240,
      3343053890,
      4016749493,
      1699691293,
      1103962373,
      3625875870,
      2256883143,
      3830138730,
      1031889488,
      3479347698,
      1535977030,
      4236805024,
      3251091107,
      2132092099,
      1774941330,
      1199868427,
      1452454533,
      157007616,
      2904115357,
      342012276,
      595725824,
      1480756522,
      206960106,
      497939518,
      591360097,
      863170706,
      2375253569,
      3596610801,
      1814182875,
      2094937945,
      3421402208,
      1082520231,
      3463918190,
      2785509508,
      435703966,
      3908032597,
      1641649973,
      2842273706,
      3305899714,
      1510255612,
      2148256476,
      2655287854,
      3276092548,
      4258621189,
      236887753,
      3681803219,
      274041037,
      1734335097,
      3815195456,
      3317970021,
      1899903192,
      1026095262,
      4050517792,
      356393447,
      2410691914,
      3873677099,
      3682840055,
      3913112168,
      2491498743,
      4132185628,
      2489919796,
      1091903735,
      1979897079,
      3170134830,
      3567386728,
      3557303409,
      857797738,
      1136121015,
      1342202287,
      507115054,
      2535736646,
      337727348,
      3213592640,
      1301675037,
      2528481711,
      1895095763,
      1721773893,
      3216771564,
      62756741,
      2142006736,
      835421444,
      2531993523,
      1442658625,
      3659876326,
      2882144922,
      676362277,
      1392781812,
      170690266,
      3921047035,
      1759253602,
      3611846912,
      1745797284,
      664899054,
      1329594018,
      3901205900,
      3045908486,
      2062866102,
      2865634940,
      3543621612,
      3464012697,
      1080764994,
      553557557,
      3656615353,
      3996768171,
      991055499,
      499776247,
      1265440854,
      648242737,
      3940784050,
      980351604,
      3713745714,
      1749149687,
      3396870395,
      4211799374,
      3640570775,
      1161844396,
      3125318951,
      1431517754,
      545492359,
      4268468663,
      3499529547,
      1437099964,
      2702547544,
      3433638243,
      2581715763,
      2787789398,
      1060185593,
      1593081372,
      2418618748,
      4260947970,
      69676912,
      2159744348,
      86519011,
      2512459080,
      3838209314,
      1220612927,
      3339683548,
      133810670,
      1090789135,
      1078426020,
      1569222167,
      845107691,
      3583754449,
      4072456591,
      1091646820,
      628848692,
      1613405280,
      3757631651,
      526609435,
      236106946,
      48312990,
      2942717905,
      3402727701,
      1797494240,
      859738849,
      992217954,
      4005476642,
      2243076622,
      3870952857,
      3732016268,
      765654824,
      3490871365,
      2511836413,
      1685915746,
      3888969200,
      1414112111,
      2273134842,
      3281911079,
      4080962846,
      172450625,
      2569994100,
      980381355,
      4109958455,
      2819808352,
      2716589560,
      2568741196,
      3681446669,
      3329971472,
      1835478071,
      660984891,
      3704678404,
      4045999559,
      3422617507,
      3040415634,
      1762651403,
      1719377915,
      3470491036,
      2693910283,
      3642056355,
      3138596744,
      1364962596,
      2073328063,
      1983633131,
      926494387,
      3423689081,
      2150032023,
      4096667949,
      1749200295,
      3328846651,
      309677260,
      2016342300,
      1779581495,
      3079819751,
      111262694,
      1274766160,
      443224088,
      298511866,
      1025883608,
      3806446537,
      1145181785,
      168956806,
      3641502830,
      3584813610,
      1689216846,
      3666258015,
      3200248200,
      1692713982,
      2646376535,
      4042768518,
      1618508792,
      1610833997,
      3523052358,
      4130873264,
      2001055236,
      3610705100,
      2202168115,
      4028541809,
      2961195399,
      1006657119,
      2006996926,
      3186142756,
      1430667929,
      3210227297,
      1314452623,
      4074634658,
      4101304120,
      2273951170,
      1399257539,
      3367210612,
      3027628629,
      1190975929,
      2062231137,
      2333990788,
      2221543033,
      2438960610,
      1181637006,
      548689776,
      2362791313,
      3372408396,
      3104550113,
      3145860560,
      296247880,
      1970579870,
      3078560182,
      3769228297,
      1714227617,
      3291629107,
      3898220290,
      166772364,
      1251581989,
      493813264,
      448347421,
      195405023,
      2709975567,
      677966185,
      3703036547,
      1463355134,
      2715995803,
      1338867538,
      1343315457,
      2802222074,
      2684532164,
      233230375,
      2599980071,
      2000651841,
      3277868038,
      1638401717,
      4028070440,
      3237316320,
      6314154,
      819756386,
      300326615,
      590932579,
      1405279636,
      3267499572,
      3150704214,
      2428286686,
      3959192993,
      3461946742,
      1862657033,
      1266418056,
      963775037,
      2089974820,
      2263052895,
      1917689273,
      448879540,
      3550394620,
      3981727096,
      150775221,
      3627908307,
      1303187396,
      508620638,
      2975983352,
      2726630617,
      1817252668,
      1876281319,
      1457606340,
      908771278,
      3720792119,
      3617206836,
      2455994898,
      1729034894,
      1080033504,
      976866871,
      3556439503,
      2881648439,
      1522871579,
      1555064734,
      1336096578,
      3548522304,
      2579274686,
      3574697629,
      3205460757,
      3593280638,
      3338716283,
      3079412587,
      564236357,
      2993598910,
      1781952180,
      1464380207,
      3163844217,
      3332601554,
      1699332808,
      1393555694,
      1183702653,
      3581086237,
      1288719814,
      691649499,
      2847557200,
      2895455976,
      3193889540,
      2717570544,
      1781354906,
      1676643554,
      2592534050,
      3230253752,
      1126444790,
      2770207658,
      2633158820,
      2210423226,
      2615765581,
      2414155088,
      3127139286,
      673620729,
      2805611233,
      1269405062,
      4015350505,
      3341807571,
      4149409754,
      1057255273,
      2012875353,
      2162469141,
      2276492801,
      2601117357,
      993977747,
      3918593370,
      2654263191,
      753973209,
      36408145,
      2530585658,
      25011837,
      3520020182,
      2088578344,
      530523599,
      2918365339,
      1524020338,
      1518925132,
      3760827505,
      3759777254,
      1202760957,
      3985898139,
      3906192525,
      674977740,
      4174734889,
      2031300136,
      2019492241,
      3983892565,
      4153806404,
      3822280332,
      352677332,
      2297720250,
      60907813,
      90501309,
      3286998549,
      1016092578,
      2535922412,
      2839152426,
      457141659,
      509813237,
      4120667899,
      652014361,
      1966332200,
      2975202805,
      55981186,
      2327461051,
      676427537,
      3255491064,
      2882294119,
      3433927263,
      1307055953,
      942726286,
      933058658,
      2468411793,
      3933900994,
      4215176142,
      1361170020,
      2001714738,
      2830558078,
      3274259782,
      1222529897,
      1679025792,
      2729314320,
      3714953764,
      1770335741,
      151462246,
      3013232138,
      1682292957,
      1483529935,
      471910574,
      1539241949,
      458788160,
      3436315007,
      1807016891,
      3718408830,
      978976581,
      1043663428,
      3165965781,
      1927990952,
      4200891579,
      2372276910,
      3208408903,
      3533431907,
      1412390302,
      2931980059,
      4132332400,
      1947078029,
      3881505623,
      4168226417,
      2941484381,
      1077988104,
      1320477388,
      886195818,
      18198404,
      3786409e3,
      2509781533,
      112762804,
      3463356488,
      1866414978,
      891333506,
      18488651,
      661792760,
      1628790961,
      3885187036,
      3141171499,
      876946877,
      2693282273,
      1372485963,
      791857591,
      2686433993,
      3759982718,
      3167212022,
      3472953795,
      2716379847,
      445679433,
      3561995674,
      3504004811,
      3574258232,
      54117162,
      3331405415,
      2381918588,
      3769707343,
      4154350007,
      1140177722,
      4074052095,
      668550556,
      3214352940,
      367459370,
      261225585,
      2610173221,
      4209349473,
      3468074219,
      3265815641,
      314222801,
      3066103646,
      3808782860,
      282218597,
      3406013506,
      3773591054,
      379116347,
      1285071038,
      846784868,
      2669647154,
      3771962079,
      3550491691,
      2305946142,
      453669953,
      1268987020,
      3317592352,
      3279303384,
      3744833421,
      2610507566,
      3859509063,
      266596637,
      3847019092,
      517658769,
      3462560207,
      3443424879,
      370717030,
      4247526661,
      2224018117,
      4143653529,
      4112773975,
      2788324899,
      2477274417,
      1456262402,
      2901442914,
      1517677493,
      1846949527,
      2295493580,
      3734397586,
      2176403920,
      1280348187,
      1908823572,
      3871786941,
      846861322,
      1172426758,
      3287448474,
      3383383037,
      1655181056,
      3139813346,
      901632758,
      1897031941,
      2986607138,
      3066810236,
      3447102507,
      1393639104,
      373351379,
      950779232,
      625454576,
      3124240540,
      4148612726,
      2007998917,
      544563296,
      2244738638,
      2330496472,
      2058025392,
      1291430526,
      424198748,
      50039436,
      29584100,
      3605783033,
      2429876329,
      2791104160,
      1057563949,
      3255363231,
      3075367218,
      3463963227,
      1469046755,
      985887462
    ];
    C_ORIG = [
      1332899944,
      1700884034,
      1701343084,
      1684370003,
      1668446532,
      1869963892
    ];
    bcryptjs_default = {
      setRandomFallback,
      genSaltSync,
      genSalt,
      hashSync,
      hash,
      compareSync,
      compare,
      getRounds,
      getSalt,
      truncates,
      encodeBase64,
      decodeBase64
    };
  }
});

// ../../node_modules/.pnpm/postgres-array@2.0.0/node_modules/postgres-array/index.js
var require_postgres_array = __commonJS({
  "../../node_modules/.pnpm/postgres-array@2.0.0/node_modules/postgres-array/index.js"(exports) {
    "use strict";
    exports.parse = function(source, transform2) {
      return new ArrayParser(source, transform2).parse();
    };
    var ArrayParser = class _ArrayParser {
      constructor(source, transform2) {
        this.source = source;
        this.transform = transform2 || identity;
        this.position = 0;
        this.entries = [];
        this.recorded = [];
        this.dimension = 0;
      }
      isEof() {
        return this.position >= this.source.length;
      }
      nextCharacter() {
        var character = this.source[this.position++];
        if (character === "\\") {
          return {
            value: this.source[this.position++],
            escaped: true
          };
        }
        return {
          value: character,
          escaped: false
        };
      }
      record(character) {
        this.recorded.push(character);
      }
      newEntry(includeEmpty) {
        var entry;
        if (this.recorded.length > 0 || includeEmpty) {
          entry = this.recorded.join("");
          if (entry === "NULL" && !includeEmpty) {
            entry = null;
          }
          if (entry !== null) entry = this.transform(entry);
          this.entries.push(entry);
          this.recorded = [];
        }
      }
      consumeDimensions() {
        if (this.source[0] === "[") {
          while (!this.isEof()) {
            var char2 = this.nextCharacter();
            if (char2.value === "=") break;
          }
        }
      }
      parse(nested) {
        var character, parser, quote;
        this.consumeDimensions();
        while (!this.isEof()) {
          character = this.nextCharacter();
          if (character.value === "{" && !quote) {
            this.dimension++;
            if (this.dimension > 1) {
              parser = new _ArrayParser(this.source.substr(this.position - 1), this.transform);
              this.entries.push(parser.parse(true));
              this.position += parser.position - 2;
            }
          } else if (character.value === "}" && !quote) {
            this.dimension--;
            if (!this.dimension) {
              this.newEntry();
              if (nested) return this.entries;
            }
          } else if (character.value === '"' && !character.escaped) {
            if (quote) this.newEntry(true);
            quote = !quote;
          } else if (character.value === "," && !quote) {
            this.newEntry();
          } else {
            this.record(character.value);
          }
        }
        if (this.dimension !== 0) {
          throw new Error("array dimension not balanced");
        }
        return this.entries;
      }
    };
    function identity(value) {
      return value;
    }
  }
});

// ../../node_modules/.pnpm/pg-types@2.2.0/node_modules/pg-types/lib/arrayParser.js
var require_arrayParser = __commonJS({
  "../../node_modules/.pnpm/pg-types@2.2.0/node_modules/pg-types/lib/arrayParser.js"(exports, module) {
    var array2 = require_postgres_array();
    module.exports = {
      create: function(source, transform2) {
        return {
          parse: function() {
            return array2.parse(source, transform2);
          }
        };
      }
    };
  }
});

// ../../node_modules/.pnpm/postgres-date@1.0.7/node_modules/postgres-date/index.js
var require_postgres_date = __commonJS({
  "../../node_modules/.pnpm/postgres-date@1.0.7/node_modules/postgres-date/index.js"(exports, module) {
    "use strict";
    var DATE_TIME = /(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/;
    var DATE = /^(\d{1,})-(\d{2})-(\d{2})( BC)?$/;
    var TIME_ZONE = /([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/;
    var INFINITY = /^-?infinity$/;
    module.exports = function parseDate(isoDate) {
      if (INFINITY.test(isoDate)) {
        return Number(isoDate.replace("i", "I"));
      }
      var matches = DATE_TIME.exec(isoDate);
      if (!matches) {
        return getDate(isoDate) || null;
      }
      var isBC = !!matches[8];
      var year = parseInt(matches[1], 10);
      if (isBC) {
        year = bcYearToNegativeYear(year);
      }
      var month = parseInt(matches[2], 10) - 1;
      var day = matches[3];
      var hour = parseInt(matches[4], 10);
      var minute = parseInt(matches[5], 10);
      var second = parseInt(matches[6], 10);
      var ms = matches[7];
      ms = ms ? 1e3 * parseFloat(ms) : 0;
      var date6;
      var offset = timeZoneOffset(isoDate);
      if (offset != null) {
        date6 = new Date(Date.UTC(year, month, day, hour, minute, second, ms));
        if (is0To99(year)) {
          date6.setUTCFullYear(year);
        }
        if (offset !== 0) {
          date6.setTime(date6.getTime() - offset);
        }
      } else {
        date6 = new Date(year, month, day, hour, minute, second, ms);
        if (is0To99(year)) {
          date6.setFullYear(year);
        }
      }
      return date6;
    };
    function getDate(isoDate) {
      var matches = DATE.exec(isoDate);
      if (!matches) {
        return;
      }
      var year = parseInt(matches[1], 10);
      var isBC = !!matches[4];
      if (isBC) {
        year = bcYearToNegativeYear(year);
      }
      var month = parseInt(matches[2], 10) - 1;
      var day = matches[3];
      var date6 = new Date(year, month, day);
      if (is0To99(year)) {
        date6.setFullYear(year);
      }
      return date6;
    }
    function timeZoneOffset(isoDate) {
      if (isoDate.endsWith("+00")) {
        return 0;
      }
      var zone = TIME_ZONE.exec(isoDate.split(" ")[1]);
      if (!zone) return;
      var type = zone[1];
      if (type === "Z") {
        return 0;
      }
      var sign = type === "-" ? -1 : 1;
      var offset = parseInt(zone[2], 10) * 3600 + parseInt(zone[3] || 0, 10) * 60 + parseInt(zone[4] || 0, 10);
      return offset * sign * 1e3;
    }
    function bcYearToNegativeYear(year) {
      return -(year - 1);
    }
    function is0To99(num) {
      return num >= 0 && num < 100;
    }
  }
});

// ../../node_modules/.pnpm/xtend@4.0.2/node_modules/xtend/mutable.js
var require_mutable = __commonJS({
  "../../node_modules/.pnpm/xtend@4.0.2/node_modules/xtend/mutable.js"(exports, module) {
    module.exports = extend2;
    var hasOwnProperty = Object.prototype.hasOwnProperty;
    function extend2(target) {
      for (var i = 1; i < arguments.length; i++) {
        var source = arguments[i];
        for (var key in source) {
          if (hasOwnProperty.call(source, key)) {
            target[key] = source[key];
          }
        }
      }
      return target;
    }
  }
});

// ../../node_modules/.pnpm/postgres-interval@1.2.0/node_modules/postgres-interval/index.js
var require_postgres_interval = __commonJS({
  "../../node_modules/.pnpm/postgres-interval@1.2.0/node_modules/postgres-interval/index.js"(exports, module) {
    "use strict";
    var extend2 = require_mutable();
    module.exports = PostgresInterval;
    function PostgresInterval(raw) {
      if (!(this instanceof PostgresInterval)) {
        return new PostgresInterval(raw);
      }
      extend2(this, parse3(raw));
    }
    var properties = ["seconds", "minutes", "hours", "days", "months", "years"];
    PostgresInterval.prototype.toPostgres = function() {
      var filtered = properties.filter(this.hasOwnProperty, this);
      if (this.milliseconds && filtered.indexOf("seconds") < 0) {
        filtered.push("seconds");
      }
      if (filtered.length === 0) return "0";
      return filtered.map(function(property) {
        var value = this[property] || 0;
        if (property === "seconds" && this.milliseconds) {
          value = (value + this.milliseconds / 1e3).toFixed(6).replace(/\.?0+$/, "");
        }
        return value + " " + property;
      }, this).join(" ");
    };
    var propertiesISOEquivalent = {
      years: "Y",
      months: "M",
      days: "D",
      hours: "H",
      minutes: "M",
      seconds: "S"
    };
    var dateProperties = ["years", "months", "days"];
    var timeProperties = ["hours", "minutes", "seconds"];
    PostgresInterval.prototype.toISOString = PostgresInterval.prototype.toISO = function() {
      var datePart = dateProperties.map(buildProperty, this).join("");
      var timePart = timeProperties.map(buildProperty, this).join("");
      return "P" + datePart + "T" + timePart;
      function buildProperty(property) {
        var value = this[property] || 0;
        if (property === "seconds" && this.milliseconds) {
          value = (value + this.milliseconds / 1e3).toFixed(6).replace(/0+$/, "");
        }
        return value + propertiesISOEquivalent[property];
      }
    };
    var NUMBER = "([+-]?\\d+)";
    var YEAR = NUMBER + "\\s+years?";
    var MONTH = NUMBER + "\\s+mons?";
    var DAY = NUMBER + "\\s+days?";
    var TIME = "([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?";
    var INTERVAL = new RegExp([YEAR, MONTH, DAY, TIME].map(function(regexString) {
      return "(" + regexString + ")?";
    }).join("\\s*"));
    var positions = {
      years: 2,
      months: 4,
      days: 6,
      hours: 9,
      minutes: 10,
      seconds: 11,
      milliseconds: 12
    };
    var negatives = ["hours", "minutes", "seconds", "milliseconds"];
    function parseMilliseconds(fraction) {
      var microseconds = fraction + "000000".slice(fraction.length);
      return parseInt(microseconds, 10) / 1e3;
    }
    function parse3(interval2) {
      if (!interval2) return {};
      var matches = INTERVAL.exec(interval2);
      var isNegative = matches[8] === "-";
      return Object.keys(positions).reduce(function(parsed, property) {
        var position = positions[property];
        var value = matches[position];
        if (!value) return parsed;
        value = property === "milliseconds" ? parseMilliseconds(value) : parseInt(value, 10);
        if (!value) return parsed;
        if (isNegative && ~negatives.indexOf(property)) {
          value *= -1;
        }
        parsed[property] = value;
        return parsed;
      }, {});
    }
  }
});

// ../../node_modules/.pnpm/postgres-bytea@1.0.1/node_modules/postgres-bytea/index.js
var require_postgres_bytea = __commonJS({
  "../../node_modules/.pnpm/postgres-bytea@1.0.1/node_modules/postgres-bytea/index.js"(exports, module) {
    "use strict";
    var bufferFrom = Buffer.from || Buffer;
    module.exports = function parseBytea(input) {
      if (/^\\x/.test(input)) {
        return bufferFrom(input.substr(2), "hex");
      }
      var output = "";
      var i = 0;
      while (i < input.length) {
        if (input[i] !== "\\") {
          output += input[i];
          ++i;
        } else {
          if (/[0-7]{3}/.test(input.substr(i + 1, 3))) {
            output += String.fromCharCode(parseInt(input.substr(i + 1, 3), 8));
            i += 4;
          } else {
            var backslashes = 1;
            while (i + backslashes < input.length && input[i + backslashes] === "\\") {
              backslashes++;
            }
            for (var k = 0; k < Math.floor(backslashes / 2); ++k) {
              output += "\\";
            }
            i += Math.floor(backslashes / 2) * 2;
          }
        }
      }
      return bufferFrom(output, "binary");
    };
  }
});

// ../../node_modules/.pnpm/pg-types@2.2.0/node_modules/pg-types/lib/textParsers.js
var require_textParsers = __commonJS({
  "../../node_modules/.pnpm/pg-types@2.2.0/node_modules/pg-types/lib/textParsers.js"(exports, module) {
    var array2 = require_postgres_array();
    var arrayParser = require_arrayParser();
    var parseDate = require_postgres_date();
    var parseInterval = require_postgres_interval();
    var parseByteA = require_postgres_bytea();
    function allowNull(fn) {
      return function nullAllowed(value) {
        if (value === null) return value;
        return fn(value);
      };
    }
    function parseBool(value) {
      if (value === null) return value;
      return value === "TRUE" || value === "t" || value === "true" || value === "y" || value === "yes" || value === "on" || value === "1";
    }
    function parseBoolArray(value) {
      if (!value) return null;
      return array2.parse(value, parseBool);
    }
    function parseBaseTenInt(string4) {
      return parseInt(string4, 10);
    }
    function parseIntegerArray(value) {
      if (!value) return null;
      return array2.parse(value, allowNull(parseBaseTenInt));
    }
    function parseBigIntegerArray(value) {
      if (!value) return null;
      return array2.parse(value, allowNull(function(entry) {
        return parseBigInteger(entry).trim();
      }));
    }
    var parsePointArray = function(value) {
      if (!value) {
        return null;
      }
      var p = arrayParser.create(value, function(entry) {
        if (entry !== null) {
          entry = parsePoint(entry);
        }
        return entry;
      });
      return p.parse();
    };
    var parseFloatArray = function(value) {
      if (!value) {
        return null;
      }
      var p = arrayParser.create(value, function(entry) {
        if (entry !== null) {
          entry = parseFloat(entry);
        }
        return entry;
      });
      return p.parse();
    };
    var parseStringArray = function(value) {
      if (!value) {
        return null;
      }
      var p = arrayParser.create(value);
      return p.parse();
    };
    var parseDateArray = function(value) {
      if (!value) {
        return null;
      }
      var p = arrayParser.create(value, function(entry) {
        if (entry !== null) {
          entry = parseDate(entry);
        }
        return entry;
      });
      return p.parse();
    };
    var parseIntervalArray = function(value) {
      if (!value) {
        return null;
      }
      var p = arrayParser.create(value, function(entry) {
        if (entry !== null) {
          entry = parseInterval(entry);
        }
        return entry;
      });
      return p.parse();
    };
    var parseByteAArray = function(value) {
      if (!value) {
        return null;
      }
      return array2.parse(value, allowNull(parseByteA));
    };
    var parseInteger = function(value) {
      return parseInt(value, 10);
    };
    var parseBigInteger = function(value) {
      var valStr = String(value);
      if (/^\d+$/.test(valStr)) {
        return valStr;
      }
      return value;
    };
    var parseJsonArray = function(value) {
      if (!value) {
        return null;
      }
      return array2.parse(value, allowNull(JSON.parse));
    };
    var parsePoint = function(value) {
      if (value[0] !== "(") {
        return null;
      }
      value = value.substring(1, value.length - 1).split(",");
      return {
        x: parseFloat(value[0]),
        y: parseFloat(value[1])
      };
    };
    var parseCircle = function(value) {
      if (value[0] !== "<" && value[1] !== "(") {
        return null;
      }
      var point2 = "(";
      var radius = "";
      var pointParsed = false;
      for (var i = 2; i < value.length - 1; i++) {
        if (!pointParsed) {
          point2 += value[i];
        }
        if (value[i] === ")") {
          pointParsed = true;
          continue;
        } else if (!pointParsed) {
          continue;
        }
        if (value[i] === ",") {
          continue;
        }
        radius += value[i];
      }
      var result = parsePoint(point2);
      result.radius = parseFloat(radius);
      return result;
    };
    var init = function(register) {
      register(20, parseBigInteger);
      register(21, parseInteger);
      register(23, parseInteger);
      register(26, parseInteger);
      register(700, parseFloat);
      register(701, parseFloat);
      register(16, parseBool);
      register(1082, parseDate);
      register(1114, parseDate);
      register(1184, parseDate);
      register(600, parsePoint);
      register(651, parseStringArray);
      register(718, parseCircle);
      register(1e3, parseBoolArray);
      register(1001, parseByteAArray);
      register(1005, parseIntegerArray);
      register(1007, parseIntegerArray);
      register(1028, parseIntegerArray);
      register(1016, parseBigIntegerArray);
      register(1017, parsePointArray);
      register(1021, parseFloatArray);
      register(1022, parseFloatArray);
      register(1231, parseFloatArray);
      register(1014, parseStringArray);
      register(1015, parseStringArray);
      register(1008, parseStringArray);
      register(1009, parseStringArray);
      register(1040, parseStringArray);
      register(1041, parseStringArray);
      register(1115, parseDateArray);
      register(1182, parseDateArray);
      register(1185, parseDateArray);
      register(1186, parseInterval);
      register(1187, parseIntervalArray);
      register(17, parseByteA);
      register(114, JSON.parse.bind(JSON));
      register(3802, JSON.parse.bind(JSON));
      register(199, parseJsonArray);
      register(3807, parseJsonArray);
      register(3907, parseStringArray);
      register(2951, parseStringArray);
      register(791, parseStringArray);
      register(1183, parseStringArray);
      register(1270, parseStringArray);
    };
    module.exports = {
      init
    };
  }
});

// ../../node_modules/.pnpm/pg-int8@1.0.1/node_modules/pg-int8/index.js
var require_pg_int8 = __commonJS({
  "../../node_modules/.pnpm/pg-int8@1.0.1/node_modules/pg-int8/index.js"(exports, module) {
    "use strict";
    var BASE = 1e6;
    function readInt8(buffer) {
      var high = buffer.readInt32BE(0);
      var low = buffer.readUInt32BE(4);
      var sign = "";
      if (high < 0) {
        high = ~high + (low === 0);
        low = ~low + 1 >>> 0;
        sign = "-";
      }
      var result = "";
      var carry;
      var t;
      var digits;
      var pad;
      var l;
      var i;
      {
        carry = high % BASE;
        high = high / BASE >>> 0;
        t = 4294967296 * carry + low;
        low = t / BASE >>> 0;
        digits = "" + (t - BASE * low);
        if (low === 0 && high === 0) {
          return sign + digits + result;
        }
        pad = "";
        l = 6 - digits.length;
        for (i = 0; i < l; i++) {
          pad += "0";
        }
        result = pad + digits + result;
      }
      {
        carry = high % BASE;
        high = high / BASE >>> 0;
        t = 4294967296 * carry + low;
        low = t / BASE >>> 0;
        digits = "" + (t - BASE * low);
        if (low === 0 && high === 0) {
          return sign + digits + result;
        }
        pad = "";
        l = 6 - digits.length;
        for (i = 0; i < l; i++) {
          pad += "0";
        }
        result = pad + digits + result;
      }
      {
        carry = high % BASE;
        high = high / BASE >>> 0;
        t = 4294967296 * carry + low;
        low = t / BASE >>> 0;
        digits = "" + (t - BASE * low);
        if (low === 0 && high === 0) {
          return sign + digits + result;
        }
        pad = "";
        l = 6 - digits.length;
        for (i = 0; i < l; i++) {
          pad += "0";
        }
        result = pad + digits + result;
      }
      {
        carry = high % BASE;
        t = 4294967296 * carry + low;
        digits = "" + t % BASE;
        return sign + digits + result;
      }
    }
    module.exports = readInt8;
  }
});

// ../../node_modules/.pnpm/pg-types@2.2.0/node_modules/pg-types/lib/binaryParsers.js
var require_binaryParsers = __commonJS({
  "../../node_modules/.pnpm/pg-types@2.2.0/node_modules/pg-types/lib/binaryParsers.js"(exports, module) {
    var parseInt64 = require_pg_int8();
    var parseBits = function(data, bits, offset, invert, callback) {
      offset = offset || 0;
      invert = invert || false;
      callback = callback || function(lastValue, newValue, bits2) {
        return lastValue * Math.pow(2, bits2) + newValue;
      };
      var offsetBytes = offset >> 3;
      var inv = function(value) {
        if (invert) {
          return ~value & 255;
        }
        return value;
      };
      var mask = 255;
      var firstBits = 8 - offset % 8;
      if (bits < firstBits) {
        mask = 255 << 8 - bits & 255;
        firstBits = bits;
      }
      if (offset) {
        mask = mask >> offset % 8;
      }
      var result = 0;
      if (offset % 8 + bits >= 8) {
        result = callback(0, inv(data[offsetBytes]) & mask, firstBits);
      }
      var bytes = bits + offset >> 3;
      for (var i = offsetBytes + 1; i < bytes; i++) {
        result = callback(result, inv(data[i]), 8);
      }
      var lastBits = (bits + offset) % 8;
      if (lastBits > 0) {
        result = callback(result, inv(data[bytes]) >> 8 - lastBits, lastBits);
      }
      return result;
    };
    var parseFloatFromBits = function(data, precisionBits, exponentBits) {
      var bias = Math.pow(2, exponentBits - 1) - 1;
      var sign = parseBits(data, 1);
      var exponent = parseBits(data, exponentBits, 1);
      if (exponent === 0) {
        return 0;
      }
      var precisionBitsCounter = 1;
      var parsePrecisionBits = function(lastValue, newValue, bits) {
        if (lastValue === 0) {
          lastValue = 1;
        }
        for (var i = 1; i <= bits; i++) {
          precisionBitsCounter /= 2;
          if ((newValue & 1 << bits - i) > 0) {
            lastValue += precisionBitsCounter;
          }
        }
        return lastValue;
      };
      var mantissa = parseBits(data, precisionBits, exponentBits + 1, false, parsePrecisionBits);
      if (exponent == Math.pow(2, exponentBits + 1) - 1) {
        if (mantissa === 0) {
          return sign === 0 ? Infinity : -Infinity;
        }
        return NaN;
      }
      return (sign === 0 ? 1 : -1) * Math.pow(2, exponent - bias) * mantissa;
    };
    var parseInt16 = function(value) {
      if (parseBits(value, 1) == 1) {
        return -1 * (parseBits(value, 15, 1, true) + 1);
      }
      return parseBits(value, 15, 1);
    };
    var parseInt32 = function(value) {
      if (parseBits(value, 1) == 1) {
        return -1 * (parseBits(value, 31, 1, true) + 1);
      }
      return parseBits(value, 31, 1);
    };
    var parseFloat32 = function(value) {
      return parseFloatFromBits(value, 23, 8);
    };
    var parseFloat64 = function(value) {
      return parseFloatFromBits(value, 52, 11);
    };
    var parseNumeric = function(value) {
      var sign = parseBits(value, 16, 32);
      if (sign == 49152) {
        return NaN;
      }
      var weight = Math.pow(1e4, parseBits(value, 16, 16));
      var result = 0;
      var digits = [];
      var ndigits = parseBits(value, 16);
      for (var i = 0; i < ndigits; i++) {
        result += parseBits(value, 16, 64 + 16 * i) * weight;
        weight /= 1e4;
      }
      var scale = Math.pow(10, parseBits(value, 16, 48));
      return (sign === 0 ? 1 : -1) * Math.round(result * scale) / scale;
    };
    var parseDate = function(isUTC, value) {
      var sign = parseBits(value, 1);
      var rawValue = parseBits(value, 63, 1);
      var result = new Date((sign === 0 ? 1 : -1) * rawValue / 1e3 + 9466848e5);
      if (!isUTC) {
        result.setTime(result.getTime() + result.getTimezoneOffset() * 6e4);
      }
      result.usec = rawValue % 1e3;
      result.getMicroSeconds = function() {
        return this.usec;
      };
      result.setMicroSeconds = function(value2) {
        this.usec = value2;
      };
      result.getUTCMicroSeconds = function() {
        return this.usec;
      };
      return result;
    };
    var parseArray = function(value) {
      var dim = parseBits(value, 32);
      var flags = parseBits(value, 32, 32);
      var elementType = parseBits(value, 32, 64);
      var offset = 96;
      var dims = [];
      for (var i = 0; i < dim; i++) {
        dims[i] = parseBits(value, 32, offset);
        offset += 32;
        offset += 32;
      }
      var parseElement = function(elementType2) {
        var length = parseBits(value, 32, offset);
        offset += 32;
        if (length == 4294967295) {
          return null;
        }
        var result;
        if (elementType2 == 23 || elementType2 == 20) {
          result = parseBits(value, length * 8, offset);
          offset += length * 8;
          return result;
        } else if (elementType2 == 25) {
          result = value.toString(this.encoding, offset >> 3, (offset += length << 3) >> 3);
          return result;
        } else {
          console.log("ERROR: ElementType not implemented: " + elementType2);
        }
      };
      var parse3 = function(dimension, elementType2) {
        var array2 = [];
        var i2;
        if (dimension.length > 1) {
          var count3 = dimension.shift();
          for (i2 = 0; i2 < count3; i2++) {
            array2[i2] = parse3(dimension, elementType2);
          }
          dimension.unshift(count3);
        } else {
          for (i2 = 0; i2 < dimension[0]; i2++) {
            array2[i2] = parseElement(elementType2);
          }
        }
        return array2;
      };
      return parse3(dims, elementType);
    };
    var parseText = function(value) {
      return value.toString("utf8");
    };
    var parseBool = function(value) {
      if (value === null) return null;
      return parseBits(value, 8) > 0;
    };
    var init = function(register) {
      register(20, parseInt64);
      register(21, parseInt16);
      register(23, parseInt32);
      register(26, parseInt32);
      register(1700, parseNumeric);
      register(700, parseFloat32);
      register(701, parseFloat64);
      register(16, parseBool);
      register(1114, parseDate.bind(null, false));
      register(1184, parseDate.bind(null, true));
      register(1e3, parseArray);
      register(1007, parseArray);
      register(1016, parseArray);
      register(1008, parseArray);
      register(1009, parseArray);
      register(25, parseText);
    };
    module.exports = {
      init
    };
  }
});

// ../../node_modules/.pnpm/pg-types@2.2.0/node_modules/pg-types/lib/builtins.js
var require_builtins = __commonJS({
  "../../node_modules/.pnpm/pg-types@2.2.0/node_modules/pg-types/lib/builtins.js"(exports, module) {
    module.exports = {
      BOOL: 16,
      BYTEA: 17,
      CHAR: 18,
      INT8: 20,
      INT2: 21,
      INT4: 23,
      REGPROC: 24,
      TEXT: 25,
      OID: 26,
      TID: 27,
      XID: 28,
      CID: 29,
      JSON: 114,
      XML: 142,
      PG_NODE_TREE: 194,
      SMGR: 210,
      PATH: 602,
      POLYGON: 604,
      CIDR: 650,
      FLOAT4: 700,
      FLOAT8: 701,
      ABSTIME: 702,
      RELTIME: 703,
      TINTERVAL: 704,
      CIRCLE: 718,
      MACADDR8: 774,
      MONEY: 790,
      MACADDR: 829,
      INET: 869,
      ACLITEM: 1033,
      BPCHAR: 1042,
      VARCHAR: 1043,
      DATE: 1082,
      TIME: 1083,
      TIMESTAMP: 1114,
      TIMESTAMPTZ: 1184,
      INTERVAL: 1186,
      TIMETZ: 1266,
      BIT: 1560,
      VARBIT: 1562,
      NUMERIC: 1700,
      REFCURSOR: 1790,
      REGPROCEDURE: 2202,
      REGOPER: 2203,
      REGOPERATOR: 2204,
      REGCLASS: 2205,
      REGTYPE: 2206,
      UUID: 2950,
      TXID_SNAPSHOT: 2970,
      PG_LSN: 3220,
      PG_NDISTINCT: 3361,
      PG_DEPENDENCIES: 3402,
      TSVECTOR: 3614,
      TSQUERY: 3615,
      GTSVECTOR: 3642,
      REGCONFIG: 3734,
      REGDICTIONARY: 3769,
      JSONB: 3802,
      REGNAMESPACE: 4089,
      REGROLE: 4096
    };
  }
});

// ../../node_modules/.pnpm/pg-types@2.2.0/node_modules/pg-types/index.js
var require_pg_types = __commonJS({
  "../../node_modules/.pnpm/pg-types@2.2.0/node_modules/pg-types/index.js"(exports) {
    var textParsers = require_textParsers();
    var binaryParsers = require_binaryParsers();
    var arrayParser = require_arrayParser();
    var builtinTypes = require_builtins();
    exports.getTypeParser = getTypeParser;
    exports.setTypeParser = setTypeParser;
    exports.arrayParser = arrayParser;
    exports.builtins = builtinTypes;
    var typeParsers = {
      text: {},
      binary: {}
    };
    function noParse(val) {
      return String(val);
    }
    function getTypeParser(oid, format) {
      format = format || "text";
      if (!typeParsers[format]) {
        return noParse;
      }
      return typeParsers[format][oid] || noParse;
    }
    function setTypeParser(oid, format, parseFn) {
      if (typeof format == "function") {
        parseFn = format;
        format = "text";
      }
      typeParsers[format][oid] = parseFn;
    }
    textParsers.init(function(oid, converter) {
      typeParsers.text[oid] = converter;
    });
    binaryParsers.init(function(oid, converter) {
      typeParsers.binary[oid] = converter;
    });
  }
});

// ../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/defaults.js
var require_defaults = __commonJS({
  "../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/defaults.js"(exports, module) {
    "use strict";
    var user;
    try {
      user = process.platform === "win32" ? process.env.USERNAME : process.env.USER;
    } catch {
    }
    module.exports = {
      // database host. defaults to localhost
      host: "localhost",
      // database user's name
      user,
      // name of database to connect
      database: void 0,
      // database user's password
      password: null,
      // a Postgres connection string to be used instead of setting individual connection items
      // NOTE:  Setting this value will cause it to override any other value (such as database or user) defined
      // in the defaults object.
      connectionString: void 0,
      // database port
      port: 5432,
      // number of rows to return at a time from a prepared statement's
      // portal. 0 will return all rows at once
      rows: 0,
      // binary result mode
      binary: false,
      // Connection pool options - see https://github.com/brianc/node-pg-pool
      // number of connections to use in connection pool
      // 0 will disable connection pooling
      max: 10,
      // max milliseconds a client can go unused before it is removed
      // from the pool and destroyed
      idleTimeoutMillis: 3e4,
      client_encoding: "",
      ssl: false,
      application_name: void 0,
      fallback_application_name: void 0,
      options: void 0,
      parseInputDatesAsUTC: false,
      // max milliseconds any query using this connection will execute for before timing out in error.
      // false=unlimited
      statement_timeout: false,
      // Abort any statement that waits longer than the specified duration in milliseconds while attempting to acquire a lock.
      // false=unlimited
      lock_timeout: false,
      // Terminate any session with an open transaction that has been idle for longer than the specified duration in milliseconds
      // false=unlimited
      idle_in_transaction_session_timeout: false,
      // max milliseconds to wait for query to complete (client side)
      query_timeout: false,
      connect_timeout: 0,
      keepalives: 1,
      keepalives_idle: 0
    };
    var pgTypes = require_pg_types();
    var parseBigInteger = pgTypes.getTypeParser(20, "text");
    var parseBigIntegerArray = pgTypes.getTypeParser(1016, "text");
    module.exports.__defineSetter__("parseInt8", function(val) {
      pgTypes.setTypeParser(20, "text", val ? pgTypes.getTypeParser(23, "text") : parseBigInteger);
      pgTypes.setTypeParser(1016, "text", val ? pgTypes.getTypeParser(1007, "text") : parseBigIntegerArray);
    });
  }
});

// ../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/utils.js
var require_utils3 = __commonJS({
  "../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/utils.js"(exports, module) {
    "use strict";
    var defaults2 = require_defaults();
    var util2 = __require("util");
    var { isDate } = util2.types || util2;
    function escapeElement(elementRepresentation) {
      const escaped = elementRepresentation.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
      return '"' + escaped + '"';
    }
    function arrayString(val) {
      let result = "{";
      for (let i = 0; i < val.length; i++) {
        if (i > 0) {
          result = result + ",";
        }
        if (val[i] === null || typeof val[i] === "undefined") {
          result = result + "NULL";
        } else if (Array.isArray(val[i])) {
          result = result + arrayString(val[i]);
        } else if (ArrayBuffer.isView(val[i])) {
          let item = val[i];
          if (!(item instanceof Buffer)) {
            const buf = Buffer.from(item.buffer, item.byteOffset, item.byteLength);
            if (buf.length === item.byteLength) {
              item = buf;
            } else {
              item = buf.slice(item.byteOffset, item.byteOffset + item.byteLength);
            }
          }
          result += "\\\\x" + item.toString("hex");
        } else {
          result += escapeElement(prepareValue(val[i]));
        }
      }
      result = result + "}";
      return result;
    }
    var prepareValue = function(val, seen) {
      if (val == null) {
        return null;
      }
      if (typeof val === "object") {
        if (val instanceof Buffer) {
          return val;
        }
        if (ArrayBuffer.isView(val)) {
          const buf = Buffer.from(val.buffer, val.byteOffset, val.byteLength);
          if (buf.length === val.byteLength) {
            return buf;
          }
          return buf.slice(val.byteOffset, val.byteOffset + val.byteLength);
        }
        if (isDate(val)) {
          if (defaults2.parseInputDatesAsUTC) {
            return dateToStringUTC(val);
          } else {
            return dateToString(val);
          }
        }
        if (Array.isArray(val)) {
          return arrayString(val);
        }
        return prepareObject(val, seen);
      }
      return val.toString();
    };
    function prepareObject(val, seen) {
      if (val && typeof val.toPostgres === "function") {
        seen = seen || [];
        if (seen.indexOf(val) !== -1) {
          throw new Error('circular reference detected while preparing "' + val + '" for query');
        }
        seen.push(val);
        return prepareValue(val.toPostgres(prepareValue), seen);
      }
      return JSON.stringify(val);
    }
    function dateToString(date6) {
      let offset = -date6.getTimezoneOffset();
      let year = date6.getFullYear();
      const isBCYear = year < 1;
      if (isBCYear) year = Math.abs(year) + 1;
      let ret = String(year).padStart(4, "0") + "-" + String(date6.getMonth() + 1).padStart(2, "0") + "-" + String(date6.getDate()).padStart(2, "0") + "T" + String(date6.getHours()).padStart(2, "0") + ":" + String(date6.getMinutes()).padStart(2, "0") + ":" + String(date6.getSeconds()).padStart(2, "0") + "." + String(date6.getMilliseconds()).padStart(3, "0");
      if (offset < 0) {
        ret += "-";
        offset *= -1;
      } else {
        ret += "+";
      }
      ret += String(Math.floor(offset / 60)).padStart(2, "0") + ":" + String(offset % 60).padStart(2, "0");
      if (isBCYear) ret += " BC";
      return ret;
    }
    function dateToStringUTC(date6) {
      let year = date6.getUTCFullYear();
      const isBCYear = year < 1;
      if (isBCYear) year = Math.abs(year) + 1;
      let ret = String(year).padStart(4, "0") + "-" + String(date6.getUTCMonth() + 1).padStart(2, "0") + "-" + String(date6.getUTCDate()).padStart(2, "0") + "T" + String(date6.getUTCHours()).padStart(2, "0") + ":" + String(date6.getUTCMinutes()).padStart(2, "0") + ":" + String(date6.getUTCSeconds()).padStart(2, "0") + "." + String(date6.getUTCMilliseconds()).padStart(3, "0");
      ret += "+00:00";
      if (isBCYear) ret += " BC";
      return ret;
    }
    function normalizeQueryConfig(config2, values, callback) {
      config2 = typeof config2 === "string" ? { text: config2 } : config2;
      if (values) {
        if (typeof values === "function") {
          config2.callback = values;
        } else {
          config2.values = values;
        }
      }
      if (callback) {
        config2.callback = callback;
      }
      return config2;
    }
    var escapeIdentifier2 = function(str) {
      return '"' + str.replace(/"/g, '""') + '"';
    };
    var escapeLiteral2 = function(str) {
      let hasBackslash = false;
      let escaped = "'";
      if (str == null) {
        return "''";
      }
      if (typeof str !== "string") {
        return "''";
      }
      for (let i = 0; i < str.length; i++) {
        const c = str[i];
        if (c === "'") {
          escaped += c + c;
        } else if (c === "\\") {
          escaped += c + c;
          hasBackslash = true;
        } else {
          escaped += c;
        }
      }
      escaped += "'";
      if (hasBackslash === true) {
        escaped = " E" + escaped;
      }
      return escaped;
    };
    module.exports = {
      prepareValue: function prepareValueWrapper(value) {
        return prepareValue(value);
      },
      normalizeQueryConfig,
      escapeIdentifier: escapeIdentifier2,
      escapeLiteral: escapeLiteral2
    };
  }
});

// ../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/crypto/utils-legacy.js
var require_utils_legacy = __commonJS({
  "../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/crypto/utils-legacy.js"(exports, module) {
    "use strict";
    var nodeCrypto2 = __require("crypto");
    function md5(string4) {
      return nodeCrypto2.createHash("md5").update(string4, "utf-8").digest("hex");
    }
    function postgresMd5PasswordHash(user, password, salt) {
      const inner = md5(password + user);
      const outer = md5(Buffer.concat([Buffer.from(inner), salt]));
      return "md5" + outer;
    }
    function sha256(text2) {
      return nodeCrypto2.createHash("sha256").update(text2).digest();
    }
    function hashByName(hashName, text2) {
      hashName = hashName.replace(/(\D)-/, "$1");
      return nodeCrypto2.createHash(hashName).update(text2).digest();
    }
    function hmacSha256(key, msg) {
      return nodeCrypto2.createHmac("sha256", key).update(msg).digest();
    }
    async function deriveKey(password, salt, iterations) {
      return nodeCrypto2.pbkdf2Sync(password, salt, iterations, 32, "sha256");
    }
    module.exports = {
      postgresMd5PasswordHash,
      randomBytes: nodeCrypto2.randomBytes,
      deriveKey,
      sha256,
      hashByName,
      hmacSha256,
      md5
    };
  }
});

// ../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/crypto/utils-webcrypto.js
var require_utils_webcrypto = __commonJS({
  "../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/crypto/utils-webcrypto.js"(exports, module) {
    var nodeCrypto2 = __require("crypto");
    module.exports = {
      postgresMd5PasswordHash,
      randomBytes: randomBytes4,
      deriveKey,
      sha256,
      hashByName,
      hmacSha256,
      md5
    };
    var webCrypto = nodeCrypto2.webcrypto || globalThis.crypto;
    var subtleCrypto = webCrypto.subtle;
    var textEncoder = new TextEncoder();
    function randomBytes4(length) {
      return webCrypto.getRandomValues(Buffer.alloc(length));
    }
    async function md5(string4) {
      try {
        return nodeCrypto2.createHash("md5").update(string4, "utf-8").digest("hex");
      } catch (e) {
        const data = typeof string4 === "string" ? textEncoder.encode(string4) : string4;
        const hash2 = await subtleCrypto.digest("MD5", data);
        return Array.from(new Uint8Array(hash2)).map((b) => b.toString(16).padStart(2, "0")).join("");
      }
    }
    async function postgresMd5PasswordHash(user, password, salt) {
      const inner = await md5(password + user);
      const outer = await md5(Buffer.concat([Buffer.from(inner), salt]));
      return "md5" + outer;
    }
    async function sha256(text2) {
      return await subtleCrypto.digest("SHA-256", text2);
    }
    async function hashByName(hashName, text2) {
      return await subtleCrypto.digest(hashName, text2);
    }
    async function hmacSha256(keyBuffer, msg) {
      const key = await subtleCrypto.importKey("raw", keyBuffer, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
      return await subtleCrypto.sign("HMAC", key, textEncoder.encode(msg));
    }
    async function deriveKey(password, salt, iterations) {
      const key = await subtleCrypto.importKey("raw", textEncoder.encode(password), "PBKDF2", false, ["deriveBits"]);
      const params = { name: "PBKDF2", hash: "SHA-256", salt, iterations };
      return await subtleCrypto.deriveBits(params, key, 32 * 8, ["deriveBits"]);
    }
  }
});

// ../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/crypto/utils.js
var require_utils4 = __commonJS({
  "../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/crypto/utils.js"(exports, module) {
    "use strict";
    var useLegacyCrypto = parseInt(process.versions && process.versions.node && process.versions.node.split(".")[0]) < 15;
    if (useLegacyCrypto) {
      module.exports = require_utils_legacy();
    } else {
      module.exports = require_utils_webcrypto();
    }
  }
});

// ../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/crypto/cert-signatures.js
var require_cert_signatures = __commonJS({
  "../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/crypto/cert-signatures.js"(exports, module) {
    function x509Error(msg, cert) {
      return new Error("SASL channel binding: " + msg + " when parsing public certificate " + cert.toString("base64"));
    }
    function readASN1Length(data, index2) {
      let length = data[index2++];
      if (length < 128) return { length, index: index2 };
      const lengthBytes = length & 127;
      if (lengthBytes > 4) throw x509Error("bad length", data);
      length = 0;
      for (let i = 0; i < lengthBytes; i++) {
        length = length << 8 | data[index2++];
      }
      return { length, index: index2 };
    }
    function readASN1OID(data, index2) {
      if (data[index2++] !== 6) throw x509Error("non-OID data", data);
      const { length: OIDLength, index: indexAfterOIDLength } = readASN1Length(data, index2);
      index2 = indexAfterOIDLength;
      const lastIndex = index2 + OIDLength;
      const byte1 = data[index2++];
      let oid = (byte1 / 40 >> 0) + "." + byte1 % 40;
      while (index2 < lastIndex) {
        let value = 0;
        while (index2 < lastIndex) {
          const nextByte = data[index2++];
          value = value << 7 | nextByte & 127;
          if (nextByte < 128) break;
        }
        oid += "." + value;
      }
      return { oid, index: index2 };
    }
    function expectASN1Seq(data, index2) {
      if (data[index2++] !== 48) throw x509Error("non-sequence data", data);
      return readASN1Length(data, index2);
    }
    function signatureAlgorithmHashFromCertificate(data, index2) {
      if (index2 === void 0) index2 = 0;
      index2 = expectASN1Seq(data, index2).index;
      const { length: certInfoLength, index: indexAfterCertInfoLength } = expectASN1Seq(data, index2);
      index2 = indexAfterCertInfoLength + certInfoLength;
      index2 = expectASN1Seq(data, index2).index;
      const { oid, index: indexAfterOID } = readASN1OID(data, index2);
      switch (oid) {
        // RSA
        case "1.2.840.113549.1.1.4":
          return "MD5";
        case "1.2.840.113549.1.1.5":
          return "SHA-1";
        case "1.2.840.113549.1.1.11":
          return "SHA-256";
        case "1.2.840.113549.1.1.12":
          return "SHA-384";
        case "1.2.840.113549.1.1.13":
          return "SHA-512";
        case "1.2.840.113549.1.1.14":
          return "SHA-224";
        case "1.2.840.113549.1.1.15":
          return "SHA512-224";
        case "1.2.840.113549.1.1.16":
          return "SHA512-256";
        // ECDSA
        case "1.2.840.10045.4.1":
          return "SHA-1";
        case "1.2.840.10045.4.3.1":
          return "SHA-224";
        case "1.2.840.10045.4.3.2":
          return "SHA-256";
        case "1.2.840.10045.4.3.3":
          return "SHA-384";
        case "1.2.840.10045.4.3.4":
          return "SHA-512";
        // RSASSA-PSS: hash is indicated separately
        case "1.2.840.113549.1.1.10": {
          index2 = indexAfterOID;
          index2 = expectASN1Seq(data, index2).index;
          if (data[index2++] !== 160) throw x509Error("non-tag data", data);
          index2 = readASN1Length(data, index2).index;
          index2 = expectASN1Seq(data, index2).index;
          const { oid: hashOID } = readASN1OID(data, index2);
          switch (hashOID) {
            // standalone hash OIDs
            case "1.2.840.113549.2.5":
              return "MD5";
            case "1.3.14.3.2.26":
              return "SHA-1";
            case "2.16.840.1.101.3.4.2.1":
              return "SHA-256";
            case "2.16.840.1.101.3.4.2.2":
              return "SHA-384";
            case "2.16.840.1.101.3.4.2.3":
              return "SHA-512";
          }
          throw x509Error("unknown hash OID " + hashOID, data);
        }
        // Ed25519 -- see https: return//github.com/openssl/openssl/issues/15477
        case "1.3.101.110":
        case "1.3.101.112":
          return "SHA-512";
        // Ed448 -- still not in pg 17.2 (if supported, digest would be SHAKE256 x 64 bytes)
        case "1.3.101.111":
        case "1.3.101.113":
          throw x509Error("Ed448 certificate channel binding is not currently supported by Postgres");
      }
      throw x509Error("unknown OID " + oid, data);
    }
    module.exports = { signatureAlgorithmHashFromCertificate };
  }
});

// ../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/crypto/sasl.js
var require_sasl = __commonJS({
  "../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/crypto/sasl.js"(exports, module) {
    "use strict";
    var crypto4 = require_utils4();
    var { signatureAlgorithmHashFromCertificate } = require_cert_signatures();
    function startSession(mechanisms, stream) {
      const candidates = ["SCRAM-SHA-256"];
      if (stream) candidates.unshift("SCRAM-SHA-256-PLUS");
      const mechanism = candidates.find((candidate) => mechanisms.includes(candidate));
      if (!mechanism) {
        throw new Error("SASL: Only mechanism(s) " + candidates.join(" and ") + " are supported");
      }
      if (mechanism === "SCRAM-SHA-256-PLUS" && typeof stream.getPeerCertificate !== "function") {
        throw new Error("SASL: Mechanism SCRAM-SHA-256-PLUS requires a certificate");
      }
      const clientNonce = crypto4.randomBytes(18).toString("base64");
      const gs2Header = mechanism === "SCRAM-SHA-256-PLUS" ? "p=tls-server-end-point" : stream ? "y" : "n";
      return {
        mechanism,
        clientNonce,
        response: gs2Header + ",,n=*,r=" + clientNonce,
        message: "SASLInitialResponse"
      };
    }
    async function continueSession(session, password, serverData, stream) {
      if (session.message !== "SASLInitialResponse") {
        throw new Error("SASL: Last message was not SASLInitialResponse");
      }
      if (typeof password !== "string") {
        throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string");
      }
      if (password === "") {
        throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a non-empty string");
      }
      if (typeof serverData !== "string") {
        throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a string");
      }
      const sv = parseServerFirstMessage(serverData);
      if (!sv.nonce.startsWith(session.clientNonce)) {
        throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce");
      } else if (sv.nonce.length === session.clientNonce.length) {
        throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short");
      }
      const clientFirstMessageBare = "n=*,r=" + session.clientNonce;
      const serverFirstMessage = "r=" + sv.nonce + ",s=" + sv.salt + ",i=" + sv.iteration;
      let channelBinding = stream ? "eSws" : "biws";
      if (session.mechanism === "SCRAM-SHA-256-PLUS") {
        const peerCert = stream.getPeerCertificate().raw;
        let hashName = signatureAlgorithmHashFromCertificate(peerCert);
        if (hashName === "MD5" || hashName === "SHA-1") hashName = "SHA-256";
        const certHash = await crypto4.hashByName(hashName, peerCert);
        const bindingData = Buffer.concat([Buffer.from("p=tls-server-end-point,,"), Buffer.from(certHash)]);
        channelBinding = bindingData.toString("base64");
      }
      const clientFinalMessageWithoutProof = "c=" + channelBinding + ",r=" + sv.nonce;
      const authMessage = clientFirstMessageBare + "," + serverFirstMessage + "," + clientFinalMessageWithoutProof;
      const saltBytes = Buffer.from(sv.salt, "base64");
      const saltedPassword = await crypto4.deriveKey(password, saltBytes, sv.iteration);
      const clientKey = await crypto4.hmacSha256(saltedPassword, "Client Key");
      const storedKey = await crypto4.sha256(clientKey);
      const clientSignature = await crypto4.hmacSha256(storedKey, authMessage);
      const clientProof = xorBuffers(Buffer.from(clientKey), Buffer.from(clientSignature)).toString("base64");
      const serverKey = await crypto4.hmacSha256(saltedPassword, "Server Key");
      const serverSignatureBytes = await crypto4.hmacSha256(serverKey, authMessage);
      session.message = "SASLResponse";
      session.serverSignature = Buffer.from(serverSignatureBytes).toString("base64");
      session.response = clientFinalMessageWithoutProof + ",p=" + clientProof;
    }
    function finalizeSession(session, serverData) {
      if (session.message !== "SASLResponse") {
        throw new Error("SASL: Last message was not SASLResponse");
      }
      if (typeof serverData !== "string") {
        throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: serverData must be a string");
      }
      const { serverSignature } = parseServerFinalMessage(serverData);
      if (serverSignature !== session.serverSignature) {
        throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match");
      }
    }
    function isPrintableChars(text2) {
      if (typeof text2 !== "string") {
        throw new TypeError("SASL: text must be a string");
      }
      return text2.split("").map((_, i) => text2.charCodeAt(i)).every((c) => c >= 33 && c <= 43 || c >= 45 && c <= 126);
    }
    function isBase64(text2) {
      return /^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(text2);
    }
    function parseAttributePairs(text2) {
      if (typeof text2 !== "string") {
        throw new TypeError("SASL: attribute pairs text must be a string");
      }
      return new Map(
        text2.split(",").map((attrValue) => {
          if (!/^.=/.test(attrValue)) {
            throw new Error("SASL: Invalid attribute pair entry");
          }
          const name = attrValue[0];
          const value = attrValue.substring(2);
          return [name, value];
        })
      );
    }
    function parseServerFirstMessage(data) {
      const attrPairs = parseAttributePairs(data);
      const nonce = attrPairs.get("r");
      if (!nonce) {
        throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing");
      } else if (!isPrintableChars(nonce)) {
        throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce must only contain printable characters");
      }
      const salt = attrPairs.get("s");
      if (!salt) {
        throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing");
      } else if (!isBase64(salt)) {
        throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64");
      }
      const iterationText = attrPairs.get("i");
      if (!iterationText) {
        throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing");
      } else if (!/^[1-9][0-9]*$/.test(iterationText)) {
        throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration count");
      }
      const iteration = parseInt(iterationText, 10);
      return {
        nonce,
        salt,
        iteration
      };
    }
    function parseServerFinalMessage(serverData) {
      const attrPairs = parseAttributePairs(serverData);
      const serverSignature = attrPairs.get("v");
      if (!serverSignature) {
        throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing");
      } else if (!isBase64(serverSignature)) {
        throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature must be base64");
      }
      return {
        serverSignature
      };
    }
    function xorBuffers(a, b) {
      if (!Buffer.isBuffer(a)) {
        throw new TypeError("first argument must be a Buffer");
      }
      if (!Buffer.isBuffer(b)) {
        throw new TypeError("second argument must be a Buffer");
      }
      if (a.length !== b.length) {
        throw new Error("Buffer lengths must match");
      }
      if (a.length === 0) {
        throw new Error("Buffers cannot be empty");
      }
      return Buffer.from(a.map((_, i) => a[i] ^ b[i]));
    }
    module.exports = {
      startSession,
      continueSession,
      finalizeSession
    };
  }
});

// ../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/type-overrides.js
var require_type_overrides = __commonJS({
  "../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/type-overrides.js"(exports, module) {
    "use strict";
    var types3 = require_pg_types();
    function TypeOverrides2(userTypes) {
      this._types = userTypes || types3;
      this.text = {};
      this.binary = {};
    }
    TypeOverrides2.prototype.getOverrides = function(format) {
      switch (format) {
        case "text":
          return this.text;
        case "binary":
          return this.binary;
        default:
          return {};
      }
    };
    TypeOverrides2.prototype.setTypeParser = function(oid, format, parseFn) {
      if (typeof format === "function") {
        parseFn = format;
        format = "text";
      }
      this.getOverrides(format)[oid] = parseFn;
    };
    TypeOverrides2.prototype.getTypeParser = function(oid, format) {
      format = format || "text";
      return this.getOverrides(format)[oid] || this._types.getTypeParser(oid, format);
    };
    module.exports = TypeOverrides2;
  }
});

// ../../node_modules/.pnpm/pg-connection-string@2.12.0/node_modules/pg-connection-string/index.js
var require_pg_connection_string = __commonJS({
  "../../node_modules/.pnpm/pg-connection-string@2.12.0/node_modules/pg-connection-string/index.js"(exports, module) {
    "use strict";
    function parse3(str, options = {}) {
      if (str.charAt(0) === "/") {
        const config3 = str.split(" ");
        return { host: config3[0], database: config3[1] };
      }
      const config2 = {};
      let result;
      let dummyHost = false;
      if (/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(str)) {
        str = encodeURI(str).replace(/%25(\d\d)/g, "%$1");
      }
      try {
        try {
          result = new URL(str, "postgres://base");
        } catch (e) {
          result = new URL(str.replace("@/", "@___DUMMY___/"), "postgres://base");
          dummyHost = true;
        }
      } catch (err) {
        err.input && (err.input = "*****REDACTED*****");
        throw err;
      }
      for (const entry of result.searchParams.entries()) {
        config2[entry[0]] = entry[1];
      }
      config2.user = config2.user || decodeURIComponent(result.username);
      config2.password = config2.password || decodeURIComponent(result.password);
      if (result.protocol == "socket:") {
        config2.host = decodeURI(result.pathname);
        config2.database = result.searchParams.get("db");
        config2.client_encoding = result.searchParams.get("encoding");
        return config2;
      }
      const hostname2 = dummyHost ? "" : result.hostname;
      if (!config2.host) {
        config2.host = decodeURIComponent(hostname2);
      } else if (hostname2 && /^%2f/i.test(hostname2)) {
        result.pathname = hostname2 + result.pathname;
      }
      if (!config2.port) {
        config2.port = result.port;
      }
      const pathname = result.pathname.slice(1) || null;
      config2.database = pathname ? decodeURI(pathname) : null;
      if (config2.ssl === "true" || config2.ssl === "1") {
        config2.ssl = true;
      }
      if (config2.ssl === "0") {
        config2.ssl = false;
      }
      if (config2.sslcert || config2.sslkey || config2.sslrootcert || config2.sslmode) {
        config2.ssl = {};
      }
      const fs2 = config2.sslcert || config2.sslkey || config2.sslrootcert ? __require("fs") : null;
      if (config2.sslcert) {
        config2.ssl.cert = fs2.readFileSync(config2.sslcert).toString();
      }
      if (config2.sslkey) {
        config2.ssl.key = fs2.readFileSync(config2.sslkey).toString();
      }
      if (config2.sslrootcert) {
        config2.ssl.ca = fs2.readFileSync(config2.sslrootcert).toString();
      }
      if (options.useLibpqCompat && config2.uselibpqcompat) {
        throw new Error("Both useLibpqCompat and uselibpqcompat are set. Please use only one of them.");
      }
      if (config2.uselibpqcompat === "true" || options.useLibpqCompat) {
        switch (config2.sslmode) {
          case "disable": {
            config2.ssl = false;
            break;
          }
          case "prefer": {
            config2.ssl.rejectUnauthorized = false;
            break;
          }
          case "require": {
            if (config2.sslrootcert) {
              config2.ssl.checkServerIdentity = function() {
              };
            } else {
              config2.ssl.rejectUnauthorized = false;
            }
            break;
          }
          case "verify-ca": {
            if (!config2.ssl.ca) {
              throw new Error(
                "SECURITY WARNING: Using sslmode=verify-ca requires specifying a CA with sslrootcert. If a public CA is used, verify-ca allows connections to a server that somebody else may have registered with the CA, making you vulnerable to Man-in-the-Middle attacks. Either specify a custom CA certificate with sslrootcert parameter or use sslmode=verify-full for proper security."
              );
            }
            config2.ssl.checkServerIdentity = function() {
            };
            break;
          }
          case "verify-full": {
            break;
          }
        }
      } else {
        switch (config2.sslmode) {
          case "disable": {
            config2.ssl = false;
            break;
          }
          case "prefer":
          case "require":
          case "verify-ca":
          case "verify-full": {
            if (config2.sslmode !== "verify-full") {
              deprecatedSslModeWarning(config2.sslmode);
            }
            break;
          }
          case "no-verify": {
            config2.ssl.rejectUnauthorized = false;
            break;
          }
        }
      }
      return config2;
    }
    function toConnectionOptions(sslConfig) {
      const connectionOptions = Object.entries(sslConfig).reduce((c, [key, value]) => {
        if (value !== void 0 && value !== null) {
          c[key] = value;
        }
        return c;
      }, {});
      return connectionOptions;
    }
    function toClientConfig(config2) {
      const poolConfig = Object.entries(config2).reduce((c, [key, value]) => {
        if (key === "ssl") {
          const sslConfig = value;
          if (typeof sslConfig === "boolean") {
            c[key] = sslConfig;
          }
          if (typeof sslConfig === "object") {
            c[key] = toConnectionOptions(sslConfig);
          }
        } else if (value !== void 0 && value !== null) {
          if (key === "port") {
            if (value !== "") {
              const v = parseInt(value, 10);
              if (isNaN(v)) {
                throw new Error(`Invalid ${key}: ${value}`);
              }
              c[key] = v;
            }
          } else {
            c[key] = value;
          }
        }
        return c;
      }, {});
      return poolConfig;
    }
    function parseIntoClientConfig(str) {
      return toClientConfig(parse3(str));
    }
    function deprecatedSslModeWarning(sslmode) {
      if (!deprecatedSslModeWarning.warned && typeof process !== "undefined" && process.emitWarning) {
        deprecatedSslModeWarning.warned = true;
        process.emitWarning(`SECURITY WARNING: The SSL modes 'prefer', 'require', and 'verify-ca' are treated as aliases for 'verify-full'.
In the next major version (pg-connection-string v3.0.0 and pg v9.0.0), these modes will adopt standard libpq semantics, which have weaker security guarantees.

To prepare for this change:
- If you want the current behavior, explicitly use 'sslmode=verify-full'
- If you want libpq compatibility now, use 'uselibpqcompat=true&sslmode=${sslmode}'

See https://www.postgresql.org/docs/current/libpq-ssl.html for libpq SSL mode definitions.`);
      }
    }
    module.exports = parse3;
    parse3.parse = parse3;
    parse3.toClientConfig = toClientConfig;
    parse3.parseIntoClientConfig = parseIntoClientConfig;
  }
});

// ../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/connection-parameters.js
var require_connection_parameters = __commonJS({
  "../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/connection-parameters.js"(exports, module) {
    "use strict";
    var dns = __require("dns");
    var defaults2 = require_defaults();
    var parse3 = require_pg_connection_string().parse;
    var val = function(key, config2, envVar) {
      if (config2[key]) {
        return config2[key];
      }
      if (envVar === void 0) {
        envVar = process.env["PG" + key.toUpperCase()];
      } else if (envVar === false) {
      } else {
        envVar = process.env[envVar];
      }
      return envVar || defaults2[key];
    };
    var readSSLConfigFromEnvironment = function() {
      switch (process.env.PGSSLMODE) {
        case "disable":
          return false;
        case "prefer":
        case "require":
        case "verify-ca":
        case "verify-full":
          return true;
        case "no-verify":
          return { rejectUnauthorized: false };
      }
      return defaults2.ssl;
    };
    var quoteParamValue = function(value) {
      return "'" + ("" + value).replace(/\\/g, "\\\\").replace(/'/g, "\\'") + "'";
    };
    var add = function(params, config2, paramName) {
      const value = config2[paramName];
      if (value !== void 0 && value !== null) {
        params.push(paramName + "=" + quoteParamValue(value));
      }
    };
    var ConnectionParameters = class {
      constructor(config2) {
        config2 = typeof config2 === "string" ? parse3(config2) : config2 || {};
        if (config2.connectionString) {
          config2 = Object.assign({}, config2, parse3(config2.connectionString));
        }
        this.user = val("user", config2);
        this.database = val("database", config2);
        if (this.database === void 0) {
          this.database = this.user;
        }
        this.port = parseInt(val("port", config2), 10);
        this.host = val("host", config2);
        Object.defineProperty(this, "password", {
          configurable: true,
          enumerable: false,
          writable: true,
          value: val("password", config2)
        });
        this.binary = val("binary", config2);
        this.options = val("options", config2);
        this.ssl = typeof config2.ssl === "undefined" ? readSSLConfigFromEnvironment() : config2.ssl;
        if (typeof this.ssl === "string") {
          if (this.ssl === "true") {
            this.ssl = true;
          }
        }
        if (this.ssl === "no-verify") {
          this.ssl = { rejectUnauthorized: false };
        }
        if (this.ssl && this.ssl.key) {
          Object.defineProperty(this.ssl, "key", {
            enumerable: false
          });
        }
        this.client_encoding = val("client_encoding", config2);
        this.replication = val("replication", config2);
        this.isDomainSocket = !(this.host || "").indexOf("/");
        this.application_name = val("application_name", config2, "PGAPPNAME");
        this.fallback_application_name = val("fallback_application_name", config2, false);
        this.statement_timeout = val("statement_timeout", config2, false);
        this.lock_timeout = val("lock_timeout", config2, false);
        this.idle_in_transaction_session_timeout = val("idle_in_transaction_session_timeout", config2, false);
        this.query_timeout = val("query_timeout", config2, false);
        if (config2.connectionTimeoutMillis === void 0) {
          this.connect_timeout = process.env.PGCONNECT_TIMEOUT || 0;
        } else {
          this.connect_timeout = Math.floor(config2.connectionTimeoutMillis / 1e3);
        }
        if (config2.keepAlive === false) {
          this.keepalives = 0;
        } else if (config2.keepAlive === true) {
          this.keepalives = 1;
        }
        if (typeof config2.keepAliveInitialDelayMillis === "number") {
          this.keepalives_idle = Math.floor(config2.keepAliveInitialDelayMillis / 1e3);
        }
      }
      getLibpqConnectionString(cb) {
        const params = [];
        add(params, this, "user");
        add(params, this, "password");
        add(params, this, "port");
        add(params, this, "application_name");
        add(params, this, "fallback_application_name");
        add(params, this, "connect_timeout");
        add(params, this, "options");
        const ssl = typeof this.ssl === "object" ? this.ssl : this.ssl ? { sslmode: this.ssl } : {};
        add(params, ssl, "sslmode");
        add(params, ssl, "sslca");
        add(params, ssl, "sslkey");
        add(params, ssl, "sslcert");
        add(params, ssl, "sslrootcert");
        if (this.database) {
          params.push("dbname=" + quoteParamValue(this.database));
        }
        if (this.replication) {
          params.push("replication=" + quoteParamValue(this.replication));
        }
        if (this.host) {
          params.push("host=" + quoteParamValue(this.host));
        }
        if (this.isDomainSocket) {
          return cb(null, params.join(" "));
        }
        if (this.client_encoding) {
          params.push("client_encoding=" + quoteParamValue(this.client_encoding));
        }
        dns.lookup(this.host, function(err, address) {
          if (err) return cb(err, null);
          params.push("hostaddr=" + quoteParamValue(address));
          return cb(null, params.join(" "));
        });
      }
    };
    module.exports = ConnectionParameters;
  }
});

// ../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/result.js
var require_result = __commonJS({
  "../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/result.js"(exports, module) {
    "use strict";
    var types3 = require_pg_types();
    var matchRegexp = /^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/;
    var Result2 = class {
      constructor(rowMode, types4) {
        this.command = null;
        this.rowCount = null;
        this.oid = null;
        this.rows = [];
        this.fields = [];
        this._parsers = void 0;
        this._types = types4;
        this.RowCtor = null;
        this.rowAsArray = rowMode === "array";
        if (this.rowAsArray) {
          this.parseRow = this._parseRowAsArray;
        }
        this._prebuiltEmptyResultObject = null;
      }
      // adds a command complete message
      addCommandComplete(msg) {
        let match;
        if (msg.text) {
          match = matchRegexp.exec(msg.text);
        } else {
          match = matchRegexp.exec(msg.command);
        }
        if (match) {
          this.command = match[1];
          if (match[3]) {
            this.oid = parseInt(match[2], 10);
            this.rowCount = parseInt(match[3], 10);
          } else if (match[2]) {
            this.rowCount = parseInt(match[2], 10);
          }
        }
      }
      _parseRowAsArray(rowData) {
        const row = new Array(rowData.length);
        for (let i = 0, len = rowData.length; i < len; i++) {
          const rawValue = rowData[i];
          if (rawValue !== null) {
            row[i] = this._parsers[i](rawValue);
          } else {
            row[i] = null;
          }
        }
        return row;
      }
      parseRow(rowData) {
        const row = { ...this._prebuiltEmptyResultObject };
        for (let i = 0, len = rowData.length; i < len; i++) {
          const rawValue = rowData[i];
          const field = this.fields[i].name;
          if (rawValue !== null) {
            const v = this.fields[i].format === "binary" ? Buffer.from(rawValue) : rawValue;
            row[field] = this._parsers[i](v);
          } else {
            row[field] = null;
          }
        }
        return row;
      }
      addRow(row) {
        this.rows.push(row);
      }
      addFields(fieldDescriptions) {
        this.fields = fieldDescriptions;
        if (this.fields.length) {
          this._parsers = new Array(fieldDescriptions.length);
        }
        const row = {};
        for (let i = 0; i < fieldDescriptions.length; i++) {
          const desc2 = fieldDescriptions[i];
          row[desc2.name] = null;
          if (this._types) {
            this._parsers[i] = this._types.getTypeParser(desc2.dataTypeID, desc2.format || "text");
          } else {
            this._parsers[i] = types3.getTypeParser(desc2.dataTypeID, desc2.format || "text");
          }
        }
        this._prebuiltEmptyResultObject = { ...row };
      }
    };
    module.exports = Result2;
  }
});

// ../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/query.js
var require_query2 = __commonJS({
  "../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/query.js"(exports, module) {
    "use strict";
    var { EventEmitter: EventEmitter2 } = __require("events");
    var Result2 = require_result();
    var utils = require_utils3();
    var Query2 = class extends EventEmitter2 {
      constructor(config2, values, callback) {
        super();
        config2 = utils.normalizeQueryConfig(config2, values, callback);
        this.text = config2.text;
        this.values = config2.values;
        this.rows = config2.rows;
        this.types = config2.types;
        this.name = config2.name;
        this.queryMode = config2.queryMode;
        this.binary = config2.binary;
        this.portal = config2.portal || "";
        this.callback = config2.callback;
        this._rowMode = config2.rowMode;
        if (process.domain && config2.callback) {
          this.callback = process.domain.bind(config2.callback);
        }
        this._result = new Result2(this._rowMode, this.types);
        this._results = this._result;
        this._canceledDueToError = false;
      }
      requiresPreparation() {
        if (this.queryMode === "extended") {
          return true;
        }
        if (this.name) {
          return true;
        }
        if (this.rows) {
          return true;
        }
        if (!this.text) {
          return false;
        }
        if (!this.values) {
          return false;
        }
        return this.values.length > 0;
      }
      _checkForMultirow() {
        if (this._result.command) {
          if (!Array.isArray(this._results)) {
            this._results = [this._result];
          }
          this._result = new Result2(this._rowMode, this._result._types);
          this._results.push(this._result);
        }
      }
      // associates row metadata from the supplied
      // message with this query object
      // metadata used when parsing row results
      handleRowDescription(msg) {
        this._checkForMultirow();
        this._result.addFields(msg.fields);
        this._accumulateRows = this.callback || !this.listeners("row").length;
      }
      handleDataRow(msg) {
        let row;
        if (this._canceledDueToError) {
          return;
        }
        try {
          row = this._result.parseRow(msg.fields);
        } catch (err) {
          this._canceledDueToError = err;
          return;
        }
        this.emit("row", row, this._result);
        if (this._accumulateRows) {
          this._result.addRow(row);
        }
      }
      handleCommandComplete(msg, connection) {
        this._checkForMultirow();
        this._result.addCommandComplete(msg);
        if (this.rows) {
          connection.sync();
        }
      }
      // if a named prepared statement is created with empty query text
      // the backend will send an emptyQuery message but *not* a command complete message
      // since we pipeline sync immediately after execute we don't need to do anything here
      // unless we have rows specified, in which case we did not pipeline the initial sync call
      handleEmptyQuery(connection) {
        if (this.rows) {
          connection.sync();
        }
      }
      handleError(err, connection) {
        if (this._canceledDueToError) {
          err = this._canceledDueToError;
          this._canceledDueToError = false;
        }
        if (this.callback) {
          return this.callback(err);
        }
        this.emit("error", err);
      }
      handleReadyForQuery(con) {
        if (this._canceledDueToError) {
          return this.handleError(this._canceledDueToError, con);
        }
        if (this.callback) {
          try {
            this.callback(null, this._results);
          } catch (err) {
            process.nextTick(() => {
              throw err;
            });
          }
        }
        this.emit("end", this._results);
      }
      submit(connection) {
        if (typeof this.text !== "string" && typeof this.name !== "string") {
          return new Error("A query must have either text or a name. Supplying neither is unsupported.");
        }
        const previous = connection.parsedStatements[this.name];
        if (this.text && previous && this.text !== previous) {
          return new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);
        }
        if (this.values && !Array.isArray(this.values)) {
          return new Error("Query values must be an array");
        }
        if (this.requiresPreparation()) {
          connection.stream.cork && connection.stream.cork();
          try {
            this.prepare(connection);
          } finally {
            connection.stream.uncork && connection.stream.uncork();
          }
        } else {
          connection.query(this.text);
        }
        return null;
      }
      hasBeenParsed(connection) {
        return this.name && connection.parsedStatements[this.name];
      }
      handlePortalSuspended(connection) {
        this._getRows(connection, this.rows);
      }
      _getRows(connection, rows) {
        connection.execute({
          portal: this.portal,
          rows
        });
        if (!rows) {
          connection.sync();
        } else {
          connection.flush();
        }
      }
      // http://developer.postgresql.org/pgdocs/postgres/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY
      prepare(connection) {
        if (!this.hasBeenParsed(connection)) {
          connection.parse({
            text: this.text,
            name: this.name,
            types: this.types
          });
        }
        try {
          connection.bind({
            portal: this.portal,
            statement: this.name,
            values: this.values,
            binary: this.binary,
            valueMapper: utils.prepareValue
          });
        } catch (err) {
          this.handleError(err, connection);
          return;
        }
        connection.describe({
          type: "P",
          name: this.portal || ""
        });
        this._getRows(connection, this.rows);
      }
      handleCopyInResponse(connection) {
        connection.sendCopyFail("No source stream defined");
      }
      handleCopyData(msg, connection) {
      }
    };
    module.exports = Query2;
  }
});

// ../../node_modules/.pnpm/pg-protocol@1.13.0/node_modules/pg-protocol/dist/messages.js
var require_messages = __commonJS({
  "../../node_modules/.pnpm/pg-protocol@1.13.0/node_modules/pg-protocol/dist/messages.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.NoticeMessage = exports.DataRowMessage = exports.CommandCompleteMessage = exports.ReadyForQueryMessage = exports.NotificationResponseMessage = exports.BackendKeyDataMessage = exports.AuthenticationMD5Password = exports.ParameterStatusMessage = exports.ParameterDescriptionMessage = exports.RowDescriptionMessage = exports.Field = exports.CopyResponse = exports.CopyDataMessage = exports.DatabaseError = exports.copyDone = exports.emptyQuery = exports.replicationStart = exports.portalSuspended = exports.noData = exports.closeComplete = exports.bindComplete = exports.parseComplete = void 0;
    exports.parseComplete = {
      name: "parseComplete",
      length: 5
    };
    exports.bindComplete = {
      name: "bindComplete",
      length: 5
    };
    exports.closeComplete = {
      name: "closeComplete",
      length: 5
    };
    exports.noData = {
      name: "noData",
      length: 5
    };
    exports.portalSuspended = {
      name: "portalSuspended",
      length: 5
    };
    exports.replicationStart = {
      name: "replicationStart",
      length: 4
    };
    exports.emptyQuery = {
      name: "emptyQuery",
      length: 4
    };
    exports.copyDone = {
      name: "copyDone",
      length: 4
    };
    var DatabaseError2 = class extends Error {
      constructor(message, length, name) {
        super(message);
        this.length = length;
        this.name = name;
      }
    };
    exports.DatabaseError = DatabaseError2;
    var CopyDataMessage = class {
      constructor(length, chunk2) {
        this.length = length;
        this.chunk = chunk2;
        this.name = "copyData";
      }
    };
    exports.CopyDataMessage = CopyDataMessage;
    var CopyResponse = class {
      constructor(length, name, binary, columnCount) {
        this.length = length;
        this.name = name;
        this.binary = binary;
        this.columnTypes = new Array(columnCount);
      }
    };
    exports.CopyResponse = CopyResponse;
    var Field = class {
      constructor(name, tableID, columnID, dataTypeID, dataTypeSize, dataTypeModifier, format) {
        this.name = name;
        this.tableID = tableID;
        this.columnID = columnID;
        this.dataTypeID = dataTypeID;
        this.dataTypeSize = dataTypeSize;
        this.dataTypeModifier = dataTypeModifier;
        this.format = format;
      }
    };
    exports.Field = Field;
    var RowDescriptionMessage = class {
      constructor(length, fieldCount) {
        this.length = length;
        this.fieldCount = fieldCount;
        this.name = "rowDescription";
        this.fields = new Array(this.fieldCount);
      }
    };
    exports.RowDescriptionMessage = RowDescriptionMessage;
    var ParameterDescriptionMessage = class {
      constructor(length, parameterCount) {
        this.length = length;
        this.parameterCount = parameterCount;
        this.name = "parameterDescription";
        this.dataTypeIDs = new Array(this.parameterCount);
      }
    };
    exports.ParameterDescriptionMessage = ParameterDescriptionMessage;
    var ParameterStatusMessage = class {
      constructor(length, parameterName, parameterValue) {
        this.length = length;
        this.parameterName = parameterName;
        this.parameterValue = parameterValue;
        this.name = "parameterStatus";
      }
    };
    exports.ParameterStatusMessage = ParameterStatusMessage;
    var AuthenticationMD5Password = class {
      constructor(length, salt) {
        this.length = length;
        this.salt = salt;
        this.name = "authenticationMD5Password";
      }
    };
    exports.AuthenticationMD5Password = AuthenticationMD5Password;
    var BackendKeyDataMessage = class {
      constructor(length, processID, secretKey) {
        this.length = length;
        this.processID = processID;
        this.secretKey = secretKey;
        this.name = "backendKeyData";
      }
    };
    exports.BackendKeyDataMessage = BackendKeyDataMessage;
    var NotificationResponseMessage = class {
      constructor(length, processId, channel, payload) {
        this.length = length;
        this.processId = processId;
        this.channel = channel;
        this.payload = payload;
        this.name = "notification";
      }
    };
    exports.NotificationResponseMessage = NotificationResponseMessage;
    var ReadyForQueryMessage = class {
      constructor(length, status) {
        this.length = length;
        this.status = status;
        this.name = "readyForQuery";
      }
    };
    exports.ReadyForQueryMessage = ReadyForQueryMessage;
    var CommandCompleteMessage = class {
      constructor(length, text2) {
        this.length = length;
        this.text = text2;
        this.name = "commandComplete";
      }
    };
    exports.CommandCompleteMessage = CommandCompleteMessage;
    var DataRowMessage = class {
      constructor(length, fields) {
        this.length = length;
        this.fields = fields;
        this.name = "dataRow";
        this.fieldCount = fields.length;
      }
    };
    exports.DataRowMessage = DataRowMessage;
    var NoticeMessage = class {
      constructor(length, message) {
        this.length = length;
        this.message = message;
        this.name = "notice";
      }
    };
    exports.NoticeMessage = NoticeMessage;
  }
});

// ../../node_modules/.pnpm/pg-protocol@1.13.0/node_modules/pg-protocol/dist/buffer-writer.js
var require_buffer_writer = __commonJS({
  "../../node_modules/.pnpm/pg-protocol@1.13.0/node_modules/pg-protocol/dist/buffer-writer.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Writer = void 0;
    var Writer = class {
      constructor(size = 256) {
        this.size = size;
        this.offset = 5;
        this.headerPosition = 0;
        this.buffer = Buffer.allocUnsafe(size);
      }
      ensure(size) {
        const remaining = this.buffer.length - this.offset;
        if (remaining < size) {
          const oldBuffer = this.buffer;
          const newSize = oldBuffer.length + (oldBuffer.length >> 1) + size;
          this.buffer = Buffer.allocUnsafe(newSize);
          oldBuffer.copy(this.buffer);
        }
      }
      addInt32(num) {
        this.ensure(4);
        this.buffer[this.offset++] = num >>> 24 & 255;
        this.buffer[this.offset++] = num >>> 16 & 255;
        this.buffer[this.offset++] = num >>> 8 & 255;
        this.buffer[this.offset++] = num >>> 0 & 255;
        return this;
      }
      addInt16(num) {
        this.ensure(2);
        this.buffer[this.offset++] = num >>> 8 & 255;
        this.buffer[this.offset++] = num >>> 0 & 255;
        return this;
      }
      addCString(string4) {
        if (!string4) {
          this.ensure(1);
        } else {
          const len = Buffer.byteLength(string4);
          this.ensure(len + 1);
          this.buffer.write(string4, this.offset, "utf-8");
          this.offset += len;
        }
        this.buffer[this.offset++] = 0;
        return this;
      }
      addString(string4 = "") {
        const len = Buffer.byteLength(string4);
        this.ensure(len);
        this.buffer.write(string4, this.offset);
        this.offset += len;
        return this;
      }
      add(otherBuffer) {
        this.ensure(otherBuffer.length);
        otherBuffer.copy(this.buffer, this.offset);
        this.offset += otherBuffer.length;
        return this;
      }
      join(code) {
        if (code) {
          this.buffer[this.headerPosition] = code;
          const length = this.offset - (this.headerPosition + 1);
          this.buffer.writeInt32BE(length, this.headerPosition + 1);
        }
        return this.buffer.slice(code ? 0 : 5, this.offset);
      }
      flush(code) {
        const result = this.join(code);
        this.offset = 5;
        this.headerPosition = 0;
        this.buffer = Buffer.allocUnsafe(this.size);
        return result;
      }
    };
    exports.Writer = Writer;
  }
});

// ../../node_modules/.pnpm/pg-protocol@1.13.0/node_modules/pg-protocol/dist/serializer.js
var require_serializer = __commonJS({
  "../../node_modules/.pnpm/pg-protocol@1.13.0/node_modules/pg-protocol/dist/serializer.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.serialize = void 0;
    var buffer_writer_1 = require_buffer_writer();
    var writer = new buffer_writer_1.Writer();
    var startup = (opts) => {
      writer.addInt16(3).addInt16(0);
      for (const key of Object.keys(opts)) {
        writer.addCString(key).addCString(opts[key]);
      }
      writer.addCString("client_encoding").addCString("UTF8");
      const bodyBuffer = writer.addCString("").flush();
      const length = bodyBuffer.length + 4;
      return new buffer_writer_1.Writer().addInt32(length).add(bodyBuffer).flush();
    };
    var requestSsl = () => {
      const response = Buffer.allocUnsafe(8);
      response.writeInt32BE(8, 0);
      response.writeInt32BE(80877103, 4);
      return response;
    };
    var password = (password2) => {
      return writer.addCString(password2).flush(
        112
        /* code.startup */
      );
    };
    var sendSASLInitialResponseMessage = function(mechanism, initialResponse) {
      writer.addCString(mechanism).addInt32(Buffer.byteLength(initialResponse)).addString(initialResponse);
      return writer.flush(
        112
        /* code.startup */
      );
    };
    var sendSCRAMClientFinalMessage = function(additionalData) {
      return writer.addString(additionalData).flush(
        112
        /* code.startup */
      );
    };
    var query = (text2) => {
      return writer.addCString(text2).flush(
        81
        /* code.query */
      );
    };
    var emptyArray = [];
    var parse3 = (query2) => {
      const name = query2.name || "";
      if (name.length > 63) {
        console.error("Warning! Postgres only supports 63 characters for query names.");
        console.error("You supplied %s (%s)", name, name.length);
        console.error("This can cause conflicts and silent errors executing queries");
      }
      const types3 = query2.types || emptyArray;
      const len = types3.length;
      const buffer = writer.addCString(name).addCString(query2.text).addInt16(len);
      for (let i = 0; i < len; i++) {
        buffer.addInt32(types3[i]);
      }
      return writer.flush(
        80
        /* code.parse */
      );
    };
    var paramWriter = new buffer_writer_1.Writer();
    var writeValues = function(values, valueMapper) {
      for (let i = 0; i < values.length; i++) {
        const mappedVal = valueMapper ? valueMapper(values[i], i) : values[i];
        if (mappedVal == null) {
          writer.addInt16(
            0
            /* ParamType.STRING */
          );
          paramWriter.addInt32(-1);
        } else if (mappedVal instanceof Buffer) {
          writer.addInt16(
            1
            /* ParamType.BINARY */
          );
          paramWriter.addInt32(mappedVal.length);
          paramWriter.add(mappedVal);
        } else {
          writer.addInt16(
            0
            /* ParamType.STRING */
          );
          paramWriter.addInt32(Buffer.byteLength(mappedVal));
          paramWriter.addString(mappedVal);
        }
      }
    };
    var bind = (config2 = {}) => {
      const portal = config2.portal || "";
      const statement = config2.statement || "";
      const binary = config2.binary || false;
      const values = config2.values || emptyArray;
      const len = values.length;
      writer.addCString(portal).addCString(statement);
      writer.addInt16(len);
      writeValues(values, config2.valueMapper);
      writer.addInt16(len);
      writer.add(paramWriter.flush());
      writer.addInt16(1);
      writer.addInt16(
        binary ? 1 : 0
        /* ParamType.STRING */
      );
      return writer.flush(
        66
        /* code.bind */
      );
    };
    var emptyExecute = Buffer.from([69, 0, 0, 0, 9, 0, 0, 0, 0, 0]);
    var execute = (config2) => {
      if (!config2 || !config2.portal && !config2.rows) {
        return emptyExecute;
      }
      const portal = config2.portal || "";
      const rows = config2.rows || 0;
      const portalLength = Buffer.byteLength(portal);
      const len = 4 + portalLength + 1 + 4;
      const buff = Buffer.allocUnsafe(1 + len);
      buff[0] = 69;
      buff.writeInt32BE(len, 1);
      buff.write(portal, 5, "utf-8");
      buff[portalLength + 5] = 0;
      buff.writeUInt32BE(rows, buff.length - 4);
      return buff;
    };
    var cancel = (processID, secretKey) => {
      const buffer = Buffer.allocUnsafe(16);
      buffer.writeInt32BE(16, 0);
      buffer.writeInt16BE(1234, 4);
      buffer.writeInt16BE(5678, 6);
      buffer.writeInt32BE(processID, 8);
      buffer.writeInt32BE(secretKey, 12);
      return buffer;
    };
    var cstringMessage = (code, string4) => {
      const stringLen = Buffer.byteLength(string4);
      const len = 4 + stringLen + 1;
      const buffer = Buffer.allocUnsafe(1 + len);
      buffer[0] = code;
      buffer.writeInt32BE(len, 1);
      buffer.write(string4, 5, "utf-8");
      buffer[len] = 0;
      return buffer;
    };
    var emptyDescribePortal = writer.addCString("P").flush(
      68
      /* code.describe */
    );
    var emptyDescribeStatement = writer.addCString("S").flush(
      68
      /* code.describe */
    );
    var describe = (msg) => {
      return msg.name ? cstringMessage(68, `${msg.type}${msg.name || ""}`) : msg.type === "P" ? emptyDescribePortal : emptyDescribeStatement;
    };
    var close = (msg) => {
      const text2 = `${msg.type}${msg.name || ""}`;
      return cstringMessage(67, text2);
    };
    var copyData = (chunk2) => {
      return writer.add(chunk2).flush(
        100
        /* code.copyFromChunk */
      );
    };
    var copyFail = (message) => {
      return cstringMessage(102, message);
    };
    var codeOnlyBuffer = (code) => Buffer.from([code, 0, 0, 0, 4]);
    var flushBuffer = codeOnlyBuffer(
      72
      /* code.flush */
    );
    var syncBuffer = codeOnlyBuffer(
      83
      /* code.sync */
    );
    var endBuffer = codeOnlyBuffer(
      88
      /* code.end */
    );
    var copyDoneBuffer = codeOnlyBuffer(
      99
      /* code.copyDone */
    );
    var serialize = {
      startup,
      password,
      requestSsl,
      sendSASLInitialResponseMessage,
      sendSCRAMClientFinalMessage,
      query,
      parse: parse3,
      bind,
      execute,
      describe,
      close,
      flush: () => flushBuffer,
      sync: () => syncBuffer,
      end: () => endBuffer,
      copyData,
      copyDone: () => copyDoneBuffer,
      copyFail,
      cancel
    };
    exports.serialize = serialize;
  }
});

// ../../node_modules/.pnpm/pg-protocol@1.13.0/node_modules/pg-protocol/dist/buffer-reader.js
var require_buffer_reader = __commonJS({
  "../../node_modules/.pnpm/pg-protocol@1.13.0/node_modules/pg-protocol/dist/buffer-reader.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BufferReader = void 0;
    var BufferReader = class {
      constructor(offset = 0) {
        this.offset = offset;
        this.buffer = Buffer.allocUnsafe(0);
        this.encoding = "utf-8";
      }
      setBuffer(offset, buffer) {
        this.offset = offset;
        this.buffer = buffer;
      }
      int16() {
        const result = this.buffer.readInt16BE(this.offset);
        this.offset += 2;
        return result;
      }
      byte() {
        const result = this.buffer[this.offset];
        this.offset++;
        return result;
      }
      int32() {
        const result = this.buffer.readInt32BE(this.offset);
        this.offset += 4;
        return result;
      }
      uint32() {
        const result = this.buffer.readUInt32BE(this.offset);
        this.offset += 4;
        return result;
      }
      string(length) {
        const result = this.buffer.toString(this.encoding, this.offset, this.offset + length);
        this.offset += length;
        return result;
      }
      cstring() {
        const start = this.offset;
        let end = start;
        while (this.buffer[end++] !== 0) {
        }
        this.offset = end;
        return this.buffer.toString(this.encoding, start, end - 1);
      }
      bytes(length) {
        const result = this.buffer.slice(this.offset, this.offset + length);
        this.offset += length;
        return result;
      }
    };
    exports.BufferReader = BufferReader;
  }
});

// ../../node_modules/.pnpm/pg-protocol@1.13.0/node_modules/pg-protocol/dist/parser.js
var require_parser = __commonJS({
  "../../node_modules/.pnpm/pg-protocol@1.13.0/node_modules/pg-protocol/dist/parser.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Parser = void 0;
    var messages_1 = require_messages();
    var buffer_reader_1 = require_buffer_reader();
    var CODE_LENGTH = 1;
    var LEN_LENGTH = 4;
    var HEADER_LENGTH = CODE_LENGTH + LEN_LENGTH;
    var LATEINIT_LENGTH = -1;
    var emptyBuffer = Buffer.allocUnsafe(0);
    var Parser = class {
      constructor(opts) {
        this.buffer = emptyBuffer;
        this.bufferLength = 0;
        this.bufferOffset = 0;
        this.reader = new buffer_reader_1.BufferReader();
        if ((opts === null || opts === void 0 ? void 0 : opts.mode) === "binary") {
          throw new Error("Binary mode not supported yet");
        }
        this.mode = (opts === null || opts === void 0 ? void 0 : opts.mode) || "text";
      }
      parse(buffer, callback) {
        this.mergeBuffer(buffer);
        const bufferFullLength = this.bufferOffset + this.bufferLength;
        let offset = this.bufferOffset;
        while (offset + HEADER_LENGTH <= bufferFullLength) {
          const code = this.buffer[offset];
          const length = this.buffer.readUInt32BE(offset + CODE_LENGTH);
          const fullMessageLength = CODE_LENGTH + length;
          if (fullMessageLength + offset <= bufferFullLength) {
            const message = this.handlePacket(offset + HEADER_LENGTH, code, length, this.buffer);
            callback(message);
            offset += fullMessageLength;
          } else {
            break;
          }
        }
        if (offset === bufferFullLength) {
          this.buffer = emptyBuffer;
          this.bufferLength = 0;
          this.bufferOffset = 0;
        } else {
          this.bufferLength = bufferFullLength - offset;
          this.bufferOffset = offset;
        }
      }
      mergeBuffer(buffer) {
        if (this.bufferLength > 0) {
          const newLength = this.bufferLength + buffer.byteLength;
          const newFullLength = newLength + this.bufferOffset;
          if (newFullLength > this.buffer.byteLength) {
            let newBuffer;
            if (newLength <= this.buffer.byteLength && this.bufferOffset >= this.bufferLength) {
              newBuffer = this.buffer;
            } else {
              let newBufferLength = this.buffer.byteLength * 2;
              while (newLength >= newBufferLength) {
                newBufferLength *= 2;
              }
              newBuffer = Buffer.allocUnsafe(newBufferLength);
            }
            this.buffer.copy(newBuffer, 0, this.bufferOffset, this.bufferOffset + this.bufferLength);
            this.buffer = newBuffer;
            this.bufferOffset = 0;
          }
          buffer.copy(this.buffer, this.bufferOffset + this.bufferLength);
          this.bufferLength = newLength;
        } else {
          this.buffer = buffer;
          this.bufferOffset = 0;
          this.bufferLength = buffer.byteLength;
        }
      }
      handlePacket(offset, code, length, bytes) {
        const { reader } = this;
        reader.setBuffer(offset, bytes);
        let message;
        switch (code) {
          case 50:
            message = messages_1.bindComplete;
            break;
          case 49:
            message = messages_1.parseComplete;
            break;
          case 51:
            message = messages_1.closeComplete;
            break;
          case 110:
            message = messages_1.noData;
            break;
          case 115:
            message = messages_1.portalSuspended;
            break;
          case 99:
            message = messages_1.copyDone;
            break;
          case 87:
            message = messages_1.replicationStart;
            break;
          case 73:
            message = messages_1.emptyQuery;
            break;
          case 68:
            message = parseDataRowMessage(reader);
            break;
          case 67:
            message = parseCommandCompleteMessage(reader);
            break;
          case 90:
            message = parseReadyForQueryMessage(reader);
            break;
          case 65:
            message = parseNotificationMessage(reader);
            break;
          case 82:
            message = parseAuthenticationResponse(reader, length);
            break;
          case 83:
            message = parseParameterStatusMessage(reader);
            break;
          case 75:
            message = parseBackendKeyData(reader);
            break;
          case 69:
            message = parseErrorMessage(reader, "error");
            break;
          case 78:
            message = parseErrorMessage(reader, "notice");
            break;
          case 84:
            message = parseRowDescriptionMessage(reader);
            break;
          case 116:
            message = parseParameterDescriptionMessage(reader);
            break;
          case 71:
            message = parseCopyInMessage(reader);
            break;
          case 72:
            message = parseCopyOutMessage(reader);
            break;
          case 100:
            message = parseCopyData(reader, length);
            break;
          default:
            return new messages_1.DatabaseError("received invalid response: " + code.toString(16), length, "error");
        }
        reader.setBuffer(0, emptyBuffer);
        message.length = length;
        return message;
      }
    };
    exports.Parser = Parser;
    var parseReadyForQueryMessage = (reader) => {
      const status = reader.string(1);
      return new messages_1.ReadyForQueryMessage(LATEINIT_LENGTH, status);
    };
    var parseCommandCompleteMessage = (reader) => {
      const text2 = reader.cstring();
      return new messages_1.CommandCompleteMessage(LATEINIT_LENGTH, text2);
    };
    var parseCopyData = (reader, length) => {
      const chunk2 = reader.bytes(length - 4);
      return new messages_1.CopyDataMessage(LATEINIT_LENGTH, chunk2);
    };
    var parseCopyInMessage = (reader) => parseCopyMessage(reader, "copyInResponse");
    var parseCopyOutMessage = (reader) => parseCopyMessage(reader, "copyOutResponse");
    var parseCopyMessage = (reader, messageName) => {
      const isBinary = reader.byte() !== 0;
      const columnCount = reader.int16();
      const message = new messages_1.CopyResponse(LATEINIT_LENGTH, messageName, isBinary, columnCount);
      for (let i = 0; i < columnCount; i++) {
        message.columnTypes[i] = reader.int16();
      }
      return message;
    };
    var parseNotificationMessage = (reader) => {
      const processId = reader.int32();
      const channel = reader.cstring();
      const payload = reader.cstring();
      return new messages_1.NotificationResponseMessage(LATEINIT_LENGTH, processId, channel, payload);
    };
    var parseRowDescriptionMessage = (reader) => {
      const fieldCount = reader.int16();
      const message = new messages_1.RowDescriptionMessage(LATEINIT_LENGTH, fieldCount);
      for (let i = 0; i < fieldCount; i++) {
        message.fields[i] = parseField(reader);
      }
      return message;
    };
    var parseField = (reader) => {
      const name = reader.cstring();
      const tableID = reader.uint32();
      const columnID = reader.int16();
      const dataTypeID = reader.uint32();
      const dataTypeSize = reader.int16();
      const dataTypeModifier = reader.int32();
      const mode = reader.int16() === 0 ? "text" : "binary";
      return new messages_1.Field(name, tableID, columnID, dataTypeID, dataTypeSize, dataTypeModifier, mode);
    };
    var parseParameterDescriptionMessage = (reader) => {
      const parameterCount = reader.int16();
      const message = new messages_1.ParameterDescriptionMessage(LATEINIT_LENGTH, parameterCount);
      for (let i = 0; i < parameterCount; i++) {
        message.dataTypeIDs[i] = reader.int32();
      }
      return message;
    };
    var parseDataRowMessage = (reader) => {
      const fieldCount = reader.int16();
      const fields = new Array(fieldCount);
      for (let i = 0; i < fieldCount; i++) {
        const len = reader.int32();
        fields[i] = len === -1 ? null : reader.string(len);
      }
      return new messages_1.DataRowMessage(LATEINIT_LENGTH, fields);
    };
    var parseParameterStatusMessage = (reader) => {
      const name = reader.cstring();
      const value = reader.cstring();
      return new messages_1.ParameterStatusMessage(LATEINIT_LENGTH, name, value);
    };
    var parseBackendKeyData = (reader) => {
      const processID = reader.int32();
      const secretKey = reader.int32();
      return new messages_1.BackendKeyDataMessage(LATEINIT_LENGTH, processID, secretKey);
    };
    var parseAuthenticationResponse = (reader, length) => {
      const code = reader.int32();
      const message = {
        name: "authenticationOk",
        length
      };
      switch (code) {
        case 0:
          break;
        case 3:
          if (message.length === 8) {
            message.name = "authenticationCleartextPassword";
          }
          break;
        case 5:
          if (message.length === 12) {
            message.name = "authenticationMD5Password";
            const salt = reader.bytes(4);
            return new messages_1.AuthenticationMD5Password(LATEINIT_LENGTH, salt);
          }
          break;
        case 10:
          {
            message.name = "authenticationSASL";
            message.mechanisms = [];
            let mechanism;
            do {
              mechanism = reader.cstring();
              if (mechanism) {
                message.mechanisms.push(mechanism);
              }
            } while (mechanism);
          }
          break;
        case 11:
          message.name = "authenticationSASLContinue";
          message.data = reader.string(length - 8);
          break;
        case 12:
          message.name = "authenticationSASLFinal";
          message.data = reader.string(length - 8);
          break;
        default:
          throw new Error("Unknown authenticationOk message type " + code);
      }
      return message;
    };
    var parseErrorMessage = (reader, name) => {
      const fields = {};
      let fieldType = reader.string(1);
      while (fieldType !== "\0") {
        fields[fieldType] = reader.cstring();
        fieldType = reader.string(1);
      }
      const messageValue = fields.M;
      const message = name === "notice" ? new messages_1.NoticeMessage(LATEINIT_LENGTH, messageValue) : new messages_1.DatabaseError(messageValue, LATEINIT_LENGTH, name);
      message.severity = fields.S;
      message.code = fields.C;
      message.detail = fields.D;
      message.hint = fields.H;
      message.position = fields.P;
      message.internalPosition = fields.p;
      message.internalQuery = fields.q;
      message.where = fields.W;
      message.schema = fields.s;
      message.table = fields.t;
      message.column = fields.c;
      message.dataType = fields.d;
      message.constraint = fields.n;
      message.file = fields.F;
      message.line = fields.L;
      message.routine = fields.R;
      return message;
    };
  }
});

// ../../node_modules/.pnpm/pg-protocol@1.13.0/node_modules/pg-protocol/dist/index.js
var require_dist = __commonJS({
  "../../node_modules/.pnpm/pg-protocol@1.13.0/node_modules/pg-protocol/dist/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DatabaseError = exports.serialize = exports.parse = void 0;
    var messages_1 = require_messages();
    Object.defineProperty(exports, "DatabaseError", { enumerable: true, get: function() {
      return messages_1.DatabaseError;
    } });
    var serializer_1 = require_serializer();
    Object.defineProperty(exports, "serialize", { enumerable: true, get: function() {
      return serializer_1.serialize;
    } });
    var parser_1 = require_parser();
    function parse3(stream, callback) {
      const parser = new parser_1.Parser();
      stream.on("data", (buffer) => parser.parse(buffer, callback));
      return new Promise((resolve) => stream.on("end", () => resolve()));
    }
    exports.parse = parse3;
  }
});

// ../../node_modules/.pnpm/pg-cloudflare@1.3.0/node_modules/pg-cloudflare/dist/empty.js
var require_empty = __commonJS({
  "../../node_modules/.pnpm/pg-cloudflare@1.3.0/node_modules/pg-cloudflare/dist/empty.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.default = {};
  }
});

// ../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/stream.js
var require_stream = __commonJS({
  "../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/stream.js"(exports, module) {
    var { getStream, getSecureStream } = getStreamFuncs();
    module.exports = {
      /**
       * Get a socket stream compatible with the current runtime environment.
       * @returns {Duplex}
       */
      getStream,
      /**
       * Get a TLS secured socket, compatible with the current environment,
       * using the socket and other settings given in `options`.
       * @returns {Duplex}
       */
      getSecureStream
    };
    function getNodejsStreamFuncs() {
      function getStream2(ssl) {
        const net = __require("net");
        return new net.Socket();
      }
      function getSecureStream2(options) {
        const tls = __require("tls");
        return tls.connect(options);
      }
      return {
        getStream: getStream2,
        getSecureStream: getSecureStream2
      };
    }
    function getCloudflareStreamFuncs() {
      function getStream2(ssl) {
        const { CloudflareSocket } = require_empty();
        return new CloudflareSocket(ssl);
      }
      function getSecureStream2(options) {
        options.socket.startTls(options);
        return options.socket;
      }
      return {
        getStream: getStream2,
        getSecureStream: getSecureStream2
      };
    }
    function isCloudflareRuntime() {
      if (typeof navigator === "object" && navigator !== null && typeof navigator.userAgent === "string") {
        return navigator.userAgent === "Cloudflare-Workers";
      }
      if (typeof Response === "function") {
        const resp = new Response(null, { cf: { thing: true } });
        if (typeof resp.cf === "object" && resp.cf !== null && resp.cf.thing) {
          return true;
        }
      }
      return false;
    }
    function getStreamFuncs() {
      if (isCloudflareRuntime()) {
        return getCloudflareStreamFuncs();
      }
      return getNodejsStreamFuncs();
    }
  }
});

// ../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/connection.js
var require_connection = __commonJS({
  "../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/connection.js"(exports, module) {
    "use strict";
    var EventEmitter2 = __require("events").EventEmitter;
    var { parse: parse3, serialize } = require_dist();
    var { getStream, getSecureStream } = require_stream();
    var flushBuffer = serialize.flush();
    var syncBuffer = serialize.sync();
    var endBuffer = serialize.end();
    var Connection2 = class extends EventEmitter2 {
      constructor(config2) {
        super();
        config2 = config2 || {};
        this.stream = config2.stream || getStream(config2.ssl);
        if (typeof this.stream === "function") {
          this.stream = this.stream(config2);
        }
        this._keepAlive = config2.keepAlive;
        this._keepAliveInitialDelayMillis = config2.keepAliveInitialDelayMillis;
        this.parsedStatements = {};
        this.ssl = config2.ssl || false;
        this._ending = false;
        this._emitMessage = false;
        const self = this;
        this.on("newListener", function(eventName) {
          if (eventName === "message") {
            self._emitMessage = true;
          }
        });
      }
      connect(port2, host) {
        const self = this;
        this._connecting = true;
        this.stream.setNoDelay(true);
        this.stream.connect(port2, host);
        this.stream.once("connect", function() {
          if (self._keepAlive) {
            self.stream.setKeepAlive(true, self._keepAliveInitialDelayMillis);
          }
          self.emit("connect");
        });
        const reportStreamError = function(error40) {
          if (self._ending && (error40.code === "ECONNRESET" || error40.code === "EPIPE")) {
            return;
          }
          self.emit("error", error40);
        };
        this.stream.on("error", reportStreamError);
        this.stream.on("close", function() {
          self.emit("end");
        });
        if (!this.ssl) {
          return this.attachListeners(this.stream);
        }
        this.stream.once("data", function(buffer) {
          const responseCode = buffer.toString("utf8");
          switch (responseCode) {
            case "S":
              break;
            case "N":
              self.stream.end();
              return self.emit("error", new Error("The server does not support SSL connections"));
            default:
              self.stream.end();
              return self.emit("error", new Error("There was an error establishing an SSL connection"));
          }
          const options = {
            socket: self.stream
          };
          if (self.ssl !== true) {
            Object.assign(options, self.ssl);
            if ("key" in self.ssl) {
              options.key = self.ssl.key;
            }
          }
          const net = __require("net");
          if (net.isIP && net.isIP(host) === 0) {
            options.servername = host;
          }
          try {
            self.stream = getSecureStream(options);
          } catch (err) {
            return self.emit("error", err);
          }
          self.attachListeners(self.stream);
          self.stream.on("error", reportStreamError);
          self.emit("sslconnect");
        });
      }
      attachListeners(stream) {
        parse3(stream, (msg) => {
          const eventName = msg.name === "error" ? "errorMessage" : msg.name;
          if (this._emitMessage) {
            this.emit("message", msg);
          }
          this.emit(eventName, msg);
        });
      }
      requestSsl() {
        this.stream.write(serialize.requestSsl());
      }
      startup(config2) {
        this.stream.write(serialize.startup(config2));
      }
      cancel(processID, secretKey) {
        this._send(serialize.cancel(processID, secretKey));
      }
      password(password) {
        this._send(serialize.password(password));
      }
      sendSASLInitialResponseMessage(mechanism, initialResponse) {
        this._send(serialize.sendSASLInitialResponseMessage(mechanism, initialResponse));
      }
      sendSCRAMClientFinalMessage(additionalData) {
        this._send(serialize.sendSCRAMClientFinalMessage(additionalData));
      }
      _send(buffer) {
        if (!this.stream.writable) {
          return false;
        }
        return this.stream.write(buffer);
      }
      query(text2) {
        this._send(serialize.query(text2));
      }
      // send parse message
      parse(query) {
        this._send(serialize.parse(query));
      }
      // send bind message
      bind(config2) {
        this._send(serialize.bind(config2));
      }
      // send execute message
      execute(config2) {
        this._send(serialize.execute(config2));
      }
      flush() {
        if (this.stream.writable) {
          this.stream.write(flushBuffer);
        }
      }
      sync() {
        this._ending = true;
        this._send(syncBuffer);
      }
      ref() {
        this.stream.ref();
      }
      unref() {
        this.stream.unref();
      }
      end() {
        this._ending = true;
        if (!this._connecting || !this.stream.writable) {
          this.stream.end();
          return;
        }
        return this.stream.write(endBuffer, () => {
          this.stream.end();
        });
      }
      close(msg) {
        this._send(serialize.close(msg));
      }
      describe(msg) {
        this._send(serialize.describe(msg));
      }
      sendCopyFromChunk(chunk2) {
        this._send(serialize.copyData(chunk2));
      }
      endCopyFrom() {
        this._send(serialize.copyDone());
      }
      sendCopyFail(msg) {
        this._send(serialize.copyFail(msg));
      }
    };
    module.exports = Connection2;
  }
});

// ../../node_modules/.pnpm/split2@4.2.0/node_modules/split2/index.js
var require_split2 = __commonJS({
  "../../node_modules/.pnpm/split2@4.2.0/node_modules/split2/index.js"(exports, module) {
    "use strict";
    var { Transform } = __require("stream");
    var { StringDecoder } = __require("string_decoder");
    var kLast = /* @__PURE__ */ Symbol("last");
    var kDecoder = /* @__PURE__ */ Symbol("decoder");
    function transform2(chunk2, enc, cb) {
      let list;
      if (this.overflow) {
        const buf = this[kDecoder].write(chunk2);
        list = buf.split(this.matcher);
        if (list.length === 1) return cb();
        list.shift();
        this.overflow = false;
      } else {
        this[kLast] += this[kDecoder].write(chunk2);
        list = this[kLast].split(this.matcher);
      }
      this[kLast] = list.pop();
      for (let i = 0; i < list.length; i++) {
        try {
          push(this, this.mapper(list[i]));
        } catch (error40) {
          return cb(error40);
        }
      }
      this.overflow = this[kLast].length > this.maxLength;
      if (this.overflow && !this.skipOverflow) {
        cb(new Error("maximum buffer reached"));
        return;
      }
      cb();
    }
    function flush(cb) {
      this[kLast] += this[kDecoder].end();
      if (this[kLast]) {
        try {
          push(this, this.mapper(this[kLast]));
        } catch (error40) {
          return cb(error40);
        }
      }
      cb();
    }
    function push(self, val) {
      if (val !== void 0) {
        self.push(val);
      }
    }
    function noop(incoming) {
      return incoming;
    }
    function split(matcher, mapper, options) {
      matcher = matcher || /\r?\n/;
      mapper = mapper || noop;
      options = options || {};
      switch (arguments.length) {
        case 1:
          if (typeof matcher === "function") {
            mapper = matcher;
            matcher = /\r?\n/;
          } else if (typeof matcher === "object" && !(matcher instanceof RegExp) && !matcher[Symbol.split]) {
            options = matcher;
            matcher = /\r?\n/;
          }
          break;
        case 2:
          if (typeof matcher === "function") {
            options = mapper;
            mapper = matcher;
            matcher = /\r?\n/;
          } else if (typeof mapper === "object") {
            options = mapper;
            mapper = noop;
          }
      }
      options = Object.assign({}, options);
      options.autoDestroy = true;
      options.transform = transform2;
      options.flush = flush;
      options.readableObjectMode = true;
      const stream = new Transform(options);
      stream[kLast] = "";
      stream[kDecoder] = new StringDecoder("utf8");
      stream.matcher = matcher;
      stream.mapper = mapper;
      stream.maxLength = options.maxLength;
      stream.skipOverflow = options.skipOverflow || false;
      stream.overflow = false;
      stream._destroy = function(err, cb) {
        this._writableState.errorEmitted = false;
        cb(err);
      };
      return stream;
    }
    module.exports = split;
  }
});

// ../../node_modules/.pnpm/pgpass@1.0.5/node_modules/pgpass/lib/helper.js
var require_helper = __commonJS({
  "../../node_modules/.pnpm/pgpass@1.0.5/node_modules/pgpass/lib/helper.js"(exports, module) {
    "use strict";
    var path4 = __require("path");
    var Stream = __require("stream").Stream;
    var split = require_split2();
    var util2 = __require("util");
    var defaultPort = 5432;
    var isWin = process.platform === "win32";
    var warnStream = process.stderr;
    var S_IRWXG = 56;
    var S_IRWXO = 7;
    var S_IFMT = 61440;
    var S_IFREG = 32768;
    function isRegFile(mode) {
      return (mode & S_IFMT) == S_IFREG;
    }
    var fieldNames = ["host", "port", "database", "user", "password"];
    var nrOfFields = fieldNames.length;
    var passKey = fieldNames[nrOfFields - 1];
    function warn() {
      var isWritable = warnStream instanceof Stream && true === warnStream.writable;
      if (isWritable) {
        var args = Array.prototype.slice.call(arguments).concat("\n");
        warnStream.write(util2.format.apply(util2, args));
      }
    }
    Object.defineProperty(module.exports, "isWin", {
      get: function() {
        return isWin;
      },
      set: function(val) {
        isWin = val;
      }
    });
    module.exports.warnTo = function(stream) {
      var old = warnStream;
      warnStream = stream;
      return old;
    };
    module.exports.getFileName = function(rawEnv) {
      var env = rawEnv || process.env;
      var file2 = env.PGPASSFILE || (isWin ? path4.join(env.APPDATA || "./", "postgresql", "pgpass.conf") : path4.join(env.HOME || "./", ".pgpass"));
      return file2;
    };
    module.exports.usePgPass = function(stats, fname) {
      if (Object.prototype.hasOwnProperty.call(process.env, "PGPASSWORD")) {
        return false;
      }
      if (isWin) {
        return true;
      }
      fname = fname || "<unkn>";
      if (!isRegFile(stats.mode)) {
        warn('WARNING: password file "%s" is not a plain file', fname);
        return false;
      }
      if (stats.mode & (S_IRWXG | S_IRWXO)) {
        warn('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less', fname);
        return false;
      }
      return true;
    };
    var matcher = module.exports.match = function(connInfo, entry) {
      return fieldNames.slice(0, -1).reduce(function(prev, field, idx) {
        if (idx == 1) {
          if (Number(connInfo[field] || defaultPort) === Number(entry[field])) {
            return prev && true;
          }
        }
        return prev && (entry[field] === "*" || entry[field] === connInfo[field]);
      }, true);
    };
    module.exports.getPassword = function(connInfo, stream, cb) {
      var pass;
      var lineStream = stream.pipe(split());
      function onLine(line2) {
        var entry = parseLine(line2);
        if (entry && isValidEntry(entry) && matcher(connInfo, entry)) {
          pass = entry[passKey];
          lineStream.end();
        }
      }
      var onEnd = function() {
        stream.destroy();
        cb(pass);
      };
      var onErr = function(err) {
        stream.destroy();
        warn("WARNING: error on reading file: %s", err);
        cb(void 0);
      };
      stream.on("error", onErr);
      lineStream.on("data", onLine).on("end", onEnd).on("error", onErr);
    };
    var parseLine = module.exports.parseLine = function(line2) {
      if (line2.length < 11 || line2.match(/^\s+#/)) {
        return null;
      }
      var curChar = "";
      var prevChar = "";
      var fieldIdx = 0;
      var startIdx = 0;
      var endIdx = 0;
      var obj = {};
      var isLastField = false;
      var addToObj = function(idx, i0, i1) {
        var field = line2.substring(i0, i1);
        if (!Object.hasOwnProperty.call(process.env, "PGPASS_NO_DEESCAPE")) {
          field = field.replace(/\\([:\\])/g, "$1");
        }
        obj[fieldNames[idx]] = field;
      };
      for (var i = 0; i < line2.length - 1; i += 1) {
        curChar = line2.charAt(i + 1);
        prevChar = line2.charAt(i);
        isLastField = fieldIdx == nrOfFields - 1;
        if (isLastField) {
          addToObj(fieldIdx, startIdx);
          break;
        }
        if (i >= 0 && curChar == ":" && prevChar !== "\\") {
          addToObj(fieldIdx, startIdx, i + 1);
          startIdx = i + 2;
          fieldIdx += 1;
        }
      }
      obj = Object.keys(obj).length === nrOfFields ? obj : null;
      return obj;
    };
    var isValidEntry = module.exports.isValidEntry = function(entry) {
      var rules = {
        // host
        0: function(x) {
          return x.length > 0;
        },
        // port
        1: function(x) {
          if (x === "*") {
            return true;
          }
          x = Number(x);
          return isFinite(x) && x > 0 && x < 9007199254740992 && Math.floor(x) === x;
        },
        // database
        2: function(x) {
          return x.length > 0;
        },
        // username
        3: function(x) {
          return x.length > 0;
        },
        // password
        4: function(x) {
          return x.length > 0;
        }
      };
      for (var idx = 0; idx < fieldNames.length; idx += 1) {
        var rule = rules[idx];
        var value = entry[fieldNames[idx]] || "";
        var res = rule(value);
        if (!res) {
          return false;
        }
      }
      return true;
    };
  }
});

// ../../node_modules/.pnpm/pgpass@1.0.5/node_modules/pgpass/lib/index.js
var require_lib4 = __commonJS({
  "../../node_modules/.pnpm/pgpass@1.0.5/node_modules/pgpass/lib/index.js"(exports, module) {
    "use strict";
    var path4 = __require("path");
    var fs2 = __require("fs");
    var helper = require_helper();
    module.exports = function(connInfo, cb) {
      var file2 = helper.getFileName();
      fs2.stat(file2, function(err, stat) {
        if (err || !helper.usePgPass(stat, file2)) {
          return cb(void 0);
        }
        var st = fs2.createReadStream(file2);
        helper.getPassword(connInfo, st, cb);
      });
    };
    module.exports.warnTo = helper.warnTo;
  }
});

// ../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/client.js
var require_client = __commonJS({
  "../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/client.js"(exports, module) {
    var EventEmitter2 = __require("events").EventEmitter;
    var utils = require_utils3();
    var nodeUtils = __require("util");
    var sasl = require_sasl();
    var TypeOverrides2 = require_type_overrides();
    var ConnectionParameters = require_connection_parameters();
    var Query2 = require_query2();
    var defaults2 = require_defaults();
    var Connection2 = require_connection();
    var crypto4 = require_utils4();
    var activeQueryDeprecationNotice = nodeUtils.deprecate(
      () => {
      },
      "Client.activeQuery is deprecated and will be removed in pg@9.0"
    );
    var queryQueueDeprecationNotice = nodeUtils.deprecate(
      () => {
      },
      "Client.queryQueue is deprecated and will be removed in pg@9.0."
    );
    var pgPassDeprecationNotice = nodeUtils.deprecate(
      () => {
      },
      "pgpass support is deprecated and will be removed in pg@9.0. You can provide an async function as the password property to the Client/Pool constructor that returns a password instead. Within this function you can call the pgpass module in your own code."
    );
    var byoPromiseDeprecationNotice = nodeUtils.deprecate(
      () => {
      },
      "Passing a custom Promise implementation to the Client/Pool constructor is deprecated and will be removed in pg@9.0."
    );
    var queryQueueLengthDeprecationNotice = nodeUtils.deprecate(
      () => {
      },
      "Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead."
    );
    var Client2 = class extends EventEmitter2 {
      constructor(config2) {
        super();
        this.connectionParameters = new ConnectionParameters(config2);
        this.user = this.connectionParameters.user;
        this.database = this.connectionParameters.database;
        this.port = this.connectionParameters.port;
        this.host = this.connectionParameters.host;
        Object.defineProperty(this, "password", {
          configurable: true,
          enumerable: false,
          writable: true,
          value: this.connectionParameters.password
        });
        this.replication = this.connectionParameters.replication;
        const c = config2 || {};
        if (c.Promise) {
          byoPromiseDeprecationNotice();
        }
        this._Promise = c.Promise || global.Promise;
        this._types = new TypeOverrides2(c.types);
        this._ending = false;
        this._ended = false;
        this._connecting = false;
        this._connected = false;
        this._connectionError = false;
        this._queryable = true;
        this._activeQuery = null;
        this.enableChannelBinding = Boolean(c.enableChannelBinding);
        this.connection = c.connection || new Connection2({
          stream: c.stream,
          ssl: this.connectionParameters.ssl,
          keepAlive: c.keepAlive || false,
          keepAliveInitialDelayMillis: c.keepAliveInitialDelayMillis || 0,
          encoding: this.connectionParameters.client_encoding || "utf8"
        });
        this._queryQueue = [];
        this.binary = c.binary || defaults2.binary;
        this.processID = null;
        this.secretKey = null;
        this.ssl = this.connectionParameters.ssl || false;
        if (this.ssl && this.ssl.key) {
          Object.defineProperty(this.ssl, "key", {
            enumerable: false
          });
        }
        this._connectionTimeoutMillis = c.connectionTimeoutMillis || 0;
      }
      get activeQuery() {
        activeQueryDeprecationNotice();
        return this._activeQuery;
      }
      set activeQuery(val) {
        activeQueryDeprecationNotice();
        this._activeQuery = val;
      }
      _getActiveQuery() {
        return this._activeQuery;
      }
      _errorAllQueries(err) {
        const enqueueError = (query) => {
          process.nextTick(() => {
            query.handleError(err, this.connection);
          });
        };
        const activeQuery = this._getActiveQuery();
        if (activeQuery) {
          enqueueError(activeQuery);
          this._activeQuery = null;
        }
        this._queryQueue.forEach(enqueueError);
        this._queryQueue.length = 0;
      }
      _connect(callback) {
        const self = this;
        const con = this.connection;
        this._connectionCallback = callback;
        if (this._connecting || this._connected) {
          const err = new Error("Client has already been connected. You cannot reuse a client.");
          process.nextTick(() => {
            callback(err);
          });
          return;
        }
        this._connecting = true;
        if (this._connectionTimeoutMillis > 0) {
          this.connectionTimeoutHandle = setTimeout(() => {
            con._ending = true;
            con.stream.destroy(new Error("timeout expired"));
          }, this._connectionTimeoutMillis);
          if (this.connectionTimeoutHandle.unref) {
            this.connectionTimeoutHandle.unref();
          }
        }
        if (this.host && this.host.indexOf("/") === 0) {
          con.connect(this.host + "/.s.PGSQL." + this.port);
        } else {
          con.connect(this.port, this.host);
        }
        con.on("connect", function() {
          if (self.ssl) {
            con.requestSsl();
          } else {
            con.startup(self.getStartupConf());
          }
        });
        con.on("sslconnect", function() {
          con.startup(self.getStartupConf());
        });
        this._attachListeners(con);
        con.once("end", () => {
          const error40 = this._ending ? new Error("Connection terminated") : new Error("Connection terminated unexpectedly");
          clearTimeout(this.connectionTimeoutHandle);
          this._errorAllQueries(error40);
          this._ended = true;
          if (!this._ending) {
            if (this._connecting && !this._connectionError) {
              if (this._connectionCallback) {
                this._connectionCallback(error40);
              } else {
                this._handleErrorEvent(error40);
              }
            } else if (!this._connectionError) {
              this._handleErrorEvent(error40);
            }
          }
          process.nextTick(() => {
            this.emit("end");
          });
        });
      }
      connect(callback) {
        if (callback) {
          this._connect(callback);
          return;
        }
        return new this._Promise((resolve, reject) => {
          this._connect((error40) => {
            if (error40) {
              reject(error40);
            } else {
              resolve(this);
            }
          });
        });
      }
      _attachListeners(con) {
        con.on("authenticationCleartextPassword", this._handleAuthCleartextPassword.bind(this));
        con.on("authenticationMD5Password", this._handleAuthMD5Password.bind(this));
        con.on("authenticationSASL", this._handleAuthSASL.bind(this));
        con.on("authenticationSASLContinue", this._handleAuthSASLContinue.bind(this));
        con.on("authenticationSASLFinal", this._handleAuthSASLFinal.bind(this));
        con.on("backendKeyData", this._handleBackendKeyData.bind(this));
        con.on("error", this._handleErrorEvent.bind(this));
        con.on("errorMessage", this._handleErrorMessage.bind(this));
        con.on("readyForQuery", this._handleReadyForQuery.bind(this));
        con.on("notice", this._handleNotice.bind(this));
        con.on("rowDescription", this._handleRowDescription.bind(this));
        con.on("dataRow", this._handleDataRow.bind(this));
        con.on("portalSuspended", this._handlePortalSuspended.bind(this));
        con.on("emptyQuery", this._handleEmptyQuery.bind(this));
        con.on("commandComplete", this._handleCommandComplete.bind(this));
        con.on("parseComplete", this._handleParseComplete.bind(this));
        con.on("copyInResponse", this._handleCopyInResponse.bind(this));
        con.on("copyData", this._handleCopyData.bind(this));
        con.on("notification", this._handleNotification.bind(this));
      }
      _getPassword(cb) {
        const con = this.connection;
        if (typeof this.password === "function") {
          this._Promise.resolve().then(() => this.password(this.connectionParameters)).then((pass) => {
            if (pass !== void 0) {
              if (typeof pass !== "string") {
                con.emit("error", new TypeError("Password must be a string"));
                return;
              }
              this.connectionParameters.password = this.password = pass;
            } else {
              this.connectionParameters.password = this.password = null;
            }
            cb();
          }).catch((err) => {
            con.emit("error", err);
          });
        } else if (this.password !== null) {
          cb();
        } else {
          try {
            const pgPass = require_lib4();
            pgPass(this.connectionParameters, (pass) => {
              if (void 0 !== pass) {
                pgPassDeprecationNotice();
                this.connectionParameters.password = this.password = pass;
              }
              cb();
            });
          } catch (e) {
            this.emit("error", e);
          }
        }
      }
      _handleAuthCleartextPassword(msg) {
        this._getPassword(() => {
          this.connection.password(this.password);
        });
      }
      _handleAuthMD5Password(msg) {
        this._getPassword(async () => {
          try {
            const hashedPassword = await crypto4.postgresMd5PasswordHash(this.user, this.password, msg.salt);
            this.connection.password(hashedPassword);
          } catch (e) {
            this.emit("error", e);
          }
        });
      }
      _handleAuthSASL(msg) {
        this._getPassword(() => {
          try {
            this.saslSession = sasl.startSession(msg.mechanisms, this.enableChannelBinding && this.connection.stream);
            this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism, this.saslSession.response);
          } catch (err) {
            this.connection.emit("error", err);
          }
        });
      }
      async _handleAuthSASLContinue(msg) {
        try {
          await sasl.continueSession(
            this.saslSession,
            this.password,
            msg.data,
            this.enableChannelBinding && this.connection.stream
          );
          this.connection.sendSCRAMClientFinalMessage(this.saslSession.response);
        } catch (err) {
          this.connection.emit("error", err);
        }
      }
      _handleAuthSASLFinal(msg) {
        try {
          sasl.finalizeSession(this.saslSession, msg.data);
          this.saslSession = null;
        } catch (err) {
          this.connection.emit("error", err);
        }
      }
      _handleBackendKeyData(msg) {
        this.processID = msg.processID;
        this.secretKey = msg.secretKey;
      }
      _handleReadyForQuery(msg) {
        if (this._connecting) {
          this._connecting = false;
          this._connected = true;
          clearTimeout(this.connectionTimeoutHandle);
          if (this._connectionCallback) {
            this._connectionCallback(null, this);
            this._connectionCallback = null;
          }
          this.emit("connect");
        }
        const activeQuery = this._getActiveQuery();
        this._activeQuery = null;
        this.readyForQuery = true;
        if (activeQuery) {
          activeQuery.handleReadyForQuery(this.connection);
        }
        this._pulseQueryQueue();
      }
      // if we receive an error event or error message
      // during the connection process we handle it here
      _handleErrorWhileConnecting(err) {
        if (this._connectionError) {
          return;
        }
        this._connectionError = true;
        clearTimeout(this.connectionTimeoutHandle);
        if (this._connectionCallback) {
          return this._connectionCallback(err);
        }
        this.emit("error", err);
      }
      // if we're connected and we receive an error event from the connection
      // this means the socket is dead - do a hard abort of all queries and emit
      // the socket error on the client as well
      _handleErrorEvent(err) {
        if (this._connecting) {
          return this._handleErrorWhileConnecting(err);
        }
        this._queryable = false;
        this._errorAllQueries(err);
        this.emit("error", err);
      }
      // handle error messages from the postgres backend
      _handleErrorMessage(msg) {
        if (this._connecting) {
          return this._handleErrorWhileConnecting(msg);
        }
        const activeQuery = this._getActiveQuery();
        if (!activeQuery) {
          this._handleErrorEvent(msg);
          return;
        }
        this._activeQuery = null;
        activeQuery.handleError(msg, this.connection);
      }
      _handleRowDescription(msg) {
        const activeQuery = this._getActiveQuery();
        if (activeQuery == null) {
          const error40 = new Error("Received unexpected rowDescription message from backend.");
          this._handleErrorEvent(error40);
          return;
        }
        activeQuery.handleRowDescription(msg);
      }
      _handleDataRow(msg) {
        const activeQuery = this._getActiveQuery();
        if (activeQuery == null) {
          const error40 = new Error("Received unexpected dataRow message from backend.");
          this._handleErrorEvent(error40);
          return;
        }
        activeQuery.handleDataRow(msg);
      }
      _handlePortalSuspended(msg) {
        const activeQuery = this._getActiveQuery();
        if (activeQuery == null) {
          const error40 = new Error("Received unexpected portalSuspended message from backend.");
          this._handleErrorEvent(error40);
          return;
        }
        activeQuery.handlePortalSuspended(this.connection);
      }
      _handleEmptyQuery(msg) {
        const activeQuery = this._getActiveQuery();
        if (activeQuery == null) {
          const error40 = new Error("Received unexpected emptyQuery message from backend.");
          this._handleErrorEvent(error40);
          return;
        }
        activeQuery.handleEmptyQuery(this.connection);
      }
      _handleCommandComplete(msg) {
        const activeQuery = this._getActiveQuery();
        if (activeQuery == null) {
          const error40 = new Error("Received unexpected commandComplete message from backend.");
          this._handleErrorEvent(error40);
          return;
        }
        activeQuery.handleCommandComplete(msg, this.connection);
      }
      _handleParseComplete() {
        const activeQuery = this._getActiveQuery();
        if (activeQuery == null) {
          const error40 = new Error("Received unexpected parseComplete message from backend.");
          this._handleErrorEvent(error40);
          return;
        }
        if (activeQuery.name) {
          this.connection.parsedStatements[activeQuery.name] = activeQuery.text;
        }
      }
      _handleCopyInResponse(msg) {
        const activeQuery = this._getActiveQuery();
        if (activeQuery == null) {
          const error40 = new Error("Received unexpected copyInResponse message from backend.");
          this._handleErrorEvent(error40);
          return;
        }
        activeQuery.handleCopyInResponse(this.connection);
      }
      _handleCopyData(msg) {
        const activeQuery = this._getActiveQuery();
        if (activeQuery == null) {
          const error40 = new Error("Received unexpected copyData message from backend.");
          this._handleErrorEvent(error40);
          return;
        }
        activeQuery.handleCopyData(msg, this.connection);
      }
      _handleNotification(msg) {
        this.emit("notification", msg);
      }
      _handleNotice(msg) {
        this.emit("notice", msg);
      }
      getStartupConf() {
        const params = this.connectionParameters;
        const data = {
          user: params.user,
          database: params.database
        };
        const appName = params.application_name || params.fallback_application_name;
        if (appName) {
          data.application_name = appName;
        }
        if (params.replication) {
          data.replication = "" + params.replication;
        }
        if (params.statement_timeout) {
          data.statement_timeout = String(parseInt(params.statement_timeout, 10));
        }
        if (params.lock_timeout) {
          data.lock_timeout = String(parseInt(params.lock_timeout, 10));
        }
        if (params.idle_in_transaction_session_timeout) {
          data.idle_in_transaction_session_timeout = String(parseInt(params.idle_in_transaction_session_timeout, 10));
        }
        if (params.options) {
          data.options = params.options;
        }
        return data;
      }
      cancel(client, query) {
        if (client.activeQuery === query) {
          const con = this.connection;
          if (this.host && this.host.indexOf("/") === 0) {
            con.connect(this.host + "/.s.PGSQL." + this.port);
          } else {
            con.connect(this.port, this.host);
          }
          con.on("connect", function() {
            con.cancel(client.processID, client.secretKey);
          });
        } else if (client._queryQueue.indexOf(query) !== -1) {
          client._queryQueue.splice(client._queryQueue.indexOf(query), 1);
        }
      }
      setTypeParser(oid, format, parseFn) {
        return this._types.setTypeParser(oid, format, parseFn);
      }
      getTypeParser(oid, format) {
        return this._types.getTypeParser(oid, format);
      }
      // escapeIdentifier and escapeLiteral moved to utility functions & exported
      // on PG
      // re-exported here for backwards compatibility
      escapeIdentifier(str) {
        return utils.escapeIdentifier(str);
      }
      escapeLiteral(str) {
        return utils.escapeLiteral(str);
      }
      _pulseQueryQueue() {
        if (this.readyForQuery === true) {
          this._activeQuery = this._queryQueue.shift();
          const activeQuery = this._getActiveQuery();
          if (activeQuery) {
            this.readyForQuery = false;
            this.hasExecuted = true;
            const queryError = activeQuery.submit(this.connection);
            if (queryError) {
              process.nextTick(() => {
                activeQuery.handleError(queryError, this.connection);
                this.readyForQuery = true;
                this._pulseQueryQueue();
              });
            }
          } else if (this.hasExecuted) {
            this._activeQuery = null;
            this.emit("drain");
          }
        }
      }
      query(config2, values, callback) {
        let query;
        let result;
        let readTimeout;
        let readTimeoutTimer;
        let queryCallback;
        if (config2 === null || config2 === void 0) {
          throw new TypeError("Client was passed a null or undefined query");
        } else if (typeof config2.submit === "function") {
          readTimeout = config2.query_timeout || this.connectionParameters.query_timeout;
          result = query = config2;
          if (!query.callback) {
            if (typeof values === "function") {
              query.callback = values;
            } else if (callback) {
              query.callback = callback;
            }
          }
        } else {
          readTimeout = config2.query_timeout || this.connectionParameters.query_timeout;
          query = new Query2(config2, values, callback);
          if (!query.callback) {
            result = new this._Promise((resolve, reject) => {
              query.callback = (err, res) => err ? reject(err) : resolve(res);
            }).catch((err) => {
              Error.captureStackTrace(err);
              throw err;
            });
          }
        }
        if (readTimeout) {
          queryCallback = query.callback || (() => {
          });
          readTimeoutTimer = setTimeout(() => {
            const error40 = new Error("Query read timeout");
            process.nextTick(() => {
              query.handleError(error40, this.connection);
            });
            queryCallback(error40);
            query.callback = () => {
            };
            const index2 = this._queryQueue.indexOf(query);
            if (index2 > -1) {
              this._queryQueue.splice(index2, 1);
            }
            this._pulseQueryQueue();
          }, readTimeout);
          query.callback = (err, res) => {
            clearTimeout(readTimeoutTimer);
            queryCallback(err, res);
          };
        }
        if (this.binary && !query.binary) {
          query.binary = true;
        }
        if (query._result && !query._result._types) {
          query._result._types = this._types;
        }
        if (!this._queryable) {
          process.nextTick(() => {
            query.handleError(new Error("Client has encountered a connection error and is not queryable"), this.connection);
          });
          return result;
        }
        if (this._ending) {
          process.nextTick(() => {
            query.handleError(new Error("Client was closed and is not queryable"), this.connection);
          });
          return result;
        }
        if (this._queryQueue.length > 0) {
          queryQueueLengthDeprecationNotice();
        }
        this._queryQueue.push(query);
        this._pulseQueryQueue();
        return result;
      }
      ref() {
        this.connection.ref();
      }
      unref() {
        this.connection.unref();
      }
      end(cb) {
        this._ending = true;
        if (!this.connection._connecting || this._ended) {
          if (cb) {
            cb();
          } else {
            return this._Promise.resolve();
          }
        }
        if (this._getActiveQuery() || !this._queryable) {
          this.connection.stream.destroy();
        } else {
          this.connection.end();
        }
        if (cb) {
          this.connection.once("end", cb);
        } else {
          return new this._Promise((resolve) => {
            this.connection.once("end", resolve);
          });
        }
      }
      get queryQueue() {
        queryQueueDeprecationNotice();
        return this._queryQueue;
      }
    };
    Client2.Query = Query2;
    module.exports = Client2;
  }
});

// ../../node_modules/.pnpm/pg-pool@3.13.0_pg@8.20.0/node_modules/pg-pool/index.js
var require_pg_pool = __commonJS({
  "../../node_modules/.pnpm/pg-pool@3.13.0_pg@8.20.0/node_modules/pg-pool/index.js"(exports, module) {
    "use strict";
    var EventEmitter2 = __require("events").EventEmitter;
    var NOOP = function() {
    };
    var removeWhere = (list, predicate) => {
      const i = list.findIndex(predicate);
      return i === -1 ? void 0 : list.splice(i, 1)[0];
    };
    var IdleItem = class {
      constructor(client, idleListener, timeoutId) {
        this.client = client;
        this.idleListener = idleListener;
        this.timeoutId = timeoutId;
      }
    };
    var PendingItem = class {
      constructor(callback) {
        this.callback = callback;
      }
    };
    function throwOnDoubleRelease() {
      throw new Error("Release called on client which has already been released to the pool.");
    }
    function promisify(Promise2, callback) {
      if (callback) {
        return { callback, result: void 0 };
      }
      let rej;
      let res;
      const cb = function(err, client) {
        err ? rej(err) : res(client);
      };
      const result = new Promise2(function(resolve, reject) {
        res = resolve;
        rej = reject;
      }).catch((err) => {
        Error.captureStackTrace(err);
        throw err;
      });
      return { callback: cb, result };
    }
    function makeIdleListener(pool2, client) {
      return function idleListener(err) {
        err.client = client;
        client.removeListener("error", idleListener);
        client.on("error", () => {
          pool2.log("additional client error after disconnection due to error", err);
        });
        pool2._remove(client);
        pool2.emit("error", err, client);
      };
    }
    var Pool4 = class extends EventEmitter2 {
      constructor(options, Client2) {
        super();
        this.options = Object.assign({}, options);
        if (options != null && "password" in options) {
          Object.defineProperty(this.options, "password", {
            configurable: true,
            enumerable: false,
            writable: true,
            value: options.password
          });
        }
        if (options != null && options.ssl && options.ssl.key) {
          Object.defineProperty(this.options.ssl, "key", {
            enumerable: false
          });
        }
        this.options.max = this.options.max || this.options.poolSize || 10;
        this.options.min = this.options.min || 0;
        this.options.maxUses = this.options.maxUses || Infinity;
        this.options.allowExitOnIdle = this.options.allowExitOnIdle || false;
        this.options.maxLifetimeSeconds = this.options.maxLifetimeSeconds || 0;
        this.log = this.options.log || function() {
        };
        this.Client = this.options.Client || Client2 || require_lib5().Client;
        this.Promise = this.options.Promise || global.Promise;
        if (typeof this.options.idleTimeoutMillis === "undefined") {
          this.options.idleTimeoutMillis = 1e4;
        }
        this._clients = [];
        this._idle = [];
        this._expired = /* @__PURE__ */ new WeakSet();
        this._pendingQueue = [];
        this._endCallback = void 0;
        this.ending = false;
        this.ended = false;
      }
      _promiseTry(f) {
        const Promise2 = this.Promise;
        if (typeof Promise2.try === "function") {
          return Promise2.try(f);
        }
        return new Promise2((resolve) => resolve(f()));
      }
      _isFull() {
        return this._clients.length >= this.options.max;
      }
      _isAboveMin() {
        return this._clients.length > this.options.min;
      }
      _pulseQueue() {
        this.log("pulse queue");
        if (this.ended) {
          this.log("pulse queue ended");
          return;
        }
        if (this.ending) {
          this.log("pulse queue on ending");
          if (this._idle.length) {
            this._idle.slice().map((item) => {
              this._remove(item.client);
            });
          }
          if (!this._clients.length) {
            this.ended = true;
            this._endCallback();
          }
          return;
        }
        if (!this._pendingQueue.length) {
          this.log("no queued requests");
          return;
        }
        if (!this._idle.length && this._isFull()) {
          return;
        }
        const pendingItem = this._pendingQueue.shift();
        if (this._idle.length) {
          const idleItem = this._idle.pop();
          clearTimeout(idleItem.timeoutId);
          const client = idleItem.client;
          client.ref && client.ref();
          const idleListener = idleItem.idleListener;
          return this._acquireClient(client, pendingItem, idleListener, false);
        }
        if (!this._isFull()) {
          return this.newClient(pendingItem);
        }
        throw new Error("unexpected condition");
      }
      _remove(client, callback) {
        const removed = removeWhere(this._idle, (item) => item.client === client);
        if (removed !== void 0) {
          clearTimeout(removed.timeoutId);
        }
        this._clients = this._clients.filter((c) => c !== client);
        const context = this;
        client.end(() => {
          context.emit("remove", client);
          if (typeof callback === "function") {
            callback();
          }
        });
      }
      connect(cb) {
        if (this.ending) {
          const err = new Error("Cannot use a pool after calling end on the pool");
          return cb ? cb(err) : this.Promise.reject(err);
        }
        const response = promisify(this.Promise, cb);
        const result = response.result;
        if (this._isFull() || this._idle.length) {
          if (this._idle.length) {
            process.nextTick(() => this._pulseQueue());
          }
          if (!this.options.connectionTimeoutMillis) {
            this._pendingQueue.push(new PendingItem(response.callback));
            return result;
          }
          const queueCallback = (err, res, done) => {
            clearTimeout(tid);
            response.callback(err, res, done);
          };
          const pendingItem = new PendingItem(queueCallback);
          const tid = setTimeout(() => {
            removeWhere(this._pendingQueue, (i) => i.callback === queueCallback);
            pendingItem.timedOut = true;
            response.callback(new Error("timeout exceeded when trying to connect"));
          }, this.options.connectionTimeoutMillis);
          if (tid.unref) {
            tid.unref();
          }
          this._pendingQueue.push(pendingItem);
          return result;
        }
        this.newClient(new PendingItem(response.callback));
        return result;
      }
      newClient(pendingItem) {
        const client = new this.Client(this.options);
        this._clients.push(client);
        const idleListener = makeIdleListener(this, client);
        this.log("checking client timeout");
        let tid;
        let timeoutHit = false;
        if (this.options.connectionTimeoutMillis) {
          tid = setTimeout(() => {
            if (client.connection) {
              this.log("ending client due to timeout");
              timeoutHit = true;
              client.connection.stream.destroy();
            } else if (!client.isConnected()) {
              this.log("ending client due to timeout");
              timeoutHit = true;
              client.end();
            }
          }, this.options.connectionTimeoutMillis);
        }
        this.log("connecting new client");
        client.connect((err) => {
          if (tid) {
            clearTimeout(tid);
          }
          client.on("error", idleListener);
          if (err) {
            this.log("client failed to connect", err);
            this._clients = this._clients.filter((c) => c !== client);
            if (timeoutHit) {
              err = new Error("Connection terminated due to connection timeout", { cause: err });
            }
            this._pulseQueue();
            if (!pendingItem.timedOut) {
              pendingItem.callback(err, void 0, NOOP);
            }
          } else {
            this.log("new client connected");
            if (this.options.onConnect) {
              this._promiseTry(() => this.options.onConnect(client)).then(
                () => {
                  this._afterConnect(client, pendingItem, idleListener);
                },
                (hookErr) => {
                  this._clients = this._clients.filter((c) => c !== client);
                  client.end(() => {
                    this._pulseQueue();
                    if (!pendingItem.timedOut) {
                      pendingItem.callback(hookErr, void 0, NOOP);
                    }
                  });
                }
              );
              return;
            }
            return this._afterConnect(client, pendingItem, idleListener);
          }
        });
      }
      _afterConnect(client, pendingItem, idleListener) {
        if (this.options.maxLifetimeSeconds !== 0) {
          const maxLifetimeTimeout = setTimeout(() => {
            this.log("ending client due to expired lifetime");
            this._expired.add(client);
            const idleIndex = this._idle.findIndex((idleItem) => idleItem.client === client);
            if (idleIndex !== -1) {
              this._acquireClient(
                client,
                new PendingItem((err, client2, clientRelease) => clientRelease()),
                idleListener,
                false
              );
            }
          }, this.options.maxLifetimeSeconds * 1e3);
          maxLifetimeTimeout.unref();
          client.once("end", () => clearTimeout(maxLifetimeTimeout));
        }
        return this._acquireClient(client, pendingItem, idleListener, true);
      }
      // acquire a client for a pending work item
      _acquireClient(client, pendingItem, idleListener, isNew) {
        if (isNew) {
          this.emit("connect", client);
        }
        this.emit("acquire", client);
        client.release = this._releaseOnce(client, idleListener);
        client.removeListener("error", idleListener);
        if (!pendingItem.timedOut) {
          if (isNew && this.options.verify) {
            this.options.verify(client, (err) => {
              if (err) {
                client.release(err);
                return pendingItem.callback(err, void 0, NOOP);
              }
              pendingItem.callback(void 0, client, client.release);
            });
          } else {
            pendingItem.callback(void 0, client, client.release);
          }
        } else {
          if (isNew && this.options.verify) {
            this.options.verify(client, client.release);
          } else {
            client.release();
          }
        }
      }
      // returns a function that wraps _release and throws if called more than once
      _releaseOnce(client, idleListener) {
        let released = false;
        return (err) => {
          if (released) {
            throwOnDoubleRelease();
          }
          released = true;
          this._release(client, idleListener, err);
        };
      }
      // release a client back to the poll, include an error
      // to remove it from the pool
      _release(client, idleListener, err) {
        client.on("error", idleListener);
        client._poolUseCount = (client._poolUseCount || 0) + 1;
        this.emit("release", err, client);
        if (err || this.ending || !client._queryable || client._ending || client._poolUseCount >= this.options.maxUses) {
          if (client._poolUseCount >= this.options.maxUses) {
            this.log("remove expended client");
          }
          return this._remove(client, this._pulseQueue.bind(this));
        }
        const isExpired = this._expired.has(client);
        if (isExpired) {
          this.log("remove expired client");
          this._expired.delete(client);
          return this._remove(client, this._pulseQueue.bind(this));
        }
        let tid;
        if (this.options.idleTimeoutMillis && this._isAboveMin()) {
          tid = setTimeout(() => {
            if (this._isAboveMin()) {
              this.log("remove idle client");
              this._remove(client, this._pulseQueue.bind(this));
            }
          }, this.options.idleTimeoutMillis);
          if (this.options.allowExitOnIdle) {
            tid.unref();
          }
        }
        if (this.options.allowExitOnIdle) {
          client.unref();
        }
        this._idle.push(new IdleItem(client, idleListener, tid));
        this._pulseQueue();
      }
      query(text2, values, cb) {
        if (typeof text2 === "function") {
          const response2 = promisify(this.Promise, text2);
          setImmediate(function() {
            return response2.callback(new Error("Passing a function as the first parameter to pool.query is not supported"));
          });
          return response2.result;
        }
        if (typeof values === "function") {
          cb = values;
          values = void 0;
        }
        const response = promisify(this.Promise, cb);
        cb = response.callback;
        this.connect((err, client) => {
          if (err) {
            return cb(err);
          }
          let clientReleased = false;
          const onError = (err2) => {
            if (clientReleased) {
              return;
            }
            clientReleased = true;
            client.release(err2);
            cb(err2);
          };
          client.once("error", onError);
          this.log("dispatching query");
          try {
            client.query(text2, values, (err2, res) => {
              this.log("query dispatched");
              client.removeListener("error", onError);
              if (clientReleased) {
                return;
              }
              clientReleased = true;
              client.release(err2);
              if (err2) {
                return cb(err2);
              }
              return cb(void 0, res);
            });
          } catch (err2) {
            client.release(err2);
            return cb(err2);
          }
        });
        return response.result;
      }
      end(cb) {
        this.log("ending");
        if (this.ending) {
          const err = new Error("Called end on pool more than once");
          return cb ? cb(err) : this.Promise.reject(err);
        }
        this.ending = true;
        const promised = promisify(this.Promise, cb);
        this._endCallback = promised.callback;
        this._pulseQueue();
        return promised.result;
      }
      get waitingCount() {
        return this._pendingQueue.length;
      }
      get idleCount() {
        return this._idle.length;
      }
      get expiredCount() {
        return this._clients.reduce((acc, client) => acc + (this._expired.has(client) ? 1 : 0), 0);
      }
      get totalCount() {
        return this._clients.length;
      }
    };
    module.exports = Pool4;
  }
});

// ../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/native/query.js
var require_query3 = __commonJS({
  "../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/native/query.js"(exports, module) {
    "use strict";
    var EventEmitter2 = __require("events").EventEmitter;
    var util2 = __require("util");
    var utils = require_utils3();
    var NativeQuery = module.exports = function(config2, values, callback) {
      EventEmitter2.call(this);
      config2 = utils.normalizeQueryConfig(config2, values, callback);
      this.text = config2.text;
      this.values = config2.values;
      this.name = config2.name;
      this.queryMode = config2.queryMode;
      this.callback = config2.callback;
      this.state = "new";
      this._arrayMode = config2.rowMode === "array";
      this._emitRowEvents = false;
      this.on(
        "newListener",
        function(event) {
          if (event === "row") this._emitRowEvents = true;
        }.bind(this)
      );
    };
    util2.inherits(NativeQuery, EventEmitter2);
    var errorFieldMap = {
      sqlState: "code",
      statementPosition: "position",
      messagePrimary: "message",
      context: "where",
      schemaName: "schema",
      tableName: "table",
      columnName: "column",
      dataTypeName: "dataType",
      constraintName: "constraint",
      sourceFile: "file",
      sourceLine: "line",
      sourceFunction: "routine"
    };
    NativeQuery.prototype.handleError = function(err) {
      const fields = this.native.pq.resultErrorFields();
      if (fields) {
        for (const key in fields) {
          const normalizedFieldName = errorFieldMap[key] || key;
          err[normalizedFieldName] = fields[key];
        }
      }
      if (this.callback) {
        this.callback(err);
      } else {
        this.emit("error", err);
      }
      this.state = "error";
    };
    NativeQuery.prototype.then = function(onSuccess, onFailure) {
      return this._getPromise().then(onSuccess, onFailure);
    };
    NativeQuery.prototype.catch = function(callback) {
      return this._getPromise().catch(callback);
    };
    NativeQuery.prototype._getPromise = function() {
      if (this._promise) return this._promise;
      this._promise = new Promise(
        function(resolve, reject) {
          this._once("end", resolve);
          this._once("error", reject);
        }.bind(this)
      );
      return this._promise;
    };
    NativeQuery.prototype.submit = function(client) {
      this.state = "running";
      const self = this;
      this.native = client.native;
      client.native.arrayMode = this._arrayMode;
      let after = function(err, rows, results) {
        client.native.arrayMode = false;
        setImmediate(function() {
          self.emit("_done");
        });
        if (err) {
          return self.handleError(err);
        }
        if (self._emitRowEvents) {
          if (results.length > 1) {
            rows.forEach((rowOfRows, i) => {
              rowOfRows.forEach((row) => {
                self.emit("row", row, results[i]);
              });
            });
          } else {
            rows.forEach(function(row) {
              self.emit("row", row, results);
            });
          }
        }
        self.state = "end";
        self.emit("end", results);
        if (self.callback) {
          self.callback(null, results);
        }
      };
      if (process.domain) {
        after = process.domain.bind(after);
      }
      if (this.name) {
        if (this.name.length > 63) {
          console.error("Warning! Postgres only supports 63 characters for query names.");
          console.error("You supplied %s (%s)", this.name, this.name.length);
          console.error("This can cause conflicts and silent errors executing queries");
        }
        const values = (this.values || []).map(utils.prepareValue);
        if (client.namedQueries[this.name]) {
          if (this.text && client.namedQueries[this.name] !== this.text) {
            const err = new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);
            return after(err);
          }
          return client.native.execute(this.name, values, after);
        }
        return client.native.prepare(this.name, this.text, values.length, function(err) {
          if (err) return after(err);
          client.namedQueries[self.name] = self.text;
          return self.native.execute(self.name, values, after);
        });
      } else if (this.values) {
        if (!Array.isArray(this.values)) {
          const err = new Error("Query values must be an array");
          return after(err);
        }
        const vals = this.values.map(utils.prepareValue);
        client.native.query(this.text, vals, after);
      } else if (this.queryMode === "extended") {
        client.native.query(this.text, [], after);
      } else {
        client.native.query(this.text, after);
      }
    };
  }
});

// ../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/native/client.js
var require_client2 = __commonJS({
  "../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/native/client.js"(exports, module) {
    var nodeUtils = __require("util");
    var Native;
    try {
      Native = __require("pg-native");
    } catch (e) {
      throw e;
    }
    var TypeOverrides2 = require_type_overrides();
    var EventEmitter2 = __require("events").EventEmitter;
    var util2 = __require("util");
    var ConnectionParameters = require_connection_parameters();
    var NativeQuery = require_query3();
    var queryQueueLengthDeprecationNotice = nodeUtils.deprecate(
      () => {
      },
      "Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead."
    );
    var Client2 = module.exports = function(config2) {
      EventEmitter2.call(this);
      config2 = config2 || {};
      this._Promise = config2.Promise || global.Promise;
      this._types = new TypeOverrides2(config2.types);
      this.native = new Native({
        types: this._types
      });
      this._queryQueue = [];
      this._ending = false;
      this._connecting = false;
      this._connected = false;
      this._queryable = true;
      const cp = this.connectionParameters = new ConnectionParameters(config2);
      if (config2.nativeConnectionString) cp.nativeConnectionString = config2.nativeConnectionString;
      this.user = cp.user;
      Object.defineProperty(this, "password", {
        configurable: true,
        enumerable: false,
        writable: true,
        value: cp.password
      });
      this.database = cp.database;
      this.host = cp.host;
      this.port = cp.port;
      this.namedQueries = {};
    };
    Client2.Query = NativeQuery;
    util2.inherits(Client2, EventEmitter2);
    Client2.prototype._errorAllQueries = function(err) {
      const enqueueError = (query) => {
        process.nextTick(() => {
          query.native = this.native;
          query.handleError(err);
        });
      };
      if (this._hasActiveQuery()) {
        enqueueError(this._activeQuery);
        this._activeQuery = null;
      }
      this._queryQueue.forEach(enqueueError);
      this._queryQueue.length = 0;
    };
    Client2.prototype._connect = function(cb) {
      const self = this;
      if (this._connecting) {
        process.nextTick(() => cb(new Error("Client has already been connected. You cannot reuse a client.")));
        return;
      }
      this._connecting = true;
      this.connectionParameters.getLibpqConnectionString(function(err, conString) {
        if (self.connectionParameters.nativeConnectionString) conString = self.connectionParameters.nativeConnectionString;
        if (err) return cb(err);
        self.native.connect(conString, function(err2) {
          if (err2) {
            self.native.end();
            return cb(err2);
          }
          self._connected = true;
          self.native.on("error", function(err3) {
            self._queryable = false;
            self._errorAllQueries(err3);
            self.emit("error", err3);
          });
          self.native.on("notification", function(msg) {
            self.emit("notification", {
              channel: msg.relname,
              payload: msg.extra
            });
          });
          self.emit("connect");
          self._pulseQueryQueue(true);
          cb(null, this);
        });
      });
    };
    Client2.prototype.connect = function(callback) {
      if (callback) {
        this._connect(callback);
        return;
      }
      return new this._Promise((resolve, reject) => {
        this._connect((error40) => {
          if (error40) {
            reject(error40);
          } else {
            resolve(this);
          }
        });
      });
    };
    Client2.prototype.query = function(config2, values, callback) {
      let query;
      let result;
      let readTimeout;
      let readTimeoutTimer;
      let queryCallback;
      if (config2 === null || config2 === void 0) {
        throw new TypeError("Client was passed a null or undefined query");
      } else if (typeof config2.submit === "function") {
        readTimeout = config2.query_timeout || this.connectionParameters.query_timeout;
        result = query = config2;
        if (typeof values === "function") {
          config2.callback = values;
        }
      } else {
        readTimeout = config2.query_timeout || this.connectionParameters.query_timeout;
        query = new NativeQuery(config2, values, callback);
        if (!query.callback) {
          let resolveOut, rejectOut;
          result = new this._Promise((resolve, reject) => {
            resolveOut = resolve;
            rejectOut = reject;
          }).catch((err) => {
            Error.captureStackTrace(err);
            throw err;
          });
          query.callback = (err, res) => err ? rejectOut(err) : resolveOut(res);
        }
      }
      if (readTimeout) {
        queryCallback = query.callback || (() => {
        });
        readTimeoutTimer = setTimeout(() => {
          const error40 = new Error("Query read timeout");
          process.nextTick(() => {
            query.handleError(error40, this.connection);
          });
          queryCallback(error40);
          query.callback = () => {
          };
          const index2 = this._queryQueue.indexOf(query);
          if (index2 > -1) {
            this._queryQueue.splice(index2, 1);
          }
          this._pulseQueryQueue();
        }, readTimeout);
        query.callback = (err, res) => {
          clearTimeout(readTimeoutTimer);
          queryCallback(err, res);
        };
      }
      if (!this._queryable) {
        query.native = this.native;
        process.nextTick(() => {
          query.handleError(new Error("Client has encountered a connection error and is not queryable"));
        });
        return result;
      }
      if (this._ending) {
        query.native = this.native;
        process.nextTick(() => {
          query.handleError(new Error("Client was closed and is not queryable"));
        });
        return result;
      }
      if (this._queryQueue.length > 0) {
        queryQueueLengthDeprecationNotice();
      }
      this._queryQueue.push(query);
      this._pulseQueryQueue();
      return result;
    };
    Client2.prototype.end = function(cb) {
      const self = this;
      this._ending = true;
      if (!this._connected) {
        this.once("connect", this.end.bind(this, cb));
      }
      let result;
      if (!cb) {
        result = new this._Promise(function(resolve, reject) {
          cb = (err) => err ? reject(err) : resolve();
        });
      }
      this.native.end(function() {
        self._connected = false;
        self._errorAllQueries(new Error("Connection terminated"));
        process.nextTick(() => {
          self.emit("end");
          if (cb) cb();
        });
      });
      return result;
    };
    Client2.prototype._hasActiveQuery = function() {
      return this._activeQuery && this._activeQuery.state !== "error" && this._activeQuery.state !== "end";
    };
    Client2.prototype._pulseQueryQueue = function(initialConnection) {
      if (!this._connected) {
        return;
      }
      if (this._hasActiveQuery()) {
        return;
      }
      const query = this._queryQueue.shift();
      if (!query) {
        if (!initialConnection) {
          this.emit("drain");
        }
        return;
      }
      this._activeQuery = query;
      query.submit(this);
      const self = this;
      query.once("_done", function() {
        self._pulseQueryQueue();
      });
    };
    Client2.prototype.cancel = function(query) {
      if (this._activeQuery === query) {
        this.native.cancel(function() {
        });
      } else if (this._queryQueue.indexOf(query) !== -1) {
        this._queryQueue.splice(this._queryQueue.indexOf(query), 1);
      }
    };
    Client2.prototype.ref = function() {
    };
    Client2.prototype.unref = function() {
    };
    Client2.prototype.setTypeParser = function(oid, format, parseFn) {
      return this._types.setTypeParser(oid, format, parseFn);
    };
    Client2.prototype.getTypeParser = function(oid, format) {
      return this._types.getTypeParser(oid, format);
    };
    Client2.prototype.isConnected = function() {
      return this._connected;
    };
  }
});

// ../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/native/index.js
var require_native = __commonJS({
  "../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/native/index.js"(exports, module) {
    "use strict";
    module.exports = require_client2();
  }
});

// ../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/index.js
var require_lib5 = __commonJS({
  "../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/index.js"(exports, module) {
    "use strict";
    var Client2 = require_client();
    var defaults2 = require_defaults();
    var Connection2 = require_connection();
    var Result2 = require_result();
    var utils = require_utils3();
    var Pool4 = require_pg_pool();
    var TypeOverrides2 = require_type_overrides();
    var { DatabaseError: DatabaseError2 } = require_dist();
    var { escapeIdentifier: escapeIdentifier2, escapeLiteral: escapeLiteral2 } = require_utils3();
    var poolFactory = (Client3) => {
      return class BoundPool extends Pool4 {
        constructor(options) {
          super(options, Client3);
        }
      };
    };
    var PG = function(clientConstructor2) {
      this.defaults = defaults2;
      this.Client = clientConstructor2;
      this.Query = this.Client.Query;
      this.Pool = poolFactory(this.Client);
      this._pools = [];
      this.Connection = Connection2;
      this.types = require_pg_types();
      this.DatabaseError = DatabaseError2;
      this.TypeOverrides = TypeOverrides2;
      this.escapeIdentifier = escapeIdentifier2;
      this.escapeLiteral = escapeLiteral2;
      this.Result = Result2;
      this.utils = utils;
    };
    var clientConstructor = Client2;
    var forceNative = false;
    try {
      forceNative = !!process.env.NODE_PG_FORCE_NATIVE;
    } catch {
    }
    if (forceNative) {
      clientConstructor = require_native();
    }
    module.exports = new PG(clientConstructor);
    Object.defineProperty(module.exports, "native", {
      configurable: true,
      enumerable: false,
      get() {
        let native = null;
        try {
          native = new PG(require_native());
        } catch (err) {
          if (err.code !== "MODULE_NOT_FOUND") {
            throw err;
          }
        }
        Object.defineProperty(module.exports, "native", {
          value: native
        });
        return native;
      }
    });
  }
});

// ../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/esm/index.mjs
var import_lib, Client, Pool, Connection, types, Query, DatabaseError, escapeIdentifier, escapeLiteral, Result, TypeOverrides, defaults, esm_default;
var init_esm = __esm({
  "../../node_modules/.pnpm/pg@8.20.0/node_modules/pg/esm/index.mjs"() {
    import_lib = __toESM(require_lib5(), 1);
    Client = import_lib.default.Client;
    Pool = import_lib.default.Pool;
    Connection = import_lib.default.Connection;
    types = import_lib.default.types;
    Query = import_lib.default.Query;
    DatabaseError = import_lib.default.DatabaseError;
    escapeIdentifier = import_lib.default.escapeIdentifier;
    escapeLiteral = import_lib.default.escapeLiteral;
    Result = import_lib.default.Result;
    TypeOverrides = import_lib.default.TypeOverrides;
    defaults = import_lib.default.defaults;
    esm_default = import_lib.default;
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/entity.js
function is(value, type) {
  if (!value || typeof value !== "object") {
    return false;
  }
  if (value instanceof type) {
    return true;
  }
  if (!Object.prototype.hasOwnProperty.call(type, entityKind)) {
    throw new Error(
      `Class "${type.name ?? "<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`
    );
  }
  let cls = Object.getPrototypeOf(value).constructor;
  if (cls) {
    while (cls) {
      if (entityKind in cls && cls[entityKind] === type[entityKind]) {
        return true;
      }
      cls = Object.getPrototypeOf(cls);
    }
  }
  return false;
}
var entityKind;
var init_entity = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/entity.js"() {
    entityKind = /* @__PURE__ */ Symbol.for("drizzle:entityKind");
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/logger.js
var ConsoleLogWriter, DefaultLogger, NoopLogger;
var init_logger2 = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/logger.js"() {
    init_entity();
    ConsoleLogWriter = class {
      static [entityKind] = "ConsoleLogWriter";
      write(message) {
        console.log(message);
      }
    };
    DefaultLogger = class {
      static [entityKind] = "DefaultLogger";
      writer;
      constructor(config2) {
        this.writer = config2?.writer ?? new ConsoleLogWriter();
      }
      logQuery(query, params) {
        const stringifiedParams = params.map((p) => {
          try {
            return JSON.stringify(p);
          } catch {
            return String(p);
          }
        });
        const paramsStr = stringifiedParams.length ? ` -- params: [${stringifiedParams.join(", ")}]` : "";
        this.writer.write(`Query: ${query}${paramsStr}`);
      }
    };
    NoopLogger = class {
      static [entityKind] = "NoopLogger";
      logQuery() {
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/query-promise.js
var QueryPromise;
var init_query_promise = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/query-promise.js"() {
    init_entity();
    QueryPromise = class {
      static [entityKind] = "QueryPromise";
      [Symbol.toStringTag] = "QueryPromise";
      catch(onRejected) {
        return this.then(void 0, onRejected);
      }
      finally(onFinally) {
        return this.then(
          (value) => {
            onFinally?.();
            return value;
          },
          (reason) => {
            onFinally?.();
            throw reason;
          }
        );
      }
      then(onFulfilled, onRejected) {
        return this.execute().then(onFulfilled, onRejected);
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/column.js
var Column;
var init_column = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/column.js"() {
    init_entity();
    Column = class {
      constructor(table, config2) {
        this.table = table;
        this.config = config2;
        this.name = config2.name;
        this.keyAsName = config2.keyAsName;
        this.notNull = config2.notNull;
        this.default = config2.default;
        this.defaultFn = config2.defaultFn;
        this.onUpdateFn = config2.onUpdateFn;
        this.hasDefault = config2.hasDefault;
        this.primary = config2.primaryKey;
        this.isUnique = config2.isUnique;
        this.uniqueName = config2.uniqueName;
        this.uniqueType = config2.uniqueType;
        this.dataType = config2.dataType;
        this.columnType = config2.columnType;
        this.generated = config2.generated;
        this.generatedIdentity = config2.generatedIdentity;
      }
      static [entityKind] = "Column";
      name;
      keyAsName;
      primary;
      notNull;
      default;
      defaultFn;
      onUpdateFn;
      hasDefault;
      isUnique;
      uniqueName;
      uniqueType;
      dataType;
      columnType;
      enumValues = void 0;
      generated = void 0;
      generatedIdentity = void 0;
      config;
      mapFromDriverValue(value) {
        return value;
      }
      mapToDriverValue(value) {
        return value;
      }
      // ** @internal */
      shouldDisableInsert() {
        return this.config.generated !== void 0 && this.config.generated.type !== "byDefault";
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/column-builder.js
var ColumnBuilder;
var init_column_builder = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/column-builder.js"() {
    init_entity();
    ColumnBuilder = class {
      static [entityKind] = "ColumnBuilder";
      config;
      constructor(name, dataType, columnType) {
        this.config = {
          name,
          keyAsName: name === "",
          notNull: false,
          default: void 0,
          hasDefault: false,
          primaryKey: false,
          isUnique: false,
          uniqueName: void 0,
          uniqueType: void 0,
          dataType,
          columnType,
          generated: void 0
        };
      }
      /**
       * Changes the data type of the column. Commonly used with `json` columns. Also, useful for branded types.
       *
       * @example
       * ```ts
       * const users = pgTable('users', {
       * 	id: integer('id').$type<UserId>().primaryKey(),
       * 	details: json('details').$type<UserDetails>().notNull(),
       * });
       * ```
       */
      $type() {
        return this;
      }
      /**
       * Adds a `not null` clause to the column definition.
       *
       * Affects the `select` model of the table - columns *without* `not null` will be nullable on select.
       */
      notNull() {
        this.config.notNull = true;
        return this;
      }
      /**
       * Adds a `default <value>` clause to the column definition.
       *
       * Affects the `insert` model of the table - columns *with* `default` are optional on insert.
       *
       * If you need to set a dynamic default value, use {@link $defaultFn} instead.
       */
      default(value) {
        this.config.default = value;
        this.config.hasDefault = true;
        return this;
      }
      /**
       * Adds a dynamic default value to the column.
       * The function will be called when the row is inserted, and the returned value will be used as the column value.
       *
       * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`.
       */
      $defaultFn(fn) {
        this.config.defaultFn = fn;
        this.config.hasDefault = true;
        return this;
      }
      /**
       * Alias for {@link $defaultFn}.
       */
      $default = this.$defaultFn;
      /**
       * Adds a dynamic update value to the column.
       * The function will be called when the row is updated, and the returned value will be used as the column value if none is provided.
       * If no `default` (or `$defaultFn`) value is provided, the function will be called when the row is inserted as well, and the returned value will be used as the column value.
       *
       * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`.
       */
      $onUpdateFn(fn) {
        this.config.onUpdateFn = fn;
        this.config.hasDefault = true;
        return this;
      }
      /**
       * Alias for {@link $onUpdateFn}.
       */
      $onUpdate = this.$onUpdateFn;
      /**
       * Adds a `primary key` clause to the column definition. This implicitly makes the column `not null`.
       *
       * In SQLite, `integer primary key` implicitly makes the column auto-incrementing.
       */
      primaryKey() {
        this.config.primaryKey = true;
        this.config.notNull = true;
        return this;
      }
      /** @internal Sets the name of the column to the key within the table definition if a name was not given. */
      setName(name) {
        if (this.config.name !== "") return;
        this.config.name = name;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/table.utils.js
var TableName;
var init_table_utils = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/table.utils.js"() {
    TableName = /* @__PURE__ */ Symbol.for("drizzle:Name");
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/foreign-keys.js
var ForeignKeyBuilder, ForeignKey;
var init_foreign_keys = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/foreign-keys.js"() {
    init_entity();
    init_table_utils();
    ForeignKeyBuilder = class {
      static [entityKind] = "PgForeignKeyBuilder";
      /** @internal */
      reference;
      /** @internal */
      _onUpdate = "no action";
      /** @internal */
      _onDelete = "no action";
      constructor(config2, actions) {
        this.reference = () => {
          const { name, columns, foreignColumns } = config2();
          return { name, columns, foreignTable: foreignColumns[0].table, foreignColumns };
        };
        if (actions) {
          this._onUpdate = actions.onUpdate;
          this._onDelete = actions.onDelete;
        }
      }
      onUpdate(action) {
        this._onUpdate = action === void 0 ? "no action" : action;
        return this;
      }
      onDelete(action) {
        this._onDelete = action === void 0 ? "no action" : action;
        return this;
      }
      /** @internal */
      build(table) {
        return new ForeignKey(table, this);
      }
    };
    ForeignKey = class {
      constructor(table, builder) {
        this.table = table;
        this.reference = builder.reference;
        this.onUpdate = builder._onUpdate;
        this.onDelete = builder._onDelete;
      }
      static [entityKind] = "PgForeignKey";
      reference;
      onUpdate;
      onDelete;
      getName() {
        const { name, columns, foreignColumns } = this.reference();
        const columnNames = columns.map((column) => column.name);
        const foreignColumnNames = foreignColumns.map((column) => column.name);
        const chunks = [
          this.table[TableName],
          ...columnNames,
          foreignColumns[0].table[TableName],
          ...foreignColumnNames
        ];
        return name ?? `${chunks.join("_")}_fk`;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/tracing-utils.js
function iife(fn, ...args) {
  return fn(...args);
}
var init_tracing_utils = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/tracing-utils.js"() {
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/unique-constraint.js
function uniqueKeyName(table, columns) {
  return `${table[TableName]}_${columns.join("_")}_unique`;
}
var UniqueConstraintBuilder, UniqueOnConstraintBuilder, UniqueConstraint;
var init_unique_constraint = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/unique-constraint.js"() {
    init_entity();
    init_table_utils();
    UniqueConstraintBuilder = class {
      constructor(columns, name) {
        this.name = name;
        this.columns = columns;
      }
      static [entityKind] = "PgUniqueConstraintBuilder";
      /** @internal */
      columns;
      /** @internal */
      nullsNotDistinctConfig = false;
      nullsNotDistinct() {
        this.nullsNotDistinctConfig = true;
        return this;
      }
      /** @internal */
      build(table) {
        return new UniqueConstraint(table, this.columns, this.nullsNotDistinctConfig, this.name);
      }
    };
    UniqueOnConstraintBuilder = class {
      static [entityKind] = "PgUniqueOnConstraintBuilder";
      /** @internal */
      name;
      constructor(name) {
        this.name = name;
      }
      on(...columns) {
        return new UniqueConstraintBuilder(columns, this.name);
      }
    };
    UniqueConstraint = class {
      constructor(table, columns, nullsNotDistinct, name) {
        this.table = table;
        this.columns = columns;
        this.name = name ?? uniqueKeyName(this.table, this.columns.map((column) => column.name));
        this.nullsNotDistinct = nullsNotDistinct;
      }
      static [entityKind] = "PgUniqueConstraint";
      columns;
      name;
      nullsNotDistinct = false;
      getName() {
        return this.name;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/utils/array.js
function parsePgArrayValue(arrayString, startFrom, inQuotes) {
  for (let i = startFrom; i < arrayString.length; i++) {
    const char2 = arrayString[i];
    if (char2 === "\\") {
      i++;
      continue;
    }
    if (char2 === '"') {
      return [arrayString.slice(startFrom, i).replace(/\\/g, ""), i + 1];
    }
    if (inQuotes) {
      continue;
    }
    if (char2 === "," || char2 === "}") {
      return [arrayString.slice(startFrom, i).replace(/\\/g, ""), i];
    }
  }
  return [arrayString.slice(startFrom).replace(/\\/g, ""), arrayString.length];
}
function parsePgNestedArray(arrayString, startFrom = 0) {
  const result = [];
  let i = startFrom;
  let lastCharIsComma = false;
  while (i < arrayString.length) {
    const char2 = arrayString[i];
    if (char2 === ",") {
      if (lastCharIsComma || i === startFrom) {
        result.push("");
      }
      lastCharIsComma = true;
      i++;
      continue;
    }
    lastCharIsComma = false;
    if (char2 === "\\") {
      i += 2;
      continue;
    }
    if (char2 === '"') {
      const [value2, startFrom2] = parsePgArrayValue(arrayString, i + 1, true);
      result.push(value2);
      i = startFrom2;
      continue;
    }
    if (char2 === "}") {
      return [result, i + 1];
    }
    if (char2 === "{") {
      const [value2, startFrom2] = parsePgNestedArray(arrayString, i + 1);
      result.push(value2);
      i = startFrom2;
      continue;
    }
    const [value, newStartFrom] = parsePgArrayValue(arrayString, i, false);
    result.push(value);
    i = newStartFrom;
  }
  return [result, i];
}
function parsePgArray(arrayString) {
  const [result] = parsePgNestedArray(arrayString, 1);
  return result;
}
function makePgArray(array2) {
  return `{${array2.map((item) => {
    if (Array.isArray(item)) {
      return makePgArray(item);
    }
    if (typeof item === "string") {
      return `"${item.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
    }
    return `${item}`;
  }).join(",")}}`;
}
var init_array = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/utils/array.js"() {
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/common.js
var PgColumnBuilder, PgColumn, ExtraConfigColumn, IndexedColumn, PgArrayBuilder, PgArray;
var init_common = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/common.js"() {
    init_column_builder();
    init_column();
    init_entity();
    init_foreign_keys();
    init_tracing_utils();
    init_unique_constraint();
    init_array();
    PgColumnBuilder = class extends ColumnBuilder {
      foreignKeyConfigs = [];
      static [entityKind] = "PgColumnBuilder";
      array(size) {
        return new PgArrayBuilder(this.config.name, this, size);
      }
      references(ref, actions = {}) {
        this.foreignKeyConfigs.push({ ref, actions });
        return this;
      }
      unique(name, config2) {
        this.config.isUnique = true;
        this.config.uniqueName = name;
        this.config.uniqueType = config2?.nulls;
        return this;
      }
      generatedAlwaysAs(as) {
        this.config.generated = {
          as,
          type: "always",
          mode: "stored"
        };
        return this;
      }
      /** @internal */
      buildForeignKeys(column, table) {
        return this.foreignKeyConfigs.map(({ ref, actions }) => {
          return iife(
            (ref2, actions2) => {
              const builder = new ForeignKeyBuilder(() => {
                const foreignColumn = ref2();
                return { columns: [column], foreignColumns: [foreignColumn] };
              });
              if (actions2.onUpdate) {
                builder.onUpdate(actions2.onUpdate);
              }
              if (actions2.onDelete) {
                builder.onDelete(actions2.onDelete);
              }
              return builder.build(table);
            },
            ref,
            actions
          );
        });
      }
      /** @internal */
      buildExtraConfigColumn(table) {
        return new ExtraConfigColumn(table, this.config);
      }
    };
    PgColumn = class extends Column {
      constructor(table, config2) {
        if (!config2.uniqueName) {
          config2.uniqueName = uniqueKeyName(table, [config2.name]);
        }
        super(table, config2);
        this.table = table;
      }
      static [entityKind] = "PgColumn";
    };
    ExtraConfigColumn = class extends PgColumn {
      static [entityKind] = "ExtraConfigColumn";
      getSQLType() {
        return this.getSQLType();
      }
      indexConfig = {
        order: this.config.order ?? "asc",
        nulls: this.config.nulls ?? "last",
        opClass: this.config.opClass
      };
      defaultConfig = {
        order: "asc",
        nulls: "last",
        opClass: void 0
      };
      asc() {
        this.indexConfig.order = "asc";
        return this;
      }
      desc() {
        this.indexConfig.order = "desc";
        return this;
      }
      nullsFirst() {
        this.indexConfig.nulls = "first";
        return this;
      }
      nullsLast() {
        this.indexConfig.nulls = "last";
        return this;
      }
      /**
       * ### PostgreSQL documentation quote
       *
       * > An operator class with optional parameters can be specified for each column of an index.
       * The operator class identifies the operators to be used by the index for that column.
       * For example, a B-tree index on four-byte integers would use the int4_ops class;
       * this operator class includes comparison functions for four-byte integers.
       * In practice the default operator class for the column's data type is usually sufficient.
       * The main point of having operator classes is that for some data types, there could be more than one meaningful ordering.
       * For example, we might want to sort a complex-number data type either by absolute value or by real part.
       * We could do this by defining two operator classes for the data type and then selecting the proper class when creating an index.
       * More information about operator classes check:
       *
       * ### Useful links
       * https://www.postgresql.org/docs/current/sql-createindex.html
       *
       * https://www.postgresql.org/docs/current/indexes-opclass.html
       *
       * https://www.postgresql.org/docs/current/xindex.html
       *
       * ### Additional types
       * If you have the `pg_vector` extension installed in your database, you can use the
       * `vector_l2_ops`, `vector_ip_ops`, `vector_cosine_ops`, `vector_l1_ops`, `bit_hamming_ops`, `bit_jaccard_ops`, `halfvec_l2_ops`, `sparsevec_l2_ops` options, which are predefined types.
       *
       * **You can always specify any string you want in the operator class, in case Drizzle doesn't have it natively in its types**
       *
       * @param opClass
       * @returns
       */
      op(opClass) {
        this.indexConfig.opClass = opClass;
        return this;
      }
    };
    IndexedColumn = class {
      static [entityKind] = "IndexedColumn";
      constructor(name, keyAsName, type, indexConfig) {
        this.name = name;
        this.keyAsName = keyAsName;
        this.type = type;
        this.indexConfig = indexConfig;
      }
      name;
      keyAsName;
      type;
      indexConfig;
    };
    PgArrayBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgArrayBuilder";
      constructor(name, baseBuilder, size) {
        super(name, "array", "PgArray");
        this.config.baseBuilder = baseBuilder;
        this.config.size = size;
      }
      /** @internal */
      build(table) {
        const baseColumn = this.config.baseBuilder.build(table);
        return new PgArray(
          table,
          this.config,
          baseColumn
        );
      }
    };
    PgArray = class _PgArray extends PgColumn {
      constructor(table, config2, baseColumn, range) {
        super(table, config2);
        this.baseColumn = baseColumn;
        this.range = range;
        this.size = config2.size;
      }
      size;
      static [entityKind] = "PgArray";
      getSQLType() {
        return `${this.baseColumn.getSQLType()}[${typeof this.size === "number" ? this.size : ""}]`;
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          value = parsePgArray(value);
        }
        return value.map((v) => this.baseColumn.mapFromDriverValue(v));
      }
      mapToDriverValue(value, isNestedArray = false) {
        const a = value.map(
          (v) => v === null ? null : is(this.baseColumn, _PgArray) ? this.baseColumn.mapToDriverValue(v, true) : this.baseColumn.mapToDriverValue(v)
        );
        if (isNestedArray) return a;
        return makePgArray(a);
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/enum.js
function isPgEnum(obj) {
  return !!obj && typeof obj === "function" && isPgEnumSym in obj && obj[isPgEnumSym] === true;
}
function pgEnum(enumName, input) {
  return Array.isArray(input) ? pgEnumWithSchema(enumName, [...input], void 0) : pgEnumObjectWithSchema(enumName, input, void 0);
}
function pgEnumWithSchema(enumName, values, schema) {
  const enumInstance = Object.assign(
    (name) => new PgEnumColumnBuilder(name ?? "", enumInstance),
    {
      enumName,
      enumValues: values,
      schema,
      [isPgEnumSym]: true
    }
  );
  return enumInstance;
}
function pgEnumObjectWithSchema(enumName, values, schema) {
  const enumInstance = Object.assign(
    (name) => new PgEnumObjectColumnBuilder(name ?? "", enumInstance),
    {
      enumName,
      enumValues: Object.values(values),
      schema,
      [isPgEnumSym]: true
    }
  );
  return enumInstance;
}
var PgEnumObjectColumnBuilder, PgEnumObjectColumn, isPgEnumSym, PgEnumColumnBuilder, PgEnumColumn;
var init_enum = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/enum.js"() {
    init_entity();
    init_common();
    PgEnumObjectColumnBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgEnumObjectColumnBuilder";
      constructor(name, enumInstance) {
        super(name, "string", "PgEnumObjectColumn");
        this.config.enum = enumInstance;
      }
      /** @internal */
      build(table) {
        return new PgEnumObjectColumn(
          table,
          this.config
        );
      }
    };
    PgEnumObjectColumn = class extends PgColumn {
      static [entityKind] = "PgEnumObjectColumn";
      enum;
      enumValues = this.config.enum.enumValues;
      constructor(table, config2) {
        super(table, config2);
        this.enum = config2.enum;
      }
      getSQLType() {
        return this.enum.enumName;
      }
    };
    isPgEnumSym = /* @__PURE__ */ Symbol.for("drizzle:isPgEnum");
    PgEnumColumnBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgEnumColumnBuilder";
      constructor(name, enumInstance) {
        super(name, "string", "PgEnumColumn");
        this.config.enum = enumInstance;
      }
      /** @internal */
      build(table) {
        return new PgEnumColumn(
          table,
          this.config
        );
      }
    };
    PgEnumColumn = class extends PgColumn {
      static [entityKind] = "PgEnumColumn";
      enum = this.config.enum;
      enumValues = this.config.enum.enumValues;
      constructor(table, config2) {
        super(table, config2);
        this.enum = config2.enum;
      }
      getSQLType() {
        return this.enum.enumName;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/subquery.js
var Subquery, WithSubquery;
var init_subquery = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/subquery.js"() {
    init_entity();
    Subquery = class {
      static [entityKind] = "Subquery";
      constructor(sql2, fields, alias, isWith = false, usedTables = []) {
        this._ = {
          brand: "Subquery",
          sql: sql2,
          selectedFields: fields,
          alias,
          isWith,
          usedTables
        };
      }
      // getSQL(): SQL<unknown> {
      // 	return new SQL([this]);
      // }
    };
    WithSubquery = class extends Subquery {
      static [entityKind] = "WithSubquery";
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/version.js
var version;
var init_version = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/version.js"() {
    version = "0.45.2";
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/tracing.js
var otel, rawTracer, tracer;
var init_tracing = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/tracing.js"() {
    init_tracing_utils();
    init_version();
    tracer = {
      startActiveSpan(name, fn) {
        if (!otel) {
          return fn();
        }
        if (!rawTracer) {
          rawTracer = otel.trace.getTracer("drizzle-orm", version);
        }
        return iife(
          (otel2, rawTracer2) => rawTracer2.startActiveSpan(
            name,
            (span) => {
              try {
                return fn(span);
              } catch (e) {
                span.setStatus({
                  code: otel2.SpanStatusCode.ERROR,
                  message: e instanceof Error ? e.message : "Unknown error"
                  // eslint-disable-line no-instanceof/no-instanceof
                });
                throw e;
              } finally {
                span.end();
              }
            }
          ),
          otel,
          rawTracer
        );
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/view-common.js
var ViewBaseConfig;
var init_view_common = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/view-common.js"() {
    ViewBaseConfig = /* @__PURE__ */ Symbol.for("drizzle:ViewBaseConfig");
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/table.js
function isTable(table) {
  return typeof table === "object" && table !== null && IsDrizzleTable in table;
}
function getTableName(table) {
  return table[TableName];
}
function getTableUniqueName(table) {
  return `${table[Schema] ?? "public"}.${table[TableName]}`;
}
var Schema, Columns, ExtraConfigColumns, OriginalName, BaseName, IsAlias, ExtraConfigBuilder, IsDrizzleTable, Table;
var init_table = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/table.js"() {
    init_entity();
    init_table_utils();
    Schema = /* @__PURE__ */ Symbol.for("drizzle:Schema");
    Columns = /* @__PURE__ */ Symbol.for("drizzle:Columns");
    ExtraConfigColumns = /* @__PURE__ */ Symbol.for("drizzle:ExtraConfigColumns");
    OriginalName = /* @__PURE__ */ Symbol.for("drizzle:OriginalName");
    BaseName = /* @__PURE__ */ Symbol.for("drizzle:BaseName");
    IsAlias = /* @__PURE__ */ Symbol.for("drizzle:IsAlias");
    ExtraConfigBuilder = /* @__PURE__ */ Symbol.for("drizzle:ExtraConfigBuilder");
    IsDrizzleTable = /* @__PURE__ */ Symbol.for("drizzle:IsDrizzleTable");
    Table = class {
      static [entityKind] = "Table";
      /** @internal */
      static Symbol = {
        Name: TableName,
        Schema,
        OriginalName,
        Columns,
        ExtraConfigColumns,
        BaseName,
        IsAlias,
        ExtraConfigBuilder
      };
      /**
       * @internal
       * Can be changed if the table is aliased.
       */
      [TableName];
      /**
       * @internal
       * Used to store the original name of the table, before any aliasing.
       */
      [OriginalName];
      /** @internal */
      [Schema];
      /** @internal */
      [Columns];
      /** @internal */
      [ExtraConfigColumns];
      /**
       *  @internal
       * Used to store the table name before the transformation via the `tableCreator` functions.
       */
      [BaseName];
      /** @internal */
      [IsAlias] = false;
      /** @internal */
      [IsDrizzleTable] = true;
      /** @internal */
      [ExtraConfigBuilder] = void 0;
      constructor(name, schema, baseName) {
        this[TableName] = this[OriginalName] = name;
        this[Schema] = schema;
        this[BaseName] = baseName;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/sql/sql.js
function isSQLWrapper(value) {
  return value !== null && value !== void 0 && typeof value.getSQL === "function";
}
function mergeQueries(queries) {
  const result = { sql: "", params: [] };
  for (const query of queries) {
    result.sql += query.sql;
    result.params.push(...query.params);
    if (query.typings?.length) {
      if (!result.typings) {
        result.typings = [];
      }
      result.typings.push(...query.typings);
    }
  }
  return result;
}
function isDriverValueEncoder(value) {
  return typeof value === "object" && value !== null && "mapToDriverValue" in value && typeof value.mapToDriverValue === "function";
}
function sql(strings, ...params) {
  const queryChunks = [];
  if (params.length > 0 || strings.length > 0 && strings[0] !== "") {
    queryChunks.push(new StringChunk(strings[0]));
  }
  for (const [paramIndex, param2] of params.entries()) {
    queryChunks.push(param2, new StringChunk(strings[paramIndex + 1]));
  }
  return new SQL(queryChunks);
}
function fillPlaceholders(params, values) {
  return params.map((p) => {
    if (is(p, Placeholder)) {
      if (!(p.name in values)) {
        throw new Error(`No value for placeholder "${p.name}" was provided`);
      }
      return values[p.name];
    }
    if (is(p, Param) && is(p.value, Placeholder)) {
      if (!(p.value.name in values)) {
        throw new Error(`No value for placeholder "${p.value.name}" was provided`);
      }
      return p.encoder.mapToDriverValue(values[p.value.name]);
    }
    return p;
  });
}
function isView(view) {
  return typeof view === "object" && view !== null && IsDrizzleView in view;
}
var FakePrimitiveParam, StringChunk, SQL, Name, noopDecoder, noopEncoder, noopMapper, Param, Placeholder, IsDrizzleView, View;
var init_sql = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/sql/sql.js"() {
    init_entity();
    init_enum();
    init_subquery();
    init_tracing();
    init_view_common();
    init_column();
    init_table();
    FakePrimitiveParam = class {
      static [entityKind] = "FakePrimitiveParam";
    };
    StringChunk = class {
      static [entityKind] = "StringChunk";
      value;
      constructor(value) {
        this.value = Array.isArray(value) ? value : [value];
      }
      getSQL() {
        return new SQL([this]);
      }
    };
    SQL = class _SQL {
      constructor(queryChunks) {
        this.queryChunks = queryChunks;
        for (const chunk2 of queryChunks) {
          if (is(chunk2, Table)) {
            const schemaName = chunk2[Table.Symbol.Schema];
            this.usedTables.push(
              schemaName === void 0 ? chunk2[Table.Symbol.Name] : schemaName + "." + chunk2[Table.Symbol.Name]
            );
          }
        }
      }
      static [entityKind] = "SQL";
      /** @internal */
      decoder = noopDecoder;
      shouldInlineParams = false;
      /** @internal */
      usedTables = [];
      append(query) {
        this.queryChunks.push(...query.queryChunks);
        return this;
      }
      toQuery(config2) {
        return tracer.startActiveSpan("drizzle.buildSQL", (span) => {
          const query = this.buildQueryFromSourceParams(this.queryChunks, config2);
          span?.setAttributes({
            "drizzle.query.text": query.sql,
            "drizzle.query.params": JSON.stringify(query.params)
          });
          return query;
        });
      }
      buildQueryFromSourceParams(chunks, _config) {
        const config2 = Object.assign({}, _config, {
          inlineParams: _config.inlineParams || this.shouldInlineParams,
          paramStartIndex: _config.paramStartIndex || { value: 0 }
        });
        const {
          casing,
          escapeName,
          escapeParam,
          prepareTyping,
          inlineParams,
          paramStartIndex
        } = config2;
        return mergeQueries(chunks.map((chunk2) => {
          if (is(chunk2, StringChunk)) {
            return { sql: chunk2.value.join(""), params: [] };
          }
          if (is(chunk2, Name)) {
            return { sql: escapeName(chunk2.value), params: [] };
          }
          if (chunk2 === void 0) {
            return { sql: "", params: [] };
          }
          if (Array.isArray(chunk2)) {
            const result = [new StringChunk("(")];
            for (const [i, p] of chunk2.entries()) {
              result.push(p);
              if (i < chunk2.length - 1) {
                result.push(new StringChunk(", "));
              }
            }
            result.push(new StringChunk(")"));
            return this.buildQueryFromSourceParams(result, config2);
          }
          if (is(chunk2, _SQL)) {
            return this.buildQueryFromSourceParams(chunk2.queryChunks, {
              ...config2,
              inlineParams: inlineParams || chunk2.shouldInlineParams
            });
          }
          if (is(chunk2, Table)) {
            const schemaName = chunk2[Table.Symbol.Schema];
            const tableName = chunk2[Table.Symbol.Name];
            return {
              sql: schemaName === void 0 || chunk2[IsAlias] ? escapeName(tableName) : escapeName(schemaName) + "." + escapeName(tableName),
              params: []
            };
          }
          if (is(chunk2, Column)) {
            const columnName = casing.getColumnCasing(chunk2);
            if (_config.invokeSource === "indexes") {
              return { sql: escapeName(columnName), params: [] };
            }
            const schemaName = chunk2.table[Table.Symbol.Schema];
            return {
              sql: chunk2.table[IsAlias] || schemaName === void 0 ? escapeName(chunk2.table[Table.Symbol.Name]) + "." + escapeName(columnName) : escapeName(schemaName) + "." + escapeName(chunk2.table[Table.Symbol.Name]) + "." + escapeName(columnName),
              params: []
            };
          }
          if (is(chunk2, View)) {
            const schemaName = chunk2[ViewBaseConfig].schema;
            const viewName = chunk2[ViewBaseConfig].name;
            return {
              sql: schemaName === void 0 || chunk2[ViewBaseConfig].isAlias ? escapeName(viewName) : escapeName(schemaName) + "." + escapeName(viewName),
              params: []
            };
          }
          if (is(chunk2, Param)) {
            if (is(chunk2.value, Placeholder)) {
              return { sql: escapeParam(paramStartIndex.value++, chunk2), params: [chunk2], typings: ["none"] };
            }
            const mappedValue = chunk2.value === null ? null : chunk2.encoder.mapToDriverValue(chunk2.value);
            if (is(mappedValue, _SQL)) {
              return this.buildQueryFromSourceParams([mappedValue], config2);
            }
            if (inlineParams) {
              return { sql: this.mapInlineParam(mappedValue, config2), params: [] };
            }
            let typings = ["none"];
            if (prepareTyping) {
              typings = [prepareTyping(chunk2.encoder)];
            }
            return { sql: escapeParam(paramStartIndex.value++, mappedValue), params: [mappedValue], typings };
          }
          if (is(chunk2, Placeholder)) {
            return { sql: escapeParam(paramStartIndex.value++, chunk2), params: [chunk2], typings: ["none"] };
          }
          if (is(chunk2, _SQL.Aliased) && chunk2.fieldAlias !== void 0) {
            return { sql: escapeName(chunk2.fieldAlias), params: [] };
          }
          if (is(chunk2, Subquery)) {
            if (chunk2._.isWith) {
              return { sql: escapeName(chunk2._.alias), params: [] };
            }
            return this.buildQueryFromSourceParams([
              new StringChunk("("),
              chunk2._.sql,
              new StringChunk(") "),
              new Name(chunk2._.alias)
            ], config2);
          }
          if (isPgEnum(chunk2)) {
            if (chunk2.schema) {
              return { sql: escapeName(chunk2.schema) + "." + escapeName(chunk2.enumName), params: [] };
            }
            return { sql: escapeName(chunk2.enumName), params: [] };
          }
          if (isSQLWrapper(chunk2)) {
            if (chunk2.shouldOmitSQLParens?.()) {
              return this.buildQueryFromSourceParams([chunk2.getSQL()], config2);
            }
            return this.buildQueryFromSourceParams([
              new StringChunk("("),
              chunk2.getSQL(),
              new StringChunk(")")
            ], config2);
          }
          if (inlineParams) {
            return { sql: this.mapInlineParam(chunk2, config2), params: [] };
          }
          return { sql: escapeParam(paramStartIndex.value++, chunk2), params: [chunk2], typings: ["none"] };
        }));
      }
      mapInlineParam(chunk2, { escapeString }) {
        if (chunk2 === null) {
          return "null";
        }
        if (typeof chunk2 === "number" || typeof chunk2 === "boolean") {
          return chunk2.toString();
        }
        if (typeof chunk2 === "string") {
          return escapeString(chunk2);
        }
        if (typeof chunk2 === "object") {
          const mappedValueAsString = chunk2.toString();
          if (mappedValueAsString === "[object Object]") {
            return escapeString(JSON.stringify(chunk2));
          }
          return escapeString(mappedValueAsString);
        }
        throw new Error("Unexpected param value: " + chunk2);
      }
      getSQL() {
        return this;
      }
      as(alias) {
        if (alias === void 0) {
          return this;
        }
        return new _SQL.Aliased(this, alias);
      }
      mapWith(decoder) {
        this.decoder = typeof decoder === "function" ? { mapFromDriverValue: decoder } : decoder;
        return this;
      }
      inlineParams() {
        this.shouldInlineParams = true;
        return this;
      }
      /**
       * This method is used to conditionally include a part of the query.
       *
       * @param condition - Condition to check
       * @returns itself if the condition is `true`, otherwise `undefined`
       */
      if(condition) {
        return condition ? this : void 0;
      }
    };
    Name = class {
      constructor(value) {
        this.value = value;
      }
      static [entityKind] = "Name";
      brand;
      getSQL() {
        return new SQL([this]);
      }
    };
    noopDecoder = {
      mapFromDriverValue: (value) => value
    };
    noopEncoder = {
      mapToDriverValue: (value) => value
    };
    noopMapper = {
      ...noopDecoder,
      ...noopEncoder
    };
    Param = class {
      /**
       * @param value - Parameter value
       * @param encoder - Encoder to convert the value to a driver parameter
       */
      constructor(value, encoder = noopEncoder) {
        this.value = value;
        this.encoder = encoder;
      }
      static [entityKind] = "Param";
      brand;
      getSQL() {
        return new SQL([this]);
      }
    };
    ((sql2) => {
      function empty() {
        return new SQL([]);
      }
      sql2.empty = empty;
      function fromList(list) {
        return new SQL(list);
      }
      sql2.fromList = fromList;
      function raw(str) {
        return new SQL([new StringChunk(str)]);
      }
      sql2.raw = raw;
      function join(chunks, separator) {
        const result = [];
        for (const [i, chunk2] of chunks.entries()) {
          if (i > 0 && separator !== void 0) {
            result.push(separator);
          }
          result.push(chunk2);
        }
        return new SQL(result);
      }
      sql2.join = join;
      function identifier(value) {
        return new Name(value);
      }
      sql2.identifier = identifier;
      function placeholder2(name2) {
        return new Placeholder(name2);
      }
      sql2.placeholder = placeholder2;
      function param2(value, encoder) {
        return new Param(value, encoder);
      }
      sql2.param = param2;
    })(sql || (sql = {}));
    ((SQL2) => {
      class Aliased {
        constructor(sql2, fieldAlias) {
          this.sql = sql2;
          this.fieldAlias = fieldAlias;
        }
        static [entityKind] = "SQL.Aliased";
        /** @internal */
        isSelectionField = false;
        getSQL() {
          return this.sql;
        }
        /** @internal */
        clone() {
          return new Aliased(this.sql, this.fieldAlias);
        }
      }
      SQL2.Aliased = Aliased;
    })(SQL || (SQL = {}));
    Placeholder = class {
      constructor(name2) {
        this.name = name2;
      }
      static [entityKind] = "Placeholder";
      getSQL() {
        return new SQL([this]);
      }
    };
    IsDrizzleView = /* @__PURE__ */ Symbol.for("drizzle:IsDrizzleView");
    View = class {
      static [entityKind] = "View";
      /** @internal */
      [ViewBaseConfig];
      /** @internal */
      [IsDrizzleView] = true;
      constructor({ name: name2, schema, selectedFields, query }) {
        this[ViewBaseConfig] = {
          name: name2,
          originalName: name2,
          schema,
          selectedFields,
          query,
          isExisting: !query,
          isAlias: false
        };
      }
      getSQL() {
        return new SQL([this]);
      }
    };
    Column.prototype.getSQL = function() {
      return new SQL([this]);
    };
    Table.prototype.getSQL = function() {
      return new SQL([this]);
    };
    Subquery.prototype.getSQL = function() {
      return new SQL([this]);
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/alias.js
function aliasedTable(table, tableAlias) {
  return new Proxy(table, new TableAliasProxyHandler(tableAlias, false));
}
function aliasedTableColumn(column, tableAlias) {
  return new Proxy(
    column,
    new ColumnAliasProxyHandler(new Proxy(column.table, new TableAliasProxyHandler(tableAlias, false)))
  );
}
function mapColumnsInAliasedSQLToAlias(query, alias) {
  return new SQL.Aliased(mapColumnsInSQLToAlias(query.sql, alias), query.fieldAlias);
}
function mapColumnsInSQLToAlias(query, alias) {
  return sql.join(query.queryChunks.map((c) => {
    if (is(c, Column)) {
      return aliasedTableColumn(c, alias);
    }
    if (is(c, SQL)) {
      return mapColumnsInSQLToAlias(c, alias);
    }
    if (is(c, SQL.Aliased)) {
      return mapColumnsInAliasedSQLToAlias(c, alias);
    }
    return c;
  }));
}
var ColumnAliasProxyHandler, TableAliasProxyHandler, RelationTableAliasProxyHandler;
var init_alias = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/alias.js"() {
    init_column();
    init_entity();
    init_sql();
    init_table();
    init_view_common();
    ColumnAliasProxyHandler = class {
      constructor(table) {
        this.table = table;
      }
      static [entityKind] = "ColumnAliasProxyHandler";
      get(columnObj, prop) {
        if (prop === "table") {
          return this.table;
        }
        return columnObj[prop];
      }
    };
    TableAliasProxyHandler = class {
      constructor(alias, replaceOriginalName) {
        this.alias = alias;
        this.replaceOriginalName = replaceOriginalName;
      }
      static [entityKind] = "TableAliasProxyHandler";
      get(target, prop) {
        if (prop === Table.Symbol.IsAlias) {
          return true;
        }
        if (prop === Table.Symbol.Name) {
          return this.alias;
        }
        if (this.replaceOriginalName && prop === Table.Symbol.OriginalName) {
          return this.alias;
        }
        if (prop === ViewBaseConfig) {
          return {
            ...target[ViewBaseConfig],
            name: this.alias,
            isAlias: true
          };
        }
        if (prop === Table.Symbol.Columns) {
          const columns = target[Table.Symbol.Columns];
          if (!columns) {
            return columns;
          }
          const proxiedColumns = {};
          Object.keys(columns).map((key) => {
            proxiedColumns[key] = new Proxy(
              columns[key],
              new ColumnAliasProxyHandler(new Proxy(target, this))
            );
          });
          return proxiedColumns;
        }
        const value = target[prop];
        if (is(value, Column)) {
          return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(target, this)));
        }
        return value;
      }
    };
    RelationTableAliasProxyHandler = class {
      constructor(alias) {
        this.alias = alias;
      }
      static [entityKind] = "RelationTableAliasProxyHandler";
      get(target, prop) {
        if (prop === "sourceTable") {
          return aliasedTable(target.sourceTable, this.alias);
        }
        return target[prop];
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/selection-proxy.js
var SelectionProxyHandler;
var init_selection_proxy = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/selection-proxy.js"() {
    init_alias();
    init_column();
    init_entity();
    init_sql();
    init_subquery();
    init_view_common();
    SelectionProxyHandler = class _SelectionProxyHandler {
      static [entityKind] = "SelectionProxyHandler";
      config;
      constructor(config2) {
        this.config = { ...config2 };
      }
      get(subquery, prop) {
        if (prop === "_") {
          return {
            ...subquery["_"],
            selectedFields: new Proxy(
              subquery._.selectedFields,
              this
            )
          };
        }
        if (prop === ViewBaseConfig) {
          return {
            ...subquery[ViewBaseConfig],
            selectedFields: new Proxy(
              subquery[ViewBaseConfig].selectedFields,
              this
            )
          };
        }
        if (typeof prop === "symbol") {
          return subquery[prop];
        }
        const columns = is(subquery, Subquery) ? subquery._.selectedFields : is(subquery, View) ? subquery[ViewBaseConfig].selectedFields : subquery;
        const value = columns[prop];
        if (is(value, SQL.Aliased)) {
          if (this.config.sqlAliasedBehavior === "sql" && !value.isSelectionField) {
            return value.sql;
          }
          const newValue = value.clone();
          newValue.isSelectionField = true;
          return newValue;
        }
        if (is(value, SQL)) {
          if (this.config.sqlBehavior === "sql") {
            return value;
          }
          throw new Error(
            `You tried to reference "${prop}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`
          );
        }
        if (is(value, Column)) {
          if (this.config.alias) {
            return new Proxy(
              value,
              new ColumnAliasProxyHandler(
                new Proxy(
                  value.table,
                  new TableAliasProxyHandler(this.config.alias, this.config.replaceOriginalName ?? false)
                )
              )
            );
          }
          return value;
        }
        if (typeof value !== "object" || value === null) {
          return value;
        }
        return new Proxy(value, new _SelectionProxyHandler(this.config));
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/utils.js
function mapResultRow(columns, row, joinsNotNullableMap) {
  const nullifyMap = {};
  const result = columns.reduce(
    (result2, { path: path4, field }, columnIndex) => {
      let decoder;
      if (is(field, Column)) {
        decoder = field;
      } else if (is(field, SQL)) {
        decoder = field.decoder;
      } else if (is(field, Subquery)) {
        decoder = field._.sql.decoder;
      } else {
        decoder = field.sql.decoder;
      }
      let node = result2;
      for (const [pathChunkIndex, pathChunk] of path4.entries()) {
        if (pathChunkIndex < path4.length - 1) {
          if (!(pathChunk in node)) {
            node[pathChunk] = {};
          }
          node = node[pathChunk];
        } else {
          const rawValue = row[columnIndex];
          const value = node[pathChunk] = rawValue === null ? null : decoder.mapFromDriverValue(rawValue);
          if (joinsNotNullableMap && is(field, Column) && path4.length === 2) {
            const objectName = path4[0];
            if (!(objectName in nullifyMap)) {
              nullifyMap[objectName] = value === null ? getTableName(field.table) : false;
            } else if (typeof nullifyMap[objectName] === "string" && nullifyMap[objectName] !== getTableName(field.table)) {
              nullifyMap[objectName] = false;
            }
          }
        }
      }
      return result2;
    },
    {}
  );
  if (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) {
    for (const [objectName, tableName] of Object.entries(nullifyMap)) {
      if (typeof tableName === "string" && !joinsNotNullableMap[tableName]) {
        result[objectName] = null;
      }
    }
  }
  return result;
}
function orderSelectedFields(fields, pathPrefix) {
  return Object.entries(fields).reduce((result, [name, field]) => {
    if (typeof name !== "string") {
      return result;
    }
    const newPath = pathPrefix ? [...pathPrefix, name] : [name];
    if (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased) || is(field, Subquery)) {
      result.push({ path: newPath, field });
    } else if (is(field, Table)) {
      result.push(...orderSelectedFields(field[Table.Symbol.Columns], newPath));
    } else {
      result.push(...orderSelectedFields(field, newPath));
    }
    return result;
  }, []);
}
function haveSameKeys(left, right) {
  const leftKeys = Object.keys(left);
  const rightKeys = Object.keys(right);
  if (leftKeys.length !== rightKeys.length) {
    return false;
  }
  for (const [index2, key] of leftKeys.entries()) {
    if (key !== rightKeys[index2]) {
      return false;
    }
  }
  return true;
}
function mapUpdateSet(table, values) {
  const entries = Object.entries(values).filter(([, value]) => value !== void 0).map(([key, value]) => {
    if (is(value, SQL) || is(value, Column)) {
      return [key, value];
    } else {
      return [key, new Param(value, table[Table.Symbol.Columns][key])];
    }
  });
  if (entries.length === 0) {
    throw new Error("No values to set");
  }
  return Object.fromEntries(entries);
}
function applyMixins(baseClass, extendedClasses) {
  for (const extendedClass of extendedClasses) {
    for (const name of Object.getOwnPropertyNames(extendedClass.prototype)) {
      if (name === "constructor") continue;
      Object.defineProperty(
        baseClass.prototype,
        name,
        Object.getOwnPropertyDescriptor(extendedClass.prototype, name) || /* @__PURE__ */ Object.create(null)
      );
    }
  }
}
function getTableColumns(table) {
  return table[Table.Symbol.Columns];
}
function getViewSelectedFields(view) {
  return view[ViewBaseConfig].selectedFields;
}
function getTableLikeName(table) {
  return is(table, Subquery) ? table._.alias : is(table, View) ? table[ViewBaseConfig].name : is(table, SQL) ? void 0 : table[Table.Symbol.IsAlias] ? table[Table.Symbol.Name] : table[Table.Symbol.BaseName];
}
function getColumnNameAndConfig(a, b) {
  return {
    name: typeof a === "string" && a.length > 0 ? a : "",
    config: typeof a === "object" ? a : b
  };
}
function isConfig(data) {
  if (typeof data !== "object" || data === null) return false;
  if (data.constructor.name !== "Object") return false;
  if ("logger" in data) {
    const type = typeof data["logger"];
    if (type !== "boolean" && (type !== "object" || typeof data["logger"]["logQuery"] !== "function") && type !== "undefined") return false;
    return true;
  }
  if ("schema" in data) {
    const type = typeof data["schema"];
    if (type !== "object" && type !== "undefined") return false;
    return true;
  }
  if ("casing" in data) {
    const type = typeof data["casing"];
    if (type !== "string" && type !== "undefined") return false;
    return true;
  }
  if ("mode" in data) {
    if (data["mode"] !== "default" || data["mode"] !== "planetscale" || data["mode"] !== void 0) return false;
    return true;
  }
  if ("connection" in data) {
    const type = typeof data["connection"];
    if (type !== "string" && type !== "object" && type !== "undefined") return false;
    return true;
  }
  if ("client" in data) {
    const type = typeof data["client"];
    if (type !== "object" && type !== "function" && type !== "undefined") return false;
    return true;
  }
  if (Object.keys(data).length === 0) return true;
  return false;
}
var textDecoder;
var init_utils = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/utils.js"() {
    init_column();
    init_entity();
    init_sql();
    init_subquery();
    init_table();
    init_view_common();
    textDecoder = typeof TextDecoder === "undefined" ? null : new TextDecoder();
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/int.common.js
var PgIntColumnBaseBuilder;
var init_int_common = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/int.common.js"() {
    init_entity();
    init_common();
    PgIntColumnBaseBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgIntColumnBaseBuilder";
      generatedAlwaysAsIdentity(sequence) {
        if (sequence) {
          const { name, ...options } = sequence;
          this.config.generatedIdentity = {
            type: "always",
            sequenceName: name,
            sequenceOptions: options
          };
        } else {
          this.config.generatedIdentity = {
            type: "always"
          };
        }
        this.config.hasDefault = true;
        this.config.notNull = true;
        return this;
      }
      generatedByDefaultAsIdentity(sequence) {
        if (sequence) {
          const { name, ...options } = sequence;
          this.config.generatedIdentity = {
            type: "byDefault",
            sequenceName: name,
            sequenceOptions: options
          };
        } else {
          this.config.generatedIdentity = {
            type: "byDefault"
          };
        }
        this.config.hasDefault = true;
        this.config.notNull = true;
        return this;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/bigint.js
function bigint(a, b) {
  const { name, config: config2 } = getColumnNameAndConfig(a, b);
  if (config2.mode === "number") {
    return new PgBigInt53Builder(name);
  }
  return new PgBigInt64Builder(name);
}
var PgBigInt53Builder, PgBigInt53, PgBigInt64Builder, PgBigInt64;
var init_bigint = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/bigint.js"() {
    init_entity();
    init_utils();
    init_common();
    init_int_common();
    PgBigInt53Builder = class extends PgIntColumnBaseBuilder {
      static [entityKind] = "PgBigInt53Builder";
      constructor(name) {
        super(name, "number", "PgBigInt53");
      }
      /** @internal */
      build(table) {
        return new PgBigInt53(table, this.config);
      }
    };
    PgBigInt53 = class extends PgColumn {
      static [entityKind] = "PgBigInt53";
      getSQLType() {
        return "bigint";
      }
      mapFromDriverValue(value) {
        if (typeof value === "number") {
          return value;
        }
        return Number(value);
      }
    };
    PgBigInt64Builder = class extends PgIntColumnBaseBuilder {
      static [entityKind] = "PgBigInt64Builder";
      constructor(name) {
        super(name, "bigint", "PgBigInt64");
      }
      /** @internal */
      build(table) {
        return new PgBigInt64(
          table,
          this.config
        );
      }
    };
    PgBigInt64 = class extends PgColumn {
      static [entityKind] = "PgBigInt64";
      getSQLType() {
        return "bigint";
      }
      // eslint-disable-next-line unicorn/prefer-native-coercion-functions
      mapFromDriverValue(value) {
        return BigInt(value);
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/bigserial.js
function bigserial(a, b) {
  const { name, config: config2 } = getColumnNameAndConfig(a, b);
  if (config2.mode === "number") {
    return new PgBigSerial53Builder(name);
  }
  return new PgBigSerial64Builder(name);
}
var PgBigSerial53Builder, PgBigSerial53, PgBigSerial64Builder, PgBigSerial64;
var init_bigserial = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/bigserial.js"() {
    init_entity();
    init_utils();
    init_common();
    PgBigSerial53Builder = class extends PgColumnBuilder {
      static [entityKind] = "PgBigSerial53Builder";
      constructor(name) {
        super(name, "number", "PgBigSerial53");
        this.config.hasDefault = true;
        this.config.notNull = true;
      }
      /** @internal */
      build(table) {
        return new PgBigSerial53(
          table,
          this.config
        );
      }
    };
    PgBigSerial53 = class extends PgColumn {
      static [entityKind] = "PgBigSerial53";
      getSQLType() {
        return "bigserial";
      }
      mapFromDriverValue(value) {
        if (typeof value === "number") {
          return value;
        }
        return Number(value);
      }
    };
    PgBigSerial64Builder = class extends PgColumnBuilder {
      static [entityKind] = "PgBigSerial64Builder";
      constructor(name) {
        super(name, "bigint", "PgBigSerial64");
        this.config.hasDefault = true;
      }
      /** @internal */
      build(table) {
        return new PgBigSerial64(
          table,
          this.config
        );
      }
    };
    PgBigSerial64 = class extends PgColumn {
      static [entityKind] = "PgBigSerial64";
      getSQLType() {
        return "bigserial";
      }
      // eslint-disable-next-line unicorn/prefer-native-coercion-functions
      mapFromDriverValue(value) {
        return BigInt(value);
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/boolean.js
function boolean(name) {
  return new PgBooleanBuilder(name ?? "");
}
var PgBooleanBuilder, PgBoolean;
var init_boolean = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/boolean.js"() {
    init_entity();
    init_common();
    PgBooleanBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgBooleanBuilder";
      constructor(name) {
        super(name, "boolean", "PgBoolean");
      }
      /** @internal */
      build(table) {
        return new PgBoolean(table, this.config);
      }
    };
    PgBoolean = class extends PgColumn {
      static [entityKind] = "PgBoolean";
      getSQLType() {
        return "boolean";
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/char.js
function char(a, b = {}) {
  const { name, config: config2 } = getColumnNameAndConfig(a, b);
  return new PgCharBuilder(name, config2);
}
var PgCharBuilder, PgChar;
var init_char = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/char.js"() {
    init_entity();
    init_utils();
    init_common();
    PgCharBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgCharBuilder";
      constructor(name, config2) {
        super(name, "string", "PgChar");
        this.config.length = config2.length;
        this.config.enumValues = config2.enum;
      }
      /** @internal */
      build(table) {
        return new PgChar(
          table,
          this.config
        );
      }
    };
    PgChar = class extends PgColumn {
      static [entityKind] = "PgChar";
      length = this.config.length;
      enumValues = this.config.enumValues;
      getSQLType() {
        return this.length === void 0 ? `char` : `char(${this.length})`;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/cidr.js
function cidr(name) {
  return new PgCidrBuilder(name ?? "");
}
var PgCidrBuilder, PgCidr;
var init_cidr = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/cidr.js"() {
    init_entity();
    init_common();
    PgCidrBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgCidrBuilder";
      constructor(name) {
        super(name, "string", "PgCidr");
      }
      /** @internal */
      build(table) {
        return new PgCidr(table, this.config);
      }
    };
    PgCidr = class extends PgColumn {
      static [entityKind] = "PgCidr";
      getSQLType() {
        return "cidr";
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/custom.js
function customType(customTypeParams) {
  return (a, b) => {
    const { name, config: config2 } = getColumnNameAndConfig(a, b);
    return new PgCustomColumnBuilder(name, config2, customTypeParams);
  };
}
var PgCustomColumnBuilder, PgCustomColumn;
var init_custom = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/custom.js"() {
    init_entity();
    init_utils();
    init_common();
    PgCustomColumnBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgCustomColumnBuilder";
      constructor(name, fieldConfig, customTypeParams) {
        super(name, "custom", "PgCustomColumn");
        this.config.fieldConfig = fieldConfig;
        this.config.customTypeParams = customTypeParams;
      }
      /** @internal */
      build(table) {
        return new PgCustomColumn(
          table,
          this.config
        );
      }
    };
    PgCustomColumn = class extends PgColumn {
      static [entityKind] = "PgCustomColumn";
      sqlName;
      mapTo;
      mapFrom;
      constructor(table, config2) {
        super(table, config2);
        this.sqlName = config2.customTypeParams.dataType(config2.fieldConfig);
        this.mapTo = config2.customTypeParams.toDriver;
        this.mapFrom = config2.customTypeParams.fromDriver;
      }
      getSQLType() {
        return this.sqlName;
      }
      mapFromDriverValue(value) {
        return typeof this.mapFrom === "function" ? this.mapFrom(value) : value;
      }
      mapToDriverValue(value) {
        return typeof this.mapTo === "function" ? this.mapTo(value) : value;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/date.common.js
var PgDateColumnBaseBuilder;
var init_date_common = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/date.common.js"() {
    init_entity();
    init_sql();
    init_common();
    PgDateColumnBaseBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgDateColumnBaseBuilder";
      defaultNow() {
        return this.default(sql`now()`);
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/date.js
function date(a, b) {
  const { name, config: config2 } = getColumnNameAndConfig(a, b);
  if (config2?.mode === "date") {
    return new PgDateBuilder(name);
  }
  return new PgDateStringBuilder(name);
}
var PgDateBuilder, PgDate, PgDateStringBuilder, PgDateString;
var init_date = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/date.js"() {
    init_entity();
    init_utils();
    init_common();
    init_date_common();
    PgDateBuilder = class extends PgDateColumnBaseBuilder {
      static [entityKind] = "PgDateBuilder";
      constructor(name) {
        super(name, "date", "PgDate");
      }
      /** @internal */
      build(table) {
        return new PgDate(table, this.config);
      }
    };
    PgDate = class extends PgColumn {
      static [entityKind] = "PgDate";
      getSQLType() {
        return "date";
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") return new Date(value);
        return value;
      }
      mapToDriverValue(value) {
        return value.toISOString();
      }
    };
    PgDateStringBuilder = class extends PgDateColumnBaseBuilder {
      static [entityKind] = "PgDateStringBuilder";
      constructor(name) {
        super(name, "string", "PgDateString");
      }
      /** @internal */
      build(table) {
        return new PgDateString(
          table,
          this.config
        );
      }
    };
    PgDateString = class extends PgColumn {
      static [entityKind] = "PgDateString";
      getSQLType() {
        return "date";
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") return value;
        return value.toISOString().slice(0, -14);
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/double-precision.js
function doublePrecision(name) {
  return new PgDoublePrecisionBuilder(name ?? "");
}
var PgDoublePrecisionBuilder, PgDoublePrecision;
var init_double_precision = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/double-precision.js"() {
    init_entity();
    init_common();
    PgDoublePrecisionBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgDoublePrecisionBuilder";
      constructor(name) {
        super(name, "number", "PgDoublePrecision");
      }
      /** @internal */
      build(table) {
        return new PgDoublePrecision(
          table,
          this.config
        );
      }
    };
    PgDoublePrecision = class extends PgColumn {
      static [entityKind] = "PgDoublePrecision";
      getSQLType() {
        return "double precision";
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          return Number.parseFloat(value);
        }
        return value;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/inet.js
function inet(name) {
  return new PgInetBuilder(name ?? "");
}
var PgInetBuilder, PgInet;
var init_inet = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/inet.js"() {
    init_entity();
    init_common();
    PgInetBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgInetBuilder";
      constructor(name) {
        super(name, "string", "PgInet");
      }
      /** @internal */
      build(table) {
        return new PgInet(table, this.config);
      }
    };
    PgInet = class extends PgColumn {
      static [entityKind] = "PgInet";
      getSQLType() {
        return "inet";
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/integer.js
function integer(name) {
  return new PgIntegerBuilder(name ?? "");
}
var PgIntegerBuilder, PgInteger;
var init_integer = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/integer.js"() {
    init_entity();
    init_common();
    init_int_common();
    PgIntegerBuilder = class extends PgIntColumnBaseBuilder {
      static [entityKind] = "PgIntegerBuilder";
      constructor(name) {
        super(name, "number", "PgInteger");
      }
      /** @internal */
      build(table) {
        return new PgInteger(table, this.config);
      }
    };
    PgInteger = class extends PgColumn {
      static [entityKind] = "PgInteger";
      getSQLType() {
        return "integer";
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          return Number.parseInt(value);
        }
        return value;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/interval.js
function interval(a, b = {}) {
  const { name, config: config2 } = getColumnNameAndConfig(a, b);
  return new PgIntervalBuilder(name, config2);
}
var PgIntervalBuilder, PgInterval;
var init_interval = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/interval.js"() {
    init_entity();
    init_utils();
    init_common();
    PgIntervalBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgIntervalBuilder";
      constructor(name, intervalConfig) {
        super(name, "string", "PgInterval");
        this.config.intervalConfig = intervalConfig;
      }
      /** @internal */
      build(table) {
        return new PgInterval(table, this.config);
      }
    };
    PgInterval = class extends PgColumn {
      static [entityKind] = "PgInterval";
      fields = this.config.intervalConfig.fields;
      precision = this.config.intervalConfig.precision;
      getSQLType() {
        const fields = this.fields ? ` ${this.fields}` : "";
        const precision = this.precision ? `(${this.precision})` : "";
        return `interval${fields}${precision}`;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/json.js
function json(name) {
  return new PgJsonBuilder(name ?? "");
}
var PgJsonBuilder, PgJson;
var init_json = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/json.js"() {
    init_entity();
    init_common();
    PgJsonBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgJsonBuilder";
      constructor(name) {
        super(name, "json", "PgJson");
      }
      /** @internal */
      build(table) {
        return new PgJson(table, this.config);
      }
    };
    PgJson = class extends PgColumn {
      static [entityKind] = "PgJson";
      constructor(table, config2) {
        super(table, config2);
      }
      getSQLType() {
        return "json";
      }
      mapToDriverValue(value) {
        return JSON.stringify(value);
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          try {
            return JSON.parse(value);
          } catch {
            return value;
          }
        }
        return value;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/jsonb.js
function jsonb(name) {
  return new PgJsonbBuilder(name ?? "");
}
var PgJsonbBuilder, PgJsonb;
var init_jsonb = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/jsonb.js"() {
    init_entity();
    init_common();
    PgJsonbBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgJsonbBuilder";
      constructor(name) {
        super(name, "json", "PgJsonb");
      }
      /** @internal */
      build(table) {
        return new PgJsonb(table, this.config);
      }
    };
    PgJsonb = class extends PgColumn {
      static [entityKind] = "PgJsonb";
      constructor(table, config2) {
        super(table, config2);
      }
      getSQLType() {
        return "jsonb";
      }
      mapToDriverValue(value) {
        return JSON.stringify(value);
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          try {
            return JSON.parse(value);
          } catch {
            return value;
          }
        }
        return value;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/line.js
function line(a, b) {
  const { name, config: config2 } = getColumnNameAndConfig(a, b);
  if (!config2?.mode || config2.mode === "tuple") {
    return new PgLineBuilder(name);
  }
  return new PgLineABCBuilder(name);
}
var PgLineBuilder, PgLineTuple, PgLineABCBuilder, PgLineABC;
var init_line = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/line.js"() {
    init_entity();
    init_utils();
    init_common();
    PgLineBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgLineBuilder";
      constructor(name) {
        super(name, "array", "PgLine");
      }
      /** @internal */
      build(table) {
        return new PgLineTuple(
          table,
          this.config
        );
      }
    };
    PgLineTuple = class extends PgColumn {
      static [entityKind] = "PgLine";
      getSQLType() {
        return "line";
      }
      mapFromDriverValue(value) {
        const [a, b, c] = value.slice(1, -1).split(",");
        return [Number.parseFloat(a), Number.parseFloat(b), Number.parseFloat(c)];
      }
      mapToDriverValue(value) {
        return `{${value[0]},${value[1]},${value[2]}}`;
      }
    };
    PgLineABCBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgLineABCBuilder";
      constructor(name) {
        super(name, "json", "PgLineABC");
      }
      /** @internal */
      build(table) {
        return new PgLineABC(
          table,
          this.config
        );
      }
    };
    PgLineABC = class extends PgColumn {
      static [entityKind] = "PgLineABC";
      getSQLType() {
        return "line";
      }
      mapFromDriverValue(value) {
        const [a, b, c] = value.slice(1, -1).split(",");
        return { a: Number.parseFloat(a), b: Number.parseFloat(b), c: Number.parseFloat(c) };
      }
      mapToDriverValue(value) {
        return `{${value.a},${value.b},${value.c}}`;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/macaddr.js
function macaddr(name) {
  return new PgMacaddrBuilder(name ?? "");
}
var PgMacaddrBuilder, PgMacaddr;
var init_macaddr = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/macaddr.js"() {
    init_entity();
    init_common();
    PgMacaddrBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgMacaddrBuilder";
      constructor(name) {
        super(name, "string", "PgMacaddr");
      }
      /** @internal */
      build(table) {
        return new PgMacaddr(table, this.config);
      }
    };
    PgMacaddr = class extends PgColumn {
      static [entityKind] = "PgMacaddr";
      getSQLType() {
        return "macaddr";
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/macaddr8.js
function macaddr8(name) {
  return new PgMacaddr8Builder(name ?? "");
}
var PgMacaddr8Builder, PgMacaddr8;
var init_macaddr8 = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/macaddr8.js"() {
    init_entity();
    init_common();
    PgMacaddr8Builder = class extends PgColumnBuilder {
      static [entityKind] = "PgMacaddr8Builder";
      constructor(name) {
        super(name, "string", "PgMacaddr8");
      }
      /** @internal */
      build(table) {
        return new PgMacaddr8(table, this.config);
      }
    };
    PgMacaddr8 = class extends PgColumn {
      static [entityKind] = "PgMacaddr8";
      getSQLType() {
        return "macaddr8";
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/numeric.js
function numeric(a, b) {
  const { name, config: config2 } = getColumnNameAndConfig(a, b);
  const mode = config2?.mode;
  return mode === "number" ? new PgNumericNumberBuilder(name, config2?.precision, config2?.scale) : mode === "bigint" ? new PgNumericBigIntBuilder(name, config2?.precision, config2?.scale) : new PgNumericBuilder(name, config2?.precision, config2?.scale);
}
var PgNumericBuilder, PgNumeric, PgNumericNumberBuilder, PgNumericNumber, PgNumericBigIntBuilder, PgNumericBigInt;
var init_numeric = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/numeric.js"() {
    init_entity();
    init_utils();
    init_common();
    PgNumericBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgNumericBuilder";
      constructor(name, precision, scale) {
        super(name, "string", "PgNumeric");
        this.config.precision = precision;
        this.config.scale = scale;
      }
      /** @internal */
      build(table) {
        return new PgNumeric(table, this.config);
      }
    };
    PgNumeric = class extends PgColumn {
      static [entityKind] = "PgNumeric";
      precision;
      scale;
      constructor(table, config2) {
        super(table, config2);
        this.precision = config2.precision;
        this.scale = config2.scale;
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") return value;
        return String(value);
      }
      getSQLType() {
        if (this.precision !== void 0 && this.scale !== void 0) {
          return `numeric(${this.precision}, ${this.scale})`;
        } else if (this.precision === void 0) {
          return "numeric";
        } else {
          return `numeric(${this.precision})`;
        }
      }
    };
    PgNumericNumberBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgNumericNumberBuilder";
      constructor(name, precision, scale) {
        super(name, "number", "PgNumericNumber");
        this.config.precision = precision;
        this.config.scale = scale;
      }
      /** @internal */
      build(table) {
        return new PgNumericNumber(
          table,
          this.config
        );
      }
    };
    PgNumericNumber = class extends PgColumn {
      static [entityKind] = "PgNumericNumber";
      precision;
      scale;
      constructor(table, config2) {
        super(table, config2);
        this.precision = config2.precision;
        this.scale = config2.scale;
      }
      mapFromDriverValue(value) {
        if (typeof value === "number") return value;
        return Number(value);
      }
      mapToDriverValue = String;
      getSQLType() {
        if (this.precision !== void 0 && this.scale !== void 0) {
          return `numeric(${this.precision}, ${this.scale})`;
        } else if (this.precision === void 0) {
          return "numeric";
        } else {
          return `numeric(${this.precision})`;
        }
      }
    };
    PgNumericBigIntBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgNumericBigIntBuilder";
      constructor(name, precision, scale) {
        super(name, "bigint", "PgNumericBigInt");
        this.config.precision = precision;
        this.config.scale = scale;
      }
      /** @internal */
      build(table) {
        return new PgNumericBigInt(
          table,
          this.config
        );
      }
    };
    PgNumericBigInt = class extends PgColumn {
      static [entityKind] = "PgNumericBigInt";
      precision;
      scale;
      constructor(table, config2) {
        super(table, config2);
        this.precision = config2.precision;
        this.scale = config2.scale;
      }
      mapFromDriverValue = BigInt;
      mapToDriverValue = String;
      getSQLType() {
        if (this.precision !== void 0 && this.scale !== void 0) {
          return `numeric(${this.precision}, ${this.scale})`;
        } else if (this.precision === void 0) {
          return "numeric";
        } else {
          return `numeric(${this.precision})`;
        }
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/point.js
function point(a, b) {
  const { name, config: config2 } = getColumnNameAndConfig(a, b);
  if (!config2?.mode || config2.mode === "tuple") {
    return new PgPointTupleBuilder(name);
  }
  return new PgPointObjectBuilder(name);
}
var PgPointTupleBuilder, PgPointTuple, PgPointObjectBuilder, PgPointObject;
var init_point = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/point.js"() {
    init_entity();
    init_utils();
    init_common();
    PgPointTupleBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgPointTupleBuilder";
      constructor(name) {
        super(name, "array", "PgPointTuple");
      }
      /** @internal */
      build(table) {
        return new PgPointTuple(
          table,
          this.config
        );
      }
    };
    PgPointTuple = class extends PgColumn {
      static [entityKind] = "PgPointTuple";
      getSQLType() {
        return "point";
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          const [x, y] = value.slice(1, -1).split(",");
          return [Number.parseFloat(x), Number.parseFloat(y)];
        }
        return [value.x, value.y];
      }
      mapToDriverValue(value) {
        return `(${value[0]},${value[1]})`;
      }
    };
    PgPointObjectBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgPointObjectBuilder";
      constructor(name) {
        super(name, "json", "PgPointObject");
      }
      /** @internal */
      build(table) {
        return new PgPointObject(
          table,
          this.config
        );
      }
    };
    PgPointObject = class extends PgColumn {
      static [entityKind] = "PgPointObject";
      getSQLType() {
        return "point";
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          const [x, y] = value.slice(1, -1).split(",");
          return { x: Number.parseFloat(x), y: Number.parseFloat(y) };
        }
        return value;
      }
      mapToDriverValue(value) {
        return `(${value.x},${value.y})`;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/postgis_extension/utils.js
function hexToBytes(hex) {
  const bytes = [];
  for (let c = 0; c < hex.length; c += 2) {
    bytes.push(Number.parseInt(hex.slice(c, c + 2), 16));
  }
  return new Uint8Array(bytes);
}
function bytesToFloat64(bytes, offset) {
  const buffer = new ArrayBuffer(8);
  const view = new DataView(buffer);
  for (let i = 0; i < 8; i++) {
    view.setUint8(i, bytes[offset + i]);
  }
  return view.getFloat64(0, true);
}
function parseEWKB(hex) {
  const bytes = hexToBytes(hex);
  let offset = 0;
  const byteOrder = bytes[offset];
  offset += 1;
  const view = new DataView(bytes.buffer);
  const geomType = view.getUint32(offset, byteOrder === 1);
  offset += 4;
  let _srid;
  if (geomType & 536870912) {
    _srid = view.getUint32(offset, byteOrder === 1);
    offset += 4;
  }
  if ((geomType & 65535) === 1) {
    const x = bytesToFloat64(bytes, offset);
    offset += 8;
    const y = bytesToFloat64(bytes, offset);
    offset += 8;
    return [x, y];
  }
  throw new Error("Unsupported geometry type");
}
var init_utils2 = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/postgis_extension/utils.js"() {
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/postgis_extension/geometry.js
function geometry(a, b) {
  const { name, config: config2 } = getColumnNameAndConfig(a, b);
  if (!config2?.mode || config2.mode === "tuple") {
    return new PgGeometryBuilder(name);
  }
  return new PgGeometryObjectBuilder(name);
}
var PgGeometryBuilder, PgGeometry, PgGeometryObjectBuilder, PgGeometryObject;
var init_geometry = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/postgis_extension/geometry.js"() {
    init_entity();
    init_utils();
    init_common();
    init_utils2();
    PgGeometryBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgGeometryBuilder";
      constructor(name) {
        super(name, "array", "PgGeometry");
      }
      /** @internal */
      build(table) {
        return new PgGeometry(
          table,
          this.config
        );
      }
    };
    PgGeometry = class extends PgColumn {
      static [entityKind] = "PgGeometry";
      getSQLType() {
        return "geometry(point)";
      }
      mapFromDriverValue(value) {
        return parseEWKB(value);
      }
      mapToDriverValue(value) {
        return `point(${value[0]} ${value[1]})`;
      }
    };
    PgGeometryObjectBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgGeometryObjectBuilder";
      constructor(name) {
        super(name, "json", "PgGeometryObject");
      }
      /** @internal */
      build(table) {
        return new PgGeometryObject(
          table,
          this.config
        );
      }
    };
    PgGeometryObject = class extends PgColumn {
      static [entityKind] = "PgGeometryObject";
      getSQLType() {
        return "geometry(point)";
      }
      mapFromDriverValue(value) {
        const parsed = parseEWKB(value);
        return { x: parsed[0], y: parsed[1] };
      }
      mapToDriverValue(value) {
        return `point(${value.x} ${value.y})`;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/real.js
function real(name) {
  return new PgRealBuilder(name ?? "");
}
var PgRealBuilder, PgReal;
var init_real = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/real.js"() {
    init_entity();
    init_common();
    PgRealBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgRealBuilder";
      constructor(name, length) {
        super(name, "number", "PgReal");
        this.config.length = length;
      }
      /** @internal */
      build(table) {
        return new PgReal(table, this.config);
      }
    };
    PgReal = class extends PgColumn {
      static [entityKind] = "PgReal";
      constructor(table, config2) {
        super(table, config2);
      }
      getSQLType() {
        return "real";
      }
      mapFromDriverValue = (value) => {
        if (typeof value === "string") {
          return Number.parseFloat(value);
        }
        return value;
      };
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/serial.js
function serial(name) {
  return new PgSerialBuilder(name ?? "");
}
var PgSerialBuilder, PgSerial;
var init_serial = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/serial.js"() {
    init_entity();
    init_common();
    PgSerialBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgSerialBuilder";
      constructor(name) {
        super(name, "number", "PgSerial");
        this.config.hasDefault = true;
        this.config.notNull = true;
      }
      /** @internal */
      build(table) {
        return new PgSerial(table, this.config);
      }
    };
    PgSerial = class extends PgColumn {
      static [entityKind] = "PgSerial";
      getSQLType() {
        return "serial";
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/smallint.js
function smallint(name) {
  return new PgSmallIntBuilder(name ?? "");
}
var PgSmallIntBuilder, PgSmallInt;
var init_smallint = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/smallint.js"() {
    init_entity();
    init_common();
    init_int_common();
    PgSmallIntBuilder = class extends PgIntColumnBaseBuilder {
      static [entityKind] = "PgSmallIntBuilder";
      constructor(name) {
        super(name, "number", "PgSmallInt");
      }
      /** @internal */
      build(table) {
        return new PgSmallInt(table, this.config);
      }
    };
    PgSmallInt = class extends PgColumn {
      static [entityKind] = "PgSmallInt";
      getSQLType() {
        return "smallint";
      }
      mapFromDriverValue = (value) => {
        if (typeof value === "string") {
          return Number(value);
        }
        return value;
      };
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/smallserial.js
function smallserial(name) {
  return new PgSmallSerialBuilder(name ?? "");
}
var PgSmallSerialBuilder, PgSmallSerial;
var init_smallserial = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/smallserial.js"() {
    init_entity();
    init_common();
    PgSmallSerialBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgSmallSerialBuilder";
      constructor(name) {
        super(name, "number", "PgSmallSerial");
        this.config.hasDefault = true;
        this.config.notNull = true;
      }
      /** @internal */
      build(table) {
        return new PgSmallSerial(
          table,
          this.config
        );
      }
    };
    PgSmallSerial = class extends PgColumn {
      static [entityKind] = "PgSmallSerial";
      getSQLType() {
        return "smallserial";
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/text.js
function text(a, b = {}) {
  const { name, config: config2 } = getColumnNameAndConfig(a, b);
  return new PgTextBuilder(name, config2);
}
var PgTextBuilder, PgText;
var init_text = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/text.js"() {
    init_entity();
    init_utils();
    init_common();
    PgTextBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgTextBuilder";
      constructor(name, config2) {
        super(name, "string", "PgText");
        this.config.enumValues = config2.enum;
      }
      /** @internal */
      build(table) {
        return new PgText(table, this.config);
      }
    };
    PgText = class extends PgColumn {
      static [entityKind] = "PgText";
      enumValues = this.config.enumValues;
      getSQLType() {
        return "text";
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/time.js
function time(a, b = {}) {
  const { name, config: config2 } = getColumnNameAndConfig(a, b);
  return new PgTimeBuilder(name, config2.withTimezone ?? false, config2.precision);
}
var PgTimeBuilder, PgTime;
var init_time = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/time.js"() {
    init_entity();
    init_utils();
    init_common();
    init_date_common();
    PgTimeBuilder = class extends PgDateColumnBaseBuilder {
      constructor(name, withTimezone, precision) {
        super(name, "string", "PgTime");
        this.withTimezone = withTimezone;
        this.precision = precision;
        this.config.withTimezone = withTimezone;
        this.config.precision = precision;
      }
      static [entityKind] = "PgTimeBuilder";
      /** @internal */
      build(table) {
        return new PgTime(table, this.config);
      }
    };
    PgTime = class extends PgColumn {
      static [entityKind] = "PgTime";
      withTimezone;
      precision;
      constructor(table, config2) {
        super(table, config2);
        this.withTimezone = config2.withTimezone;
        this.precision = config2.precision;
      }
      getSQLType() {
        const precision = this.precision === void 0 ? "" : `(${this.precision})`;
        return `time${precision}${this.withTimezone ? " with time zone" : ""}`;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/timestamp.js
function timestamp(a, b = {}) {
  const { name, config: config2 } = getColumnNameAndConfig(a, b);
  if (config2?.mode === "string") {
    return new PgTimestampStringBuilder(name, config2.withTimezone ?? false, config2.precision);
  }
  return new PgTimestampBuilder(name, config2?.withTimezone ?? false, config2?.precision);
}
var PgTimestampBuilder, PgTimestamp, PgTimestampStringBuilder, PgTimestampString;
var init_timestamp = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/timestamp.js"() {
    init_entity();
    init_utils();
    init_common();
    init_date_common();
    PgTimestampBuilder = class extends PgDateColumnBaseBuilder {
      static [entityKind] = "PgTimestampBuilder";
      constructor(name, withTimezone, precision) {
        super(name, "date", "PgTimestamp");
        this.config.withTimezone = withTimezone;
        this.config.precision = precision;
      }
      /** @internal */
      build(table) {
        return new PgTimestamp(table, this.config);
      }
    };
    PgTimestamp = class extends PgColumn {
      static [entityKind] = "PgTimestamp";
      withTimezone;
      precision;
      constructor(table, config2) {
        super(table, config2);
        this.withTimezone = config2.withTimezone;
        this.precision = config2.precision;
      }
      getSQLType() {
        const precision = this.precision === void 0 ? "" : ` (${this.precision})`;
        return `timestamp${precision}${this.withTimezone ? " with time zone" : ""}`;
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") return new Date(this.withTimezone ? value : value + "+0000");
        return value;
      }
      mapToDriverValue = (value) => {
        return value.toISOString();
      };
    };
    PgTimestampStringBuilder = class extends PgDateColumnBaseBuilder {
      static [entityKind] = "PgTimestampStringBuilder";
      constructor(name, withTimezone, precision) {
        super(name, "string", "PgTimestampString");
        this.config.withTimezone = withTimezone;
        this.config.precision = precision;
      }
      /** @internal */
      build(table) {
        return new PgTimestampString(
          table,
          this.config
        );
      }
    };
    PgTimestampString = class extends PgColumn {
      static [entityKind] = "PgTimestampString";
      withTimezone;
      precision;
      constructor(table, config2) {
        super(table, config2);
        this.withTimezone = config2.withTimezone;
        this.precision = config2.precision;
      }
      getSQLType() {
        const precision = this.precision === void 0 ? "" : `(${this.precision})`;
        return `timestamp${precision}${this.withTimezone ? " with time zone" : ""}`;
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") return value;
        const shortened = value.toISOString().slice(0, -1).replace("T", " ");
        if (this.withTimezone) {
          const offset = value.getTimezoneOffset();
          const sign = offset <= 0 ? "+" : "-";
          return `${shortened}${sign}${Math.floor(Math.abs(offset) / 60).toString().padStart(2, "0")}`;
        }
        return shortened;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/uuid.js
function uuid(name) {
  return new PgUUIDBuilder(name ?? "");
}
var PgUUIDBuilder, PgUUID;
var init_uuid = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/uuid.js"() {
    init_entity();
    init_sql();
    init_common();
    PgUUIDBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgUUIDBuilder";
      constructor(name) {
        super(name, "string", "PgUUID");
      }
      /**
       * Adds `default gen_random_uuid()` to the column definition.
       */
      defaultRandom() {
        return this.default(sql`gen_random_uuid()`);
      }
      /** @internal */
      build(table) {
        return new PgUUID(table, this.config);
      }
    };
    PgUUID = class extends PgColumn {
      static [entityKind] = "PgUUID";
      getSQLType() {
        return "uuid";
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/varchar.js
function varchar(a, b = {}) {
  const { name, config: config2 } = getColumnNameAndConfig(a, b);
  return new PgVarcharBuilder(name, config2);
}
var PgVarcharBuilder, PgVarchar;
var init_varchar = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/varchar.js"() {
    init_entity();
    init_utils();
    init_common();
    PgVarcharBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgVarcharBuilder";
      constructor(name, config2) {
        super(name, "string", "PgVarchar");
        this.config.length = config2.length;
        this.config.enumValues = config2.enum;
      }
      /** @internal */
      build(table) {
        return new PgVarchar(
          table,
          this.config
        );
      }
    };
    PgVarchar = class extends PgColumn {
      static [entityKind] = "PgVarchar";
      length = this.config.length;
      enumValues = this.config.enumValues;
      getSQLType() {
        return this.length === void 0 ? `varchar` : `varchar(${this.length})`;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/vector_extension/bit.js
function bit(a, b) {
  const { name, config: config2 } = getColumnNameAndConfig(a, b);
  return new PgBinaryVectorBuilder(name, config2);
}
var PgBinaryVectorBuilder, PgBinaryVector;
var init_bit = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/vector_extension/bit.js"() {
    init_entity();
    init_utils();
    init_common();
    PgBinaryVectorBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgBinaryVectorBuilder";
      constructor(name, config2) {
        super(name, "string", "PgBinaryVector");
        this.config.dimensions = config2.dimensions;
      }
      /** @internal */
      build(table) {
        return new PgBinaryVector(
          table,
          this.config
        );
      }
    };
    PgBinaryVector = class extends PgColumn {
      static [entityKind] = "PgBinaryVector";
      dimensions = this.config.dimensions;
      getSQLType() {
        return `bit(${this.dimensions})`;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/vector_extension/halfvec.js
function halfvec(a, b) {
  const { name, config: config2 } = getColumnNameAndConfig(a, b);
  return new PgHalfVectorBuilder(name, config2);
}
var PgHalfVectorBuilder, PgHalfVector;
var init_halfvec = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/vector_extension/halfvec.js"() {
    init_entity();
    init_utils();
    init_common();
    PgHalfVectorBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgHalfVectorBuilder";
      constructor(name, config2) {
        super(name, "array", "PgHalfVector");
        this.config.dimensions = config2.dimensions;
      }
      /** @internal */
      build(table) {
        return new PgHalfVector(
          table,
          this.config
        );
      }
    };
    PgHalfVector = class extends PgColumn {
      static [entityKind] = "PgHalfVector";
      dimensions = this.config.dimensions;
      getSQLType() {
        return `halfvec(${this.dimensions})`;
      }
      mapToDriverValue(value) {
        return JSON.stringify(value);
      }
      mapFromDriverValue(value) {
        return value.slice(1, -1).split(",").map((v) => Number.parseFloat(v));
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/vector_extension/sparsevec.js
function sparsevec(a, b) {
  const { name, config: config2 } = getColumnNameAndConfig(a, b);
  return new PgSparseVectorBuilder(name, config2);
}
var PgSparseVectorBuilder, PgSparseVector;
var init_sparsevec = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/vector_extension/sparsevec.js"() {
    init_entity();
    init_utils();
    init_common();
    PgSparseVectorBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgSparseVectorBuilder";
      constructor(name, config2) {
        super(name, "string", "PgSparseVector");
        this.config.dimensions = config2.dimensions;
      }
      /** @internal */
      build(table) {
        return new PgSparseVector(
          table,
          this.config
        );
      }
    };
    PgSparseVector = class extends PgColumn {
      static [entityKind] = "PgSparseVector";
      dimensions = this.config.dimensions;
      getSQLType() {
        return `sparsevec(${this.dimensions})`;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/vector_extension/vector.js
function vector(a, b) {
  const { name, config: config2 } = getColumnNameAndConfig(a, b);
  return new PgVectorBuilder(name, config2);
}
var PgVectorBuilder, PgVector;
var init_vector = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/vector_extension/vector.js"() {
    init_entity();
    init_utils();
    init_common();
    PgVectorBuilder = class extends PgColumnBuilder {
      static [entityKind] = "PgVectorBuilder";
      constructor(name, config2) {
        super(name, "array", "PgVector");
        this.config.dimensions = config2.dimensions;
      }
      /** @internal */
      build(table) {
        return new PgVector(
          table,
          this.config
        );
      }
    };
    PgVector = class extends PgColumn {
      static [entityKind] = "PgVector";
      dimensions = this.config.dimensions;
      getSQLType() {
        return `vector(${this.dimensions})`;
      }
      mapToDriverValue(value) {
        return JSON.stringify(value);
      }
      mapFromDriverValue(value) {
        return value.slice(1, -1).split(",").map((v) => Number.parseFloat(v));
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/all.js
function getPgColumnBuilders() {
  return {
    bigint,
    bigserial,
    boolean,
    char,
    cidr,
    customType,
    date,
    doublePrecision,
    inet,
    integer,
    interval,
    json,
    jsonb,
    line,
    macaddr,
    macaddr8,
    numeric,
    point,
    geometry,
    real,
    serial,
    smallint,
    smallserial,
    text,
    time,
    timestamp,
    uuid,
    varchar,
    bit,
    halfvec,
    sparsevec,
    vector
  };
}
var init_all = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/all.js"() {
    init_bigint();
    init_bigserial();
    init_boolean();
    init_char();
    init_cidr();
    init_custom();
    init_date();
    init_double_precision();
    init_inet();
    init_integer();
    init_interval();
    init_json();
    init_jsonb();
    init_line();
    init_macaddr();
    init_macaddr8();
    init_numeric();
    init_point();
    init_geometry();
    init_real();
    init_serial();
    init_smallint();
    init_smallserial();
    init_text();
    init_time();
    init_timestamp();
    init_uuid();
    init_varchar();
    init_bit();
    init_halfvec();
    init_sparsevec();
    init_vector();
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/table.js
function pgTableWithSchema(name, columns, extraConfig, schema, baseName = name) {
  const rawTable = new PgTable(name, schema, baseName);
  const parsedColumns = typeof columns === "function" ? columns(getPgColumnBuilders()) : columns;
  const builtColumns = Object.fromEntries(
    Object.entries(parsedColumns).map(([name2, colBuilderBase]) => {
      const colBuilder = colBuilderBase;
      colBuilder.setName(name2);
      const column = colBuilder.build(rawTable);
      rawTable[InlineForeignKeys].push(...colBuilder.buildForeignKeys(column, rawTable));
      return [name2, column];
    })
  );
  const builtColumnsForExtraConfig = Object.fromEntries(
    Object.entries(parsedColumns).map(([name2, colBuilderBase]) => {
      const colBuilder = colBuilderBase;
      colBuilder.setName(name2);
      const column = colBuilder.buildExtraConfigColumn(rawTable);
      return [name2, column];
    })
  );
  const table = Object.assign(rawTable, builtColumns);
  table[Table.Symbol.Columns] = builtColumns;
  table[Table.Symbol.ExtraConfigColumns] = builtColumnsForExtraConfig;
  if (extraConfig) {
    table[PgTable.Symbol.ExtraConfigBuilder] = extraConfig;
  }
  return Object.assign(table, {
    enableRLS: () => {
      table[PgTable.Symbol.EnableRLS] = true;
      return table;
    }
  });
}
var InlineForeignKeys, EnableRLS, PgTable, pgTable;
var init_table2 = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/table.js"() {
    init_entity();
    init_table();
    init_all();
    InlineForeignKeys = /* @__PURE__ */ Symbol.for("drizzle:PgInlineForeignKeys");
    EnableRLS = /* @__PURE__ */ Symbol.for("drizzle:EnableRLS");
    PgTable = class extends Table {
      static [entityKind] = "PgTable";
      /** @internal */
      static Symbol = Object.assign({}, Table.Symbol, {
        InlineForeignKeys,
        EnableRLS
      });
      /**@internal */
      [InlineForeignKeys] = [];
      /** @internal */
      [EnableRLS] = false;
      /** @internal */
      [Table.Symbol.ExtraConfigBuilder] = void 0;
      /** @internal */
      [Table.Symbol.ExtraConfigColumns] = {};
    };
    pgTable = (name, columns, extraConfig) => {
      return pgTableWithSchema(name, columns, extraConfig, void 0);
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/checks.js
var CheckBuilder, Check;
var init_checks = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/checks.js"() {
    init_entity();
    CheckBuilder = class {
      constructor(name, value) {
        this.name = name;
        this.value = value;
      }
      static [entityKind] = "PgCheckBuilder";
      brand;
      /** @internal */
      build(table) {
        return new Check(table, this);
      }
    };
    Check = class {
      constructor(table, builder) {
        this.table = table;
        this.name = builder.name;
        this.value = builder.value;
      }
      static [entityKind] = "PgCheck";
      name;
      value;
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/index.js
var init_columns = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/index.js"() {
    init_bigint();
    init_bigserial();
    init_boolean();
    init_char();
    init_cidr();
    init_common();
    init_custom();
    init_date();
    init_double_precision();
    init_enum();
    init_inet();
    init_int_common();
    init_integer();
    init_interval();
    init_json();
    init_jsonb();
    init_line();
    init_macaddr();
    init_macaddr8();
    init_numeric();
    init_point();
    init_geometry();
    init_real();
    init_serial();
    init_smallint();
    init_smallserial();
    init_text();
    init_time();
    init_timestamp();
    init_uuid();
    init_varchar();
    init_bit();
    init_halfvec();
    init_sparsevec();
    init_vector();
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/indexes.js
function index(name) {
  return new IndexBuilderOn(false, name);
}
function uniqueIndex(name) {
  return new IndexBuilderOn(true, name);
}
var IndexBuilderOn, IndexBuilder, Index;
var init_indexes = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/indexes.js"() {
    init_sql();
    init_entity();
    init_columns();
    IndexBuilderOn = class {
      constructor(unique, name) {
        this.unique = unique;
        this.name = name;
      }
      static [entityKind] = "PgIndexBuilderOn";
      on(...columns) {
        return new IndexBuilder(
          columns.map((it) => {
            if (is(it, SQL)) {
              return it;
            }
            it = it;
            const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig);
            it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig));
            return clonedIndexedColumn;
          }),
          this.unique,
          false,
          this.name
        );
      }
      onOnly(...columns) {
        return new IndexBuilder(
          columns.map((it) => {
            if (is(it, SQL)) {
              return it;
            }
            it = it;
            const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig);
            it.indexConfig = it.defaultConfig;
            return clonedIndexedColumn;
          }),
          this.unique,
          true,
          this.name
        );
      }
      /**
       * Specify what index method to use. Choices are `btree`, `hash`, `gist`, `spgist`, `gin`, `brin`, or user-installed access methods like `bloom`. The default method is `btree.
       *
       * If you have the `pg_vector` extension installed in your database, you can use the `hnsw` and `ivfflat` options, which are predefined types.
       *
       * **You can always specify any string you want in the method, in case Drizzle doesn't have it natively in its types**
       *
       * @param method The name of the index method to be used
       * @param columns
       * @returns
       */
      using(method, ...columns) {
        return new IndexBuilder(
          columns.map((it) => {
            if (is(it, SQL)) {
              return it;
            }
            it = it;
            const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig);
            it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig));
            return clonedIndexedColumn;
          }),
          this.unique,
          true,
          this.name,
          method
        );
      }
    };
    IndexBuilder = class {
      static [entityKind] = "PgIndexBuilder";
      /** @internal */
      config;
      constructor(columns, unique, only, name, method = "btree") {
        this.config = {
          name,
          columns,
          unique,
          only,
          method
        };
      }
      concurrently() {
        this.config.concurrently = true;
        return this;
      }
      with(obj) {
        this.config.with = obj;
        return this;
      }
      where(condition) {
        this.config.where = condition;
        return this;
      }
      /** @internal */
      build(table) {
        return new Index(this.config, table);
      }
    };
    Index = class {
      static [entityKind] = "PgIndex";
      config;
      constructor(config2, table) {
        this.config = { ...config2, table };
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/policies.js
var PgPolicy;
var init_policies = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/policies.js"() {
    init_entity();
    PgPolicy = class {
      constructor(name, config2) {
        this.name = name;
        if (config2) {
          this.as = config2.as;
          this.for = config2.for;
          this.to = config2.to;
          this.using = config2.using;
          this.withCheck = config2.withCheck;
        }
      }
      static [entityKind] = "PgPolicy";
      as;
      for;
      to;
      using;
      withCheck;
      /** @internal */
      _linkedTable;
      link(table) {
        this._linkedTable = table;
        return this;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/primary-keys.js
var PrimaryKeyBuilder, PrimaryKey;
var init_primary_keys = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/primary-keys.js"() {
    init_entity();
    init_table2();
    PrimaryKeyBuilder = class {
      static [entityKind] = "PgPrimaryKeyBuilder";
      /** @internal */
      columns;
      /** @internal */
      name;
      constructor(columns, name) {
        this.columns = columns;
        this.name = name;
      }
      /** @internal */
      build(table) {
        return new PrimaryKey(table, this.columns, this.name);
      }
    };
    PrimaryKey = class {
      constructor(table, columns, name) {
        this.table = table;
        this.columns = columns;
        this.name = name;
      }
      static [entityKind] = "PgPrimaryKey";
      columns;
      name;
      getName() {
        return this.name ?? `${this.table[PgTable.Symbol.Name]}_${this.columns.map((column) => column.name).join("_")}_pk`;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/view-common.js
var PgViewConfig;
var init_view_common2 = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/view-common.js"() {
    PgViewConfig = /* @__PURE__ */ Symbol.for("drizzle:PgViewConfig");
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/casing.js
function toSnakeCase(input) {
  const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? [];
  return words.map((word) => word.toLowerCase()).join("_");
}
function toCamelCase(input) {
  const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? [];
  return words.reduce((acc, word, i) => {
    const formattedWord = i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`;
    return acc + formattedWord;
  }, "");
}
function noopCase(input) {
  return input;
}
var CasingCache;
var init_casing = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/casing.js"() {
    init_entity();
    init_table();
    CasingCache = class {
      static [entityKind] = "CasingCache";
      /** @internal */
      cache = {};
      cachedTables = {};
      convert;
      constructor(casing) {
        this.convert = casing === "snake_case" ? toSnakeCase : casing === "camelCase" ? toCamelCase : noopCase;
      }
      getColumnCasing(column) {
        if (!column.keyAsName) return column.name;
        const schema = column.table[Table.Symbol.Schema] ?? "public";
        const tableName = column.table[Table.Symbol.OriginalName];
        const key = `${schema}.${tableName}.${column.name}`;
        if (!this.cache[key]) {
          this.cacheTable(column.table);
        }
        return this.cache[key];
      }
      cacheTable(table) {
        const schema = table[Table.Symbol.Schema] ?? "public";
        const tableName = table[Table.Symbol.OriginalName];
        const tableKey = `${schema}.${tableName}`;
        if (!this.cachedTables[tableKey]) {
          for (const column of Object.values(table[Table.Symbol.Columns])) {
            const columnKey = `${tableKey}.${column.name}`;
            this.cache[columnKey] = this.convert(column.name);
          }
          this.cachedTables[tableKey] = true;
        }
      }
      clearCache() {
        this.cache = {};
        this.cachedTables = {};
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/errors.js
var DrizzleError, DrizzleQueryError, TransactionRollbackError;
var init_errors2 = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/errors.js"() {
    init_entity();
    DrizzleError = class extends Error {
      static [entityKind] = "DrizzleError";
      constructor({ message, cause }) {
        super(message);
        this.name = "DrizzleError";
        this.cause = cause;
      }
    };
    DrizzleQueryError = class _DrizzleQueryError extends Error {
      constructor(query, params, cause) {
        super(`Failed query: ${query}
params: ${params}`);
        this.query = query;
        this.params = params;
        this.cause = cause;
        Error.captureStackTrace(this, _DrizzleQueryError);
        if (cause) this.cause = cause;
      }
    };
    TransactionRollbackError = class extends DrizzleError {
      static [entityKind] = "TransactionRollbackError";
      constructor() {
        super({ message: "Rollback" });
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/sql/expressions/conditions.js
function bindIfParam(value, column) {
  if (isDriverValueEncoder(column) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column) && !is(value, Table) && !is(value, View)) {
    return new Param(value, column);
  }
  return value;
}
function and(...unfilteredConditions) {
  const conditions = unfilteredConditions.filter(
    (c) => c !== void 0
  );
  if (conditions.length === 0) {
    return void 0;
  }
  if (conditions.length === 1) {
    return new SQL(conditions);
  }
  return new SQL([
    new StringChunk("("),
    sql.join(conditions, new StringChunk(" and ")),
    new StringChunk(")")
  ]);
}
function or(...unfilteredConditions) {
  const conditions = unfilteredConditions.filter(
    (c) => c !== void 0
  );
  if (conditions.length === 0) {
    return void 0;
  }
  if (conditions.length === 1) {
    return new SQL(conditions);
  }
  return new SQL([
    new StringChunk("("),
    sql.join(conditions, new StringChunk(" or ")),
    new StringChunk(")")
  ]);
}
function not(condition) {
  return sql`not ${condition}`;
}
function inArray(column, values) {
  if (Array.isArray(values)) {
    if (values.length === 0) {
      return sql`false`;
    }
    return sql`${column} in ${values.map((v) => bindIfParam(v, column))}`;
  }
  return sql`${column} in ${bindIfParam(values, column)}`;
}
function notInArray(column, values) {
  if (Array.isArray(values)) {
    if (values.length === 0) {
      return sql`true`;
    }
    return sql`${column} not in ${values.map((v) => bindIfParam(v, column))}`;
  }
  return sql`${column} not in ${bindIfParam(values, column)}`;
}
function isNull(value) {
  return sql`${value} is null`;
}
function isNotNull(value) {
  return sql`${value} is not null`;
}
function exists(subquery) {
  return sql`exists ${subquery}`;
}
function notExists(subquery) {
  return sql`not exists ${subquery}`;
}
function between(column, min, max) {
  return sql`${column} between ${bindIfParam(min, column)} and ${bindIfParam(
    max,
    column
  )}`;
}
function notBetween(column, min, max) {
  return sql`${column} not between ${bindIfParam(
    min,
    column
  )} and ${bindIfParam(max, column)}`;
}
function like(column, value) {
  return sql`${column} like ${value}`;
}
function notLike(column, value) {
  return sql`${column} not like ${value}`;
}
function ilike(column, value) {
  return sql`${column} ilike ${value}`;
}
function notIlike(column, value) {
  return sql`${column} not ilike ${value}`;
}
var eq, ne, gt, gte, lt, lte;
var init_conditions = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/sql/expressions/conditions.js"() {
    init_column();
    init_entity();
    init_table();
    init_sql();
    eq = (left, right) => {
      return sql`${left} = ${bindIfParam(right, left)}`;
    };
    ne = (left, right) => {
      return sql`${left} <> ${bindIfParam(right, left)}`;
    };
    gt = (left, right) => {
      return sql`${left} > ${bindIfParam(right, left)}`;
    };
    gte = (left, right) => {
      return sql`${left} >= ${bindIfParam(right, left)}`;
    };
    lt = (left, right) => {
      return sql`${left} < ${bindIfParam(right, left)}`;
    };
    lte = (left, right) => {
      return sql`${left} <= ${bindIfParam(right, left)}`;
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/sql/expressions/select.js
function asc(column) {
  return sql`${column} asc`;
}
function desc(column) {
  return sql`${column} desc`;
}
var init_select = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/sql/expressions/select.js"() {
    init_sql();
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/sql/expressions/index.js
var init_expressions = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/sql/expressions/index.js"() {
    init_conditions();
    init_select();
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/relations.js
function getOperators() {
  return {
    and,
    between,
    eq,
    exists,
    gt,
    gte,
    ilike,
    inArray,
    isNull,
    isNotNull,
    like,
    lt,
    lte,
    ne,
    not,
    notBetween,
    notExists,
    notLike,
    notIlike,
    notInArray,
    or,
    sql
  };
}
function getOrderByOperators() {
  return {
    sql,
    asc,
    desc
  };
}
function extractTablesRelationalConfig(schema, configHelpers) {
  if (Object.keys(schema).length === 1 && "default" in schema && !is(schema["default"], Table)) {
    schema = schema["default"];
  }
  const tableNamesMap = {};
  const relationsBuffer = {};
  const tablesConfig = {};
  for (const [key, value] of Object.entries(schema)) {
    if (is(value, Table)) {
      const dbName = getTableUniqueName(value);
      const bufferedRelations = relationsBuffer[dbName];
      tableNamesMap[dbName] = key;
      tablesConfig[key] = {
        tsName: key,
        dbName: value[Table.Symbol.Name],
        schema: value[Table.Symbol.Schema],
        columns: value[Table.Symbol.Columns],
        relations: bufferedRelations?.relations ?? {},
        primaryKey: bufferedRelations?.primaryKey ?? []
      };
      for (const column of Object.values(
        value[Table.Symbol.Columns]
      )) {
        if (column.primary) {
          tablesConfig[key].primaryKey.push(column);
        }
      }
      const extraConfig = value[Table.Symbol.ExtraConfigBuilder]?.(value[Table.Symbol.ExtraConfigColumns]);
      if (extraConfig) {
        for (const configEntry of Object.values(extraConfig)) {
          if (is(configEntry, PrimaryKeyBuilder)) {
            tablesConfig[key].primaryKey.push(...configEntry.columns);
          }
        }
      }
    } else if (is(value, Relations)) {
      const dbName = getTableUniqueName(value.table);
      const tableName = tableNamesMap[dbName];
      const relations2 = value.config(
        configHelpers(value.table)
      );
      let primaryKey;
      for (const [relationName, relation] of Object.entries(relations2)) {
        if (tableName) {
          const tableConfig = tablesConfig[tableName];
          tableConfig.relations[relationName] = relation;
          if (primaryKey) {
            tableConfig.primaryKey.push(...primaryKey);
          }
        } else {
          if (!(dbName in relationsBuffer)) {
            relationsBuffer[dbName] = {
              relations: {},
              primaryKey
            };
          }
          relationsBuffer[dbName].relations[relationName] = relation;
        }
      }
    }
  }
  return { tables: tablesConfig, tableNamesMap };
}
function createOne(sourceTable) {
  return function one(table, config2) {
    return new One(
      sourceTable,
      table,
      config2,
      config2?.fields.reduce((res, f) => res && f.notNull, true) ?? false
    );
  };
}
function createMany(sourceTable) {
  return function many(referencedTable, config2) {
    return new Many(sourceTable, referencedTable, config2);
  };
}
function normalizeRelation(schema, tableNamesMap, relation) {
  if (is(relation, One) && relation.config) {
    return {
      fields: relation.config.fields,
      references: relation.config.references
    };
  }
  const referencedTableTsName = tableNamesMap[getTableUniqueName(relation.referencedTable)];
  if (!referencedTableTsName) {
    throw new Error(
      `Table "${relation.referencedTable[Table.Symbol.Name]}" not found in schema`
    );
  }
  const referencedTableConfig = schema[referencedTableTsName];
  if (!referencedTableConfig) {
    throw new Error(`Table "${referencedTableTsName}" not found in schema`);
  }
  const sourceTable = relation.sourceTable;
  const sourceTableTsName = tableNamesMap[getTableUniqueName(sourceTable)];
  if (!sourceTableTsName) {
    throw new Error(
      `Table "${sourceTable[Table.Symbol.Name]}" not found in schema`
    );
  }
  const reverseRelations = [];
  for (const referencedTableRelation of Object.values(
    referencedTableConfig.relations
  )) {
    if (relation.relationName && relation !== referencedTableRelation && referencedTableRelation.relationName === relation.relationName || !relation.relationName && referencedTableRelation.referencedTable === relation.sourceTable) {
      reverseRelations.push(referencedTableRelation);
    }
  }
  if (reverseRelations.length > 1) {
    throw relation.relationName ? new Error(
      `There are multiple relations with name "${relation.relationName}" in table "${referencedTableTsName}"`
    ) : new Error(
      `There are multiple relations between "${referencedTableTsName}" and "${relation.sourceTable[Table.Symbol.Name]}". Please specify relation name`
    );
  }
  if (reverseRelations[0] && is(reverseRelations[0], One) && reverseRelations[0].config) {
    return {
      fields: reverseRelations[0].config.references,
      references: reverseRelations[0].config.fields
    };
  }
  throw new Error(
    `There is not enough information to infer relation "${sourceTableTsName}.${relation.fieldName}"`
  );
}
function createTableRelationsHelpers(sourceTable) {
  return {
    one: createOne(sourceTable),
    many: createMany(sourceTable)
  };
}
function mapRelationalRow(tablesConfig, tableConfig, row, buildQueryResultSelection, mapColumnValue = (value) => value) {
  const result = {};
  for (const [
    selectionItemIndex,
    selectionItem
  ] of buildQueryResultSelection.entries()) {
    if (selectionItem.isJson) {
      const relation = tableConfig.relations[selectionItem.tsKey];
      const rawSubRows = row[selectionItemIndex];
      const subRows = typeof rawSubRows === "string" ? JSON.parse(rawSubRows) : rawSubRows;
      result[selectionItem.tsKey] = is(relation, One) ? subRows && mapRelationalRow(
        tablesConfig,
        tablesConfig[selectionItem.relationTableTsKey],
        subRows,
        selectionItem.selection,
        mapColumnValue
      ) : subRows.map(
        (subRow) => mapRelationalRow(
          tablesConfig,
          tablesConfig[selectionItem.relationTableTsKey],
          subRow,
          selectionItem.selection,
          mapColumnValue
        )
      );
    } else {
      const value = mapColumnValue(row[selectionItemIndex]);
      const field = selectionItem.field;
      let decoder;
      if (is(field, Column)) {
        decoder = field;
      } else if (is(field, SQL)) {
        decoder = field.decoder;
      } else {
        decoder = field.sql.decoder;
      }
      result[selectionItem.tsKey] = value === null ? null : decoder.mapFromDriverValue(value);
    }
  }
  return result;
}
var Relation, Relations, One, Many;
var init_relations = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/relations.js"() {
    init_table();
    init_column();
    init_entity();
    init_primary_keys();
    init_expressions();
    init_sql();
    Relation = class {
      constructor(sourceTable, referencedTable, relationName) {
        this.sourceTable = sourceTable;
        this.referencedTable = referencedTable;
        this.relationName = relationName;
        this.referencedTableName = referencedTable[Table.Symbol.Name];
      }
      static [entityKind] = "Relation";
      referencedTableName;
      fieldName;
    };
    Relations = class {
      constructor(table, config2) {
        this.table = table;
        this.config = config2;
      }
      static [entityKind] = "Relations";
    };
    One = class _One extends Relation {
      constructor(sourceTable, referencedTable, config2, isNullable) {
        super(sourceTable, referencedTable, config2?.relationName);
        this.config = config2;
        this.isNullable = isNullable;
      }
      static [entityKind] = "One";
      withFieldName(fieldName) {
        const relation = new _One(
          this.sourceTable,
          this.referencedTable,
          this.config,
          this.isNullable
        );
        relation.fieldName = fieldName;
        return relation;
      }
    };
    Many = class _Many extends Relation {
      constructor(sourceTable, referencedTable, config2) {
        super(sourceTable, referencedTable, config2?.relationName);
        this.config = config2;
      }
      static [entityKind] = "Many";
      withFieldName(fieldName) {
        const relation = new _Many(
          this.sourceTable,
          this.referencedTable,
          this.config
        );
        relation.fieldName = fieldName;
        return relation;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/sql/functions/aggregate.js
function count(expression) {
  return sql`count(${expression || sql.raw("*")})`.mapWith(Number);
}
function sum(expression) {
  return sql`sum(${expression})`.mapWith(String);
}
var init_aggregate = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/sql/functions/aggregate.js"() {
    init_sql();
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/sql/functions/vector.js
var init_vector2 = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/sql/functions/vector.js"() {
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/sql/functions/index.js
var init_functions = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/sql/functions/index.js"() {
    init_aggregate();
    init_vector2();
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/sql/index.js
var init_sql2 = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/sql/index.js"() {
    init_expressions();
    init_functions();
    init_sql();
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/view-base.js
var PgViewBase;
var init_view_base = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/view-base.js"() {
    init_entity();
    init_sql();
    PgViewBase = class extends View {
      static [entityKind] = "PgViewBase";
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/dialect.js
var PgDialect;
var init_dialect = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/dialect.js"() {
    init_alias();
    init_casing();
    init_column();
    init_entity();
    init_errors2();
    init_columns();
    init_table2();
    init_relations();
    init_sql2();
    init_sql();
    init_subquery();
    init_table();
    init_utils();
    init_view_common();
    init_view_base();
    PgDialect = class {
      static [entityKind] = "PgDialect";
      /** @internal */
      casing;
      constructor(config2) {
        this.casing = new CasingCache(config2?.casing);
      }
      async migrate(migrations, session, config2) {
        const migrationsTable = typeof config2 === "string" ? "__drizzle_migrations" : config2.migrationsTable ?? "__drizzle_migrations";
        const migrationsSchema = typeof config2 === "string" ? "drizzle" : config2.migrationsSchema ?? "drizzle";
        const migrationTableCreate = sql`
			CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} (
				id SERIAL PRIMARY KEY,
				hash text NOT NULL,
				created_at bigint
			)
		`;
        await session.execute(sql`CREATE SCHEMA IF NOT EXISTS ${sql.identifier(migrationsSchema)}`);
        await session.execute(migrationTableCreate);
        const dbMigrations = await session.all(
          sql`select id, hash, created_at from ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} order by created_at desc limit 1`
        );
        const lastDbMigration = dbMigrations[0];
        await session.transaction(async (tx) => {
          for await (const migration of migrations) {
            if (!lastDbMigration || Number(lastDbMigration.created_at) < migration.folderMillis) {
              for (const stmt of migration.sql) {
                await tx.execute(sql.raw(stmt));
              }
              await tx.execute(
                sql`insert into ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} ("hash", "created_at") values(${migration.hash}, ${migration.folderMillis})`
              );
            }
          }
        });
      }
      escapeName(name) {
        return `"${name.replace(/"/g, '""')}"`;
      }
      escapeParam(num) {
        return `$${num + 1}`;
      }
      escapeString(str) {
        return `'${str.replace(/'/g, "''")}'`;
      }
      buildWithCTE(queries) {
        if (!queries?.length) return void 0;
        const withSqlChunks = [sql`with `];
        for (const [i, w] of queries.entries()) {
          withSqlChunks.push(sql`${sql.identifier(w._.alias)} as (${w._.sql})`);
          if (i < queries.length - 1) {
            withSqlChunks.push(sql`, `);
          }
        }
        withSqlChunks.push(sql` `);
        return sql.join(withSqlChunks);
      }
      buildDeleteQuery({ table, where, returning, withList }) {
        const withSql = this.buildWithCTE(withList);
        const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
        const whereSql = where ? sql` where ${where}` : void 0;
        return sql`${withSql}delete from ${table}${whereSql}${returningSql}`;
      }
      buildUpdateSet(table, set2) {
        const tableColumns = table[Table.Symbol.Columns];
        const columnNames = Object.keys(tableColumns).filter(
          (colName) => set2[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0
        );
        const setSize = columnNames.length;
        return sql.join(columnNames.flatMap((colName, i) => {
          const col = tableColumns[colName];
          const onUpdateFnResult = col.onUpdateFn?.();
          const value = set2[colName] ?? (is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col));
          const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`;
          if (i < setSize - 1) {
            return [res, sql.raw(", ")];
          }
          return [res];
        }));
      }
      buildUpdateQuery({ table, set: set2, where, returning, withList, from, joins }) {
        const withSql = this.buildWithCTE(withList);
        const tableName = table[PgTable.Symbol.Name];
        const tableSchema = table[PgTable.Symbol.Schema];
        const origTableName = table[PgTable.Symbol.OriginalName];
        const alias = tableName === origTableName ? void 0 : tableName;
        const tableSql = sql`${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}`;
        const setSql = this.buildUpdateSet(table, set2);
        const fromSql = from && sql.join([sql.raw(" from "), this.buildFromTable(from)]);
        const joinsSql = this.buildJoins(joins);
        const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: !from })}` : void 0;
        const whereSql = where ? sql` where ${where}` : void 0;
        return sql`${withSql}update ${tableSql} set ${setSql}${fromSql}${joinsSql}${whereSql}${returningSql}`;
      }
      /**
       * Builds selection SQL with provided fields/expressions
       *
       * Examples:
       *
       * `select <selection> from`
       *
       * `insert ... returning <selection>`
       *
       * If `isSingleTable` is true, then columns won't be prefixed with table name
       */
      buildSelection(fields, { isSingleTable = false } = {}) {
        const columnsLen = fields.length;
        const chunks = fields.flatMap(({ field }, i) => {
          const chunk2 = [];
          if (is(field, SQL.Aliased) && field.isSelectionField) {
            chunk2.push(sql.identifier(field.fieldAlias));
          } else if (is(field, SQL.Aliased) || is(field, SQL)) {
            const query = is(field, SQL.Aliased) ? field.sql : field;
            if (isSingleTable) {
              chunk2.push(
                new SQL(
                  query.queryChunks.map((c) => {
                    if (is(c, PgColumn)) {
                      return sql.identifier(this.casing.getColumnCasing(c));
                    }
                    return c;
                  })
                )
              );
            } else {
              chunk2.push(query);
            }
            if (is(field, SQL.Aliased)) {
              chunk2.push(sql` as ${sql.identifier(field.fieldAlias)}`);
            }
          } else if (is(field, Column)) {
            if (isSingleTable) {
              chunk2.push(sql.identifier(this.casing.getColumnCasing(field)));
            } else {
              chunk2.push(field);
            }
          } else if (is(field, Subquery)) {
            const entries = Object.entries(field._.selectedFields);
            if (entries.length === 1) {
              const entry = entries[0][1];
              const fieldDecoder = is(entry, SQL) ? entry.decoder : is(entry, Column) ? { mapFromDriverValue: (v) => entry.mapFromDriverValue(v) } : entry.sql.decoder;
              if (fieldDecoder) {
                field._.sql.decoder = fieldDecoder;
              }
            }
            chunk2.push(field);
          }
          if (i < columnsLen - 1) {
            chunk2.push(sql`, `);
          }
          return chunk2;
        });
        return sql.join(chunks);
      }
      buildJoins(joins) {
        if (!joins || joins.length === 0) {
          return void 0;
        }
        const joinsArray = [];
        for (const [index2, joinMeta] of joins.entries()) {
          if (index2 === 0) {
            joinsArray.push(sql` `);
          }
          const table = joinMeta.table;
          const lateralSql = joinMeta.lateral ? sql` lateral` : void 0;
          const onSql = joinMeta.on ? sql` on ${joinMeta.on}` : void 0;
          if (is(table, PgTable)) {
            const tableName = table[PgTable.Symbol.Name];
            const tableSchema = table[PgTable.Symbol.Schema];
            const origTableName = table[PgTable.Symbol.OriginalName];
            const alias = tableName === origTableName ? void 0 : joinMeta.alias;
            joinsArray.push(
              sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}`
            );
          } else if (is(table, View)) {
            const viewName = table[ViewBaseConfig].name;
            const viewSchema = table[ViewBaseConfig].schema;
            const origViewName = table[ViewBaseConfig].originalName;
            const alias = viewName === origViewName ? void 0 : joinMeta.alias;
            joinsArray.push(
              sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${viewSchema ? sql`${sql.identifier(viewSchema)}.` : void 0}${sql.identifier(origViewName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}`
            );
          } else {
            joinsArray.push(
              sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${table}${onSql}`
            );
          }
          if (index2 < joins.length - 1) {
            joinsArray.push(sql` `);
          }
        }
        return sql.join(joinsArray);
      }
      buildFromTable(table) {
        if (is(table, Table) && table[Table.Symbol.IsAlias]) {
          let fullName = sql`${sql.identifier(table[Table.Symbol.OriginalName])}`;
          if (table[Table.Symbol.Schema]) {
            fullName = sql`${sql.identifier(table[Table.Symbol.Schema])}.${fullName}`;
          }
          return sql`${fullName} ${sql.identifier(table[Table.Symbol.Name])}`;
        }
        return table;
      }
      buildSelectQuery({
        withList,
        fields,
        fieldsFlat,
        where,
        having,
        table,
        joins,
        orderBy,
        groupBy,
        limit,
        offset,
        lockingClause,
        distinct,
        setOperators
      }) {
        const fieldsList = fieldsFlat ?? orderSelectedFields(fields);
        for (const f of fieldsList) {
          if (is(f.field, Column) && getTableName(f.field.table) !== (is(table, Subquery) ? table._.alias : is(table, PgViewBase) ? table[ViewBaseConfig].name : is(table, SQL) ? void 0 : getTableName(table)) && !((table2) => joins?.some(
            ({ alias }) => alias === (table2[Table.Symbol.IsAlias] ? getTableName(table2) : table2[Table.Symbol.BaseName])
          ))(f.field.table)) {
            const tableName = getTableName(f.field.table);
            throw new Error(
              `Your "${f.path.join("->")}" field references a column "${tableName}"."${f.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?`
            );
          }
        }
        const isSingleTable = !joins || joins.length === 0;
        const withSql = this.buildWithCTE(withList);
        let distinctSql;
        if (distinct) {
          distinctSql = distinct === true ? sql` distinct` : sql` distinct on (${sql.join(distinct.on, sql`, `)})`;
        }
        const selection = this.buildSelection(fieldsList, { isSingleTable });
        const tableSql = this.buildFromTable(table);
        const joinsSql = this.buildJoins(joins);
        const whereSql = where ? sql` where ${where}` : void 0;
        const havingSql = having ? sql` having ${having}` : void 0;
        let orderBySql;
        if (orderBy && orderBy.length > 0) {
          orderBySql = sql` order by ${sql.join(orderBy, sql`, `)}`;
        }
        let groupBySql;
        if (groupBy && groupBy.length > 0) {
          groupBySql = sql` group by ${sql.join(groupBy, sql`, `)}`;
        }
        const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
        const offsetSql = offset ? sql` offset ${offset}` : void 0;
        const lockingClauseSql = sql.empty();
        if (lockingClause) {
          const clauseSql = sql` for ${sql.raw(lockingClause.strength)}`;
          if (lockingClause.config.of) {
            clauseSql.append(
              sql` of ${sql.join(
                Array.isArray(lockingClause.config.of) ? lockingClause.config.of : [lockingClause.config.of],
                sql`, `
              )}`
            );
          }
          if (lockingClause.config.noWait) {
            clauseSql.append(sql` nowait`);
          } else if (lockingClause.config.skipLocked) {
            clauseSql.append(sql` skip locked`);
          }
          lockingClauseSql.append(clauseSql);
        }
        const finalQuery = sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}${lockingClauseSql}`;
        if (setOperators.length > 0) {
          return this.buildSetOperations(finalQuery, setOperators);
        }
        return finalQuery;
      }
      buildSetOperations(leftSelect, setOperators) {
        const [setOperator, ...rest] = setOperators;
        if (!setOperator) {
          throw new Error("Cannot pass undefined values to any set operator");
        }
        if (rest.length === 0) {
          return this.buildSetOperationQuery({ leftSelect, setOperator });
        }
        return this.buildSetOperations(
          this.buildSetOperationQuery({ leftSelect, setOperator }),
          rest
        );
      }
      buildSetOperationQuery({
        leftSelect,
        setOperator: { type, isAll, rightSelect, limit, orderBy, offset }
      }) {
        const leftChunk = sql`(${leftSelect.getSQL()}) `;
        const rightChunk = sql`(${rightSelect.getSQL()})`;
        let orderBySql;
        if (orderBy && orderBy.length > 0) {
          const orderByValues = [];
          for (const singleOrderBy of orderBy) {
            if (is(singleOrderBy, PgColumn)) {
              orderByValues.push(sql.identifier(singleOrderBy.name));
            } else if (is(singleOrderBy, SQL)) {
              for (let i = 0; i < singleOrderBy.queryChunks.length; i++) {
                const chunk2 = singleOrderBy.queryChunks[i];
                if (is(chunk2, PgColumn)) {
                  singleOrderBy.queryChunks[i] = sql.identifier(chunk2.name);
                }
              }
              orderByValues.push(sql`${singleOrderBy}`);
            } else {
              orderByValues.push(sql`${singleOrderBy}`);
            }
          }
          orderBySql = sql` order by ${sql.join(orderByValues, sql`, `)} `;
        }
        const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
        const operatorChunk = sql.raw(`${type} ${isAll ? "all " : ""}`);
        const offsetSql = offset ? sql` offset ${offset}` : void 0;
        return sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;
      }
      buildInsertQuery({ table, values: valuesOrSelect, onConflict, returning, withList, select, overridingSystemValue_ }) {
        const valuesSqlList = [];
        const columns = table[Table.Symbol.Columns];
        const colEntries = Object.entries(columns).filter(([_, col]) => !col.shouldDisableInsert());
        const insertOrder = colEntries.map(
          ([, column]) => sql.identifier(this.casing.getColumnCasing(column))
        );
        if (select) {
          const select2 = valuesOrSelect;
          if (is(select2, SQL)) {
            valuesSqlList.push(select2);
          } else {
            valuesSqlList.push(select2.getSQL());
          }
        } else {
          const values = valuesOrSelect;
          valuesSqlList.push(sql.raw("values "));
          for (const [valueIndex, value] of values.entries()) {
            const valueList = [];
            for (const [fieldName, col] of colEntries) {
              const colValue = value[fieldName];
              if (colValue === void 0 || is(colValue, Param) && colValue.value === void 0) {
                if (col.defaultFn !== void 0) {
                  const defaultFnResult = col.defaultFn();
                  const defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);
                  valueList.push(defaultValue);
                } else if (!col.default && col.onUpdateFn !== void 0) {
                  const onUpdateFnResult = col.onUpdateFn();
                  const newValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col);
                  valueList.push(newValue);
                } else {
                  valueList.push(sql`default`);
                }
              } else {
                valueList.push(colValue);
              }
            }
            valuesSqlList.push(valueList);
            if (valueIndex < values.length - 1) {
              valuesSqlList.push(sql`, `);
            }
          }
        }
        const withSql = this.buildWithCTE(withList);
        const valuesSql = sql.join(valuesSqlList);
        const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
        const onConflictSql = onConflict ? sql` on conflict ${onConflict}` : void 0;
        const overridingSql = overridingSystemValue_ === true ? sql`overriding system value ` : void 0;
        return sql`${withSql}insert into ${table} ${insertOrder} ${overridingSql}${valuesSql}${onConflictSql}${returningSql}`;
      }
      buildRefreshMaterializedViewQuery({ view, concurrently, withNoData }) {
        const concurrentlySql = concurrently ? sql` concurrently` : void 0;
        const withNoDataSql = withNoData ? sql` with no data` : void 0;
        return sql`refresh materialized view${concurrentlySql} ${view}${withNoDataSql}`;
      }
      prepareTyping(encoder) {
        if (is(encoder, PgJsonb) || is(encoder, PgJson)) {
          return "json";
        } else if (is(encoder, PgNumeric)) {
          return "decimal";
        } else if (is(encoder, PgTime)) {
          return "time";
        } else if (is(encoder, PgTimestamp) || is(encoder, PgTimestampString)) {
          return "timestamp";
        } else if (is(encoder, PgDate) || is(encoder, PgDateString)) {
          return "date";
        } else if (is(encoder, PgUUID)) {
          return "uuid";
        } else {
          return "none";
        }
      }
      sqlToQuery(sql2, invokeSource) {
        return sql2.toQuery({
          casing: this.casing,
          escapeName: this.escapeName,
          escapeParam: this.escapeParam,
          escapeString: this.escapeString,
          prepareTyping: this.prepareTyping,
          invokeSource
        });
      }
      // buildRelationalQueryWithPK({
      // 	fullSchema,
      // 	schema,
      // 	tableNamesMap,
      // 	table,
      // 	tableConfig,
      // 	queryConfig: config,
      // 	tableAlias,
      // 	isRoot = false,
      // 	joinOn,
      // }: {
      // 	fullSchema: Record<string, unknown>;
      // 	schema: TablesRelationalConfig;
      // 	tableNamesMap: Record<string, string>;
      // 	table: PgTable;
      // 	tableConfig: TableRelationalConfig;
      // 	queryConfig: true | DBQueryConfig<'many', true>;
      // 	tableAlias: string;
      // 	isRoot?: boolean;
      // 	joinOn?: SQL;
      // }): BuildRelationalQueryResult<PgTable, PgColumn> {
      // 	// For { "<relation>": true }, return a table with selection of all columns
      // 	if (config === true) {
      // 		const selectionEntries = Object.entries(tableConfig.columns);
      // 		const selection: BuildRelationalQueryResult<PgTable, PgColumn>['selection'] = selectionEntries.map((
      // 			[key, value],
      // 		) => ({
      // 			dbKey: value.name,
      // 			tsKey: key,
      // 			field: value as PgColumn,
      // 			relationTableTsKey: undefined,
      // 			isJson: false,
      // 			selection: [],
      // 		}));
      // 		return {
      // 			tableTsKey: tableConfig.tsName,
      // 			sql: table,
      // 			selection,
      // 		};
      // 	}
      // 	// let selection: BuildRelationalQueryResult<PgTable, PgColumn>['selection'] = [];
      // 	// let selectionForBuild = selection;
      // 	const aliasedColumns = Object.fromEntries(
      // 		Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]),
      // 	);
      // 	const aliasedRelations = Object.fromEntries(
      // 		Object.entries(tableConfig.relations).map(([key, value]) => [key, aliasedRelation(value, tableAlias)]),
      // 	);
      // 	const aliasedFields = Object.assign({}, aliasedColumns, aliasedRelations);
      // 	let where, hasUserDefinedWhere;
      // 	if (config.where) {
      // 		const whereSql = typeof config.where === 'function' ? config.where(aliasedFields, operators) : config.where;
      // 		where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
      // 		hasUserDefinedWhere = !!where;
      // 	}
      // 	where = and(joinOn, where);
      // 	// const fieldsSelection: { tsKey: string; value: PgColumn | SQL.Aliased; isExtra?: boolean }[] = [];
      // 	let joins: Join[] = [];
      // 	let selectedColumns: string[] = [];
      // 	// Figure out which columns to select
      // 	if (config.columns) {
      // 		let isIncludeMode = false;
      // 		for (const [field, value] of Object.entries(config.columns)) {
      // 			if (value === undefined) {
      // 				continue;
      // 			}
      // 			if (field in tableConfig.columns) {
      // 				if (!isIncludeMode && value === true) {
      // 					isIncludeMode = true;
      // 				}
      // 				selectedColumns.push(field);
      // 			}
      // 		}
      // 		if (selectedColumns.length > 0) {
      // 			selectedColumns = isIncludeMode
      // 				? selectedColumns.filter((c) => config.columns?.[c] === true)
      // 				: Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
      // 		}
      // 	} else {
      // 		// Select all columns if selection is not specified
      // 		selectedColumns = Object.keys(tableConfig.columns);
      // 	}
      // 	// for (const field of selectedColumns) {
      // 	// 	const column = tableConfig.columns[field]! as PgColumn;
      // 	// 	fieldsSelection.push({ tsKey: field, value: column });
      // 	// }
      // 	let initiallySelectedRelations: {
      // 		tsKey: string;
      // 		queryConfig: true | DBQueryConfig<'many', false>;
      // 		relation: Relation;
      // 	}[] = [];
      // 	// let selectedRelations: BuildRelationalQueryResult<PgTable, PgColumn>['selection'] = [];
      // 	// Figure out which relations to select
      // 	if (config.with) {
      // 		initiallySelectedRelations = Object.entries(config.with)
      // 			.filter((entry): entry is [typeof entry[0], NonNullable<typeof entry[1]>] => !!entry[1])
      // 			.map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey]! }));
      // 	}
      // 	const manyRelations = initiallySelectedRelations.filter((r) =>
      // 		is(r.relation, Many)
      // 		&& (schema[tableNamesMap[r.relation.referencedTable[Table.Symbol.Name]]!]?.primaryKey.length ?? 0) > 0
      // 	);
      // 	// If this is the last Many relation (or there are no Many relations), we are on the innermost subquery level
      // 	const isInnermostQuery = manyRelations.length < 2;
      // 	const selectedExtras: {
      // 		tsKey: string;
      // 		value: SQL.Aliased;
      // 	}[] = [];
      // 	// Figure out which extras to select
      // 	if (isInnermostQuery && config.extras) {
      // 		const extras = typeof config.extras === 'function'
      // 			? config.extras(aliasedFields, { sql })
      // 			: config.extras;
      // 		for (const [tsKey, value] of Object.entries(extras)) {
      // 			selectedExtras.push({
      // 				tsKey,
      // 				value: mapColumnsInAliasedSQLToAlias(value, tableAlias),
      // 			});
      // 		}
      // 	}
      // 	// Transform `fieldsSelection` into `selection`
      // 	// `fieldsSelection` shouldn't be used after this point
      // 	// for (const { tsKey, value, isExtra } of fieldsSelection) {
      // 	// 	selection.push({
      // 	// 		dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey]!.name,
      // 	// 		tsKey,
      // 	// 		field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value,
      // 	// 		relationTableTsKey: undefined,
      // 	// 		isJson: false,
      // 	// 		isExtra,
      // 	// 		selection: [],
      // 	// 	});
      // 	// }
      // 	let orderByOrig = typeof config.orderBy === 'function'
      // 		? config.orderBy(aliasedFields, orderByOperators)
      // 		: config.orderBy ?? [];
      // 	if (!Array.isArray(orderByOrig)) {
      // 		orderByOrig = [orderByOrig];
      // 	}
      // 	const orderBy = orderByOrig.map((orderByValue) => {
      // 		if (is(orderByValue, Column)) {
      // 			return aliasedTableColumn(orderByValue, tableAlias) as PgColumn;
      // 		}
      // 		return mapColumnsInSQLToAlias(orderByValue, tableAlias);
      // 	});
      // 	const limit = isInnermostQuery ? config.limit : undefined;
      // 	const offset = isInnermostQuery ? config.offset : undefined;
      // 	// For non-root queries without additional config except columns, return a table with selection
      // 	if (
      // 		!isRoot
      // 		&& initiallySelectedRelations.length === 0
      // 		&& selectedExtras.length === 0
      // 		&& !where
      // 		&& orderBy.length === 0
      // 		&& limit === undefined
      // 		&& offset === undefined
      // 	) {
      // 		return {
      // 			tableTsKey: tableConfig.tsName,
      // 			sql: table,
      // 			selection: selectedColumns.map((key) => ({
      // 				dbKey: tableConfig.columns[key]!.name,
      // 				tsKey: key,
      // 				field: tableConfig.columns[key] as PgColumn,
      // 				relationTableTsKey: undefined,
      // 				isJson: false,
      // 				selection: [],
      // 			})),
      // 		};
      // 	}
      // 	const selectedRelationsWithoutPK:
      // 	// Process all relations without primary keys, because they need to be joined differently and will all be on the same query level
      // 	for (
      // 		const {
      // 			tsKey: selectedRelationTsKey,
      // 			queryConfig: selectedRelationConfigValue,
      // 			relation,
      // 		} of initiallySelectedRelations
      // 	) {
      // 		const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
      // 		const relationTableName = relation.referencedTable[Table.Symbol.Name];
      // 		const relationTableTsName = tableNamesMap[relationTableName]!;
      // 		const relationTable = schema[relationTableTsName]!;
      // 		if (relationTable.primaryKey.length > 0) {
      // 			continue;
      // 		}
      // 		const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
      // 		const joinOn = and(
      // 			...normalizedRelation.fields.map((field, i) =>
      // 				eq(
      // 					aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),
      // 					aliasedTableColumn(field, tableAlias),
      // 				)
      // 			),
      // 		);
      // 		const builtRelation = this.buildRelationalQueryWithoutPK({
      // 			fullSchema,
      // 			schema,
      // 			tableNamesMap,
      // 			table: fullSchema[relationTableTsName] as PgTable,
      // 			tableConfig: schema[relationTableTsName]!,
      // 			queryConfig: selectedRelationConfigValue,
      // 			tableAlias: relationTableAlias,
      // 			joinOn,
      // 			nestedQueryRelation: relation,
      // 		});
      // 		const field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier('data')}`.as(selectedRelationTsKey);
      // 		joins.push({
      // 			on: sql`true`,
      // 			table: new Subquery(builtRelation.sql as SQL, {}, relationTableAlias),
      // 			alias: relationTableAlias,
      // 			joinType: 'left',
      // 			lateral: true,
      // 		});
      // 		selectedRelations.push({
      // 			dbKey: selectedRelationTsKey,
      // 			tsKey: selectedRelationTsKey,
      // 			field,
      // 			relationTableTsKey: relationTableTsName,
      // 			isJson: true,
      // 			selection: builtRelation.selection,
      // 		});
      // 	}
      // 	const oneRelations = initiallySelectedRelations.filter((r): r is typeof r & { relation: One } =>
      // 		is(r.relation, One)
      // 	);
      // 	// Process all One relations with PKs, because they can all be joined on the same level
      // 	for (
      // 		const {
      // 			tsKey: selectedRelationTsKey,
      // 			queryConfig: selectedRelationConfigValue,
      // 			relation,
      // 		} of oneRelations
      // 	) {
      // 		const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
      // 		const relationTableName = relation.referencedTable[Table.Symbol.Name];
      // 		const relationTableTsName = tableNamesMap[relationTableName]!;
      // 		const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
      // 		const relationTable = schema[relationTableTsName]!;
      // 		if (relationTable.primaryKey.length === 0) {
      // 			continue;
      // 		}
      // 		const joinOn = and(
      // 			...normalizedRelation.fields.map((field, i) =>
      // 				eq(
      // 					aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),
      // 					aliasedTableColumn(field, tableAlias),
      // 				)
      // 			),
      // 		);
      // 		const builtRelation = this.buildRelationalQueryWithPK({
      // 			fullSchema,
      // 			schema,
      // 			tableNamesMap,
      // 			table: fullSchema[relationTableTsName] as PgTable,
      // 			tableConfig: schema[relationTableTsName]!,
      // 			queryConfig: selectedRelationConfigValue,
      // 			tableAlias: relationTableAlias,
      // 			joinOn,
      // 		});
      // 		const field = sql`case when ${sql.identifier(relationTableAlias)} is null then null else json_build_array(${
      // 			sql.join(
      // 				builtRelation.selection.map(({ field }) =>
      // 					is(field, SQL.Aliased)
      // 						? sql`${sql.identifier(relationTableAlias)}.${sql.identifier(field.fieldAlias)}`
      // 						: is(field, Column)
      // 						? aliasedTableColumn(field, relationTableAlias)
      // 						: field
      // 				),
      // 				sql`, `,
      // 			)
      // 		}) end`.as(selectedRelationTsKey);
      // 		const isLateralJoin = is(builtRelation.sql, SQL);
      // 		joins.push({
      // 			on: isLateralJoin ? sql`true` : joinOn,
      // 			table: is(builtRelation.sql, SQL)
      // 				? new Subquery(builtRelation.sql, {}, relationTableAlias)
      // 				: aliasedTable(builtRelation.sql, relationTableAlias),
      // 			alias: relationTableAlias,
      // 			joinType: 'left',
      // 			lateral: is(builtRelation.sql, SQL),
      // 		});
      // 		selectedRelations.push({
      // 			dbKey: selectedRelationTsKey,
      // 			tsKey: selectedRelationTsKey,
      // 			field,
      // 			relationTableTsKey: relationTableTsName,
      // 			isJson: true,
      // 			selection: builtRelation.selection,
      // 		});
      // 	}
      // 	let distinct: PgSelectConfig['distinct'];
      // 	let tableFrom: PgTable | Subquery = table;
      // 	// Process first Many relation - each one requires a nested subquery
      // 	const manyRelation = manyRelations[0];
      // 	if (manyRelation) {
      // 		const {
      // 			tsKey: selectedRelationTsKey,
      // 			queryConfig: selectedRelationQueryConfig,
      // 			relation,
      // 		} = manyRelation;
      // 		distinct = {
      // 			on: tableConfig.primaryKey.map((c) => aliasedTableColumn(c as PgColumn, tableAlias)),
      // 		};
      // 		const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
      // 		const relationTableName = relation.referencedTable[Table.Symbol.Name];
      // 		const relationTableTsName = tableNamesMap[relationTableName]!;
      // 		const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
      // 		const joinOn = and(
      // 			...normalizedRelation.fields.map((field, i) =>
      // 				eq(
      // 					aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),
      // 					aliasedTableColumn(field, tableAlias),
      // 				)
      // 			),
      // 		);
      // 		const builtRelationJoin = this.buildRelationalQueryWithPK({
      // 			fullSchema,
      // 			schema,
      // 			tableNamesMap,
      // 			table: fullSchema[relationTableTsName] as PgTable,
      // 			tableConfig: schema[relationTableTsName]!,
      // 			queryConfig: selectedRelationQueryConfig,
      // 			tableAlias: relationTableAlias,
      // 			joinOn,
      // 		});
      // 		const builtRelationSelectionField = sql`case when ${
      // 			sql.identifier(relationTableAlias)
      // 		} is null then '[]' else json_agg(json_build_array(${
      // 			sql.join(
      // 				builtRelationJoin.selection.map(({ field }) =>
      // 					is(field, SQL.Aliased)
      // 						? sql`${sql.identifier(relationTableAlias)}.${sql.identifier(field.fieldAlias)}`
      // 						: is(field, Column)
      // 						? aliasedTableColumn(field, relationTableAlias)
      // 						: field
      // 				),
      // 				sql`, `,
      // 			)
      // 		})) over (partition by ${sql.join(distinct.on, sql`, `)}) end`.as(selectedRelationTsKey);
      // 		const isLateralJoin = is(builtRelationJoin.sql, SQL);
      // 		joins.push({
      // 			on: isLateralJoin ? sql`true` : joinOn,
      // 			table: isLateralJoin
      // 				? new Subquery(builtRelationJoin.sql as SQL, {}, relationTableAlias)
      // 				: aliasedTable(builtRelationJoin.sql as PgTable, relationTableAlias),
      // 			alias: relationTableAlias,
      // 			joinType: 'left',
      // 			lateral: isLateralJoin,
      // 		});
      // 		// Build the "from" subquery with the remaining Many relations
      // 		const builtTableFrom = this.buildRelationalQueryWithPK({
      // 			fullSchema,
      // 			schema,
      // 			tableNamesMap,
      // 			table,
      // 			tableConfig,
      // 			queryConfig: {
      // 				...config,
      // 				where: undefined,
      // 				orderBy: undefined,
      // 				limit: undefined,
      // 				offset: undefined,
      // 				with: manyRelations.slice(1).reduce<NonNullable<typeof config['with']>>(
      // 					(result, { tsKey, queryConfig: configValue }) => {
      // 						result[tsKey] = configValue;
      // 						return result;
      // 					},
      // 					{},
      // 				),
      // 			},
      // 			tableAlias,
      // 		});
      // 		selectedRelations.push({
      // 			dbKey: selectedRelationTsKey,
      // 			tsKey: selectedRelationTsKey,
      // 			field: builtRelationSelectionField,
      // 			relationTableTsKey: relationTableTsName,
      // 			isJson: true,
      // 			selection: builtRelationJoin.selection,
      // 		});
      // 		// selection = builtTableFrom.selection.map((item) =>
      // 		// 	is(item.field, SQL.Aliased)
      // 		// 		? { ...item, field: sql`${sql.identifier(tableAlias)}.${sql.identifier(item.field.fieldAlias)}` }
      // 		// 		: item
      // 		// );
      // 		// selectionForBuild = [{
      // 		// 	dbKey: '*',
      // 		// 	tsKey: '*',
      // 		// 	field: sql`${sql.identifier(tableAlias)}.*`,
      // 		// 	selection: [],
      // 		// 	isJson: false,
      // 		// 	relationTableTsKey: undefined,
      // 		// }];
      // 		// const newSelectionItem: (typeof selection)[number] = {
      // 		// 	dbKey: selectedRelationTsKey,
      // 		// 	tsKey: selectedRelationTsKey,
      // 		// 	field,
      // 		// 	relationTableTsKey: relationTableTsName,
      // 		// 	isJson: true,
      // 		// 	selection: builtRelationJoin.selection,
      // 		// };
      // 		// selection.push(newSelectionItem);
      // 		// selectionForBuild.push(newSelectionItem);
      // 		tableFrom = is(builtTableFrom.sql, PgTable)
      // 			? builtTableFrom.sql
      // 			: new Subquery(builtTableFrom.sql, {}, tableAlias);
      // 	}
      // 	if (selectedColumns.length === 0 && selectedRelations.length === 0 && selectedExtras.length === 0) {
      // 		throw new DrizzleError(`No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")`);
      // 	}
      // 	let selection: BuildRelationalQueryResult<PgTable, PgColumn>['selection'];
      // 	function prepareSelectedColumns() {
      // 		return selectedColumns.map((key) => ({
      // 			dbKey: tableConfig.columns[key]!.name,
      // 			tsKey: key,
      // 			field: tableConfig.columns[key] as PgColumn,
      // 			relationTableTsKey: undefined,
      // 			isJson: false,
      // 			selection: [],
      // 		}));
      // 	}
      // 	function prepareSelectedExtras() {
      // 		return selectedExtras.map((item) => ({
      // 			dbKey: item.value.fieldAlias,
      // 			tsKey: item.tsKey,
      // 			field: item.value,
      // 			relationTableTsKey: undefined,
      // 			isJson: false,
      // 			selection: [],
      // 		}));
      // 	}
      // 	if (isRoot) {
      // 		selection = [
      // 			...prepareSelectedColumns(),
      // 			...prepareSelectedExtras(),
      // 		];
      // 	}
      // 	if (hasUserDefinedWhere || orderBy.length > 0) {
      // 		tableFrom = new Subquery(
      // 			this.buildSelectQuery({
      // 				table: is(tableFrom, PgTable) ? aliasedTable(tableFrom, tableAlias) : tableFrom,
      // 				fields: {},
      // 				fieldsFlat: selectionForBuild.map(({ field }) => ({
      // 					path: [],
      // 					field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,
      // 				})),
      // 				joins,
      // 				distinct,
      // 			}),
      // 			{},
      // 			tableAlias,
      // 		);
      // 		selectionForBuild = selection.map((item) =>
      // 			is(item.field, SQL.Aliased)
      // 				? { ...item, field: sql`${sql.identifier(tableAlias)}.${sql.identifier(item.field.fieldAlias)}` }
      // 				: item
      // 		);
      // 		joins = [];
      // 		distinct = undefined;
      // 	}
      // 	const result = this.buildSelectQuery({
      // 		table: is(tableFrom, PgTable) ? aliasedTable(tableFrom, tableAlias) : tableFrom,
      // 		fields: {},
      // 		fieldsFlat: selectionForBuild.map(({ field }) => ({
      // 			path: [],
      // 			field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,
      // 		})),
      // 		where,
      // 		limit,
      // 		offset,
      // 		joins,
      // 		orderBy,
      // 		distinct,
      // 	});
      // 	return {
      // 		tableTsKey: tableConfig.tsName,
      // 		sql: result,
      // 		selection,
      // 	};
      // }
      buildRelationalQueryWithoutPK({
        fullSchema,
        schema,
        tableNamesMap,
        table,
        tableConfig,
        queryConfig: config2,
        tableAlias,
        nestedQueryRelation,
        joinOn
      }) {
        let selection = [];
        let limit, offset, orderBy = [], where;
        const joins = [];
        if (config2 === true) {
          const selectionEntries = Object.entries(tableConfig.columns);
          selection = selectionEntries.map(([key, value]) => ({
            dbKey: value.name,
            tsKey: key,
            field: aliasedTableColumn(value, tableAlias),
            relationTableTsKey: void 0,
            isJson: false,
            selection: []
          }));
        } else {
          const aliasedColumns = Object.fromEntries(
            Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)])
          );
          if (config2.where) {
            const whereSql = typeof config2.where === "function" ? config2.where(aliasedColumns, getOperators()) : config2.where;
            where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
          }
          const fieldsSelection = [];
          let selectedColumns = [];
          if (config2.columns) {
            let isIncludeMode = false;
            for (const [field, value] of Object.entries(config2.columns)) {
              if (value === void 0) {
                continue;
              }
              if (field in tableConfig.columns) {
                if (!isIncludeMode && value === true) {
                  isIncludeMode = true;
                }
                selectedColumns.push(field);
              }
            }
            if (selectedColumns.length > 0) {
              selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config2.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
            }
          } else {
            selectedColumns = Object.keys(tableConfig.columns);
          }
          for (const field of selectedColumns) {
            const column = tableConfig.columns[field];
            fieldsSelection.push({ tsKey: field, value: column });
          }
          let selectedRelations = [];
          if (config2.with) {
            selectedRelations = Object.entries(config2.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] }));
          }
          let extras;
          if (config2.extras) {
            extras = typeof config2.extras === "function" ? config2.extras(aliasedColumns, { sql }) : config2.extras;
            for (const [tsKey, value] of Object.entries(extras)) {
              fieldsSelection.push({
                tsKey,
                value: mapColumnsInAliasedSQLToAlias(value, tableAlias)
              });
            }
          }
          for (const { tsKey, value } of fieldsSelection) {
            selection.push({
              dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name,
              tsKey,
              field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value,
              relationTableTsKey: void 0,
              isJson: false,
              selection: []
            });
          }
          let orderByOrig = typeof config2.orderBy === "function" ? config2.orderBy(aliasedColumns, getOrderByOperators()) : config2.orderBy ?? [];
          if (!Array.isArray(orderByOrig)) {
            orderByOrig = [orderByOrig];
          }
          orderBy = orderByOrig.map((orderByValue) => {
            if (is(orderByValue, Column)) {
              return aliasedTableColumn(orderByValue, tableAlias);
            }
            return mapColumnsInSQLToAlias(orderByValue, tableAlias);
          });
          limit = config2.limit;
          offset = config2.offset;
          for (const {
            tsKey: selectedRelationTsKey,
            queryConfig: selectedRelationConfigValue,
            relation
          } of selectedRelations) {
            const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
            const relationTableName = getTableUniqueName(relation.referencedTable);
            const relationTableTsName = tableNamesMap[relationTableName];
            const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
            const joinOn2 = and(
              ...normalizedRelation.fields.map(
                (field2, i) => eq(
                  aliasedTableColumn(normalizedRelation.references[i], relationTableAlias),
                  aliasedTableColumn(field2, tableAlias)
                )
              )
            );
            const builtRelation = this.buildRelationalQueryWithoutPK({
              fullSchema,
              schema,
              tableNamesMap,
              table: fullSchema[relationTableTsName],
              tableConfig: schema[relationTableTsName],
              queryConfig: is(relation, One) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue,
              tableAlias: relationTableAlias,
              joinOn: joinOn2,
              nestedQueryRelation: relation
            });
            const field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier("data")}`.as(selectedRelationTsKey);
            joins.push({
              on: sql`true`,
              table: new Subquery(builtRelation.sql, {}, relationTableAlias),
              alias: relationTableAlias,
              joinType: "left",
              lateral: true
            });
            selection.push({
              dbKey: selectedRelationTsKey,
              tsKey: selectedRelationTsKey,
              field,
              relationTableTsKey: relationTableTsName,
              isJson: true,
              selection: builtRelation.selection
            });
          }
        }
        if (selection.length === 0) {
          throw new DrizzleError({ message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")` });
        }
        let result;
        where = and(joinOn, where);
        if (nestedQueryRelation) {
          let field = sql`json_build_array(${sql.join(
            selection.map(
              ({ field: field2, tsKey, isJson }) => isJson ? sql`${sql.identifier(`${tableAlias}_${tsKey}`)}.${sql.identifier("data")}` : is(field2, SQL.Aliased) ? field2.sql : field2
            ),
            sql`, `
          )})`;
          if (is(nestedQueryRelation, Many)) {
            field = sql`coalesce(json_agg(${field}${orderBy.length > 0 ? sql` order by ${sql.join(orderBy, sql`, `)}` : void 0}), '[]'::json)`;
          }
          const nestedSelection = [{
            dbKey: "data",
            tsKey: "data",
            field: field.as("data"),
            isJson: true,
            relationTableTsKey: tableConfig.tsName,
            selection
          }];
          const needsSubquery = limit !== void 0 || offset !== void 0 || orderBy.length > 0;
          if (needsSubquery) {
            result = this.buildSelectQuery({
              table: aliasedTable(table, tableAlias),
              fields: {},
              fieldsFlat: [{
                path: [],
                field: sql.raw("*")
              }],
              where,
              limit,
              offset,
              orderBy,
              setOperators: []
            });
            where = void 0;
            limit = void 0;
            offset = void 0;
            orderBy = [];
          } else {
            result = aliasedTable(table, tableAlias);
          }
          result = this.buildSelectQuery({
            table: is(result, PgTable) ? result : new Subquery(result, {}, tableAlias),
            fields: {},
            fieldsFlat: nestedSelection.map(({ field: field2 }) => ({
              path: [],
              field: is(field2, Column) ? aliasedTableColumn(field2, tableAlias) : field2
            })),
            joins,
            where,
            limit,
            offset,
            orderBy,
            setOperators: []
          });
        } else {
          result = this.buildSelectQuery({
            table: aliasedTable(table, tableAlias),
            fields: {},
            fieldsFlat: selection.map(({ field }) => ({
              path: [],
              field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field
            })),
            joins,
            where,
            limit,
            offset,
            orderBy,
            setOperators: []
          });
        }
        return {
          tableTsKey: tableConfig.tsName,
          sql: result,
          selection
        };
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/query-builders/query-builder.js
var TypedQueryBuilder;
var init_query_builder = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/query-builders/query-builder.js"() {
    init_entity();
    TypedQueryBuilder = class {
      static [entityKind] = "TypedQueryBuilder";
      /** @internal */
      getSelectedFields() {
        return this._.selectedFields;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/select.js
function createSetOperator(type, isAll) {
  return (leftSelect, rightSelect, ...restSelects) => {
    const setOperators = [rightSelect, ...restSelects].map((select) => ({
      type,
      isAll,
      rightSelect: select
    }));
    for (const setOperator of setOperators) {
      if (!haveSameKeys(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) {
        throw new Error(
          "Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
        );
      }
    }
    return leftSelect.addSetOperators(setOperators);
  };
}
var PgSelectBuilder, PgSelectQueryBuilderBase, PgSelectBase, getPgSetOperators, union, unionAll, intersect, intersectAll, except, exceptAll;
var init_select2 = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/select.js"() {
    init_entity();
    init_view_base();
    init_query_builder();
    init_query_promise();
    init_selection_proxy();
    init_sql();
    init_subquery();
    init_table();
    init_tracing();
    init_utils();
    init_utils();
    init_view_common();
    init_utils3();
    PgSelectBuilder = class {
      static [entityKind] = "PgSelectBuilder";
      fields;
      session;
      dialect;
      withList = [];
      distinct;
      constructor(config2) {
        this.fields = config2.fields;
        this.session = config2.session;
        this.dialect = config2.dialect;
        if (config2.withList) {
          this.withList = config2.withList;
        }
        this.distinct = config2.distinct;
      }
      authToken;
      /** @internal */
      setToken(token) {
        this.authToken = token;
        return this;
      }
      /**
       * Specify the table, subquery, or other target that you're
       * building a select query against.
       *
       * {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FROM | Postgres from documentation}
       */
      from(source) {
        const isPartialSelect = !!this.fields;
        const src = source;
        let fields;
        if (this.fields) {
          fields = this.fields;
        } else if (is(src, Subquery)) {
          fields = Object.fromEntries(
            Object.keys(src._.selectedFields).map((key) => [key, src[key]])
          );
        } else if (is(src, PgViewBase)) {
          fields = src[ViewBaseConfig].selectedFields;
        } else if (is(src, SQL)) {
          fields = {};
        } else {
          fields = getTableColumns(src);
        }
        return new PgSelectBase({
          table: src,
          fields,
          isPartialSelect,
          session: this.session,
          dialect: this.dialect,
          withList: this.withList,
          distinct: this.distinct
        }).setToken(this.authToken);
      }
    };
    PgSelectQueryBuilderBase = class extends TypedQueryBuilder {
      static [entityKind] = "PgSelectQueryBuilder";
      _;
      config;
      joinsNotNullableMap;
      tableName;
      isPartialSelect;
      session;
      dialect;
      cacheConfig = void 0;
      usedTables = /* @__PURE__ */ new Set();
      constructor({ table, fields, isPartialSelect, session, dialect, withList, distinct }) {
        super();
        this.config = {
          withList,
          table,
          fields: { ...fields },
          distinct,
          setOperators: []
        };
        this.isPartialSelect = isPartialSelect;
        this.session = session;
        this.dialect = dialect;
        this._ = {
          selectedFields: fields,
          config: this.config
        };
        this.tableName = getTableLikeName(table);
        this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
        for (const item of extractUsedTable(table)) this.usedTables.add(item);
      }
      /** @internal */
      getUsedTables() {
        return [...this.usedTables];
      }
      createJoin(joinType, lateral) {
        return (table, on) => {
          const baseTableName = this.tableName;
          const tableName = getTableLikeName(table);
          for (const item of extractUsedTable(table)) this.usedTables.add(item);
          if (typeof tableName === "string" && this.config.joins?.some((join) => join.alias === tableName)) {
            throw new Error(`Alias "${tableName}" is already used in this query`);
          }
          if (!this.isPartialSelect) {
            if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") {
              this.config.fields = {
                [baseTableName]: this.config.fields
              };
            }
            if (typeof tableName === "string" && !is(table, SQL)) {
              const selection = is(table, Subquery) ? table._.selectedFields : is(table, View) ? table[ViewBaseConfig].selectedFields : table[Table.Symbol.Columns];
              this.config.fields[tableName] = selection;
            }
          }
          if (typeof on === "function") {
            on = on(
              new Proxy(
                this.config.fields,
                new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
              )
            );
          }
          if (!this.config.joins) {
            this.config.joins = [];
          }
          this.config.joins.push({ on, table, joinType, alias: tableName, lateral });
          if (typeof tableName === "string") {
            switch (joinType) {
              case "left": {
                this.joinsNotNullableMap[tableName] = false;
                break;
              }
              case "right": {
                this.joinsNotNullableMap = Object.fromEntries(
                  Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
                );
                this.joinsNotNullableMap[tableName] = true;
                break;
              }
              case "cross":
              case "inner": {
                this.joinsNotNullableMap[tableName] = true;
                break;
              }
              case "full": {
                this.joinsNotNullableMap = Object.fromEntries(
                  Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
                );
                this.joinsNotNullableMap[tableName] = false;
                break;
              }
            }
          }
          return this;
        };
      }
      /**
       * Executes a `left join` operation by adding another table to the current query.
       *
       * Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.
       *
       * See docs: {@link https://orm.drizzle.team/docs/joins#left-join}
       *
       * @param table the table to join.
       * @param on the `on` clause.
       *
       * @example
       *
       * ```ts
       * // Select all users and their pets
       * const usersWithPets: { user: User; pets: Pet | null; }[] = await db.select()
       *   .from(users)
       *   .leftJoin(pets, eq(users.id, pets.ownerId))
       *
       * // Select userId and petId
       * const usersIdsAndPetIds: { userId: number; petId: number | null; }[] = await db.select({
       *   userId: users.id,
       *   petId: pets.id,
       * })
       *   .from(users)
       *   .leftJoin(pets, eq(users.id, pets.ownerId))
       * ```
       */
      leftJoin = this.createJoin("left", false);
      /**
       * Executes a `left join lateral` operation by adding subquery to the current query.
       *
       * A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
       *
       * Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.
       *
       * See docs: {@link https://orm.drizzle.team/docs/joins#left-join-lateral}
       *
       * @param table the subquery to join.
       * @param on the `on` clause.
       */
      leftJoinLateral = this.createJoin("left", true);
      /**
       * Executes a `right join` operation by adding another table to the current query.
       *
       * Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null.
       *
       * See docs: {@link https://orm.drizzle.team/docs/joins#right-join}
       *
       * @param table the table to join.
       * @param on the `on` clause.
       *
       * @example
       *
       * ```ts
       * // Select all users and their pets
       * const usersWithPets: { user: User | null; pets: Pet; }[] = await db.select()
       *   .from(users)
       *   .rightJoin(pets, eq(users.id, pets.ownerId))
       *
       * // Select userId and petId
       * const usersIdsAndPetIds: { userId: number | null; petId: number; }[] = await db.select({
       *   userId: users.id,
       *   petId: pets.id,
       * })
       *   .from(users)
       *   .rightJoin(pets, eq(users.id, pets.ownerId))
       * ```
       */
      rightJoin = this.createJoin("right", false);
      /**
       * Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values.
       *
       * Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
       *
       * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join}
       *
       * @param table the table to join.
       * @param on the `on` clause.
       *
       * @example
       *
       * ```ts
       * // Select all users and their pets
       * const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
       *   .from(users)
       *   .innerJoin(pets, eq(users.id, pets.ownerId))
       *
       * // Select userId and petId
       * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
       *   userId: users.id,
       *   petId: pets.id,
       * })
       *   .from(users)
       *   .innerJoin(pets, eq(users.id, pets.ownerId))
       * ```
       */
      innerJoin = this.createJoin("inner", false);
      /**
       * Executes an `inner join lateral` operation, creating a new table by combining rows from two queries that have matching values.
       *
       * A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
       *
       * Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
       *
       * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join-lateral}
       *
       * @param table the subquery to join.
       * @param on the `on` clause.
       */
      innerJoinLateral = this.createJoin("inner", true);
      /**
       * Executes a `full join` operation by combining rows from two tables into a new table.
       *
       * Calling this method retrieves all rows from both main and joined tables, merging rows with matching values and filling in `null` for non-matching columns.
       *
       * See docs: {@link https://orm.drizzle.team/docs/joins#full-join}
       *
       * @param table the table to join.
       * @param on the `on` clause.
       *
       * @example
       *
       * ```ts
       * // Select all users and their pets
       * const usersWithPets: { user: User | null; pets: Pet | null; }[] = await db.select()
       *   .from(users)
       *   .fullJoin(pets, eq(users.id, pets.ownerId))
       *
       * // Select userId and petId
       * const usersIdsAndPetIds: { userId: number | null; petId: number | null; }[] = await db.select({
       *   userId: users.id,
       *   petId: pets.id,
       * })
       *   .from(users)
       *   .fullJoin(pets, eq(users.id, pets.ownerId))
       * ```
       */
      fullJoin = this.createJoin("full", false);
      /**
       * Executes a `cross join` operation by combining rows from two tables into a new table.
       *
       * Calling this method retrieves all rows from both main and joined tables, merging all rows from each table.
       *
       * See docs: {@link https://orm.drizzle.team/docs/joins#cross-join}
       *
       * @param table the table to join.
       *
       * @example
       *
       * ```ts
       * // Select all users, each user with every pet
       * const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
       *   .from(users)
       *   .crossJoin(pets)
       *
       * // Select userId and petId
       * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
       *   userId: users.id,
       *   petId: pets.id,
       * })
       *   .from(users)
       *   .crossJoin(pets)
       * ```
       */
      crossJoin = this.createJoin("cross", false);
      /**
       * Executes a `cross join lateral` operation by combining rows from two queries into a new table.
       *
       * A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
       *
       * Calling this method retrieves all rows from both main and joined queries, merging all rows from each query.
       *
       * See docs: {@link https://orm.drizzle.team/docs/joins#cross-join-lateral}
       *
       * @param table the query to join.
       */
      crossJoinLateral = this.createJoin("cross", true);
      createSetOperator(type, isAll) {
        return (rightSelection) => {
          const rightSelect = typeof rightSelection === "function" ? rightSelection(getPgSetOperators()) : rightSelection;
          if (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) {
            throw new Error(
              "Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
            );
          }
          this.config.setOperators.push({ type, isAll, rightSelect });
          return this;
        };
      }
      /**
       * Adds `union` set operator to the query.
       *
       * Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.
       *
       * See docs: {@link https://orm.drizzle.team/docs/set-operations#union}
       *
       * @example
       *
       * ```ts
       * // Select all unique names from customers and users tables
       * await db.select({ name: users.name })
       *   .from(users)
       *   .union(
       *     db.select({ name: customers.name }).from(customers)
       *   );
       * // or
       * import { union } from 'drizzle-orm/pg-core'
       *
       * await union(
       *   db.select({ name: users.name }).from(users),
       *   db.select({ name: customers.name }).from(customers)
       * );
       * ```
       */
      union = this.createSetOperator("union", false);
      /**
       * Adds `union all` set operator to the query.
       *
       * Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.
       *
       * See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}
       *
       * @example
       *
       * ```ts
       * // Select all transaction ids from both online and in-store sales
       * await db.select({ transaction: onlineSales.transactionId })
       *   .from(onlineSales)
       *   .unionAll(
       *     db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
       *   );
       * // or
       * import { unionAll } from 'drizzle-orm/pg-core'
       *
       * await unionAll(
       *   db.select({ transaction: onlineSales.transactionId }).from(onlineSales),
       *   db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
       * );
       * ```
       */
      unionAll = this.createSetOperator("union", true);
      /**
       * Adds `intersect` set operator to the query.
       *
       * Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.
       *
       * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}
       *
       * @example
       *
       * ```ts
       * // Select course names that are offered in both departments A and B
       * await db.select({ courseName: depA.courseName })
       *   .from(depA)
       *   .intersect(
       *     db.select({ courseName: depB.courseName }).from(depB)
       *   );
       * // or
       * import { intersect } from 'drizzle-orm/pg-core'
       *
       * await intersect(
       *   db.select({ courseName: depA.courseName }).from(depA),
       *   db.select({ courseName: depB.courseName }).from(depB)
       * );
       * ```
       */
      intersect = this.createSetOperator("intersect", false);
      /**
       * Adds `intersect all` set operator to the query.
       *
       * Calling this method will retain only the rows that are present in both result sets including all duplicates.
       *
       * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect-all}
       *
       * @example
       *
       * ```ts
       * // Select all products and quantities that are ordered by both regular and VIP customers
       * await db.select({
       *   productId: regularCustomerOrders.productId,
       *   quantityOrdered: regularCustomerOrders.quantityOrdered
       * })
       * .from(regularCustomerOrders)
       * .intersectAll(
       *   db.select({
       *     productId: vipCustomerOrders.productId,
       *     quantityOrdered: vipCustomerOrders.quantityOrdered
       *   })
       *   .from(vipCustomerOrders)
       * );
       * // or
       * import { intersectAll } from 'drizzle-orm/pg-core'
       *
       * await intersectAll(
       *   db.select({
       *     productId: regularCustomerOrders.productId,
       *     quantityOrdered: regularCustomerOrders.quantityOrdered
       *   })
       *   .from(regularCustomerOrders),
       *   db.select({
       *     productId: vipCustomerOrders.productId,
       *     quantityOrdered: vipCustomerOrders.quantityOrdered
       *   })
       *   .from(vipCustomerOrders)
       * );
       * ```
       */
      intersectAll = this.createSetOperator("intersect", true);
      /**
       * Adds `except` set operator to the query.
       *
       * Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query.
       *
       * See docs: {@link https://orm.drizzle.team/docs/set-operations#except}
       *
       * @example
       *
       * ```ts
       * // Select all courses offered in department A but not in department B
       * await db.select({ courseName: depA.courseName })
       *   .from(depA)
       *   .except(
       *     db.select({ courseName: depB.courseName }).from(depB)
       *   );
       * // or
       * import { except } from 'drizzle-orm/pg-core'
       *
       * await except(
       *   db.select({ courseName: depA.courseName }).from(depA),
       *   db.select({ courseName: depB.courseName }).from(depB)
       * );
       * ```
       */
      except = this.createSetOperator("except", false);
      /**
       * Adds `except all` set operator to the query.
       *
       * Calling this method will retrieve all rows from the left query, except for the rows that are present in the result set of the right query.
       *
       * See docs: {@link https://orm.drizzle.team/docs/set-operations#except-all}
       *
       * @example
       *
       * ```ts
       * // Select all products that are ordered by regular customers but not by VIP customers
       * await db.select({
       *   productId: regularCustomerOrders.productId,
       *   quantityOrdered: regularCustomerOrders.quantityOrdered,
       * })
       * .from(regularCustomerOrders)
       * .exceptAll(
       *   db.select({
       *     productId: vipCustomerOrders.productId,
       *     quantityOrdered: vipCustomerOrders.quantityOrdered,
       *   })
       *   .from(vipCustomerOrders)
       * );
       * // or
       * import { exceptAll } from 'drizzle-orm/pg-core'
       *
       * await exceptAll(
       *   db.select({
       *     productId: regularCustomerOrders.productId,
       *     quantityOrdered: regularCustomerOrders.quantityOrdered
       *   })
       *   .from(regularCustomerOrders),
       *   db.select({
       *     productId: vipCustomerOrders.productId,
       *     quantityOrdered: vipCustomerOrders.quantityOrdered
       *   })
       *   .from(vipCustomerOrders)
       * );
       * ```
       */
      exceptAll = this.createSetOperator("except", true);
      /** @internal */
      addSetOperators(setOperators) {
        this.config.setOperators.push(...setOperators);
        return this;
      }
      /**
       * Adds a `where` clause to the query.
       *
       * Calling this method will select only those rows that fulfill a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#filtering}
       *
       * @param where the `where` clause.
       *
       * @example
       * You can use conditional operators and `sql function` to filter the rows to be selected.
       *
       * ```ts
       * // Select all cars with green color
       * await db.select().from(cars).where(eq(cars.color, 'green'));
       * // or
       * await db.select().from(cars).where(sql`${cars.color} = 'green'`)
       * ```
       *
       * You can logically combine conditional operators with `and()` and `or()` operators:
       *
       * ```ts
       * // Select all BMW cars with a green color
       * await db.select().from(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
       *
       * // Select all cars with the green or blue color
       * await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
       * ```
       */
      where(where) {
        if (typeof where === "function") {
          where = where(
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
            )
          );
        }
        this.config.where = where;
        return this;
      }
      /**
       * Adds a `having` clause to the query.
       *
       * Calling this method will select only those rows that fulfill a specified condition. It is typically used with aggregate functions to filter the aggregated data based on a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#aggregations}
       *
       * @param having the `having` clause.
       *
       * @example
       *
       * ```ts
       * // Select all brands with more than one car
       * await db.select({
       * 	brand: cars.brand,
       * 	count: sql<number>`cast(count(${cars.id}) as int)`,
       * })
       *   .from(cars)
       *   .groupBy(cars.brand)
       *   .having(({ count }) => gt(count, 1));
       * ```
       */
      having(having) {
        if (typeof having === "function") {
          having = having(
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
            )
          );
        }
        this.config.having = having;
        return this;
      }
      groupBy(...columns) {
        if (typeof columns[0] === "function") {
          const groupBy = columns[0](
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
            )
          );
          this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];
        } else {
          this.config.groupBy = columns;
        }
        return this;
      }
      orderBy(...columns) {
        if (typeof columns[0] === "function") {
          const orderBy = columns[0](
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
            )
          );
          const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
          if (this.config.setOperators.length > 0) {
            this.config.setOperators.at(-1).orderBy = orderByArray;
          } else {
            this.config.orderBy = orderByArray;
          }
        } else {
          const orderByArray = columns;
          if (this.config.setOperators.length > 0) {
            this.config.setOperators.at(-1).orderBy = orderByArray;
          } else {
            this.config.orderBy = orderByArray;
          }
        }
        return this;
      }
      /**
       * Adds a `limit` clause to the query.
       *
       * Calling this method will set the maximum number of rows that will be returned by this query.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
       *
       * @param limit the `limit` clause.
       *
       * @example
       *
       * ```ts
       * // Get the first 10 people from this query.
       * await db.select().from(people).limit(10);
       * ```
       */
      limit(limit) {
        if (this.config.setOperators.length > 0) {
          this.config.setOperators.at(-1).limit = limit;
        } else {
          this.config.limit = limit;
        }
        return this;
      }
      /**
       * Adds an `offset` clause to the query.
       *
       * Calling this method will skip a number of rows when returning results from this query.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
       *
       * @param offset the `offset` clause.
       *
       * @example
       *
       * ```ts
       * // Get the 10th-20th people from this query.
       * await db.select().from(people).offset(10).limit(10);
       * ```
       */
      offset(offset) {
        if (this.config.setOperators.length > 0) {
          this.config.setOperators.at(-1).offset = offset;
        } else {
          this.config.offset = offset;
        }
        return this;
      }
      /**
       * Adds a `for` clause to the query.
       *
       * Calling this method will specify a lock strength for this query that controls how strictly it acquires exclusive access to the rows being queried.
       *
       * See docs: {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE}
       *
       * @param strength the lock strength.
       * @param config the lock configuration.
       */
      for(strength, config2 = {}) {
        this.config.lockingClause = { strength, config: config2 };
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildSelectQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      as(alias) {
        const usedTables = [];
        usedTables.push(...extractUsedTable(this.config.table));
        if (this.config.joins) {
          for (const it of this.config.joins) usedTables.push(...extractUsedTable(it.table));
        }
        return new Proxy(
          new Subquery(this.getSQL(), this.config.fields, alias, false, [...new Set(usedTables)]),
          new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
        );
      }
      /** @internal */
      getSelectedFields() {
        return new Proxy(
          this.config.fields,
          new SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
        );
      }
      $dynamic() {
        return this;
      }
      $withCache(config2) {
        this.cacheConfig = config2 === void 0 ? { config: {}, enable: true, autoInvalidate: true } : config2 === false ? { enable: false } : { enable: true, autoInvalidate: true, ...config2 };
        return this;
      }
    };
    PgSelectBase = class extends PgSelectQueryBuilderBase {
      static [entityKind] = "PgSelect";
      /** @internal */
      _prepare(name) {
        const { session, config: config2, dialect, joinsNotNullableMap, authToken, cacheConfig, usedTables } = this;
        if (!session) {
          throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");
        }
        const { fields } = config2;
        return tracer.startActiveSpan("drizzle.prepareQuery", () => {
          const fieldsList = orderSelectedFields(fields);
          const query = session.prepareQuery(dialect.sqlToQuery(this.getSQL()), fieldsList, name, true, void 0, {
            type: "select",
            tables: [...usedTables]
          }, cacheConfig);
          query.joinsNotNullableMap = joinsNotNullableMap;
          return query.setToken(authToken);
        });
      }
      /**
       * Create a prepared statement for this query. This allows
       * the database to remember this query for the given session
       * and call it by name, rather than specifying the full query.
       *
       * {@link https://www.postgresql.org/docs/current/sql-prepare.html | Postgres prepare documentation}
       */
      prepare(name) {
        return this._prepare(name);
      }
      authToken;
      /** @internal */
      setToken(token) {
        this.authToken = token;
        return this;
      }
      execute = (placeholderValues) => {
        return tracer.startActiveSpan("drizzle.operation", () => {
          return this._prepare().execute(placeholderValues, this.authToken);
        });
      };
    };
    applyMixins(PgSelectBase, [QueryPromise]);
    getPgSetOperators = () => ({
      union,
      unionAll,
      intersect,
      intersectAll,
      except,
      exceptAll
    });
    union = createSetOperator("union", false);
    unionAll = createSetOperator("union", true);
    intersect = createSetOperator("intersect", false);
    intersectAll = createSetOperator("intersect", true);
    except = createSetOperator("except", false);
    exceptAll = createSetOperator("except", true);
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/query-builder.js
var QueryBuilder;
var init_query_builder2 = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/query-builder.js"() {
    init_entity();
    init_dialect();
    init_selection_proxy();
    init_subquery();
    init_select2();
    QueryBuilder = class {
      static [entityKind] = "PgQueryBuilder";
      dialect;
      dialectConfig;
      constructor(dialect) {
        this.dialect = is(dialect, PgDialect) ? dialect : void 0;
        this.dialectConfig = is(dialect, PgDialect) ? void 0 : dialect;
      }
      $with = (alias, selection) => {
        const queryBuilder = this;
        const as = (qb) => {
          if (typeof qb === "function") {
            qb = qb(queryBuilder);
          }
          return new Proxy(
            new WithSubquery(
              qb.getSQL(),
              selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}),
              alias,
              true
            ),
            new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
          );
        };
        return { as };
      };
      with(...queries) {
        const self = this;
        function select(fields) {
          return new PgSelectBuilder({
            fields: fields ?? void 0,
            session: void 0,
            dialect: self.getDialect(),
            withList: queries
          });
        }
        function selectDistinct(fields) {
          return new PgSelectBuilder({
            fields: fields ?? void 0,
            session: void 0,
            dialect: self.getDialect(),
            distinct: true
          });
        }
        function selectDistinctOn(on, fields) {
          return new PgSelectBuilder({
            fields: fields ?? void 0,
            session: void 0,
            dialect: self.getDialect(),
            distinct: { on }
          });
        }
        return { select, selectDistinct, selectDistinctOn };
      }
      select(fields) {
        return new PgSelectBuilder({
          fields: fields ?? void 0,
          session: void 0,
          dialect: this.getDialect()
        });
      }
      selectDistinct(fields) {
        return new PgSelectBuilder({
          fields: fields ?? void 0,
          session: void 0,
          dialect: this.getDialect(),
          distinct: true
        });
      }
      selectDistinctOn(on, fields) {
        return new PgSelectBuilder({
          fields: fields ?? void 0,
          session: void 0,
          dialect: this.getDialect(),
          distinct: { on }
        });
      }
      // Lazy load dialect to avoid circular dependency
      getDialect() {
        if (!this.dialect) {
          this.dialect = new PgDialect(this.dialectConfig);
        }
        return this.dialect;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/view.js
function pgViewWithSchema(name, selection, schema) {
  if (selection) {
    return new ManualViewBuilder(name, selection, schema);
  }
  return new ViewBuilder(name, schema);
}
function pgMaterializedViewWithSchema(name, selection, schema) {
  if (selection) {
    return new ManualMaterializedViewBuilder(name, selection, schema);
  }
  return new MaterializedViewBuilder(name, schema);
}
var DefaultViewBuilderCore, ViewBuilder, ManualViewBuilder, MaterializedViewBuilderCore, MaterializedViewBuilder, ManualMaterializedViewBuilder, PgView, PgMaterializedViewConfig, PgMaterializedView;
var init_view = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/view.js"() {
    init_entity();
    init_selection_proxy();
    init_utils();
    init_query_builder2();
    init_table2();
    init_view_base();
    init_view_common2();
    DefaultViewBuilderCore = class {
      constructor(name, schema) {
        this.name = name;
        this.schema = schema;
      }
      static [entityKind] = "PgDefaultViewBuilderCore";
      config = {};
      with(config2) {
        this.config.with = config2;
        return this;
      }
    };
    ViewBuilder = class extends DefaultViewBuilderCore {
      static [entityKind] = "PgViewBuilder";
      as(qb) {
        if (typeof qb === "function") {
          qb = qb(new QueryBuilder());
        }
        const selectionProxy = new SelectionProxyHandler({
          alias: this.name,
          sqlBehavior: "error",
          sqlAliasedBehavior: "alias",
          replaceOriginalName: true
        });
        const aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy);
        return new Proxy(
          new PgView({
            pgConfig: this.config,
            config: {
              name: this.name,
              schema: this.schema,
              selectedFields: aliasedSelection,
              query: qb.getSQL().inlineParams()
            }
          }),
          selectionProxy
        );
      }
    };
    ManualViewBuilder = class extends DefaultViewBuilderCore {
      static [entityKind] = "PgManualViewBuilder";
      columns;
      constructor(name, columns, schema) {
        super(name, schema);
        this.columns = getTableColumns(pgTable(name, columns));
      }
      existing() {
        return new Proxy(
          new PgView({
            pgConfig: void 0,
            config: {
              name: this.name,
              schema: this.schema,
              selectedFields: this.columns,
              query: void 0
            }
          }),
          new SelectionProxyHandler({
            alias: this.name,
            sqlBehavior: "error",
            sqlAliasedBehavior: "alias",
            replaceOriginalName: true
          })
        );
      }
      as(query) {
        return new Proxy(
          new PgView({
            pgConfig: this.config,
            config: {
              name: this.name,
              schema: this.schema,
              selectedFields: this.columns,
              query: query.inlineParams()
            }
          }),
          new SelectionProxyHandler({
            alias: this.name,
            sqlBehavior: "error",
            sqlAliasedBehavior: "alias",
            replaceOriginalName: true
          })
        );
      }
    };
    MaterializedViewBuilderCore = class {
      constructor(name, schema) {
        this.name = name;
        this.schema = schema;
      }
      static [entityKind] = "PgMaterializedViewBuilderCore";
      config = {};
      using(using) {
        this.config.using = using;
        return this;
      }
      with(config2) {
        this.config.with = config2;
        return this;
      }
      tablespace(tablespace) {
        this.config.tablespace = tablespace;
        return this;
      }
      withNoData() {
        this.config.withNoData = true;
        return this;
      }
    };
    MaterializedViewBuilder = class extends MaterializedViewBuilderCore {
      static [entityKind] = "PgMaterializedViewBuilder";
      as(qb) {
        if (typeof qb === "function") {
          qb = qb(new QueryBuilder());
        }
        const selectionProxy = new SelectionProxyHandler({
          alias: this.name,
          sqlBehavior: "error",
          sqlAliasedBehavior: "alias",
          replaceOriginalName: true
        });
        const aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy);
        return new Proxy(
          new PgMaterializedView({
            pgConfig: {
              with: this.config.with,
              using: this.config.using,
              tablespace: this.config.tablespace,
              withNoData: this.config.withNoData
            },
            config: {
              name: this.name,
              schema: this.schema,
              selectedFields: aliasedSelection,
              query: qb.getSQL().inlineParams()
            }
          }),
          selectionProxy
        );
      }
    };
    ManualMaterializedViewBuilder = class extends MaterializedViewBuilderCore {
      static [entityKind] = "PgManualMaterializedViewBuilder";
      columns;
      constructor(name, columns, schema) {
        super(name, schema);
        this.columns = getTableColumns(pgTable(name, columns));
      }
      existing() {
        return new Proxy(
          new PgMaterializedView({
            pgConfig: {
              tablespace: this.config.tablespace,
              using: this.config.using,
              with: this.config.with,
              withNoData: this.config.withNoData
            },
            config: {
              name: this.name,
              schema: this.schema,
              selectedFields: this.columns,
              query: void 0
            }
          }),
          new SelectionProxyHandler({
            alias: this.name,
            sqlBehavior: "error",
            sqlAliasedBehavior: "alias",
            replaceOriginalName: true
          })
        );
      }
      as(query) {
        return new Proxy(
          new PgMaterializedView({
            pgConfig: {
              tablespace: this.config.tablespace,
              using: this.config.using,
              with: this.config.with,
              withNoData: this.config.withNoData
            },
            config: {
              name: this.name,
              schema: this.schema,
              selectedFields: this.columns,
              query: query.inlineParams()
            }
          }),
          new SelectionProxyHandler({
            alias: this.name,
            sqlBehavior: "error",
            sqlAliasedBehavior: "alias",
            replaceOriginalName: true
          })
        );
      }
    };
    PgView = class extends PgViewBase {
      static [entityKind] = "PgView";
      [PgViewConfig];
      constructor({ pgConfig, config: config2 }) {
        super(config2);
        if (pgConfig) {
          this[PgViewConfig] = {
            with: pgConfig.with
          };
        }
      }
    };
    PgMaterializedViewConfig = /* @__PURE__ */ Symbol.for("drizzle:PgMaterializedViewConfig");
    PgMaterializedView = class extends PgViewBase {
      static [entityKind] = "PgMaterializedView";
      [PgMaterializedViewConfig];
      constructor({ pgConfig, config: config2 }) {
        super(config2);
        this[PgMaterializedViewConfig] = {
          with: pgConfig?.with,
          using: pgConfig?.using,
          tablespace: pgConfig?.tablespace,
          withNoData: pgConfig?.withNoData
        };
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/utils.js
function extractUsedTable(table) {
  if (is(table, PgTable)) {
    return [table[Schema] ? `${table[Schema]}.${table[Table.Symbol.BaseName]}` : table[Table.Symbol.BaseName]];
  }
  if (is(table, Subquery)) {
    return table._.usedTables ?? [];
  }
  if (is(table, SQL)) {
    return table.usedTables ?? [];
  }
  return [];
}
var init_utils3 = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/utils.js"() {
    init_entity();
    init_table2();
    init_sql();
    init_subquery();
    init_table();
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/delete.js
var PgDeleteBase;
var init_delete = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/delete.js"() {
    init_entity();
    init_query_promise();
    init_selection_proxy();
    init_table();
    init_tracing();
    init_utils();
    init_utils3();
    PgDeleteBase = class extends QueryPromise {
      constructor(table, session, dialect, withList) {
        super();
        this.session = session;
        this.dialect = dialect;
        this.config = { table, withList };
      }
      static [entityKind] = "PgDelete";
      config;
      cacheConfig;
      /**
       * Adds a `where` clause to the query.
       *
       * Calling this method will delete only those rows that fulfill a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/delete}
       *
       * @param where the `where` clause.
       *
       * @example
       * You can use conditional operators and `sql function` to filter the rows to be deleted.
       *
       * ```ts
       * // Delete all cars with green color
       * await db.delete(cars).where(eq(cars.color, 'green'));
       * // or
       * await db.delete(cars).where(sql`${cars.color} = 'green'`)
       * ```
       *
       * You can logically combine conditional operators with `and()` and `or()` operators:
       *
       * ```ts
       * // Delete all BMW cars with a green color
       * await db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
       *
       * // Delete all cars with the green or blue color
       * await db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
       * ```
       */
      where(where) {
        this.config.where = where;
        return this;
      }
      returning(fields = this.config.table[Table.Symbol.Columns]) {
        this.config.returningFields = fields;
        this.config.returning = orderSelectedFields(fields);
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildDeleteQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      /** @internal */
      _prepare(name) {
        return tracer.startActiveSpan("drizzle.prepareQuery", () => {
          return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true, void 0, {
            type: "delete",
            tables: extractUsedTable(this.config.table)
          }, this.cacheConfig);
        });
      }
      prepare(name) {
        return this._prepare(name);
      }
      authToken;
      /** @internal */
      setToken(token) {
        this.authToken = token;
        return this;
      }
      execute = (placeholderValues) => {
        return tracer.startActiveSpan("drizzle.operation", () => {
          return this._prepare().execute(placeholderValues, this.authToken);
        });
      };
      /** @internal */
      getSelectedFields() {
        return this.config.returningFields ? new Proxy(
          this.config.returningFields,
          new SelectionProxyHandler({
            alias: getTableName(this.config.table),
            sqlAliasedBehavior: "alias",
            sqlBehavior: "error"
          })
        ) : void 0;
      }
      $dynamic() {
        return this;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/insert.js
var PgInsertBuilder, PgInsertBase;
var init_insert = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/insert.js"() {
    init_entity();
    init_query_promise();
    init_selection_proxy();
    init_sql();
    init_table();
    init_tracing();
    init_utils();
    init_utils3();
    init_query_builder2();
    PgInsertBuilder = class {
      constructor(table, session, dialect, withList, overridingSystemValue_) {
        this.table = table;
        this.session = session;
        this.dialect = dialect;
        this.withList = withList;
        this.overridingSystemValue_ = overridingSystemValue_;
      }
      static [entityKind] = "PgInsertBuilder";
      authToken;
      /** @internal */
      setToken(token) {
        this.authToken = token;
        return this;
      }
      overridingSystemValue() {
        this.overridingSystemValue_ = true;
        return this;
      }
      values(values) {
        values = Array.isArray(values) ? values : [values];
        if (values.length === 0) {
          throw new Error("values() must be called with at least one value");
        }
        const mappedValues = values.map((entry) => {
          const result = {};
          const cols = this.table[Table.Symbol.Columns];
          for (const colKey of Object.keys(entry)) {
            const colValue = entry[colKey];
            result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);
          }
          return result;
        });
        return new PgInsertBase(
          this.table,
          mappedValues,
          this.session,
          this.dialect,
          this.withList,
          false,
          this.overridingSystemValue_
        ).setToken(this.authToken);
      }
      select(selectQuery) {
        const select = typeof selectQuery === "function" ? selectQuery(new QueryBuilder()) : selectQuery;
        if (!is(select, SQL) && !haveSameKeys(this.table[Columns], select._.selectedFields)) {
          throw new Error(
            "Insert select error: selected fields are not the same or are in a different order compared to the table definition"
          );
        }
        return new PgInsertBase(this.table, select, this.session, this.dialect, this.withList, true);
      }
    };
    PgInsertBase = class extends QueryPromise {
      constructor(table, values, session, dialect, withList, select, overridingSystemValue_) {
        super();
        this.session = session;
        this.dialect = dialect;
        this.config = { table, values, withList, select, overridingSystemValue_ };
      }
      static [entityKind] = "PgInsert";
      config;
      cacheConfig;
      returning(fields = this.config.table[Table.Symbol.Columns]) {
        this.config.returningFields = fields;
        this.config.returning = orderSelectedFields(fields);
        return this;
      }
      /**
       * Adds an `on conflict do nothing` clause to the query.
       *
       * Calling this method simply avoids inserting a row as its alternative action.
       *
       * See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing}
       *
       * @param config The `target` and `where` clauses.
       *
       * @example
       * ```ts
       * // Insert one row and cancel the insert if there's a conflict
       * await db.insert(cars)
       *   .values({ id: 1, brand: 'BMW' })
       *   .onConflictDoNothing();
       *
       * // Explicitly specify conflict target
       * await db.insert(cars)
       *   .values({ id: 1, brand: 'BMW' })
       *   .onConflictDoNothing({ target: cars.id });
       * ```
       */
      onConflictDoNothing(config2 = {}) {
        if (config2.target === void 0) {
          this.config.onConflict = sql`do nothing`;
        } else {
          let targetColumn = "";
          targetColumn = Array.isArray(config2.target) ? config2.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config2.target));
          const whereSql = config2.where ? sql` where ${config2.where}` : void 0;
          this.config.onConflict = sql`(${sql.raw(targetColumn)})${whereSql} do nothing`;
        }
        return this;
      }
      /**
       * Adds an `on conflict do update` clause to the query.
       *
       * Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action.
       *
       * See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts}
       *
       * @param config The `target`, `set` and `where` clauses.
       *
       * @example
       * ```ts
       * // Update the row if there's a conflict
       * await db.insert(cars)
       *   .values({ id: 1, brand: 'BMW' })
       *   .onConflictDoUpdate({
       *     target: cars.id,
       *     set: { brand: 'Porsche' }
       *   });
       *
       * // Upsert with 'where' clause
       * await db.insert(cars)
       *   .values({ id: 1, brand: 'BMW' })
       *   .onConflictDoUpdate({
       *     target: cars.id,
       *     set: { brand: 'newBMW' },
       *     targetWhere: sql`${cars.createdAt} > '2023-01-01'::date`,
       *   });
       * ```
       */
      onConflictDoUpdate(config2) {
        if (config2.where && (config2.targetWhere || config2.setWhere)) {
          throw new Error(
            'You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.'
          );
        }
        const whereSql = config2.where ? sql` where ${config2.where}` : void 0;
        const targetWhereSql = config2.targetWhere ? sql` where ${config2.targetWhere}` : void 0;
        const setWhereSql = config2.setWhere ? sql` where ${config2.setWhere}` : void 0;
        const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config2.set));
        let targetColumn = "";
        targetColumn = Array.isArray(config2.target) ? config2.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config2.target));
        this.config.onConflict = sql`(${sql.raw(targetColumn)})${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`;
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildInsertQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      /** @internal */
      _prepare(name) {
        return tracer.startActiveSpan("drizzle.prepareQuery", () => {
          return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true, void 0, {
            type: "insert",
            tables: extractUsedTable(this.config.table)
          }, this.cacheConfig);
        });
      }
      prepare(name) {
        return this._prepare(name);
      }
      authToken;
      /** @internal */
      setToken(token) {
        this.authToken = token;
        return this;
      }
      execute = (placeholderValues) => {
        return tracer.startActiveSpan("drizzle.operation", () => {
          return this._prepare().execute(placeholderValues, this.authToken);
        });
      };
      /** @internal */
      getSelectedFields() {
        return this.config.returningFields ? new Proxy(
          this.config.returningFields,
          new SelectionProxyHandler({
            alias: getTableName(this.config.table),
            sqlAliasedBehavior: "alias",
            sqlBehavior: "error"
          })
        ) : void 0;
      }
      $dynamic() {
        return this;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/refresh-materialized-view.js
var PgRefreshMaterializedView;
var init_refresh_materialized_view = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/refresh-materialized-view.js"() {
    init_entity();
    init_query_promise();
    init_tracing();
    PgRefreshMaterializedView = class extends QueryPromise {
      constructor(view, session, dialect) {
        super();
        this.session = session;
        this.dialect = dialect;
        this.config = { view };
      }
      static [entityKind] = "PgRefreshMaterializedView";
      config;
      concurrently() {
        if (this.config.withNoData !== void 0) {
          throw new Error("Cannot use concurrently and withNoData together");
        }
        this.config.concurrently = true;
        return this;
      }
      withNoData() {
        if (this.config.concurrently !== void 0) {
          throw new Error("Cannot use concurrently and withNoData together");
        }
        this.config.withNoData = true;
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildRefreshMaterializedViewQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      /** @internal */
      _prepare(name) {
        return tracer.startActiveSpan("drizzle.prepareQuery", () => {
          return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), void 0, name, true);
        });
      }
      prepare(name) {
        return this._prepare(name);
      }
      authToken;
      /** @internal */
      setToken(token) {
        this.authToken = token;
        return this;
      }
      execute = (placeholderValues) => {
        return tracer.startActiveSpan("drizzle.operation", () => {
          return this._prepare().execute(placeholderValues, this.authToken);
        });
      };
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/select.types.js
var init_select_types = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/select.types.js"() {
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/update.js
var PgUpdateBuilder, PgUpdateBase;
var init_update = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/update.js"() {
    init_entity();
    init_table2();
    init_query_promise();
    init_selection_proxy();
    init_sql();
    init_subquery();
    init_table();
    init_utils();
    init_view_common();
    init_utils3();
    PgUpdateBuilder = class {
      constructor(table, session, dialect, withList) {
        this.table = table;
        this.session = session;
        this.dialect = dialect;
        this.withList = withList;
      }
      static [entityKind] = "PgUpdateBuilder";
      authToken;
      setToken(token) {
        this.authToken = token;
        return this;
      }
      set(values) {
        return new PgUpdateBase(
          this.table,
          mapUpdateSet(this.table, values),
          this.session,
          this.dialect,
          this.withList
        ).setToken(this.authToken);
      }
    };
    PgUpdateBase = class extends QueryPromise {
      constructor(table, set2, session, dialect, withList) {
        super();
        this.session = session;
        this.dialect = dialect;
        this.config = { set: set2, table, withList, joins: [] };
        this.tableName = getTableLikeName(table);
        this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
      }
      static [entityKind] = "PgUpdate";
      config;
      tableName;
      joinsNotNullableMap;
      cacheConfig;
      from(source) {
        const src = source;
        const tableName = getTableLikeName(src);
        if (typeof tableName === "string") {
          this.joinsNotNullableMap[tableName] = true;
        }
        this.config.from = src;
        return this;
      }
      getTableLikeFields(table) {
        if (is(table, PgTable)) {
          return table[Table.Symbol.Columns];
        } else if (is(table, Subquery)) {
          return table._.selectedFields;
        }
        return table[ViewBaseConfig].selectedFields;
      }
      createJoin(joinType) {
        return (table, on) => {
          const tableName = getTableLikeName(table);
          if (typeof tableName === "string" && this.config.joins.some((join) => join.alias === tableName)) {
            throw new Error(`Alias "${tableName}" is already used in this query`);
          }
          if (typeof on === "function") {
            const from = this.config.from && !is(this.config.from, SQL) ? this.getTableLikeFields(this.config.from) : void 0;
            on = on(
              new Proxy(
                this.config.table[Table.Symbol.Columns],
                new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
              ),
              from && new Proxy(
                from,
                new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
              )
            );
          }
          this.config.joins.push({ on, table, joinType, alias: tableName });
          if (typeof tableName === "string") {
            switch (joinType) {
              case "left": {
                this.joinsNotNullableMap[tableName] = false;
                break;
              }
              case "right": {
                this.joinsNotNullableMap = Object.fromEntries(
                  Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
                );
                this.joinsNotNullableMap[tableName] = true;
                break;
              }
              case "inner": {
                this.joinsNotNullableMap[tableName] = true;
                break;
              }
              case "full": {
                this.joinsNotNullableMap = Object.fromEntries(
                  Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
                );
                this.joinsNotNullableMap[tableName] = false;
                break;
              }
            }
          }
          return this;
        };
      }
      leftJoin = this.createJoin("left");
      rightJoin = this.createJoin("right");
      innerJoin = this.createJoin("inner");
      fullJoin = this.createJoin("full");
      /**
       * Adds a 'where' clause to the query.
       *
       * Calling this method will update only those rows that fulfill a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/update}
       *
       * @param where the 'where' clause.
       *
       * @example
       * You can use conditional operators and `sql function` to filter the rows to be updated.
       *
       * ```ts
       * // Update all cars with green color
       * await db.update(cars).set({ color: 'red' })
       *   .where(eq(cars.color, 'green'));
       * // or
       * await db.update(cars).set({ color: 'red' })
       *   .where(sql`${cars.color} = 'green'`)
       * ```
       *
       * You can logically combine conditional operators with `and()` and `or()` operators:
       *
       * ```ts
       * // Update all BMW cars with a green color
       * await db.update(cars).set({ color: 'red' })
       *   .where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
       *
       * // Update all cars with the green or blue color
       * await db.update(cars).set({ color: 'red' })
       *   .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
       * ```
       */
      where(where) {
        this.config.where = where;
        return this;
      }
      returning(fields) {
        if (!fields) {
          fields = Object.assign({}, this.config.table[Table.Symbol.Columns]);
          if (this.config.from) {
            const tableName = getTableLikeName(this.config.from);
            if (typeof tableName === "string" && this.config.from && !is(this.config.from, SQL)) {
              const fromFields = this.getTableLikeFields(this.config.from);
              fields[tableName] = fromFields;
            }
            for (const join of this.config.joins) {
              const tableName2 = getTableLikeName(join.table);
              if (typeof tableName2 === "string" && !is(join.table, SQL)) {
                const fromFields = this.getTableLikeFields(join.table);
                fields[tableName2] = fromFields;
              }
            }
          }
        }
        this.config.returningFields = fields;
        this.config.returning = orderSelectedFields(fields);
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildUpdateQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      /** @internal */
      _prepare(name) {
        const query = this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true, void 0, {
          type: "insert",
          tables: extractUsedTable(this.config.table)
        }, this.cacheConfig);
        query.joinsNotNullableMap = this.joinsNotNullableMap;
        return query;
      }
      prepare(name) {
        return this._prepare(name);
      }
      authToken;
      /** @internal */
      setToken(token) {
        this.authToken = token;
        return this;
      }
      execute = (placeholderValues) => {
        return this._prepare().execute(placeholderValues, this.authToken);
      };
      /** @internal */
      getSelectedFields() {
        return this.config.returningFields ? new Proxy(
          this.config.returningFields,
          new SelectionProxyHandler({
            alias: getTableName(this.config.table),
            sqlAliasedBehavior: "alias",
            sqlBehavior: "error"
          })
        ) : void 0;
      }
      $dynamic() {
        return this;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/index.js
var init_query_builders = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/index.js"() {
    init_delete();
    init_insert();
    init_query_builder2();
    init_refresh_materialized_view();
    init_select2();
    init_select_types();
    init_update();
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/count.js
var PgCountBuilder;
var init_count = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/count.js"() {
    init_entity();
    init_sql();
    PgCountBuilder = class _PgCountBuilder extends SQL {
      constructor(params) {
        super(_PgCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
        this.params = params;
        this.mapWith(Number);
        this.session = params.session;
        this.sql = _PgCountBuilder.buildCount(
          params.source,
          params.filters
        );
      }
      sql;
      token;
      static [entityKind] = "PgCountBuilder";
      [Symbol.toStringTag] = "PgCountBuilder";
      session;
      static buildEmbeddedCount(source, filters) {
        return sql`(select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters})`;
      }
      static buildCount(source, filters) {
        return sql`select count(*) as count from ${source}${sql.raw(" where ").if(filters)}${filters};`;
      }
      /** @intrnal */
      setToken(token) {
        this.token = token;
        return this;
      }
      then(onfulfilled, onrejected) {
        return Promise.resolve(this.session.count(this.sql, this.token)).then(
          onfulfilled,
          onrejected
        );
      }
      catch(onRejected) {
        return this.then(void 0, onRejected);
      }
      finally(onFinally) {
        return this.then(
          (value) => {
            onFinally?.();
            return value;
          },
          (reason) => {
            onFinally?.();
            throw reason;
          }
        );
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/query.js
var RelationalQueryBuilder, PgRelationalQuery;
var init_query = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/query.js"() {
    init_entity();
    init_query_promise();
    init_relations();
    init_tracing();
    RelationalQueryBuilder = class {
      constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session) {
        this.fullSchema = fullSchema;
        this.schema = schema;
        this.tableNamesMap = tableNamesMap;
        this.table = table;
        this.tableConfig = tableConfig;
        this.dialect = dialect;
        this.session = session;
      }
      static [entityKind] = "PgRelationalQueryBuilder";
      findMany(config2) {
        return new PgRelationalQuery(
          this.fullSchema,
          this.schema,
          this.tableNamesMap,
          this.table,
          this.tableConfig,
          this.dialect,
          this.session,
          config2 ? config2 : {},
          "many"
        );
      }
      findFirst(config2) {
        return new PgRelationalQuery(
          this.fullSchema,
          this.schema,
          this.tableNamesMap,
          this.table,
          this.tableConfig,
          this.dialect,
          this.session,
          config2 ? { ...config2, limit: 1 } : { limit: 1 },
          "first"
        );
      }
    };
    PgRelationalQuery = class extends QueryPromise {
      constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session, config2, mode) {
        super();
        this.fullSchema = fullSchema;
        this.schema = schema;
        this.tableNamesMap = tableNamesMap;
        this.table = table;
        this.tableConfig = tableConfig;
        this.dialect = dialect;
        this.session = session;
        this.config = config2;
        this.mode = mode;
      }
      static [entityKind] = "PgRelationalQuery";
      /** @internal */
      _prepare(name) {
        return tracer.startActiveSpan("drizzle.prepareQuery", () => {
          const { query, builtQuery } = this._toSQL();
          return this.session.prepareQuery(
            builtQuery,
            void 0,
            name,
            true,
            (rawRows, mapColumnValue) => {
              const rows = rawRows.map(
                (row) => mapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue)
              );
              if (this.mode === "first") {
                return rows[0];
              }
              return rows;
            }
          );
        });
      }
      prepare(name) {
        return this._prepare(name);
      }
      _getQuery() {
        return this.dialect.buildRelationalQueryWithoutPK({
          fullSchema: this.fullSchema,
          schema: this.schema,
          tableNamesMap: this.tableNamesMap,
          table: this.table,
          tableConfig: this.tableConfig,
          queryConfig: this.config,
          tableAlias: this.tableConfig.tsName
        });
      }
      /** @internal */
      getSQL() {
        return this._getQuery().sql;
      }
      _toSQL() {
        const query = this._getQuery();
        const builtQuery = this.dialect.sqlToQuery(query.sql);
        return { query, builtQuery };
      }
      toSQL() {
        return this._toSQL().builtQuery;
      }
      authToken;
      /** @internal */
      setToken(token) {
        this.authToken = token;
        return this;
      }
      execute() {
        return tracer.startActiveSpan("drizzle.operation", () => {
          return this._prepare().execute(void 0, this.authToken);
        });
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/raw.js
var PgRaw;
var init_raw = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/raw.js"() {
    init_entity();
    init_query_promise();
    PgRaw = class extends QueryPromise {
      constructor(execute, sql2, query, mapBatchResult) {
        super();
        this.execute = execute;
        this.sql = sql2;
        this.query = query;
        this.mapBatchResult = mapBatchResult;
      }
      static [entityKind] = "PgRaw";
      /** @internal */
      getSQL() {
        return this.sql;
      }
      getQuery() {
        return this.query;
      }
      mapResult(result, isFromBatch) {
        return isFromBatch ? this.mapBatchResult(result) : result;
      }
      _prepare() {
        return this;
      }
      /** @internal */
      isResponseInArrayMode() {
        return false;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/db.js
var PgDatabase;
var init_db = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/db.js"() {
    init_entity();
    init_query_builders();
    init_selection_proxy();
    init_sql();
    init_subquery();
    init_count();
    init_query();
    init_raw();
    init_refresh_materialized_view();
    PgDatabase = class {
      constructor(dialect, session, schema) {
        this.dialect = dialect;
        this.session = session;
        this._ = schema ? {
          schema: schema.schema,
          fullSchema: schema.fullSchema,
          tableNamesMap: schema.tableNamesMap,
          session
        } : {
          schema: void 0,
          fullSchema: {},
          tableNamesMap: {},
          session
        };
        this.query = {};
        if (this._.schema) {
          for (const [tableName, columns] of Object.entries(this._.schema)) {
            this.query[tableName] = new RelationalQueryBuilder(
              schema.fullSchema,
              this._.schema,
              this._.tableNamesMap,
              schema.fullSchema[tableName],
              columns,
              dialect,
              session
            );
          }
        }
        this.$cache = { invalidate: async (_params) => {
        } };
      }
      static [entityKind] = "PgDatabase";
      query;
      /**
       * Creates a subquery that defines a temporary named result set as a CTE.
       *
       * It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
       *
       * @param alias The alias for the subquery.
       *
       * Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries.
       *
       * @example
       *
       * ```ts
       * // Create a subquery with alias 'sq' and use it in the select query
       * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
       *
       * const result = await db.with(sq).select().from(sq);
       * ```
       *
       * To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them:
       *
       * ```ts
       * // Select an arbitrary SQL value as a field in a CTE and reference it in the main query
       * const sq = db.$with('sq').as(db.select({
       *   name: sql<string>`upper(${users.name})`.as('name'),
       * })
       * .from(users));
       *
       * const result = await db.with(sq).select({ name: sq.name }).from(sq);
       * ```
       */
      $with = (alias, selection) => {
        const self = this;
        const as = (qb) => {
          if (typeof qb === "function") {
            qb = qb(new QueryBuilder(self.dialect));
          }
          return new Proxy(
            new WithSubquery(
              qb.getSQL(),
              selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}),
              alias,
              true
            ),
            new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
          );
        };
        return { as };
      };
      $count(source, filters) {
        return new PgCountBuilder({ source, filters, session: this.session });
      }
      $cache;
      /**
       * Incorporates a previously defined CTE (using `$with`) into the main query.
       *
       * This method allows the main query to reference a temporary named result set.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
       *
       * @param queries The CTEs to incorporate into the main query.
       *
       * @example
       *
       * ```ts
       * // Define a subquery 'sq' as a CTE using $with
       * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
       *
       * // Incorporate the CTE 'sq' into the main query and select from it
       * const result = await db.with(sq).select().from(sq);
       * ```
       */
      with(...queries) {
        const self = this;
        function select(fields) {
          return new PgSelectBuilder({
            fields: fields ?? void 0,
            session: self.session,
            dialect: self.dialect,
            withList: queries
          });
        }
        function selectDistinct(fields) {
          return new PgSelectBuilder({
            fields: fields ?? void 0,
            session: self.session,
            dialect: self.dialect,
            withList: queries,
            distinct: true
          });
        }
        function selectDistinctOn(on, fields) {
          return new PgSelectBuilder({
            fields: fields ?? void 0,
            session: self.session,
            dialect: self.dialect,
            withList: queries,
            distinct: { on }
          });
        }
        function update(table) {
          return new PgUpdateBuilder(table, self.session, self.dialect, queries);
        }
        function insert(table) {
          return new PgInsertBuilder(table, self.session, self.dialect, queries);
        }
        function delete_(table) {
          return new PgDeleteBase(table, self.session, self.dialect, queries);
        }
        return { select, selectDistinct, selectDistinctOn, update, insert, delete: delete_ };
      }
      select(fields) {
        return new PgSelectBuilder({
          fields: fields ?? void 0,
          session: this.session,
          dialect: this.dialect
        });
      }
      selectDistinct(fields) {
        return new PgSelectBuilder({
          fields: fields ?? void 0,
          session: this.session,
          dialect: this.dialect,
          distinct: true
        });
      }
      selectDistinctOn(on, fields) {
        return new PgSelectBuilder({
          fields: fields ?? void 0,
          session: this.session,
          dialect: this.dialect,
          distinct: { on }
        });
      }
      /**
       * Creates an update query.
       *
       * Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated.
       *
       * Use `.set()` method to specify which values to update.
       *
       * See docs: {@link https://orm.drizzle.team/docs/update}
       *
       * @param table The table to update.
       *
       * @example
       *
       * ```ts
       * // Update all rows in the 'cars' table
       * await db.update(cars).set({ color: 'red' });
       *
       * // Update rows with filters and conditions
       * await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW'));
       *
       * // Update with returning clause
       * const updatedCar: Car[] = await db.update(cars)
       *   .set({ color: 'red' })
       *   .where(eq(cars.id, 1))
       *   .returning();
       * ```
       */
      update(table) {
        return new PgUpdateBuilder(table, this.session, this.dialect);
      }
      /**
       * Creates an insert query.
       *
       * Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert.
       *
       * See docs: {@link https://orm.drizzle.team/docs/insert}
       *
       * @param table The table to insert into.
       *
       * @example
       *
       * ```ts
       * // Insert one row
       * await db.insert(cars).values({ brand: 'BMW' });
       *
       * // Insert multiple rows
       * await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]);
       *
       * // Insert with returning clause
       * const insertedCar: Car[] = await db.insert(cars)
       *   .values({ brand: 'BMW' })
       *   .returning();
       * ```
       */
      insert(table) {
        return new PgInsertBuilder(table, this.session, this.dialect);
      }
      /**
       * Creates a delete query.
       *
       * Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted.
       *
       * See docs: {@link https://orm.drizzle.team/docs/delete}
       *
       * @param table The table to delete from.
       *
       * @example
       *
       * ```ts
       * // Delete all rows in the 'cars' table
       * await db.delete(cars);
       *
       * // Delete rows with filters and conditions
       * await db.delete(cars).where(eq(cars.color, 'green'));
       *
       * // Delete with returning clause
       * const deletedCar: Car[] = await db.delete(cars)
       *   .where(eq(cars.id, 1))
       *   .returning();
       * ```
       */
      delete(table) {
        return new PgDeleteBase(table, this.session, this.dialect);
      }
      refreshMaterializedView(view) {
        return new PgRefreshMaterializedView(view, this.session, this.dialect);
      }
      authToken;
      execute(query) {
        const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
        const builtQuery = this.dialect.sqlToQuery(sequel);
        const prepared = this.session.prepareQuery(
          builtQuery,
          void 0,
          void 0,
          false
        );
        return new PgRaw(
          () => prepared.execute(void 0, this.authToken),
          sequel,
          builtQuery,
          (result) => prepared.mapResult(result, true)
        );
      }
      transaction(transaction, config2) {
        return this.session.transaction(transaction, config2);
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/cache/core/cache.js
async function hashQuery(sql2, params) {
  const dataToHash = `${sql2}-${JSON.stringify(params)}`;
  const encoder = new TextEncoder();
  const data = encoder.encode(dataToHash);
  const hashBuffer = await crypto.subtle.digest("SHA-256", data);
  const hashArray = [...new Uint8Array(hashBuffer)];
  const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
  return hashHex;
}
var Cache, NoopCache;
var init_cache = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/cache/core/cache.js"() {
    init_entity();
    Cache = class {
      static [entityKind] = "Cache";
    };
    NoopCache = class extends Cache {
      strategy() {
        return "all";
      }
      static [entityKind] = "NoopCache";
      async get(_key2) {
        return void 0;
      }
      async put(_hashedQuery, _response, _tables, _config) {
      }
      async onMutate(_params) {
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/cache/core/index.js
var init_core = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/cache/core/index.js"() {
    init_cache();
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/alias.js
var init_alias2 = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/alias.js"() {
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/roles.js
var PgRole;
var init_roles = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/roles.js"() {
    init_entity();
    PgRole = class {
      constructor(name, config2) {
        this.name = name;
        if (config2) {
          this.createDb = config2.createDb;
          this.createRole = config2.createRole;
          this.inherit = config2.inherit;
        }
      }
      static [entityKind] = "PgRole";
      /** @internal */
      _existing;
      /** @internal */
      createDb;
      /** @internal */
      createRole;
      /** @internal */
      inherit;
      existing() {
        this._existing = true;
        return this;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/sequence.js
function pgSequenceWithSchema(name, options, schema) {
  return new PgSequence(name, options, schema);
}
var PgSequence;
var init_sequence = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/sequence.js"() {
    init_entity();
    PgSequence = class {
      constructor(seqName, seqOptions, schema) {
        this.seqName = seqName;
        this.seqOptions = seqOptions;
        this.schema = schema;
      }
      static [entityKind] = "PgSequence";
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/schema.js
var PgSchema;
var init_schema = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/schema.js"() {
    init_entity();
    init_sql();
    init_enum();
    init_sequence();
    init_table2();
    init_view();
    PgSchema = class {
      constructor(schemaName) {
        this.schemaName = schemaName;
      }
      static [entityKind] = "PgSchema";
      table = (name, columns, extraConfig) => {
        return pgTableWithSchema(name, columns, extraConfig, this.schemaName);
      };
      view = (name, columns) => {
        return pgViewWithSchema(name, columns, this.schemaName);
      };
      materializedView = (name, columns) => {
        return pgMaterializedViewWithSchema(name, columns, this.schemaName);
      };
      enum(enumName, input) {
        return Array.isArray(input) ? pgEnumWithSchema(
          enumName,
          [...input],
          this.schemaName
        ) : pgEnumObjectWithSchema(enumName, input, this.schemaName);
      }
      sequence = (name, options) => {
        return pgSequenceWithSchema(name, options, this.schemaName);
      };
      getSQL() {
        return new SQL([sql.identifier(this.schemaName)]);
      }
      shouldOmitSQLParens() {
        return true;
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/session.js
var PgPreparedQuery, PgSession, PgTransaction;
var init_session = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/session.js"() {
    init_cache();
    init_entity();
    init_errors2();
    init_sql2();
    init_tracing();
    init_db();
    PgPreparedQuery = class {
      constructor(query, cache, queryMetadata, cacheConfig) {
        this.query = query;
        this.cache = cache;
        this.queryMetadata = queryMetadata;
        this.cacheConfig = cacheConfig;
        if (cache && cache.strategy() === "all" && cacheConfig === void 0) {
          this.cacheConfig = { enable: true, autoInvalidate: true };
        }
        if (!this.cacheConfig?.enable) {
          this.cacheConfig = void 0;
        }
      }
      authToken;
      getQuery() {
        return this.query;
      }
      mapResult(response, _isFromBatch) {
        return response;
      }
      /** @internal */
      setToken(token) {
        this.authToken = token;
        return this;
      }
      static [entityKind] = "PgPreparedQuery";
      /** @internal */
      joinsNotNullableMap;
      /** @internal */
      async queryWithCache(queryString, params, query) {
        if (this.cache === void 0 || is(this.cache, NoopCache) || this.queryMetadata === void 0) {
          try {
            return await query();
          } catch (e) {
            throw new DrizzleQueryError(queryString, params, e);
          }
        }
        if (this.cacheConfig && !this.cacheConfig.enable) {
          try {
            return await query();
          } catch (e) {
            throw new DrizzleQueryError(queryString, params, e);
          }
        }
        if ((this.queryMetadata.type === "insert" || this.queryMetadata.type === "update" || this.queryMetadata.type === "delete") && this.queryMetadata.tables.length > 0) {
          try {
            const [res] = await Promise.all([
              query(),
              this.cache.onMutate({ tables: this.queryMetadata.tables })
            ]);
            return res;
          } catch (e) {
            throw new DrizzleQueryError(queryString, params, e);
          }
        }
        if (!this.cacheConfig) {
          try {
            return await query();
          } catch (e) {
            throw new DrizzleQueryError(queryString, params, e);
          }
        }
        if (this.queryMetadata.type === "select") {
          const fromCache = await this.cache.get(
            this.cacheConfig.tag ?? await hashQuery(queryString, params),
            this.queryMetadata.tables,
            this.cacheConfig.tag !== void 0,
            this.cacheConfig.autoInvalidate
          );
          if (fromCache === void 0) {
            let result;
            try {
              result = await query();
            } catch (e) {
              throw new DrizzleQueryError(queryString, params, e);
            }
            await this.cache.put(
              this.cacheConfig.tag ?? await hashQuery(queryString, params),
              result,
              // make sure we send tables that were used in a query only if user wants to invalidate it on each write
              this.cacheConfig.autoInvalidate ? this.queryMetadata.tables : [],
              this.cacheConfig.tag !== void 0,
              this.cacheConfig.config
            );
            return result;
          }
          return fromCache;
        }
        try {
          return await query();
        } catch (e) {
          throw new DrizzleQueryError(queryString, params, e);
        }
      }
    };
    PgSession = class {
      constructor(dialect) {
        this.dialect = dialect;
      }
      static [entityKind] = "PgSession";
      /** @internal */
      execute(query, token) {
        return tracer.startActiveSpan("drizzle.operation", () => {
          const prepared = tracer.startActiveSpan("drizzle.prepareQuery", () => {
            return this.prepareQuery(
              this.dialect.sqlToQuery(query),
              void 0,
              void 0,
              false
            );
          });
          return prepared.setToken(token).execute(void 0, token);
        });
      }
      all(query) {
        return this.prepareQuery(
          this.dialect.sqlToQuery(query),
          void 0,
          void 0,
          false
        ).all();
      }
      /** @internal */
      async count(sql2, token) {
        const res = await this.execute(sql2, token);
        return Number(
          res[0]["count"]
        );
      }
    };
    PgTransaction = class extends PgDatabase {
      constructor(dialect, session, schema, nestedIndex = 0) {
        super(dialect, session, schema);
        this.schema = schema;
        this.nestedIndex = nestedIndex;
      }
      static [entityKind] = "PgTransaction";
      rollback() {
        throw new TransactionRollbackError();
      }
      /** @internal */
      getTransactionConfigSQL(config2) {
        const chunks = [];
        if (config2.isolationLevel) {
          chunks.push(`isolation level ${config2.isolationLevel}`);
        }
        if (config2.accessMode) {
          chunks.push(config2.accessMode);
        }
        if (typeof config2.deferrable === "boolean") {
          chunks.push(config2.deferrable ? "deferrable" : "not deferrable");
        }
        return sql.raw(chunks.join(" "));
      }
      setTransaction(config2) {
        return this.session.execute(sql`set transaction ${this.getTransactionConfigSQL(config2)}`);
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/subquery.js
var init_subquery2 = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/subquery.js"() {
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/utils/index.js
var init_utils4 = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/utils/index.js"() {
    init_array();
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/index.js
var init_pg_core = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/index.js"() {
    init_alias2();
    init_checks();
    init_columns();
    init_db();
    init_dialect();
    init_foreign_keys();
    init_indexes();
    init_policies();
    init_primary_keys();
    init_query_builders();
    init_roles();
    init_schema();
    init_sequence();
    init_session();
    init_subquery2();
    init_table2();
    init_unique_constraint();
    init_utils3();
    init_utils4();
    init_view_common2();
    init_view();
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/node-postgres/session.js
var Pool2, types2, NodePgPreparedQuery, NodePgSession, NodePgTransaction;
var init_session2 = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/node-postgres/session.js"() {
    init_esm();
    init_core();
    init_entity();
    init_logger2();
    init_pg_core();
    init_session();
    init_sql();
    init_tracing();
    init_utils();
    ({ Pool: Pool2, types: types2 } = esm_default);
    NodePgPreparedQuery = class extends PgPreparedQuery {
      constructor(client, queryString, params, logger2, cache, queryMetadata, cacheConfig, fields, name, _isResponseInArrayMode, customResultMapper) {
        super({ sql: queryString, params }, cache, queryMetadata, cacheConfig);
        this.client = client;
        this.queryString = queryString;
        this.params = params;
        this.logger = logger2;
        this.fields = fields;
        this._isResponseInArrayMode = _isResponseInArrayMode;
        this.customResultMapper = customResultMapper;
        this.rawQueryConfig = {
          name,
          text: queryString,
          types: {
            // @ts-ignore
            getTypeParser: (typeId, format) => {
              if (typeId === types2.builtins.TIMESTAMPTZ) {
                return (val) => val;
              }
              if (typeId === types2.builtins.TIMESTAMP) {
                return (val) => val;
              }
              if (typeId === types2.builtins.DATE) {
                return (val) => val;
              }
              if (typeId === types2.builtins.INTERVAL) {
                return (val) => val;
              }
              if (typeId === 1231) {
                return (val) => val;
              }
              if (typeId === 1115) {
                return (val) => val;
              }
              if (typeId === 1185) {
                return (val) => val;
              }
              if (typeId === 1187) {
                return (val) => val;
              }
              if (typeId === 1182) {
                return (val) => val;
              }
              return types2.getTypeParser(typeId, format);
            }
          }
        };
        this.queryConfig = {
          name,
          text: queryString,
          rowMode: "array",
          types: {
            // @ts-ignore
            getTypeParser: (typeId, format) => {
              if (typeId === types2.builtins.TIMESTAMPTZ) {
                return (val) => val;
              }
              if (typeId === types2.builtins.TIMESTAMP) {
                return (val) => val;
              }
              if (typeId === types2.builtins.DATE) {
                return (val) => val;
              }
              if (typeId === types2.builtins.INTERVAL) {
                return (val) => val;
              }
              if (typeId === 1231) {
                return (val) => val;
              }
              if (typeId === 1115) {
                return (val) => val;
              }
              if (typeId === 1185) {
                return (val) => val;
              }
              if (typeId === 1187) {
                return (val) => val;
              }
              if (typeId === 1182) {
                return (val) => val;
              }
              return types2.getTypeParser(typeId, format);
            }
          }
        };
      }
      static [entityKind] = "NodePgPreparedQuery";
      rawQueryConfig;
      queryConfig;
      async execute(placeholderValues = {}) {
        return tracer.startActiveSpan("drizzle.execute", async () => {
          const params = fillPlaceholders(this.params, placeholderValues);
          this.logger.logQuery(this.rawQueryConfig.text, params);
          const { fields, rawQueryConfig: rawQuery, client, queryConfig: query, joinsNotNullableMap, customResultMapper } = this;
          if (!fields && !customResultMapper) {
            return tracer.startActiveSpan("drizzle.driver.execute", async (span) => {
              span?.setAttributes({
                "drizzle.query.name": rawQuery.name,
                "drizzle.query.text": rawQuery.text,
                "drizzle.query.params": JSON.stringify(params)
              });
              return this.queryWithCache(rawQuery.text, params, async () => {
                return await client.query(rawQuery, params);
              });
            });
          }
          const result = await tracer.startActiveSpan("drizzle.driver.execute", (span) => {
            span?.setAttributes({
              "drizzle.query.name": query.name,
              "drizzle.query.text": query.text,
              "drizzle.query.params": JSON.stringify(params)
            });
            return this.queryWithCache(query.text, params, async () => {
              return await client.query(query, params);
            });
          });
          return tracer.startActiveSpan("drizzle.mapResponse", () => {
            return customResultMapper ? customResultMapper(result.rows) : result.rows.map((row) => mapResultRow(fields, row, joinsNotNullableMap));
          });
        });
      }
      all(placeholderValues = {}) {
        return tracer.startActiveSpan("drizzle.execute", () => {
          const params = fillPlaceholders(this.params, placeholderValues);
          this.logger.logQuery(this.rawQueryConfig.text, params);
          return tracer.startActiveSpan("drizzle.driver.execute", (span) => {
            span?.setAttributes({
              "drizzle.query.name": this.rawQueryConfig.name,
              "drizzle.query.text": this.rawQueryConfig.text,
              "drizzle.query.params": JSON.stringify(params)
            });
            return this.queryWithCache(this.rawQueryConfig.text, params, async () => {
              return this.client.query(this.rawQueryConfig, params);
            }).then((result) => result.rows);
          });
        });
      }
      /** @internal */
      isResponseInArrayMode() {
        return this._isResponseInArrayMode;
      }
    };
    NodePgSession = class _NodePgSession extends PgSession {
      constructor(client, dialect, schema, options = {}) {
        super(dialect);
        this.client = client;
        this.schema = schema;
        this.options = options;
        this.logger = options.logger ?? new NoopLogger();
        this.cache = options.cache ?? new NoopCache();
      }
      static [entityKind] = "NodePgSession";
      logger;
      cache;
      prepareQuery(query, fields, name, isResponseInArrayMode, customResultMapper, queryMetadata, cacheConfig) {
        return new NodePgPreparedQuery(
          this.client,
          query.sql,
          query.params,
          this.logger,
          this.cache,
          queryMetadata,
          cacheConfig,
          fields,
          name,
          isResponseInArrayMode,
          customResultMapper
        );
      }
      async transaction(transaction, config2) {
        const isPool = this.client instanceof Pool2 || Object.getPrototypeOf(this.client).constructor.name.includes("Pool");
        const session = isPool ? new _NodePgSession(await this.client.connect(), this.dialect, this.schema, this.options) : this;
        const tx = new NodePgTransaction(this.dialect, session, this.schema);
        await tx.execute(sql`begin${config2 ? sql` ${tx.getTransactionConfigSQL(config2)}` : void 0}`);
        try {
          const result = await transaction(tx);
          await tx.execute(sql`commit`);
          return result;
        } catch (error40) {
          await tx.execute(sql`rollback`);
          throw error40;
        } finally {
          if (isPool) session.client.release();
        }
      }
      async count(sql2) {
        const res = await this.execute(sql2);
        return Number(
          res["rows"][0]["count"]
        );
      }
    };
    NodePgTransaction = class _NodePgTransaction extends PgTransaction {
      static [entityKind] = "NodePgTransaction";
      async transaction(transaction) {
        const savepointName = `sp${this.nestedIndex + 1}`;
        const tx = new _NodePgTransaction(
          this.dialect,
          this.session,
          this.schema,
          this.nestedIndex + 1
        );
        await tx.execute(sql.raw(`savepoint ${savepointName}`));
        try {
          const result = await transaction(tx);
          await tx.execute(sql.raw(`release savepoint ${savepointName}`));
          return result;
        } catch (err) {
          await tx.execute(sql.raw(`rollback to savepoint ${savepointName}`));
          throw err;
        }
      }
    };
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/node-postgres/driver.js
function construct(client, config2 = {}) {
  const dialect = new PgDialect({ casing: config2.casing });
  let logger2;
  if (config2.logger === true) {
    logger2 = new DefaultLogger();
  } else if (config2.logger !== false) {
    logger2 = config2.logger;
  }
  let schema;
  if (config2.schema) {
    const tablesConfig = extractTablesRelationalConfig(
      config2.schema,
      createTableRelationsHelpers
    );
    schema = {
      fullSchema: config2.schema,
      schema: tablesConfig.tables,
      tableNamesMap: tablesConfig.tableNamesMap
    };
  }
  const driver = new NodePgDriver(client, dialect, { logger: logger2, cache: config2.cache });
  const session = driver.createSession(schema);
  const db2 = new NodePgDatabase(dialect, session, schema);
  db2.$client = client;
  db2.$cache = config2.cache;
  if (db2.$cache) {
    db2.$cache["invalidate"] = config2.cache?.onMutate;
  }
  return db2;
}
function drizzle(...params) {
  if (typeof params[0] === "string") {
    const instance = new esm_default.Pool({
      connectionString: params[0]
    });
    return construct(instance, params[1]);
  }
  if (isConfig(params[0])) {
    const { connection, client, ...drizzleConfig } = params[0];
    if (client) return construct(client, drizzleConfig);
    const instance = typeof connection === "string" ? new esm_default.Pool({
      connectionString: connection
    }) : new esm_default.Pool(connection);
    return construct(instance, drizzleConfig);
  }
  return construct(params[0], params[1]);
}
var NodePgDriver, NodePgDatabase;
var init_driver = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/node-postgres/driver.js"() {
    init_esm();
    init_entity();
    init_logger2();
    init_db();
    init_dialect();
    init_relations();
    init_utils();
    init_session2();
    NodePgDriver = class {
      constructor(client, dialect, options = {}) {
        this.client = client;
        this.dialect = dialect;
        this.options = options;
      }
      static [entityKind] = "NodePgDriver";
      createSession(schema) {
        return new NodePgSession(this.client, this.dialect, schema, {
          logger: this.options.logger,
          cache: this.options.cache
        });
      }
    };
    NodePgDatabase = class extends PgDatabase {
      static [entityKind] = "NodePgDatabase";
    };
    ((drizzle2) => {
      function mock(config2) {
        return construct({}, config2);
      }
      drizzle2.mock = mock;
    })(drizzle || (drizzle = {}));
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/node-postgres/index.js
var init_node_postgres = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/node-postgres/index.js"() {
    init_driver();
    init_session2();
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/operations.js
var init_operations = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/operations.js"() {
  }
});

// ../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/index.js
var init_drizzle_orm = __esm({
  "../../node_modules/.pnpm/drizzle-orm@0.45.2_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/index.js"() {
    init_alias();
    init_column_builder();
    init_column();
    init_entity();
    init_errors2();
    init_logger2();
    init_operations();
    init_query_promise();
    init_relations();
    init_sql2();
    init_subquery();
    init_table();
    init_utils();
    init_view_common();
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/core.js
// @__NO_SIDE_EFFECTS__
function $constructor(name, initializer3, params) {
  function init(inst, def) {
    var _a;
    Object.defineProperty(inst, "_zod", {
      value: inst._zod ?? {},
      enumerable: false
    });
    (_a = inst._zod).traits ?? (_a.traits = /* @__PURE__ */ new Set());
    inst._zod.traits.add(name);
    initializer3(inst, def);
    for (const k in _.prototype) {
      if (!(k in inst))
        Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) });
    }
    inst._zod.constr = _;
    inst._zod.def = def;
  }
  const Parent = params?.Parent ?? Object;
  class Definition extends Parent {
  }
  Object.defineProperty(Definition, "name", { value: name });
  function _(def) {
    var _a;
    const inst = params?.Parent ? new Definition() : this;
    init(inst, def);
    (_a = inst._zod).deferred ?? (_a.deferred = []);
    for (const fn of inst._zod.deferred) {
      fn();
    }
    return inst;
  }
  Object.defineProperty(_, "init", { value: init });
  Object.defineProperty(_, Symbol.hasInstance, {
    value: (inst) => {
      if (params?.Parent && inst instanceof params.Parent)
        return true;
      return inst?._zod?.traits?.has(name);
    }
  });
  Object.defineProperty(_, "name", { value: name });
  return _;
}
function config(newConfig) {
  if (newConfig)
    Object.assign(globalConfig, newConfig);
  return globalConfig;
}
var NEVER2, $brand, $ZodAsyncError, globalConfig;
var init_core2 = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/core.js"() {
    NEVER2 = Object.freeze({
      status: "aborted"
    });
    $brand = /* @__PURE__ */ Symbol("zod_brand");
    $ZodAsyncError = class extends Error {
      constructor() {
        super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
      }
    };
    globalConfig = {};
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/util.js
var util_exports = {};
__export(util_exports, {
  BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES,
  Class: () => Class,
  NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES,
  aborted: () => aborted,
  allowsEval: () => allowsEval,
  assert: () => assert,
  assertEqual: () => assertEqual,
  assertIs: () => assertIs,
  assertNever: () => assertNever,
  assertNotEqual: () => assertNotEqual,
  assignProp: () => assignProp,
  cached: () => cached,
  captureStackTrace: () => captureStackTrace,
  cleanEnum: () => cleanEnum,
  cleanRegex: () => cleanRegex,
  clone: () => clone,
  createTransparentProxy: () => createTransparentProxy,
  defineLazy: () => defineLazy,
  esc: () => esc,
  escapeRegex: () => escapeRegex,
  extend: () => extend,
  finalizeIssue: () => finalizeIssue,
  floatSafeRemainder: () => floatSafeRemainder2,
  getElementAtPath: () => getElementAtPath,
  getEnumValues: () => getEnumValues,
  getLengthableOrigin: () => getLengthableOrigin,
  getParsedType: () => getParsedType2,
  getSizableOrigin: () => getSizableOrigin,
  isObject: () => isObject,
  isPlainObject: () => isPlainObject,
  issue: () => issue,
  joinValues: () => joinValues,
  jsonStringifyReplacer: () => jsonStringifyReplacer,
  merge: () => merge,
  normalizeParams: () => normalizeParams,
  nullish: () => nullish,
  numKeys: () => numKeys,
  omit: () => omit,
  optionalKeys: () => optionalKeys,
  partial: () => partial,
  pick: () => pick,
  prefixIssues: () => prefixIssues,
  primitiveTypes: () => primitiveTypes,
  promiseAllObject: () => promiseAllObject,
  propertyKeyTypes: () => propertyKeyTypes,
  randomString: () => randomString,
  required: () => required,
  stringifyPrimitive: () => stringifyPrimitive,
  unwrapMessage: () => unwrapMessage
});
function assertEqual(val) {
  return val;
}
function assertNotEqual(val) {
  return val;
}
function assertIs(_arg) {
}
function assertNever(_x) {
  throw new Error();
}
function assert(_) {
}
function getEnumValues(entries) {
  const numericValues = Object.values(entries).filter((v) => typeof v === "number");
  const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
  return values;
}
function joinValues(array2, separator = "|") {
  return array2.map((val) => stringifyPrimitive(val)).join(separator);
}
function jsonStringifyReplacer(_, value) {
  if (typeof value === "bigint")
    return value.toString();
  return value;
}
function cached(getter) {
  const set2 = false;
  return {
    get value() {
      if (!set2) {
        const value = getter();
        Object.defineProperty(this, "value", { value });
        return value;
      }
      throw new Error("cached value already set");
    }
  };
}
function nullish(input) {
  return input === null || input === void 0;
}
function cleanRegex(source) {
  const start = source.startsWith("^") ? 1 : 0;
  const end = source.endsWith("$") ? source.length - 1 : source.length;
  return source.slice(start, end);
}
function floatSafeRemainder2(val, step) {
  const valDecCount = (val.toString().split(".")[1] || "").length;
  const stepDecCount = (step.toString().split(".")[1] || "").length;
  const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
  const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
  return valInt % stepInt / 10 ** decCount;
}
function defineLazy(object2, key, getter) {
  const set2 = false;
  Object.defineProperty(object2, key, {
    get() {
      if (!set2) {
        const value = getter();
        object2[key] = value;
        return value;
      }
      throw new Error("cached value already set");
    },
    set(v) {
      Object.defineProperty(object2, key, {
        value: v
        // configurable: true,
      });
    },
    configurable: true
  });
}
function assignProp(target, prop, value) {
  Object.defineProperty(target, prop, {
    value,
    writable: true,
    enumerable: true,
    configurable: true
  });
}
function getElementAtPath(obj, path4) {
  if (!path4)
    return obj;
  return path4.reduce((acc, key) => acc?.[key], obj);
}
function promiseAllObject(promisesObj) {
  const keys = Object.keys(promisesObj);
  const promises = keys.map((key) => promisesObj[key]);
  return Promise.all(promises).then((results) => {
    const resolvedObj = {};
    for (let i = 0; i < keys.length; i++) {
      resolvedObj[keys[i]] = results[i];
    }
    return resolvedObj;
  });
}
function randomString(length = 10) {
  const chars = "abcdefghijklmnopqrstuvwxyz";
  let str = "";
  for (let i = 0; i < length; i++) {
    str += chars[Math.floor(Math.random() * chars.length)];
  }
  return str;
}
function esc(str) {
  return JSON.stringify(str);
}
function isObject(data) {
  return typeof data === "object" && data !== null && !Array.isArray(data);
}
function isPlainObject(o) {
  if (isObject(o) === false)
    return false;
  const ctor = o.constructor;
  if (ctor === void 0)
    return true;
  const prot = ctor.prototype;
  if (isObject(prot) === false)
    return false;
  if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
    return false;
  }
  return true;
}
function numKeys(data) {
  let keyCount = 0;
  for (const key in data) {
    if (Object.prototype.hasOwnProperty.call(data, key)) {
      keyCount++;
    }
  }
  return keyCount;
}
function escapeRegex(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function clone(inst, def, params) {
  const cl = new inst._zod.constr(def ?? inst._zod.def);
  if (!def || params?.parent)
    cl._zod.parent = inst;
  return cl;
}
function normalizeParams(_params) {
  const params = _params;
  if (!params)
    return {};
  if (typeof params === "string")
    return { error: () => params };
  if (params?.message !== void 0) {
    if (params?.error !== void 0)
      throw new Error("Cannot specify both `message` and `error` params");
    params.error = params.message;
  }
  delete params.message;
  if (typeof params.error === "string")
    return { ...params, error: () => params.error };
  return params;
}
function createTransparentProxy(getter) {
  let target;
  return new Proxy({}, {
    get(_, prop, receiver) {
      target ?? (target = getter());
      return Reflect.get(target, prop, receiver);
    },
    set(_, prop, value, receiver) {
      target ?? (target = getter());
      return Reflect.set(target, prop, value, receiver);
    },
    has(_, prop) {
      target ?? (target = getter());
      return Reflect.has(target, prop);
    },
    deleteProperty(_, prop) {
      target ?? (target = getter());
      return Reflect.deleteProperty(target, prop);
    },
    ownKeys(_) {
      target ?? (target = getter());
      return Reflect.ownKeys(target);
    },
    getOwnPropertyDescriptor(_, prop) {
      target ?? (target = getter());
      return Reflect.getOwnPropertyDescriptor(target, prop);
    },
    defineProperty(_, prop, descriptor) {
      target ?? (target = getter());
      return Reflect.defineProperty(target, prop, descriptor);
    }
  });
}
function stringifyPrimitive(value) {
  if (typeof value === "bigint")
    return value.toString() + "n";
  if (typeof value === "string")
    return `"${value}"`;
  return `${value}`;
}
function optionalKeys(shape) {
  return Object.keys(shape).filter((k) => {
    return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
  });
}
function pick(schema, mask) {
  const newShape = {};
  const currDef = schema._zod.def;
  for (const key in mask) {
    if (!(key in currDef.shape)) {
      throw new Error(`Unrecognized key: "${key}"`);
    }
    if (!mask[key])
      continue;
    newShape[key] = currDef.shape[key];
  }
  return clone(schema, {
    ...schema._zod.def,
    shape: newShape,
    checks: []
  });
}
function omit(schema, mask) {
  const newShape = { ...schema._zod.def.shape };
  const currDef = schema._zod.def;
  for (const key in mask) {
    if (!(key in currDef.shape)) {
      throw new Error(`Unrecognized key: "${key}"`);
    }
    if (!mask[key])
      continue;
    delete newShape[key];
  }
  return clone(schema, {
    ...schema._zod.def,
    shape: newShape,
    checks: []
  });
}
function extend(schema, shape) {
  if (!isPlainObject(shape)) {
    throw new Error("Invalid input to extend: expected a plain object");
  }
  const def = {
    ...schema._zod.def,
    get shape() {
      const _shape = { ...schema._zod.def.shape, ...shape };
      assignProp(this, "shape", _shape);
      return _shape;
    },
    checks: []
    // delete existing checks
  };
  return clone(schema, def);
}
function merge(a, b) {
  return clone(a, {
    ...a._zod.def,
    get shape() {
      const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };
      assignProp(this, "shape", _shape);
      return _shape;
    },
    catchall: b._zod.def.catchall,
    checks: []
    // delete existing checks
  });
}
function partial(Class2, schema, mask) {
  const oldShape = schema._zod.def.shape;
  const shape = { ...oldShape };
  if (mask) {
    for (const key in mask) {
      if (!(key in oldShape)) {
        throw new Error(`Unrecognized key: "${key}"`);
      }
      if (!mask[key])
        continue;
      shape[key] = Class2 ? new Class2({
        type: "optional",
        innerType: oldShape[key]
      }) : oldShape[key];
    }
  } else {
    for (const key in oldShape) {
      shape[key] = Class2 ? new Class2({
        type: "optional",
        innerType: oldShape[key]
      }) : oldShape[key];
    }
  }
  return clone(schema, {
    ...schema._zod.def,
    shape,
    checks: []
  });
}
function required(Class2, schema, mask) {
  const oldShape = schema._zod.def.shape;
  const shape = { ...oldShape };
  if (mask) {
    for (const key in mask) {
      if (!(key in shape)) {
        throw new Error(`Unrecognized key: "${key}"`);
      }
      if (!mask[key])
        continue;
      shape[key] = new Class2({
        type: "nonoptional",
        innerType: oldShape[key]
      });
    }
  } else {
    for (const key in oldShape) {
      shape[key] = new Class2({
        type: "nonoptional",
        innerType: oldShape[key]
      });
    }
  }
  return clone(schema, {
    ...schema._zod.def,
    shape,
    // optional: [],
    checks: []
  });
}
function aborted(x, startIndex = 0) {
  for (let i = startIndex; i < x.issues.length; i++) {
    if (x.issues[i]?.continue !== true)
      return true;
  }
  return false;
}
function prefixIssues(path4, issues) {
  return issues.map((iss) => {
    var _a;
    (_a = iss).path ?? (_a.path = []);
    iss.path.unshift(path4);
    return iss;
  });
}
function unwrapMessage(message) {
  return typeof message === "string" ? message : message?.message;
}
function finalizeIssue(iss, ctx, config2) {
  const full = { ...iss, path: iss.path ?? [] };
  if (!iss.message) {
    const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input";
    full.message = message;
  }
  delete full.inst;
  delete full.continue;
  if (!ctx?.reportInput) {
    delete full.input;
  }
  return full;
}
function getSizableOrigin(input) {
  if (input instanceof Set)
    return "set";
  if (input instanceof Map)
    return "map";
  if (input instanceof File)
    return "file";
  return "unknown";
}
function getLengthableOrigin(input) {
  if (Array.isArray(input))
    return "array";
  if (typeof input === "string")
    return "string";
  return "unknown";
}
function issue(...args) {
  const [iss, input, inst] = args;
  if (typeof iss === "string") {
    return {
      message: iss,
      code: "custom",
      input,
      inst
    };
  }
  return { ...iss };
}
function cleanEnum(obj) {
  return Object.entries(obj).filter(([k, _]) => {
    return Number.isNaN(Number.parseInt(k, 10));
  }).map((el) => el[1]);
}
var captureStackTrace, allowsEval, getParsedType2, propertyKeyTypes, primitiveTypes, NUMBER_FORMAT_RANGES, BIGINT_FORMAT_RANGES, Class;
var init_util2 = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/util.js"() {
    captureStackTrace = Error.captureStackTrace ? Error.captureStackTrace : (..._args) => {
    };
    allowsEval = cached(() => {
      if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {
        return false;
      }
      try {
        const F = Function;
        new F("");
        return true;
      } catch (_) {
        return false;
      }
    });
    getParsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "undefined":
          return "undefined";
        case "string":
          return "string";
        case "number":
          return Number.isNaN(data) ? "nan" : "number";
        case "boolean":
          return "boolean";
        case "function":
          return "function";
        case "bigint":
          return "bigint";
        case "symbol":
          return "symbol";
        case "object":
          if (Array.isArray(data)) {
            return "array";
          }
          if (data === null) {
            return "null";
          }
          if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
            return "promise";
          }
          if (typeof Map !== "undefined" && data instanceof Map) {
            return "map";
          }
          if (typeof Set !== "undefined" && data instanceof Set) {
            return "set";
          }
          if (typeof Date !== "undefined" && data instanceof Date) {
            return "date";
          }
          if (typeof File !== "undefined" && data instanceof File) {
            return "file";
          }
          return "object";
        default:
          throw new Error(`Unknown data type: ${t}`);
      }
    };
    propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]);
    primitiveTypes = /* @__PURE__ */ new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]);
    NUMBER_FORMAT_RANGES = {
      safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
      int32: [-2147483648, 2147483647],
      uint32: [0, 4294967295],
      float32: [-34028234663852886e22, 34028234663852886e22],
      float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
    };
    BIGINT_FORMAT_RANGES = {
      int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")],
      uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")]
    };
    Class = class {
      constructor(..._args) {
      }
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/errors.js
function flattenError(error40, mapper = (issue2) => issue2.message) {
  const fieldErrors = {};
  const formErrors = [];
  for (const sub of error40.issues) {
    if (sub.path.length > 0) {
      fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
      fieldErrors[sub.path[0]].push(mapper(sub));
    } else {
      formErrors.push(mapper(sub));
    }
  }
  return { formErrors, fieldErrors };
}
function formatError(error40, _mapper) {
  const mapper = _mapper || function(issue2) {
    return issue2.message;
  };
  const fieldErrors = { _errors: [] };
  const processError = (error41) => {
    for (const issue2 of error41.issues) {
      if (issue2.code === "invalid_union" && issue2.errors.length) {
        issue2.errors.map((issues) => processError({ issues }));
      } else if (issue2.code === "invalid_key") {
        processError({ issues: issue2.issues });
      } else if (issue2.code === "invalid_element") {
        processError({ issues: issue2.issues });
      } else if (issue2.path.length === 0) {
        fieldErrors._errors.push(mapper(issue2));
      } else {
        let curr = fieldErrors;
        let i = 0;
        while (i < issue2.path.length) {
          const el = issue2.path[i];
          const terminal = i === issue2.path.length - 1;
          if (!terminal) {
            curr[el] = curr[el] || { _errors: [] };
          } else {
            curr[el] = curr[el] || { _errors: [] };
            curr[el]._errors.push(mapper(issue2));
          }
          curr = curr[el];
          i++;
        }
      }
    }
  };
  processError(error40);
  return fieldErrors;
}
function treeifyError(error40, _mapper) {
  const mapper = _mapper || function(issue2) {
    return issue2.message;
  };
  const result = { errors: [] };
  const processError = (error41, path4 = []) => {
    var _a, _b;
    for (const issue2 of error41.issues) {
      if (issue2.code === "invalid_union" && issue2.errors.length) {
        issue2.errors.map((issues) => processError({ issues }, issue2.path));
      } else if (issue2.code === "invalid_key") {
        processError({ issues: issue2.issues }, issue2.path);
      } else if (issue2.code === "invalid_element") {
        processError({ issues: issue2.issues }, issue2.path);
      } else {
        const fullpath = [...path4, ...issue2.path];
        if (fullpath.length === 0) {
          result.errors.push(mapper(issue2));
          continue;
        }
        let curr = result;
        let i = 0;
        while (i < fullpath.length) {
          const el = fullpath[i];
          const terminal = i === fullpath.length - 1;
          if (typeof el === "string") {
            curr.properties ?? (curr.properties = {});
            (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });
            curr = curr.properties[el];
          } else {
            curr.items ?? (curr.items = []);
            (_b = curr.items)[el] ?? (_b[el] = { errors: [] });
            curr = curr.items[el];
          }
          if (terminal) {
            curr.errors.push(mapper(issue2));
          }
          i++;
        }
      }
    }
  };
  processError(error40);
  return result;
}
function toDotPath(path4) {
  const segs = [];
  for (const seg of path4) {
    if (typeof seg === "number")
      segs.push(`[${seg}]`);
    else if (typeof seg === "symbol")
      segs.push(`[${JSON.stringify(String(seg))}]`);
    else if (/[^\w$]/.test(seg))
      segs.push(`[${JSON.stringify(seg)}]`);
    else {
      if (segs.length)
        segs.push(".");
      segs.push(seg);
    }
  }
  return segs.join("");
}
function prettifyError(error40) {
  const lines = [];
  const issues = [...error40.issues].sort((a, b) => a.path.length - b.path.length);
  for (const issue2 of issues) {
    lines.push(`\u2716 ${issue2.message}`);
    if (issue2.path?.length)
      lines.push(`  \u2192 at ${toDotPath(issue2.path)}`);
  }
  return lines.join("\n");
}
var initializer, $ZodError, $ZodRealError;
var init_errors3 = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/errors.js"() {
    init_core2();
    init_util2();
    initializer = (inst, def) => {
      inst.name = "$ZodError";
      Object.defineProperty(inst, "_zod", {
        value: inst._zod,
        enumerable: false
      });
      Object.defineProperty(inst, "issues", {
        value: def,
        enumerable: false
      });
      Object.defineProperty(inst, "message", {
        get() {
          return JSON.stringify(def, jsonStringifyReplacer, 2);
        },
        enumerable: true
        // configurable: false,
      });
      Object.defineProperty(inst, "toString", {
        value: () => inst.message,
        enumerable: false
      });
    };
    $ZodError = $constructor("$ZodError", initializer);
    $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error });
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/parse.js
var _parse, parse, _parseAsync, parseAsync, _safeParse, safeParse, _safeParseAsync, safeParseAsync;
var init_parse = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/parse.js"() {
    init_core2();
    init_errors3();
    init_util2();
    _parse = (_Err) => (schema, value, _ctx, _params) => {
      const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };
      const result = schema._zod.run({ value, issues: [] }, ctx);
      if (result instanceof Promise) {
        throw new $ZodAsyncError();
      }
      if (result.issues.length) {
        const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
        captureStackTrace(e, _params?.callee);
        throw e;
      }
      return result.value;
    };
    parse = /* @__PURE__ */ _parse($ZodRealError);
    _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
      const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
      let result = schema._zod.run({ value, issues: [] }, ctx);
      if (result instanceof Promise)
        result = await result;
      if (result.issues.length) {
        const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
        captureStackTrace(e, params?.callee);
        throw e;
      }
      return result.value;
    };
    parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError);
    _safeParse = (_Err) => (schema, value, _ctx) => {
      const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
      const result = schema._zod.run({ value, issues: [] }, ctx);
      if (result instanceof Promise) {
        throw new $ZodAsyncError();
      }
      return result.issues.length ? {
        success: false,
        error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
      } : { success: true, data: result.value };
    };
    safeParse = /* @__PURE__ */ _safeParse($ZodRealError);
    _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
      const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
      let result = schema._zod.run({ value, issues: [] }, ctx);
      if (result instanceof Promise)
        result = await result;
      return result.issues.length ? {
        success: false,
        error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
      } : { success: true, data: result.value };
    };
    safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError);
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/regexes.js
var regexes_exports = {};
__export(regexes_exports, {
  _emoji: () => _emoji,
  base64: () => base64,
  base64url: () => base64url,
  bigint: () => bigint2,
  boolean: () => boolean2,
  browserEmail: () => browserEmail,
  cidrv4: () => cidrv4,
  cidrv6: () => cidrv6,
  cuid: () => cuid,
  cuid2: () => cuid2,
  date: () => date2,
  datetime: () => datetime,
  domain: () => domain,
  duration: () => duration,
  e164: () => e164,
  email: () => email,
  emoji: () => emoji,
  extendedDuration: () => extendedDuration,
  guid: () => guid,
  hostname: () => hostname,
  html5Email: () => html5Email,
  integer: () => integer2,
  ipv4: () => ipv4,
  ipv6: () => ipv6,
  ksuid: () => ksuid,
  lowercase: () => lowercase,
  nanoid: () => nanoid,
  null: () => _null,
  number: () => number,
  rfc5322Email: () => rfc5322Email,
  string: () => string,
  time: () => time2,
  ulid: () => ulid,
  undefined: () => _undefined,
  unicodeEmail: () => unicodeEmail,
  uppercase: () => uppercase,
  uuid: () => uuid2,
  uuid4: () => uuid4,
  uuid6: () => uuid6,
  uuid7: () => uuid7,
  xid: () => xid
});
function emoji() {
  return new RegExp(_emoji, "u");
}
function timeSource(args) {
  const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
  const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
  return regex;
}
function time2(args) {
  return new RegExp(`^${timeSource(args)}$`);
}
function datetime(args) {
  const time4 = timeSource({ precision: args.precision });
  const opts = ["Z"];
  if (args.local)
    opts.push("");
  if (args.offset)
    opts.push(`([+-]\\d{2}:\\d{2})`);
  const timeRegex2 = `${time4}(?:${opts.join("|")})`;
  return new RegExp(`^${dateSource}T(?:${timeRegex2})$`);
}
var cuid, cuid2, ulid, xid, ksuid, nanoid, duration, extendedDuration, guid, uuid2, uuid4, uuid6, uuid7, email, html5Email, rfc5322Email, unicodeEmail, browserEmail, _emoji, ipv4, ipv6, cidrv4, cidrv6, base64, base64url, hostname, domain, e164, dateSource, date2, string, bigint2, integer2, number, boolean2, _null, _undefined, lowercase, uppercase;
var init_regexes = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/regexes.js"() {
    cuid = /^[cC][^\s-]{8,}$/;
    cuid2 = /^[0-9a-z]+$/;
    ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
    xid = /^[0-9a-vA-V]{20}$/;
    ksuid = /^[A-Za-z0-9]{27}$/;
    nanoid = /^[a-zA-Z0-9_-]{21}$/;
    duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
    extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
    guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
    uuid2 = (version3) => {
      if (!version3)
        return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;
      return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version3}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
    };
    uuid4 = /* @__PURE__ */ uuid2(4);
    uuid6 = /* @__PURE__ */ uuid2(6);
    uuid7 = /* @__PURE__ */ uuid2(7);
    email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
    html5Email = /^[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-]{0,61}[a-zA-Z0-9])?)*$/;
    rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u;
    browserEmail = /^[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-]{0,61}[a-zA-Z0-9])?)*$/;
    _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
    ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
    ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/;
    cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
    cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
    base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
    base64url = /^[A-Za-z0-9_-]*$/;
    hostname = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;
    domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
    e164 = /^\+(?:[0-9]){6,14}[0-9]$/;
    dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;
    date2 = /* @__PURE__ */ new RegExp(`^${dateSource}$`);
    string = (params) => {
      const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
      return new RegExp(`^${regex}$`);
    };
    bigint2 = /^\d+n?$/;
    integer2 = /^\d+$/;
    number = /^-?\d+(?:\.\d+)?/i;
    boolean2 = /true|false/i;
    _null = /null/i;
    _undefined = /undefined/i;
    lowercase = /^[^A-Z]*$/;
    uppercase = /^[^a-z]*$/;
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/checks.js
function handleCheckPropertyResult(result, payload, property) {
  if (result.issues.length) {
    payload.issues.push(...prefixIssues(property, result.issues));
  }
}
var $ZodCheck, numericOriginMap, $ZodCheckLessThan, $ZodCheckGreaterThan, $ZodCheckMultipleOf, $ZodCheckNumberFormat, $ZodCheckBigIntFormat, $ZodCheckMaxSize, $ZodCheckMinSize, $ZodCheckSizeEquals, $ZodCheckMaxLength, $ZodCheckMinLength, $ZodCheckLengthEquals, $ZodCheckStringFormat, $ZodCheckRegex, $ZodCheckLowerCase, $ZodCheckUpperCase, $ZodCheckIncludes, $ZodCheckStartsWith, $ZodCheckEndsWith, $ZodCheckProperty, $ZodCheckMimeType, $ZodCheckOverwrite;
var init_checks2 = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/checks.js"() {
    init_core2();
    init_regexes();
    init_util2();
    $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
      var _a;
      inst._zod ?? (inst._zod = {});
      inst._zod.def = def;
      (_a = inst._zod).onattach ?? (_a.onattach = []);
    });
    numericOriginMap = {
      number: "number",
      bigint: "bigint",
      object: "date"
    };
    $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => {
      $ZodCheck.init(inst, def);
      const origin = numericOriginMap[typeof def.value];
      inst._zod.onattach.push((inst2) => {
        const bag = inst2._zod.bag;
        const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
        if (def.value < curr) {
          if (def.inclusive)
            bag.maximum = def.value;
          else
            bag.exclusiveMaximum = def.value;
        }
      });
      inst._zod.check = (payload) => {
        if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {
          return;
        }
        payload.issues.push({
          origin,
          code: "too_big",
          maximum: def.value,
          input: payload.value,
          inclusive: def.inclusive,
          inst,
          continue: !def.abort
        });
      };
    });
    $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => {
      $ZodCheck.init(inst, def);
      const origin = numericOriginMap[typeof def.value];
      inst._zod.onattach.push((inst2) => {
        const bag = inst2._zod.bag;
        const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
        if (def.value > curr) {
          if (def.inclusive)
            bag.minimum = def.value;
          else
            bag.exclusiveMinimum = def.value;
        }
      });
      inst._zod.check = (payload) => {
        if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {
          return;
        }
        payload.issues.push({
          origin,
          code: "too_small",
          minimum: def.value,
          input: payload.value,
          inclusive: def.inclusive,
          inst,
          continue: !def.abort
        });
      };
    });
    $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => {
      $ZodCheck.init(inst, def);
      inst._zod.onattach.push((inst2) => {
        var _a;
        (_a = inst2._zod.bag).multipleOf ?? (_a.multipleOf = def.value);
      });
      inst._zod.check = (payload) => {
        if (typeof payload.value !== typeof def.value)
          throw new Error("Cannot mix number and bigint in multiple_of check.");
        const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder2(payload.value, def.value) === 0;
        if (isMultiple)
          return;
        payload.issues.push({
          origin: typeof payload.value,
          code: "not_multiple_of",
          divisor: def.value,
          input: payload.value,
          inst,
          continue: !def.abort
        });
      };
    });
    $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => {
      $ZodCheck.init(inst, def);
      def.format = def.format || "float64";
      const isInt = def.format?.includes("int");
      const origin = isInt ? "int" : "number";
      const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
      inst._zod.onattach.push((inst2) => {
        const bag = inst2._zod.bag;
        bag.format = def.format;
        bag.minimum = minimum;
        bag.maximum = maximum;
        if (isInt)
          bag.pattern = integer2;
      });
      inst._zod.check = (payload) => {
        const input = payload.value;
        if (isInt) {
          if (!Number.isInteger(input)) {
            payload.issues.push({
              expected: origin,
              format: def.format,
              code: "invalid_type",
              input,
              inst
            });
            return;
          }
          if (!Number.isSafeInteger(input)) {
            if (input > 0) {
              payload.issues.push({
                input,
                code: "too_big",
                maximum: Number.MAX_SAFE_INTEGER,
                note: "Integers must be within the safe integer range.",
                inst,
                origin,
                continue: !def.abort
              });
            } else {
              payload.issues.push({
                input,
                code: "too_small",
                minimum: Number.MIN_SAFE_INTEGER,
                note: "Integers must be within the safe integer range.",
                inst,
                origin,
                continue: !def.abort
              });
            }
            return;
          }
        }
        if (input < minimum) {
          payload.issues.push({
            origin: "number",
            input,
            code: "too_small",
            minimum,
            inclusive: true,
            inst,
            continue: !def.abort
          });
        }
        if (input > maximum) {
          payload.issues.push({
            origin: "number",
            input,
            code: "too_big",
            maximum,
            inst
          });
        }
      };
    });
    $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => {
      $ZodCheck.init(inst, def);
      const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format];
      inst._zod.onattach.push((inst2) => {
        const bag = inst2._zod.bag;
        bag.format = def.format;
        bag.minimum = minimum;
        bag.maximum = maximum;
      });
      inst._zod.check = (payload) => {
        const input = payload.value;
        if (input < minimum) {
          payload.issues.push({
            origin: "bigint",
            input,
            code: "too_small",
            minimum,
            inclusive: true,
            inst,
            continue: !def.abort
          });
        }
        if (input > maximum) {
          payload.issues.push({
            origin: "bigint",
            input,
            code: "too_big",
            maximum,
            inst
          });
        }
      };
    });
    $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => {
      var _a;
      $ZodCheck.init(inst, def);
      (_a = inst._zod.def).when ?? (_a.when = (payload) => {
        const val = payload.value;
        return !nullish(val) && val.size !== void 0;
      });
      inst._zod.onattach.push((inst2) => {
        const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
        if (def.maximum < curr)
          inst2._zod.bag.maximum = def.maximum;
      });
      inst._zod.check = (payload) => {
        const input = payload.value;
        const size = input.size;
        if (size <= def.maximum)
          return;
        payload.issues.push({
          origin: getSizableOrigin(input),
          code: "too_big",
          maximum: def.maximum,
          input,
          inst,
          continue: !def.abort
        });
      };
    });
    $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => {
      var _a;
      $ZodCheck.init(inst, def);
      (_a = inst._zod.def).when ?? (_a.when = (payload) => {
        const val = payload.value;
        return !nullish(val) && val.size !== void 0;
      });
      inst._zod.onattach.push((inst2) => {
        const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
        if (def.minimum > curr)
          inst2._zod.bag.minimum = def.minimum;
      });
      inst._zod.check = (payload) => {
        const input = payload.value;
        const size = input.size;
        if (size >= def.minimum)
          return;
        payload.issues.push({
          origin: getSizableOrigin(input),
          code: "too_small",
          minimum: def.minimum,
          input,
          inst,
          continue: !def.abort
        });
      };
    });
    $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => {
      var _a;
      $ZodCheck.init(inst, def);
      (_a = inst._zod.def).when ?? (_a.when = (payload) => {
        const val = payload.value;
        return !nullish(val) && val.size !== void 0;
      });
      inst._zod.onattach.push((inst2) => {
        const bag = inst2._zod.bag;
        bag.minimum = def.size;
        bag.maximum = def.size;
        bag.size = def.size;
      });
      inst._zod.check = (payload) => {
        const input = payload.value;
        const size = input.size;
        if (size === def.size)
          return;
        const tooBig = size > def.size;
        payload.issues.push({
          origin: getSizableOrigin(input),
          ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size },
          inclusive: true,
          exact: true,
          input: payload.value,
          inst,
          continue: !def.abort
        });
      };
    });
    $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {
      var _a;
      $ZodCheck.init(inst, def);
      (_a = inst._zod.def).when ?? (_a.when = (payload) => {
        const val = payload.value;
        return !nullish(val) && val.length !== void 0;
      });
      inst._zod.onattach.push((inst2) => {
        const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
        if (def.maximum < curr)
          inst2._zod.bag.maximum = def.maximum;
      });
      inst._zod.check = (payload) => {
        const input = payload.value;
        const length = input.length;
        if (length <= def.maximum)
          return;
        const origin = getLengthableOrigin(input);
        payload.issues.push({
          origin,
          code: "too_big",
          maximum: def.maximum,
          inclusive: true,
          input,
          inst,
          continue: !def.abort
        });
      };
    });
    $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => {
      var _a;
      $ZodCheck.init(inst, def);
      (_a = inst._zod.def).when ?? (_a.when = (payload) => {
        const val = payload.value;
        return !nullish(val) && val.length !== void 0;
      });
      inst._zod.onattach.push((inst2) => {
        const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
        if (def.minimum > curr)
          inst2._zod.bag.minimum = def.minimum;
      });
      inst._zod.check = (payload) => {
        const input = payload.value;
        const length = input.length;
        if (length >= def.minimum)
          return;
        const origin = getLengthableOrigin(input);
        payload.issues.push({
          origin,
          code: "too_small",
          minimum: def.minimum,
          inclusive: true,
          input,
          inst,
          continue: !def.abort
        });
      };
    });
    $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => {
      var _a;
      $ZodCheck.init(inst, def);
      (_a = inst._zod.def).when ?? (_a.when = (payload) => {
        const val = payload.value;
        return !nullish(val) && val.length !== void 0;
      });
      inst._zod.onattach.push((inst2) => {
        const bag = inst2._zod.bag;
        bag.minimum = def.length;
        bag.maximum = def.length;
        bag.length = def.length;
      });
      inst._zod.check = (payload) => {
        const input = payload.value;
        const length = input.length;
        if (length === def.length)
          return;
        const origin = getLengthableOrigin(input);
        const tooBig = length > def.length;
        payload.issues.push({
          origin,
          ...tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length },
          inclusive: true,
          exact: true,
          input: payload.value,
          inst,
          continue: !def.abort
        });
      };
    });
    $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => {
      var _a, _b;
      $ZodCheck.init(inst, def);
      inst._zod.onattach.push((inst2) => {
        const bag = inst2._zod.bag;
        bag.format = def.format;
        if (def.pattern) {
          bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
          bag.patterns.add(def.pattern);
        }
      });
      if (def.pattern)
        (_a = inst._zod).check ?? (_a.check = (payload) => {
          def.pattern.lastIndex = 0;
          if (def.pattern.test(payload.value))
            return;
          payload.issues.push({
            origin: "string",
            code: "invalid_format",
            format: def.format,
            input: payload.value,
            ...def.pattern ? { pattern: def.pattern.toString() } : {},
            inst,
            continue: !def.abort
          });
        });
      else
        (_b = inst._zod).check ?? (_b.check = () => {
        });
    });
    $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) => {
      $ZodCheckStringFormat.init(inst, def);
      inst._zod.check = (payload) => {
        def.pattern.lastIndex = 0;
        if (def.pattern.test(payload.value))
          return;
        payload.issues.push({
          origin: "string",
          code: "invalid_format",
          format: "regex",
          input: payload.value,
          pattern: def.pattern.toString(),
          inst,
          continue: !def.abort
        });
      };
    });
    $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => {
      def.pattern ?? (def.pattern = lowercase);
      $ZodCheckStringFormat.init(inst, def);
    });
    $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => {
      def.pattern ?? (def.pattern = uppercase);
      $ZodCheckStringFormat.init(inst, def);
    });
    $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => {
      $ZodCheck.init(inst, def);
      const escapedRegex = escapeRegex(def.includes);
      const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
      def.pattern = pattern;
      inst._zod.onattach.push((inst2) => {
        const bag = inst2._zod.bag;
        bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
        bag.patterns.add(pattern);
      });
      inst._zod.check = (payload) => {
        if (payload.value.includes(def.includes, def.position))
          return;
        payload.issues.push({
          origin: "string",
          code: "invalid_format",
          format: "includes",
          includes: def.includes,
          input: payload.value,
          inst,
          continue: !def.abort
        });
      };
    });
    $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => {
      $ZodCheck.init(inst, def);
      const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
      def.pattern ?? (def.pattern = pattern);
      inst._zod.onattach.push((inst2) => {
        const bag = inst2._zod.bag;
        bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
        bag.patterns.add(pattern);
      });
      inst._zod.check = (payload) => {
        if (payload.value.startsWith(def.prefix))
          return;
        payload.issues.push({
          origin: "string",
          code: "invalid_format",
          format: "starts_with",
          prefix: def.prefix,
          input: payload.value,
          inst,
          continue: !def.abort
        });
      };
    });
    $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => {
      $ZodCheck.init(inst, def);
      const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
      def.pattern ?? (def.pattern = pattern);
      inst._zod.onattach.push((inst2) => {
        const bag = inst2._zod.bag;
        bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
        bag.patterns.add(pattern);
      });
      inst._zod.check = (payload) => {
        if (payload.value.endsWith(def.suffix))
          return;
        payload.issues.push({
          origin: "string",
          code: "invalid_format",
          format: "ends_with",
          suffix: def.suffix,
          input: payload.value,
          inst,
          continue: !def.abort
        });
      };
    });
    $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, def) => {
      $ZodCheck.init(inst, def);
      inst._zod.check = (payload) => {
        const result = def.schema._zod.run({
          value: payload.value[def.property],
          issues: []
        }, {});
        if (result instanceof Promise) {
          return result.then((result2) => handleCheckPropertyResult(result2, payload, def.property));
        }
        handleCheckPropertyResult(result, payload, def.property);
        return;
      };
    });
    $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => {
      $ZodCheck.init(inst, def);
      const mimeSet = new Set(def.mime);
      inst._zod.onattach.push((inst2) => {
        inst2._zod.bag.mime = def.mime;
      });
      inst._zod.check = (payload) => {
        if (mimeSet.has(payload.value.type))
          return;
        payload.issues.push({
          code: "invalid_value",
          values: def.mime,
          input: payload.value.type,
          inst
        });
      };
    });
    $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => {
      $ZodCheck.init(inst, def);
      inst._zod.check = (payload) => {
        payload.value = def.tx(payload.value);
      };
    });
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/doc.js
var Doc;
var init_doc = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/doc.js"() {
    Doc = class {
      constructor(args = []) {
        this.content = [];
        this.indent = 0;
        if (this)
          this.args = args;
      }
      indented(fn) {
        this.indent += 1;
        fn(this);
        this.indent -= 1;
      }
      write(arg) {
        if (typeof arg === "function") {
          arg(this, { execution: "sync" });
          arg(this, { execution: "async" });
          return;
        }
        const content = arg;
        const lines = content.split("\n").filter((x) => x);
        const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));
        const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);
        for (const line2 of dedented) {
          this.content.push(line2);
        }
      }
      compile() {
        const F = Function;
        const args = this?.args;
        const content = this?.content ?? [``];
        const lines = [...content.map((x) => `  ${x}`)];
        return new F(...args, lines.join("\n"));
      }
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/versions.js
var version2;
var init_versions = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/versions.js"() {
    version2 = {
      major: 4,
      minor: 0,
      patch: 0
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/schemas.js
function isValidBase64(data) {
  if (data === "")
    return true;
  if (data.length % 4 !== 0)
    return false;
  try {
    atob(data);
    return true;
  } catch {
    return false;
  }
}
function isValidBase64URL(data) {
  if (!base64url.test(data))
    return false;
  const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
  const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "=");
  return isValidBase64(padded);
}
function isValidJWT2(token, algorithm = null) {
  try {
    const tokensParts = token.split(".");
    if (tokensParts.length !== 3)
      return false;
    const [header] = tokensParts;
    if (!header)
      return false;
    const parsedHeader = JSON.parse(atob(header));
    if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT")
      return false;
    if (!parsedHeader.alg)
      return false;
    if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm))
      return false;
    return true;
  } catch {
    return false;
  }
}
function handleArrayResult(result, final, index2) {
  if (result.issues.length) {
    final.issues.push(...prefixIssues(index2, result.issues));
  }
  final.value[index2] = result.value;
}
function handleObjectResult(result, final, key) {
  if (result.issues.length) {
    final.issues.push(...prefixIssues(key, result.issues));
  }
  final.value[key] = result.value;
}
function handleOptionalObjectResult(result, final, key, input) {
  if (result.issues.length) {
    if (input[key] === void 0) {
      if (key in input) {
        final.value[key] = void 0;
      } else {
        final.value[key] = result.value;
      }
    } else {
      final.issues.push(...prefixIssues(key, result.issues));
    }
  } else if (result.value === void 0) {
    if (key in input)
      final.value[key] = void 0;
  } else {
    final.value[key] = result.value;
  }
}
function handleUnionResults(results, final, inst, ctx) {
  for (const result of results) {
    if (result.issues.length === 0) {
      final.value = result.value;
      return final;
    }
  }
  final.issues.push({
    code: "invalid_union",
    input: final.value,
    inst,
    errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
  });
  return final;
}
function mergeValues2(a, b) {
  if (a === b) {
    return { valid: true, data: a };
  }
  if (a instanceof Date && b instanceof Date && +a === +b) {
    return { valid: true, data: a };
  }
  if (isPlainObject(a) && isPlainObject(b)) {
    const bKeys = Object.keys(b);
    const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
    const newObj = { ...a, ...b };
    for (const key of sharedKeys) {
      const sharedValue = mergeValues2(a[key], b[key]);
      if (!sharedValue.valid) {
        return {
          valid: false,
          mergeErrorPath: [key, ...sharedValue.mergeErrorPath]
        };
      }
      newObj[key] = sharedValue.data;
    }
    return { valid: true, data: newObj };
  }
  if (Array.isArray(a) && Array.isArray(b)) {
    if (a.length !== b.length) {
      return { valid: false, mergeErrorPath: [] };
    }
    const newArray = [];
    for (let index2 = 0; index2 < a.length; index2++) {
      const itemA = a[index2];
      const itemB = b[index2];
      const sharedValue = mergeValues2(itemA, itemB);
      if (!sharedValue.valid) {
        return {
          valid: false,
          mergeErrorPath: [index2, ...sharedValue.mergeErrorPath]
        };
      }
      newArray.push(sharedValue.data);
    }
    return { valid: true, data: newArray };
  }
  return { valid: false, mergeErrorPath: [] };
}
function handleIntersectionResults(result, left, right) {
  if (left.issues.length) {
    result.issues.push(...left.issues);
  }
  if (right.issues.length) {
    result.issues.push(...right.issues);
  }
  if (aborted(result))
    return result;
  const merged = mergeValues2(left.value, right.value);
  if (!merged.valid) {
    throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);
  }
  result.value = merged.data;
  return result;
}
function handleTupleResult(result, final, index2) {
  if (result.issues.length) {
    final.issues.push(...prefixIssues(index2, result.issues));
  }
  final.value[index2] = result.value;
}
function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {
  if (keyResult.issues.length) {
    if (propertyKeyTypes.has(typeof key)) {
      final.issues.push(...prefixIssues(key, keyResult.issues));
    } else {
      final.issues.push({
        origin: "map",
        code: "invalid_key",
        input,
        inst,
        issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config()))
      });
    }
  }
  if (valueResult.issues.length) {
    if (propertyKeyTypes.has(typeof key)) {
      final.issues.push(...prefixIssues(key, valueResult.issues));
    } else {
      final.issues.push({
        origin: "map",
        code: "invalid_element",
        input,
        inst,
        key,
        issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config()))
      });
    }
  }
  final.value.set(keyResult.value, valueResult.value);
}
function handleSetResult(result, final) {
  if (result.issues.length) {
    final.issues.push(...result.issues);
  }
  final.value.add(result.value);
}
function handleDefaultResult(payload, def) {
  if (payload.value === void 0) {
    payload.value = def.defaultValue;
  }
  return payload;
}
function handleNonOptionalResult(payload, inst) {
  if (!payload.issues.length && payload.value === void 0) {
    payload.issues.push({
      code: "invalid_type",
      expected: "nonoptional",
      input: payload.value,
      inst
    });
  }
  return payload;
}
function handlePipeResult(left, def, ctx) {
  if (aborted(left)) {
    return left;
  }
  return def.out._zod.run({ value: left.value, issues: left.issues }, ctx);
}
function handleReadonlyResult(payload) {
  payload.value = Object.freeze(payload.value);
  return payload;
}
function handleRefineResult(result, payload, input, inst) {
  if (!result) {
    const _iss = {
      code: "custom",
      input,
      inst,
      // incorporates params.error into issue reporting
      path: [...inst._zod.def.path ?? []],
      // incorporates params.error into issue reporting
      continue: !inst._zod.def.abort
      // params: inst._zod.def.params,
    };
    if (inst._zod.def.params)
      _iss.params = inst._zod.def.params;
    payload.issues.push(issue(_iss));
  }
}
var $ZodType, $ZodString, $ZodStringFormat, $ZodGUID, $ZodUUID, $ZodEmail, $ZodURL, $ZodEmoji, $ZodNanoID, $ZodCUID, $ZodCUID2, $ZodULID, $ZodXID, $ZodKSUID, $ZodISODateTime, $ZodISODate, $ZodISOTime, $ZodISODuration, $ZodIPv4, $ZodIPv6, $ZodCIDRv4, $ZodCIDRv6, $ZodBase64, $ZodBase64URL, $ZodE164, $ZodJWT, $ZodCustomStringFormat, $ZodNumber, $ZodNumberFormat, $ZodBoolean, $ZodBigInt, $ZodBigIntFormat, $ZodSymbol, $ZodUndefined, $ZodNull, $ZodAny, $ZodUnknown, $ZodNever, $ZodVoid, $ZodDate, $ZodArray, $ZodObject, $ZodUnion, $ZodDiscriminatedUnion, $ZodIntersection, $ZodTuple, $ZodRecord, $ZodMap, $ZodSet, $ZodEnum, $ZodLiteral, $ZodFile, $ZodTransform, $ZodOptional, $ZodNullable, $ZodDefault, $ZodPrefault, $ZodNonOptional, $ZodSuccess, $ZodCatch, $ZodNaN, $ZodPipe, $ZodReadonly, $ZodTemplateLiteral, $ZodPromise, $ZodLazy, $ZodCustom;
var init_schemas = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/schemas.js"() {
    init_checks2();
    init_core2();
    init_doc();
    init_parse();
    init_regexes();
    init_util2();
    init_versions();
    init_util2();
    $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
      var _a;
      inst ?? (inst = {});
      inst._zod.def = def;
      inst._zod.bag = inst._zod.bag || {};
      inst._zod.version = version2;
      const checks = [...inst._zod.def.checks ?? []];
      if (inst._zod.traits.has("$ZodCheck")) {
        checks.unshift(inst);
      }
      for (const ch of checks) {
        for (const fn of ch._zod.onattach) {
          fn(inst);
        }
      }
      if (checks.length === 0) {
        (_a = inst._zod).deferred ?? (_a.deferred = []);
        inst._zod.deferred?.push(() => {
          inst._zod.run = inst._zod.parse;
        });
      } else {
        const runChecks = (payload, checks2, ctx) => {
          let isAborted2 = aborted(payload);
          let asyncResult;
          for (const ch of checks2) {
            if (ch._zod.def.when) {
              const shouldRun = ch._zod.def.when(payload);
              if (!shouldRun)
                continue;
            } else if (isAborted2) {
              continue;
            }
            const currLen = payload.issues.length;
            const _ = ch._zod.check(payload);
            if (_ instanceof Promise && ctx?.async === false) {
              throw new $ZodAsyncError();
            }
            if (asyncResult || _ instanceof Promise) {
              asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
                await _;
                const nextLen = payload.issues.length;
                if (nextLen === currLen)
                  return;
                if (!isAborted2)
                  isAborted2 = aborted(payload, currLen);
              });
            } else {
              const nextLen = payload.issues.length;
              if (nextLen === currLen)
                continue;
              if (!isAborted2)
                isAborted2 = aborted(payload, currLen);
            }
          }
          if (asyncResult) {
            return asyncResult.then(() => {
              return payload;
            });
          }
          return payload;
        };
        inst._zod.run = (payload, ctx) => {
          const result = inst._zod.parse(payload, ctx);
          if (result instanceof Promise) {
            if (ctx.async === false)
              throw new $ZodAsyncError();
            return result.then((result2) => runChecks(result2, checks, ctx));
          }
          return runChecks(result, checks, ctx);
        };
      }
      inst["~standard"] = {
        validate: (value) => {
          try {
            const r = safeParse(inst, value);
            return r.success ? { value: r.data } : { issues: r.error?.issues };
          } catch (_) {
            return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues });
          }
        },
        vendor: "zod",
        version: 1
      };
    });
    $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => {
      $ZodType.init(inst, def);
      inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag);
      inst._zod.parse = (payload, _) => {
        if (def.coerce)
          try {
            payload.value = String(payload.value);
          } catch (_2) {
          }
        if (typeof payload.value === "string")
          return payload;
        payload.issues.push({
          expected: "string",
          code: "invalid_type",
          input: payload.value,
          inst
        });
        return payload;
      };
    });
    $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => {
      $ZodCheckStringFormat.init(inst, def);
      $ZodString.init(inst, def);
    });
    $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => {
      def.pattern ?? (def.pattern = guid);
      $ZodStringFormat.init(inst, def);
    });
    $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => {
      if (def.version) {
        const versionMap = {
          v1: 1,
          v2: 2,
          v3: 3,
          v4: 4,
          v5: 5,
          v6: 6,
          v7: 7,
          v8: 8
        };
        const v = versionMap[def.version];
        if (v === void 0)
          throw new Error(`Invalid UUID version: "${def.version}"`);
        def.pattern ?? (def.pattern = uuid2(v));
      } else
        def.pattern ?? (def.pattern = uuid2());
      $ZodStringFormat.init(inst, def);
    });
    $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => {
      def.pattern ?? (def.pattern = email);
      $ZodStringFormat.init(inst, def);
    });
    $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
      $ZodStringFormat.init(inst, def);
      inst._zod.check = (payload) => {
        try {
          const orig = payload.value;
          const url2 = new URL(orig);
          const href = url2.href;
          if (def.hostname) {
            def.hostname.lastIndex = 0;
            if (!def.hostname.test(url2.hostname)) {
              payload.issues.push({
                code: "invalid_format",
                format: "url",
                note: "Invalid hostname",
                pattern: hostname.source,
                input: payload.value,
                inst,
                continue: !def.abort
              });
            }
          }
          if (def.protocol) {
            def.protocol.lastIndex = 0;
            if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) {
              payload.issues.push({
                code: "invalid_format",
                format: "url",
                note: "Invalid protocol",
                pattern: def.protocol.source,
                input: payload.value,
                inst,
                continue: !def.abort
              });
            }
          }
          if (!orig.endsWith("/") && href.endsWith("/")) {
            payload.value = href.slice(0, -1);
          } else {
            payload.value = href;
          }
          return;
        } catch (_) {
          payload.issues.push({
            code: "invalid_format",
            format: "url",
            input: payload.value,
            inst,
            continue: !def.abort
          });
        }
      };
    });
    $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => {
      def.pattern ?? (def.pattern = emoji());
      $ZodStringFormat.init(inst, def);
    });
    $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => {
      def.pattern ?? (def.pattern = nanoid);
      $ZodStringFormat.init(inst, def);
    });
    $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => {
      def.pattern ?? (def.pattern = cuid);
      $ZodStringFormat.init(inst, def);
    });
    $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => {
      def.pattern ?? (def.pattern = cuid2);
      $ZodStringFormat.init(inst, def);
    });
    $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => {
      def.pattern ?? (def.pattern = ulid);
      $ZodStringFormat.init(inst, def);
    });
    $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => {
      def.pattern ?? (def.pattern = xid);
      $ZodStringFormat.init(inst, def);
    });
    $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => {
      def.pattern ?? (def.pattern = ksuid);
      $ZodStringFormat.init(inst, def);
    });
    $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => {
      def.pattern ?? (def.pattern = datetime(def));
      $ZodStringFormat.init(inst, def);
    });
    $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => {
      def.pattern ?? (def.pattern = date2);
      $ZodStringFormat.init(inst, def);
    });
    $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => {
      def.pattern ?? (def.pattern = time2(def));
      $ZodStringFormat.init(inst, def);
    });
    $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => {
      def.pattern ?? (def.pattern = duration);
      $ZodStringFormat.init(inst, def);
    });
    $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => {
      def.pattern ?? (def.pattern = ipv4);
      $ZodStringFormat.init(inst, def);
      inst._zod.onattach.push((inst2) => {
        const bag = inst2._zod.bag;
        bag.format = `ipv4`;
      });
    });
    $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => {
      def.pattern ?? (def.pattern = ipv6);
      $ZodStringFormat.init(inst, def);
      inst._zod.onattach.push((inst2) => {
        const bag = inst2._zod.bag;
        bag.format = `ipv6`;
      });
      inst._zod.check = (payload) => {
        try {
          new URL(`http://[${payload.value}]`);
        } catch {
          payload.issues.push({
            code: "invalid_format",
            format: "ipv6",
            input: payload.value,
            inst,
            continue: !def.abort
          });
        }
      };
    });
    $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => {
      def.pattern ?? (def.pattern = cidrv4);
      $ZodStringFormat.init(inst, def);
    });
    $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => {
      def.pattern ?? (def.pattern = cidrv6);
      $ZodStringFormat.init(inst, def);
      inst._zod.check = (payload) => {
        const [address, prefix] = payload.value.split("/");
        try {
          if (!prefix)
            throw new Error();
          const prefixNum = Number(prefix);
          if (`${prefixNum}` !== prefix)
            throw new Error();
          if (prefixNum < 0 || prefixNum > 128)
            throw new Error();
          new URL(`http://[${address}]`);
        } catch {
          payload.issues.push({
            code: "invalid_format",
            format: "cidrv6",
            input: payload.value,
            inst,
            continue: !def.abort
          });
        }
      };
    });
    $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
      def.pattern ?? (def.pattern = base64);
      $ZodStringFormat.init(inst, def);
      inst._zod.onattach.push((inst2) => {
        inst2._zod.bag.contentEncoding = "base64";
      });
      inst._zod.check = (payload) => {
        if (isValidBase64(payload.value))
          return;
        payload.issues.push({
          code: "invalid_format",
          format: "base64",
          input: payload.value,
          inst,
          continue: !def.abort
        });
      };
    });
    $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
      def.pattern ?? (def.pattern = base64url);
      $ZodStringFormat.init(inst, def);
      inst._zod.onattach.push((inst2) => {
        inst2._zod.bag.contentEncoding = "base64url";
      });
      inst._zod.check = (payload) => {
        if (isValidBase64URL(payload.value))
          return;
        payload.issues.push({
          code: "invalid_format",
          format: "base64url",
          input: payload.value,
          inst,
          continue: !def.abort
        });
      };
    });
    $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => {
      def.pattern ?? (def.pattern = e164);
      $ZodStringFormat.init(inst, def);
    });
    $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => {
      $ZodStringFormat.init(inst, def);
      inst._zod.check = (payload) => {
        if (isValidJWT2(payload.value, def.alg))
          return;
        payload.issues.push({
          code: "invalid_format",
          format: "jwt",
          input: payload.value,
          inst,
          continue: !def.abort
        });
      };
    });
    $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringFormat", (inst, def) => {
      $ZodStringFormat.init(inst, def);
      inst._zod.check = (payload) => {
        if (def.fn(payload.value))
          return;
        payload.issues.push({
          code: "invalid_format",
          format: def.format,
          input: payload.value,
          inst,
          continue: !def.abort
        });
      };
    });
    $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
      $ZodType.init(inst, def);
      inst._zod.pattern = inst._zod.bag.pattern ?? number;
      inst._zod.parse = (payload, _ctx) => {
        if (def.coerce)
          try {
            payload.value = Number(payload.value);
          } catch (_) {
          }
        const input = payload.value;
        if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) {
          return payload;
        }
        const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0;
        payload.issues.push({
          expected: "number",
          code: "invalid_type",
          input,
          inst,
          ...received ? { received } : {}
        });
        return payload;
      };
    });
    $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
      $ZodCheckNumberFormat.init(inst, def);
      $ZodNumber.init(inst, def);
    });
    $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => {
      $ZodType.init(inst, def);
      inst._zod.pattern = boolean2;
      inst._zod.parse = (payload, _ctx) => {
        if (def.coerce)
          try {
            payload.value = Boolean(payload.value);
          } catch (_) {
          }
        const input = payload.value;
        if (typeof input === "boolean")
          return payload;
        payload.issues.push({
          expected: "boolean",
          code: "invalid_type",
          input,
          inst
        });
        return payload;
      };
    });
    $ZodBigInt = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def) => {
      $ZodType.init(inst, def);
      inst._zod.pattern = bigint2;
      inst._zod.parse = (payload, _ctx) => {
        if (def.coerce)
          try {
            payload.value = BigInt(payload.value);
          } catch (_) {
          }
        if (typeof payload.value === "bigint")
          return payload;
        payload.issues.push({
          expected: "bigint",
          code: "invalid_type",
          input: payload.value,
          inst
        });
        return payload;
      };
    });
    $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def) => {
      $ZodCheckBigIntFormat.init(inst, def);
      $ZodBigInt.init(inst, def);
    });
    $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => {
      $ZodType.init(inst, def);
      inst._zod.parse = (payload, _ctx) => {
        const input = payload.value;
        if (typeof input === "symbol")
          return payload;
        payload.issues.push({
          expected: "symbol",
          code: "invalid_type",
          input,
          inst
        });
        return payload;
      };
    });
    $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => {
      $ZodType.init(inst, def);
      inst._zod.pattern = _undefined;
      inst._zod.values = /* @__PURE__ */ new Set([void 0]);
      inst._zod.optin = "optional";
      inst._zod.optout = "optional";
      inst._zod.parse = (payload, _ctx) => {
        const input = payload.value;
        if (typeof input === "undefined")
          return payload;
        payload.issues.push({
          expected: "undefined",
          code: "invalid_type",
          input,
          inst
        });
        return payload;
      };
    });
    $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => {
      $ZodType.init(inst, def);
      inst._zod.pattern = _null;
      inst._zod.values = /* @__PURE__ */ new Set([null]);
      inst._zod.parse = (payload, _ctx) => {
        const input = payload.value;
        if (input === null)
          return payload;
        payload.issues.push({
          expected: "null",
          code: "invalid_type",
          input,
          inst
        });
        return payload;
      };
    });
    $ZodAny = /* @__PURE__ */ $constructor("$ZodAny", (inst, def) => {
      $ZodType.init(inst, def);
      inst._zod.parse = (payload) => payload;
    });
    $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => {
      $ZodType.init(inst, def);
      inst._zod.parse = (payload) => payload;
    });
    $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => {
      $ZodType.init(inst, def);
      inst._zod.parse = (payload, _ctx) => {
        payload.issues.push({
          expected: "never",
          code: "invalid_type",
          input: payload.value,
          inst
        });
        return payload;
      };
    });
    $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => {
      $ZodType.init(inst, def);
      inst._zod.parse = (payload, _ctx) => {
        const input = payload.value;
        if (typeof input === "undefined")
          return payload;
        payload.issues.push({
          expected: "void",
          code: "invalid_type",
          input,
          inst
        });
        return payload;
      };
    });
    $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => {
      $ZodType.init(inst, def);
      inst._zod.parse = (payload, _ctx) => {
        if (def.coerce) {
          try {
            payload.value = new Date(payload.value);
          } catch (_err) {
          }
        }
        const input = payload.value;
        const isDate = input instanceof Date;
        const isValidDate = isDate && !Number.isNaN(input.getTime());
        if (isValidDate)
          return payload;
        payload.issues.push({
          expected: "date",
          code: "invalid_type",
          input,
          ...isDate ? { received: "Invalid Date" } : {},
          inst
        });
        return payload;
      };
    });
    $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
      $ZodType.init(inst, def);
      inst._zod.parse = (payload, ctx) => {
        const input = payload.value;
        if (!Array.isArray(input)) {
          payload.issues.push({
            expected: "array",
            code: "invalid_type",
            input,
            inst
          });
          return payload;
        }
        payload.value = Array(input.length);
        const proms = [];
        for (let i = 0; i < input.length; i++) {
          const item = input[i];
          const result = def.element._zod.run({
            value: item,
            issues: []
          }, ctx);
          if (result instanceof Promise) {
            proms.push(result.then((result2) => handleArrayResult(result2, payload, i)));
          } else {
            handleArrayResult(result, payload, i);
          }
        }
        if (proms.length) {
          return Promise.all(proms).then(() => payload);
        }
        return payload;
      };
    });
    $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
      $ZodType.init(inst, def);
      const _normalized = cached(() => {
        const keys = Object.keys(def.shape);
        for (const k of keys) {
          if (!(def.shape[k] instanceof $ZodType)) {
            throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
          }
        }
        const okeys = optionalKeys(def.shape);
        return {
          shape: def.shape,
          keys,
          keySet: new Set(keys),
          numKeys: keys.length,
          optionalKeys: new Set(okeys)
        };
      });
      defineLazy(inst._zod, "propValues", () => {
        const shape = def.shape;
        const propValues = {};
        for (const key in shape) {
          const field = shape[key]._zod;
          if (field.values) {
            propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set());
            for (const v of field.values)
              propValues[key].add(v);
          }
        }
        return propValues;
      });
      const generateFastpass = (shape) => {
        const doc = new Doc(["shape", "payload", "ctx"]);
        const normalized = _normalized.value;
        const parseStr = (key) => {
          const k = esc(key);
          return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
        };
        doc.write(`const input = payload.value;`);
        const ids = /* @__PURE__ */ Object.create(null);
        let counter = 0;
        for (const key of normalized.keys) {
          ids[key] = `key_${counter++}`;
        }
        doc.write(`const newResult = {}`);
        for (const key of normalized.keys) {
          if (normalized.optionalKeys.has(key)) {
            const id = ids[key];
            doc.write(`const ${id} = ${parseStr(key)};`);
            const k = esc(key);
            doc.write(`
        if (${id}.issues.length) {
          if (input[${k}] === undefined) {
            if (${k} in input) {
              newResult[${k}] = undefined;
            }
          } else {
            payload.issues = payload.issues.concat(
              ${id}.issues.map((iss) => ({
                ...iss,
                path: iss.path ? [${k}, ...iss.path] : [${k}],
              }))
            );
          }
        } else if (${id}.value === undefined) {
          if (${k} in input) newResult[${k}] = undefined;
        } else {
          newResult[${k}] = ${id}.value;
        }
        `);
          } else {
            const id = ids[key];
            doc.write(`const ${id} = ${parseStr(key)};`);
            doc.write(`
          if (${id}.issues.length) payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
            ...iss,
            path: iss.path ? [${esc(key)}, ...iss.path] : [${esc(key)}]
          })));`);
            doc.write(`newResult[${esc(key)}] = ${id}.value`);
          }
        }
        doc.write(`payload.value = newResult;`);
        doc.write(`return payload;`);
        const fn = doc.compile();
        return (payload, ctx) => fn(shape, payload, ctx);
      };
      let fastpass;
      const isObject3 = isObject;
      const jit = !globalConfig.jitless;
      const allowsEval2 = allowsEval;
      const fastEnabled = jit && allowsEval2.value;
      const catchall = def.catchall;
      let value;
      inst._zod.parse = (payload, ctx) => {
        value ?? (value = _normalized.value);
        const input = payload.value;
        if (!isObject3(input)) {
          payload.issues.push({
            expected: "object",
            code: "invalid_type",
            input,
            inst
          });
          return payload;
        }
        const proms = [];
        if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
          if (!fastpass)
            fastpass = generateFastpass(def.shape);
          payload = fastpass(payload, ctx);
        } else {
          payload.value = {};
          const shape = value.shape;
          for (const key of value.keys) {
            const el = shape[key];
            const r = el._zod.run({ value: input[key], issues: [] }, ctx);
            const isOptional = el._zod.optin === "optional" && el._zod.optout === "optional";
            if (r instanceof Promise) {
              proms.push(r.then((r2) => isOptional ? handleOptionalObjectResult(r2, payload, key, input) : handleObjectResult(r2, payload, key)));
            } else if (isOptional) {
              handleOptionalObjectResult(r, payload, key, input);
            } else {
              handleObjectResult(r, payload, key);
            }
          }
        }
        if (!catchall) {
          return proms.length ? Promise.all(proms).then(() => payload) : payload;
        }
        const unrecognized = [];
        const keySet = value.keySet;
        const _catchall = catchall._zod;
        const t = _catchall.def.type;
        for (const key of Object.keys(input)) {
          if (keySet.has(key))
            continue;
          if (t === "never") {
            unrecognized.push(key);
            continue;
          }
          const r = _catchall.run({ value: input[key], issues: [] }, ctx);
          if (r instanceof Promise) {
            proms.push(r.then((r2) => handleObjectResult(r2, payload, key)));
          } else {
            handleObjectResult(r, payload, key);
          }
        }
        if (unrecognized.length) {
          payload.issues.push({
            code: "unrecognized_keys",
            keys: unrecognized,
            input,
            inst
          });
        }
        if (!proms.length)
          return payload;
        return Promise.all(proms).then(() => {
          return payload;
        });
      };
    });
    $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {
      $ZodType.init(inst, def);
      defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0);
      defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0);
      defineLazy(inst._zod, "values", () => {
        if (def.options.every((o) => o._zod.values)) {
          return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));
        }
        return void 0;
      });
      defineLazy(inst._zod, "pattern", () => {
        if (def.options.every((o) => o._zod.pattern)) {
          const patterns = def.options.map((o) => o._zod.pattern);
          return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
        }
        return void 0;
      });
      inst._zod.parse = (payload, ctx) => {
        let async = false;
        const results = [];
        for (const option of def.options) {
          const result = option._zod.run({
            value: payload.value,
            issues: []
          }, ctx);
          if (result instanceof Promise) {
            results.push(result);
            async = true;
          } else {
            if (result.issues.length === 0)
              return result;
            results.push(result);
          }
        }
        if (!async)
          return handleUnionResults(results, payload, inst, ctx);
        return Promise.all(results).then((results2) => {
          return handleUnionResults(results2, payload, inst, ctx);
        });
      };
    });
    $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => {
      $ZodUnion.init(inst, def);
      const _super = inst._zod.parse;
      defineLazy(inst._zod, "propValues", () => {
        const propValues = {};
        for (const option of def.options) {
          const pv = option._zod.propValues;
          if (!pv || Object.keys(pv).length === 0)
            throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);
          for (const [k, v] of Object.entries(pv)) {
            if (!propValues[k])
              propValues[k] = /* @__PURE__ */ new Set();
            for (const val of v) {
              propValues[k].add(val);
            }
          }
        }
        return propValues;
      });
      const disc = cached(() => {
        const opts = def.options;
        const map2 = /* @__PURE__ */ new Map();
        for (const o of opts) {
          const values = o._zod.propValues[def.discriminator];
          if (!values || values.size === 0)
            throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);
          for (const v of values) {
            if (map2.has(v)) {
              throw new Error(`Duplicate discriminator value "${String(v)}"`);
            }
            map2.set(v, o);
          }
        }
        return map2;
      });
      inst._zod.parse = (payload, ctx) => {
        const input = payload.value;
        if (!isObject(input)) {
          payload.issues.push({
            code: "invalid_type",
            expected: "object",
            input,
            inst
          });
          return payload;
        }
        const opt = disc.value.get(input?.[def.discriminator]);
        if (opt) {
          return opt._zod.run(payload, ctx);
        }
        if (def.unionFallback) {
          return _super(payload, ctx);
        }
        payload.issues.push({
          code: "invalid_union",
          errors: [],
          note: "No matching discriminator",
          input,
          path: [def.discriminator],
          inst
        });
        return payload;
      };
    });
    $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => {
      $ZodType.init(inst, def);
      inst._zod.parse = (payload, ctx) => {
        const input = payload.value;
        const left = def.left._zod.run({ value: input, issues: [] }, ctx);
        const right = def.right._zod.run({ value: input, issues: [] }, ctx);
        const async = left instanceof Promise || right instanceof Promise;
        if (async) {
          return Promise.all([left, right]).then(([left2, right2]) => {
            return handleIntersectionResults(payload, left2, right2);
          });
        }
        return handleIntersectionResults(payload, left, right);
      };
    });
    $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => {
      $ZodType.init(inst, def);
      const items = def.items;
      const optStart = items.length - [...items].reverse().findIndex((item) => item._zod.optin !== "optional");
      inst._zod.parse = (payload, ctx) => {
        const input = payload.value;
        if (!Array.isArray(input)) {
          payload.issues.push({
            input,
            inst,
            expected: "tuple",
            code: "invalid_type"
          });
          return payload;
        }
        payload.value = [];
        const proms = [];
        if (!def.rest) {
          const tooBig = input.length > items.length;
          const tooSmall = input.length < optStart - 1;
          if (tooBig || tooSmall) {
            payload.issues.push({
              input,
              inst,
              origin: "array",
              ...tooBig ? { code: "too_big", maximum: items.length } : { code: "too_small", minimum: items.length }
            });
            return payload;
          }
        }
        let i = -1;
        for (const item of items) {
          i++;
          if (i >= input.length) {
            if (i >= optStart)
              continue;
          }
          const result = item._zod.run({
            value: input[i],
            issues: []
          }, ctx);
          if (result instanceof Promise) {
            proms.push(result.then((result2) => handleTupleResult(result2, payload, i)));
          } else {
            handleTupleResult(result, payload, i);
          }
        }
        if (def.rest) {
          const rest = input.slice(items.length);
          for (const el of rest) {
            i++;
            const result = def.rest._zod.run({
              value: el,
              issues: []
            }, ctx);
            if (result instanceof Promise) {
              proms.push(result.then((result2) => handleTupleResult(result2, payload, i)));
            } else {
              handleTupleResult(result, payload, i);
            }
          }
        }
        if (proms.length)
          return Promise.all(proms).then(() => payload);
        return payload;
      };
    });
    $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
      $ZodType.init(inst, def);
      inst._zod.parse = (payload, ctx) => {
        const input = payload.value;
        if (!isPlainObject(input)) {
          payload.issues.push({
            expected: "record",
            code: "invalid_type",
            input,
            inst
          });
          return payload;
        }
        const proms = [];
        if (def.keyType._zod.values) {
          const values = def.keyType._zod.values;
          payload.value = {};
          for (const key of values) {
            if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
              const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
              if (result instanceof Promise) {
                proms.push(result.then((result2) => {
                  if (result2.issues.length) {
                    payload.issues.push(...prefixIssues(key, result2.issues));
                  }
                  payload.value[key] = result2.value;
                }));
              } else {
                if (result.issues.length) {
                  payload.issues.push(...prefixIssues(key, result.issues));
                }
                payload.value[key] = result.value;
              }
            }
          }
          let unrecognized;
          for (const key in input) {
            if (!values.has(key)) {
              unrecognized = unrecognized ?? [];
              unrecognized.push(key);
            }
          }
          if (unrecognized && unrecognized.length > 0) {
            payload.issues.push({
              code: "unrecognized_keys",
              input,
              inst,
              keys: unrecognized
            });
          }
        } else {
          payload.value = {};
          for (const key of Reflect.ownKeys(input)) {
            if (key === "__proto__")
              continue;
            const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
            if (keyResult instanceof Promise) {
              throw new Error("Async schemas not supported in object keys currently");
            }
            if (keyResult.issues.length) {
              payload.issues.push({
                origin: "record",
                code: "invalid_key",
                issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
                input: key,
                path: [key],
                inst
              });
              payload.value[keyResult.value] = keyResult.value;
              continue;
            }
            const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
            if (result instanceof Promise) {
              proms.push(result.then((result2) => {
                if (result2.issues.length) {
                  payload.issues.push(...prefixIssues(key, result2.issues));
                }
                payload.value[keyResult.value] = result2.value;
              }));
            } else {
              if (result.issues.length) {
                payload.issues.push(...prefixIssues(key, result.issues));
              }
              payload.value[keyResult.value] = result.value;
            }
          }
        }
        if (proms.length) {
          return Promise.all(proms).then(() => payload);
        }
        return payload;
      };
    });
    $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => {
      $ZodType.init(inst, def);
      inst._zod.parse = (payload, ctx) => {
        const input = payload.value;
        if (!(input instanceof Map)) {
          payload.issues.push({
            expected: "map",
            code: "invalid_type",
            input,
            inst
          });
          return payload;
        }
        const proms = [];
        payload.value = /* @__PURE__ */ new Map();
        for (const [key, value] of input) {
          const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
          const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx);
          if (keyResult instanceof Promise || valueResult instanceof Promise) {
            proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => {
              handleMapResult(keyResult2, valueResult2, payload, key, input, inst, ctx);
            }));
          } else {
            handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);
          }
        }
        if (proms.length)
          return Promise.all(proms).then(() => payload);
        return payload;
      };
    });
    $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => {
      $ZodType.init(inst, def);
      inst._zod.parse = (payload, ctx) => {
        const input = payload.value;
        if (!(input instanceof Set)) {
          payload.issues.push({
            input,
            inst,
            expected: "set",
            code: "invalid_type"
          });
          return payload;
        }
        const proms = [];
        payload.value = /* @__PURE__ */ new Set();
        for (const item of input) {
          const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);
          if (result instanceof Promise) {
            proms.push(result.then((result2) => handleSetResult(result2, payload)));
          } else
            handleSetResult(result, payload);
        }
        if (proms.length)
          return Promise.all(proms).then(() => payload);
        return payload;
      };
    });
    $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
      $ZodType.init(inst, def);
      const values = getEnumValues(def.entries);
      inst._zod.values = new Set(values);
      inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`);
      inst._zod.parse = (payload, _ctx) => {
        const input = payload.value;
        if (inst._zod.values.has(input)) {
          return payload;
        }
        payload.issues.push({
          code: "invalid_value",
          values,
          input,
          inst
        });
        return payload;
      };
    });
    $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
      $ZodType.init(inst, def);
      inst._zod.values = new Set(def.values);
      inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? o.toString() : String(o)).join("|")})$`);
      inst._zod.parse = (payload, _ctx) => {
        const input = payload.value;
        if (inst._zod.values.has(input)) {
          return payload;
        }
        payload.issues.push({
          code: "invalid_value",
          values: def.values,
          input,
          inst
        });
        return payload;
      };
    });
    $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => {
      $ZodType.init(inst, def);
      inst._zod.parse = (payload, _ctx) => {
        const input = payload.value;
        if (input instanceof File)
          return payload;
        payload.issues.push({
          expected: "file",
          code: "invalid_type",
          input,
          inst
        });
        return payload;
      };
    });
    $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => {
      $ZodType.init(inst, def);
      inst._zod.parse = (payload, _ctx) => {
        const _out = def.transform(payload.value, payload);
        if (_ctx.async) {
          const output = _out instanceof Promise ? _out : Promise.resolve(_out);
          return output.then((output2) => {
            payload.value = output2;
            return payload;
          });
        }
        if (_out instanceof Promise) {
          throw new $ZodAsyncError();
        }
        payload.value = _out;
        return payload;
      };
    });
    $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => {
      $ZodType.init(inst, def);
      inst._zod.optin = "optional";
      inst._zod.optout = "optional";
      defineLazy(inst._zod, "values", () => {
        return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0;
      });
      defineLazy(inst._zod, "pattern", () => {
        const pattern = def.innerType._zod.pattern;
        return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0;
      });
      inst._zod.parse = (payload, ctx) => {
        if (def.innerType._zod.optin === "optional") {
          return def.innerType._zod.run(payload, ctx);
        }
        if (payload.value === void 0) {
          return payload;
        }
        return def.innerType._zod.run(payload, ctx);
      };
    });
    $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => {
      $ZodType.init(inst, def);
      defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
      defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
      defineLazy(inst._zod, "pattern", () => {
        const pattern = def.innerType._zod.pattern;
        return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0;
      });
      defineLazy(inst._zod, "values", () => {
        return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0;
      });
      inst._zod.parse = (payload, ctx) => {
        if (payload.value === null)
          return payload;
        return def.innerType._zod.run(payload, ctx);
      };
    });
    $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => {
      $ZodType.init(inst, def);
      inst._zod.optin = "optional";
      defineLazy(inst._zod, "values", () => def.innerType._zod.values);
      inst._zod.parse = (payload, ctx) => {
        if (payload.value === void 0) {
          payload.value = def.defaultValue;
          return payload;
        }
        const result = def.innerType._zod.run(payload, ctx);
        if (result instanceof Promise) {
          return result.then((result2) => handleDefaultResult(result2, def));
        }
        return handleDefaultResult(result, def);
      };
    });
    $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => {
      $ZodType.init(inst, def);
      inst._zod.optin = "optional";
      defineLazy(inst._zod, "values", () => def.innerType._zod.values);
      inst._zod.parse = (payload, ctx) => {
        if (payload.value === void 0) {
          payload.value = def.defaultValue;
        }
        return def.innerType._zod.run(payload, ctx);
      };
    });
    $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => {
      $ZodType.init(inst, def);
      defineLazy(inst._zod, "values", () => {
        const v = def.innerType._zod.values;
        return v ? new Set([...v].filter((x) => x !== void 0)) : void 0;
      });
      inst._zod.parse = (payload, ctx) => {
        const result = def.innerType._zod.run(payload, ctx);
        if (result instanceof Promise) {
          return result.then((result2) => handleNonOptionalResult(result2, inst));
        }
        return handleNonOptionalResult(result, inst);
      };
    });
    $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => {
      $ZodType.init(inst, def);
      inst._zod.parse = (payload, ctx) => {
        const result = def.innerType._zod.run(payload, ctx);
        if (result instanceof Promise) {
          return result.then((result2) => {
            payload.value = result2.issues.length === 0;
            return payload;
          });
        }
        payload.value = result.issues.length === 0;
        return payload;
      };
    });
    $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => {
      $ZodType.init(inst, def);
      inst._zod.optin = "optional";
      defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
      defineLazy(inst._zod, "values", () => def.innerType._zod.values);
      inst._zod.parse = (payload, ctx) => {
        const result = def.innerType._zod.run(payload, ctx);
        if (result instanceof Promise) {
          return result.then((result2) => {
            payload.value = result2.value;
            if (result2.issues.length) {
              payload.value = def.catchValue({
                ...payload,
                error: {
                  issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config()))
                },
                input: payload.value
              });
              payload.issues = [];
            }
            return payload;
          });
        }
        payload.value = result.value;
        if (result.issues.length) {
          payload.value = def.catchValue({
            ...payload,
            error: {
              issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config()))
            },
            input: payload.value
          });
          payload.issues = [];
        }
        return payload;
      };
    });
    $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => {
      $ZodType.init(inst, def);
      inst._zod.parse = (payload, _ctx) => {
        if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) {
          payload.issues.push({
            input: payload.value,
            inst,
            expected: "nan",
            code: "invalid_type"
          });
          return payload;
        }
        return payload;
      };
    });
    $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => {
      $ZodType.init(inst, def);
      defineLazy(inst._zod, "values", () => def.in._zod.values);
      defineLazy(inst._zod, "optin", () => def.in._zod.optin);
      defineLazy(inst._zod, "optout", () => def.out._zod.optout);
      inst._zod.parse = (payload, ctx) => {
        const left = def.in._zod.run(payload, ctx);
        if (left instanceof Promise) {
          return left.then((left2) => handlePipeResult(left2, def, ctx));
        }
        return handlePipeResult(left, def, ctx);
      };
    });
    $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => {
      $ZodType.init(inst, def);
      defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
      defineLazy(inst._zod, "values", () => def.innerType._zod.values);
      defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
      defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
      inst._zod.parse = (payload, ctx) => {
        const result = def.innerType._zod.run(payload, ctx);
        if (result instanceof Promise) {
          return result.then(handleReadonlyResult);
        }
        return handleReadonlyResult(result);
      };
    });
    $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => {
      $ZodType.init(inst, def);
      const regexParts = [];
      for (const part of def.parts) {
        if (part instanceof $ZodType) {
          if (!part._zod.pattern) {
            throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);
          }
          const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;
          if (!source)
            throw new Error(`Invalid template literal part: ${part._zod.traits}`);
          const start = source.startsWith("^") ? 1 : 0;
          const end = source.endsWith("$") ? source.length - 1 : source.length;
          regexParts.push(source.slice(start, end));
        } else if (part === null || primitiveTypes.has(typeof part)) {
          regexParts.push(escapeRegex(`${part}`));
        } else {
          throw new Error(`Invalid template literal part: ${part}`);
        }
      }
      inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`);
      inst._zod.parse = (payload, _ctx) => {
        if (typeof payload.value !== "string") {
          payload.issues.push({
            input: payload.value,
            inst,
            expected: "template_literal",
            code: "invalid_type"
          });
          return payload;
        }
        inst._zod.pattern.lastIndex = 0;
        if (!inst._zod.pattern.test(payload.value)) {
          payload.issues.push({
            input: payload.value,
            inst,
            code: "invalid_format",
            format: "template_literal",
            pattern: inst._zod.pattern.source
          });
          return payload;
        }
        return payload;
      };
    });
    $ZodPromise = /* @__PURE__ */ $constructor("$ZodPromise", (inst, def) => {
      $ZodType.init(inst, def);
      inst._zod.parse = (payload, ctx) => {
        return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));
      };
    });
    $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => {
      $ZodType.init(inst, def);
      defineLazy(inst._zod, "innerType", () => def.getter());
      defineLazy(inst._zod, "pattern", () => inst._zod.innerType._zod.pattern);
      defineLazy(inst._zod, "propValues", () => inst._zod.innerType._zod.propValues);
      defineLazy(inst._zod, "optin", () => inst._zod.innerType._zod.optin);
      defineLazy(inst._zod, "optout", () => inst._zod.innerType._zod.optout);
      inst._zod.parse = (payload, ctx) => {
        const inner = inst._zod.innerType;
        return inner._zod.run(payload, ctx);
      };
    });
    $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => {
      $ZodCheck.init(inst, def);
      $ZodType.init(inst, def);
      inst._zod.parse = (payload, _) => {
        return payload;
      };
      inst._zod.check = (payload) => {
        const input = payload.value;
        const r = def.fn(input);
        if (r instanceof Promise) {
          return r.then((r2) => handleRefineResult(r2, payload, input, inst));
        }
        handleRefineResult(r, payload, input, inst);
        return;
      };
    });
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ar.js
function ar_default() {
  return {
    localeError: error()
  };
}
var error;
var init_ar = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ar.js"() {
    init_util2();
    error = () => {
      const Sizable = {
        string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" },
        file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" },
        array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" },
        set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "number";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "array";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "\u0645\u062F\u062E\u0644",
        email: "\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A",
        url: "\u0631\u0627\u0628\u0637",
        emoji: "\u0625\u064A\u0645\u0648\u062C\u064A",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",
        date: "\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO",
        time: "\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",
        duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO",
        ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4",
        ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6",
        cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4",
        cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6",
        base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded",
        base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded",
        json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON",
        e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164",
        jwt: "JWT",
        template_literal: "\u0645\u062F\u062E\u0644"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${issue2.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${stringifyPrimitive(issue2.values[0])}`;
            return `\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return ` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"}`;
            return `\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${issue2.prefix}"`;
            if (_issue.format === "ends_with")
              return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${_issue.pattern}`;
            return `${Nouns[_issue.format] ?? issue2.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`;
          }
          case "not_multiple_of":
            return `\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${issue2.divisor}`;
          case "unrecognized_keys":
            return `\u0645\u0639\u0631\u0641${issue2.keys.length > 1 ? "\u0627\u062A" : ""} \u063A\u0631\u064A\u0628${issue2.keys.length > 1 ? "\u0629" : ""}: ${joinValues(issue2.keys, "\u060C ")}`;
          case "invalid_key":
            return `\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`;
          case "invalid_union":
            return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";
          case "invalid_element":
            return `\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`;
          default:
            return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/az.js
function az_default() {
  return {
    localeError: error2()
  };
}
var error2;
var init_az = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/az.js"() {
    init_util2();
    error2 = () => {
      const Sizable = {
        string: { unit: "simvol", verb: "olmal\u0131d\u0131r" },
        file: { unit: "bayt", verb: "olmal\u0131d\u0131r" },
        array: { unit: "element", verb: "olmal\u0131d\u0131r" },
        set: { unit: "element", verb: "olmal\u0131d\u0131r" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "number";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "array";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "input",
        email: "email address",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO datetime",
        date: "ISO date",
        time: "ISO time",
        duration: "ISO duration",
        ipv4: "IPv4 address",
        ipv6: "IPv6 address",
        cidrv4: "IPv4 range",
        cidrv6: "IPv6 range",
        base64: "base64-encoded string",
        base64url: "base64url-encoded string",
        json_string: "JSON string",
        e164: "E.164 number",
        jwt: "JWT",
        template_literal: "input"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${issue2.expected}, daxil olan ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${stringifyPrimitive(issue2.values[0])}`;
            return `Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`;
            return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `Yanl\u0131\u015F m\u0259tn: "${_issue.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`;
            if (_issue.format === "ends_with")
              return `Yanl\u0131\u015F m\u0259tn: "${_issue.suffix}" il\u0259 bitm\u0259lidir`;
            if (_issue.format === "includes")
              return `Yanl\u0131\u015F m\u0259tn: "${_issue.includes}" daxil olmal\u0131d\u0131r`;
            if (_issue.format === "regex")
              return `Yanl\u0131\u015F m\u0259tn: ${_issue.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`;
            return `Yanl\u0131\u015F ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `Yanl\u0131\u015F \u0259d\u0259d: ${issue2.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;
          case "unrecognized_keys":
            return `Tan\u0131nmayan a\xE7ar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;
          case "invalid_union":
            return "Yanl\u0131\u015F d\u0259y\u0259r";
          case "invalid_element":
            return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;
          default:
            return `Yanl\u0131\u015F d\u0259y\u0259r`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/be.js
function getBelarusianPlural(count3, one, few, many) {
  const absCount = Math.abs(count3);
  const lastDigit = absCount % 10;
  const lastTwoDigits = absCount % 100;
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
    return many;
  }
  if (lastDigit === 1) {
    return one;
  }
  if (lastDigit >= 2 && lastDigit <= 4) {
    return few;
  }
  return many;
}
function be_default() {
  return {
    localeError: error3()
  };
}
var error3;
var init_be = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/be.js"() {
    init_util2();
    error3 = () => {
      const Sizable = {
        string: {
          unit: {
            one: "\u0441\u0456\u043C\u0432\u0430\u043B",
            few: "\u0441\u0456\u043C\u0432\u0430\u043B\u044B",
            many: "\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E"
          },
          verb: "\u043C\u0435\u0446\u044C"
        },
        array: {
          unit: {
            one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442",
            few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",
            many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"
          },
          verb: "\u043C\u0435\u0446\u044C"
        },
        set: {
          unit: {
            one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442",
            few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",
            many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"
          },
          verb: "\u043C\u0435\u0446\u044C"
        },
        file: {
          unit: {
            one: "\u0431\u0430\u0439\u0442",
            few: "\u0431\u0430\u0439\u0442\u044B",
            many: "\u0431\u0430\u0439\u0442\u0430\u045E"
          },
          verb: "\u043C\u0435\u0446\u044C"
        }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "\u043B\u0456\u043A";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "\u043C\u0430\u0441\u0456\u045E";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "\u0443\u0432\u043E\u0434",
        email: "email \u0430\u0434\u0440\u0430\u0441",
        url: "URL",
        emoji: "\u044D\u043C\u043E\u0434\u0437\u0456",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441",
        date: "ISO \u0434\u0430\u0442\u0430",
        time: "ISO \u0447\u0430\u0441",
        duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C",
        ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441",
        ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441",
        cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",
        cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",
        base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64",
        base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url",
        json_string: "JSON \u0440\u0430\u0434\u043E\u043A",
        e164: "\u043D\u0443\u043C\u0430\u0440 E.164",
        jwt: "JWT",
        template_literal: "\u0443\u0432\u043E\u0434"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${issue2.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`;
            return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              const maxValue = Number(issue2.maximum);
              const unit = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
              return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.maximum.toString()} ${unit}`;
            }
            return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              const minValue = Number(issue2.minimum);
              const unit = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
              return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.minimum.toString()} ${unit}`;
            }
            return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`;
            return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`;
          case "unrecognized_keys":
            return `\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${issue2.keys.length > 1 ? "\u043A\u043B\u044E\u0447\u044B" : "\u043A\u043B\u044E\u0447"}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`;
          case "invalid_union":
            return "\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434";
          case "invalid_element":
            return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${issue2.origin}`;
          default:
            return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ca.js
function ca_default() {
  return {
    localeError: error4()
  };
}
var error4;
var init_ca = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ca.js"() {
    init_util2();
    error4 = () => {
      const Sizable = {
        string: { unit: "car\xE0cters", verb: "contenir" },
        file: { unit: "bytes", verb: "contenir" },
        array: { unit: "elements", verb: "contenir" },
        set: { unit: "elements", verb: "contenir" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "number";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "array";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "entrada",
        email: "adre\xE7a electr\xF2nica",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "data i hora ISO",
        date: "data ISO",
        time: "hora ISO",
        duration: "durada ISO",
        ipv4: "adre\xE7a IPv4",
        ipv6: "adre\xE7a IPv6",
        cidrv4: "rang IPv4",
        cidrv6: "rang IPv6",
        base64: "cadena codificada en base64",
        base64url: "cadena codificada en base64url",
        json_string: "cadena JSON",
        e164: "n\xFAmero E.164",
        jwt: "JWT",
        template_literal: "entrada"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Tipus inv\xE0lid: s'esperava ${issue2.expected}, s'ha rebut ${parsedType4(issue2.input)}`;
          // return `Tipus invàlid: s'esperava ${issue.expected}, s'ha rebut ${util.getParsedType(issue.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Valor inv\xE0lid: s'esperava ${stringifyPrimitive(issue2.values[0])}`;
            return `Opci\xF3 inv\xE0lida: s'esperava una de ${joinValues(issue2.values, " o ")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "com a m\xE0xim" : "menys de";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} contingu\xE9s ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`;
            return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} fos ${adj} ${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? "com a m\xEDnim" : "m\xE9s de";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Massa petit: s'esperava que ${issue2.origin} contingu\xE9s ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `Massa petit: s'esperava que ${issue2.origin} fos ${adj} ${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with") {
              return `Format inv\xE0lid: ha de comen\xE7ar amb "${_issue.prefix}"`;
            }
            if (_issue.format === "ends_with")
              return `Format inv\xE0lid: ha d'acabar amb "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `Format inv\xE0lid: ha d'incloure "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${_issue.pattern}`;
            return `Format inv\xE0lid per a ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${issue2.divisor}`;
          case "unrecognized_keys":
            return `Clau${issue2.keys.length > 1 ? "s" : ""} no reconeguda${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Clau inv\xE0lida a ${issue2.origin}`;
          case "invalid_union":
            return "Entrada inv\xE0lida";
          // Could also be "Tipus d'unió invàlid" but "Entrada invàlida" is more general
          case "invalid_element":
            return `Element inv\xE0lid a ${issue2.origin}`;
          default:
            return `Entrada inv\xE0lida`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/cs.js
function cs_default() {
  return {
    localeError: error5()
  };
}
var error5;
var init_cs = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/cs.js"() {
    init_util2();
    error5 = () => {
      const Sizable = {
        string: { unit: "znak\u016F", verb: "m\xEDt" },
        file: { unit: "bajt\u016F", verb: "m\xEDt" },
        array: { unit: "prvk\u016F", verb: "m\xEDt" },
        set: { unit: "prvk\u016F", verb: "m\xEDt" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "\u010D\xEDslo";
          }
          case "string": {
            return "\u0159et\u011Bzec";
          }
          case "boolean": {
            return "boolean";
          }
          case "bigint": {
            return "bigint";
          }
          case "function": {
            return "funkce";
          }
          case "symbol": {
            return "symbol";
          }
          case "undefined": {
            return "undefined";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "pole";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "regul\xE1rn\xED v\xFDraz",
        email: "e-mailov\xE1 adresa",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "datum a \u010Das ve form\xE1tu ISO",
        date: "datum ve form\xE1tu ISO",
        time: "\u010Das ve form\xE1tu ISO",
        duration: "doba trv\xE1n\xED ISO",
        ipv4: "IPv4 adresa",
        ipv6: "IPv6 adresa",
        cidrv4: "rozsah IPv4",
        cidrv6: "rozsah IPv6",
        base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64",
        base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url",
        json_string: "\u0159et\u011Bzec ve form\xE1tu JSON",
        e164: "\u010D\xEDslo E.164",
        jwt: "JWT",
        template_literal: "vstup"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${issue2.expected}, obdr\u017Eeno ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${stringifyPrimitive(issue2.values[0])}`;
            return `Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "prvk\u016F"}`;
            }
            return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "prvk\u016F"}`;
            }
            return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${_issue.pattern}`;
            return `Neplatn\xFD form\xE1t ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${issue2.divisor}`;
          case "unrecognized_keys":
            return `Nezn\xE1m\xE9 kl\xED\u010De: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Neplatn\xFD kl\xED\u010D v ${issue2.origin}`;
          case "invalid_union":
            return "Neplatn\xFD vstup";
          case "invalid_element":
            return `Neplatn\xE1 hodnota v ${issue2.origin}`;
          default:
            return `Neplatn\xFD vstup`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/de.js
function de_default() {
  return {
    localeError: error6()
  };
}
var error6;
var init_de = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/de.js"() {
    init_util2();
    error6 = () => {
      const Sizable = {
        string: { unit: "Zeichen", verb: "zu haben" },
        file: { unit: "Bytes", verb: "zu haben" },
        array: { unit: "Elemente", verb: "zu haben" },
        set: { unit: "Elemente", verb: "zu haben" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "Zahl";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "Array";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "Eingabe",
        email: "E-Mail-Adresse",
        url: "URL",
        emoji: "Emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO-Datum und -Uhrzeit",
        date: "ISO-Datum",
        time: "ISO-Uhrzeit",
        duration: "ISO-Dauer",
        ipv4: "IPv4-Adresse",
        ipv6: "IPv6-Adresse",
        cidrv4: "IPv4-Bereich",
        cidrv6: "IPv6-Bereich",
        base64: "Base64-codierter String",
        base64url: "Base64-URL-codierter String",
        json_string: "JSON-String",
        e164: "E.164-Nummer",
        jwt: "JWT",
        template_literal: "Eingabe"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Ung\xFCltige Eingabe: erwartet ${issue2.expected}, erhalten ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Ung\xFCltige Eingabe: erwartet ${stringifyPrimitive(issue2.values[0])}`;
            return `Ung\xFCltige Option: erwartet eine von ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `Zu gro\xDF: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "Elemente"} hat`;
            return `Zu gro\xDF: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ist`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} hat`;
            }
            return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ist`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `Ung\xFCltiger String: muss mit "${_issue.prefix}" beginnen`;
            if (_issue.format === "ends_with")
              return `Ung\xFCltiger String: muss mit "${_issue.suffix}" enden`;
            if (_issue.format === "includes")
              return `Ung\xFCltiger String: muss "${_issue.includes}" enthalten`;
            if (_issue.format === "regex")
              return `Ung\xFCltiger String: muss dem Muster ${_issue.pattern} entsprechen`;
            return `Ung\xFCltig: ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `Ung\xFCltige Zahl: muss ein Vielfaches von ${issue2.divisor} sein`;
          case "unrecognized_keys":
            return `${issue2.keys.length > 1 ? "Unbekannte Schl\xFCssel" : "Unbekannter Schl\xFCssel"}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Ung\xFCltiger Schl\xFCssel in ${issue2.origin}`;
          case "invalid_union":
            return "Ung\xFCltige Eingabe";
          case "invalid_element":
            return `Ung\xFCltiger Wert in ${issue2.origin}`;
          default:
            return `Ung\xFCltige Eingabe`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/en.js
function en_default2() {
  return {
    localeError: error7()
  };
}
var parsedType, error7;
var init_en2 = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/en.js"() {
    init_util2();
    parsedType = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "number";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "array";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    error7 = () => {
      const Sizable = {
        string: { unit: "characters", verb: "to have" },
        file: { unit: "bytes", verb: "to have" },
        array: { unit: "items", verb: "to have" },
        set: { unit: "items", verb: "to have" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const Nouns = {
        regex: "input",
        email: "email address",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO datetime",
        date: "ISO date",
        time: "ISO time",
        duration: "ISO duration",
        ipv4: "IPv4 address",
        ipv6: "IPv6 address",
        cidrv4: "IPv4 range",
        cidrv6: "IPv6 range",
        base64: "base64-encoded string",
        base64url: "base64url-encoded string",
        json_string: "JSON string",
        e164: "E.164 number",
        jwt: "JWT",
        template_literal: "input"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Invalid input: expected ${issue2.expected}, received ${parsedType(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`;
            return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`;
            return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with") {
              return `Invalid string: must start with "${_issue.prefix}"`;
            }
            if (_issue.format === "ends_with")
              return `Invalid string: must end with "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `Invalid string: must include "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `Invalid string: must match pattern ${_issue.pattern}`;
            return `Invalid ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `Invalid number: must be a multiple of ${issue2.divisor}`;
          case "unrecognized_keys":
            return `Unrecognized key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Invalid key in ${issue2.origin}`;
          case "invalid_union":
            return "Invalid input";
          case "invalid_element":
            return `Invalid value in ${issue2.origin}`;
          default:
            return `Invalid input`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/eo.js
function eo_default() {
  return {
    localeError: error8()
  };
}
var parsedType2, error8;
var init_eo = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/eo.js"() {
    init_util2();
    parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "nombro";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "tabelo";
          }
          if (data === null) {
            return "senvalora";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    error8 = () => {
      const Sizable = {
        string: { unit: "karaktrojn", verb: "havi" },
        file: { unit: "bajtojn", verb: "havi" },
        array: { unit: "elementojn", verb: "havi" },
        set: { unit: "elementojn", verb: "havi" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const Nouns = {
        regex: "enigo",
        email: "retadreso",
        url: "URL",
        emoji: "emo\u011Dio",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO-datotempo",
        date: "ISO-dato",
        time: "ISO-tempo",
        duration: "ISO-da\u016Dro",
        ipv4: "IPv4-adreso",
        ipv6: "IPv6-adreso",
        cidrv4: "IPv4-rango",
        cidrv6: "IPv6-rango",
        base64: "64-ume kodita karaktraro",
        base64url: "URL-64-ume kodita karaktraro",
        json_string: "JSON-karaktraro",
        e164: "E.164-nombro",
        jwt: "JWT",
        template_literal: "enigo"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Nevalida enigo: atendi\u011Dis ${issue2.expected}, ricevi\u011Dis ${parsedType2(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Nevalida enigo: atendi\u011Dis ${stringifyPrimitive(issue2.values[0])}`;
            return `Nevalida opcio: atendi\u011Dis unu el ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementojn"}`;
            return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} havu ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} estu ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `Nevalida karaktraro: devas komenci\u011Di per "${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `Nevalida karaktraro: devas fini\u011Di per "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`;
            return `Nevalida ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `Nevalida nombro: devas esti oblo de ${issue2.divisor}`;
          case "unrecognized_keys":
            return `Nekonata${issue2.keys.length > 1 ? "j" : ""} \u015Dlosilo${issue2.keys.length > 1 ? "j" : ""}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Nevalida \u015Dlosilo en ${issue2.origin}`;
          case "invalid_union":
            return "Nevalida enigo";
          case "invalid_element":
            return `Nevalida valoro en ${issue2.origin}`;
          default:
            return `Nevalida enigo`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/es.js
function es_default() {
  return {
    localeError: error9()
  };
}
var error9;
var init_es = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/es.js"() {
    init_util2();
    error9 = () => {
      const Sizable = {
        string: { unit: "caracteres", verb: "tener" },
        file: { unit: "bytes", verb: "tener" },
        array: { unit: "elementos", verb: "tener" },
        set: { unit: "elementos", verb: "tener" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "n\xFAmero";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "arreglo";
            }
            if (data === null) {
              return "nulo";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "entrada",
        email: "direcci\xF3n de correo electr\xF3nico",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "fecha y hora ISO",
        date: "fecha ISO",
        time: "hora ISO",
        duration: "duraci\xF3n ISO",
        ipv4: "direcci\xF3n IPv4",
        ipv6: "direcci\xF3n IPv6",
        cidrv4: "rango IPv4",
        cidrv6: "rango IPv6",
        base64: "cadena codificada en base64",
        base64url: "URL codificada en base64",
        json_string: "cadena JSON",
        e164: "n\xFAmero E.164",
        jwt: "JWT",
        template_literal: "entrada"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Entrada inv\xE1lida: se esperaba ${issue2.expected}, recibido ${parsedType4(issue2.input)}`;
          // return `Entrada inválida: se esperaba ${issue.expected}, recibido ${util.getParsedType(issue.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Entrada inv\xE1lida: se esperaba ${stringifyPrimitive(issue2.values[0])}`;
            return `Opci\xF3n inv\xE1lida: se esperaba una de ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `Demasiado grande: se esperaba que ${issue2.origin ?? "valor"} tuviera ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`;
            return `Demasiado grande: se esperaba que ${issue2.origin ?? "valor"} fuera ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Demasiado peque\xF1o: se esperaba que ${issue2.origin} tuviera ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `Demasiado peque\xF1o: se esperaba que ${issue2.origin} fuera ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `Cadena inv\xE1lida: debe comenzar con "${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `Cadena inv\xE1lida: debe terminar en "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `Cadena inv\xE1lida: debe incluir "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${_issue.pattern}`;
            return `Inv\xE1lido ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${issue2.divisor}`;
          case "unrecognized_keys":
            return `Llave${issue2.keys.length > 1 ? "s" : ""} desconocida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Llave inv\xE1lida en ${issue2.origin}`;
          case "invalid_union":
            return "Entrada inv\xE1lida";
          case "invalid_element":
            return `Valor inv\xE1lido en ${issue2.origin}`;
          default:
            return `Entrada inv\xE1lida`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/fa.js
function fa_default() {
  return {
    localeError: error10()
  };
}
var error10;
var init_fa = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/fa.js"() {
    init_util2();
    error10 = () => {
      const Sizable = {
        string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" },
        file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" },
        array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" },
        set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "\u0639\u062F\u062F";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "\u0622\u0631\u0627\u06CC\u0647";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "\u0648\u0631\u0648\u062F\u06CC",
        email: "\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644",
        url: "URL",
        emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",
        date: "\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648",
        time: "\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",
        duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",
        ipv4: "IPv4 \u0622\u062F\u0631\u0633",
        ipv6: "IPv6 \u0622\u062F\u0631\u0633",
        cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647",
        cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647",
        base64: "base64-encoded \u0631\u0634\u062A\u0647",
        base64url: "base64url-encoded \u0631\u0634\u062A\u0647",
        json_string: "JSON \u0631\u0634\u062A\u0647",
        e164: "E.164 \u0639\u062F\u062F",
        jwt: "JWT",
        template_literal: "\u0648\u0631\u0648\u062F\u06CC"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${issue2.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${parsedType4(issue2.input)} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`;
          case "invalid_value":
            if (issue2.values.length === 1) {
              return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${stringifyPrimitive(issue2.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`;
            }
            return `\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${joinValues(issue2.values, "|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`;
            }
            return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0628\u0627\u0634\u062F`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0628\u0627\u0634\u062F`;
            }
            return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0628\u0627\u0634\u062F`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with") {
              return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`;
            }
            if (_issue.format === "ends_with") {
              return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`;
            }
            if (_issue.format === "includes") {
              return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${_issue.includes}" \u0628\u0627\u0634\u062F`;
            }
            if (_issue.format === "regex") {
              return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${_issue.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`;
            }
            return `${Nouns[_issue.format] ?? issue2.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`;
          }
          case "not_multiple_of":
            return `\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${issue2.divisor} \u0628\u0627\u0634\u062F`;
          case "unrecognized_keys":
            return `\u06A9\u0644\u06CC\u062F${issue2.keys.length > 1 ? "\u0647\u0627\u06CC" : ""} \u0646\u0627\u0634\u0646\u0627\u0633: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${issue2.origin}`;
          case "invalid_union":
            return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`;
          case "invalid_element":
            return `\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${issue2.origin}`;
          default:
            return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/fi.js
function fi_default() {
  return {
    localeError: error11()
  };
}
var error11;
var init_fi = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/fi.js"() {
    init_util2();
    error11 = () => {
      const Sizable = {
        string: { unit: "merkki\xE4", subject: "merkkijonon" },
        file: { unit: "tavua", subject: "tiedoston" },
        array: { unit: "alkiota", subject: "listan" },
        set: { unit: "alkiota", subject: "joukon" },
        number: { unit: "", subject: "luvun" },
        bigint: { unit: "", subject: "suuren kokonaisluvun" },
        int: { unit: "", subject: "kokonaisluvun" },
        date: { unit: "", subject: "p\xE4iv\xE4m\xE4\xE4r\xE4n" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "number";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "array";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "s\xE4\xE4nn\xF6llinen lauseke",
        email: "s\xE4hk\xF6postiosoite",
        url: "URL-osoite",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO-aikaleima",
        date: "ISO-p\xE4iv\xE4m\xE4\xE4r\xE4",
        time: "ISO-aika",
        duration: "ISO-kesto",
        ipv4: "IPv4-osoite",
        ipv6: "IPv6-osoite",
        cidrv4: "IPv4-alue",
        cidrv6: "IPv6-alue",
        base64: "base64-koodattu merkkijono",
        base64url: "base64url-koodattu merkkijono",
        json_string: "JSON-merkkijono",
        e164: "E.164-luku",
        jwt: "JWT",
        template_literal: "templaattimerkkijono"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Virheellinen tyyppi: odotettiin ${issue2.expected}, oli ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Virheellinen sy\xF6te: t\xE4ytyy olla ${stringifyPrimitive(issue2.values[0])}`;
            return `Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Liian suuri: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.maximum.toString()} ${sizing.unit}`.trim();
            }
            return `Liian suuri: arvon t\xE4ytyy olla ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Liian pieni: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.minimum.toString()} ${sizing.unit}`.trim();
            }
            return `Liian pieni: arvon t\xE4ytyy olla ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `Virheellinen sy\xF6te: t\xE4ytyy alkaa "${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `Virheellinen sy\xF6te: t\xE4ytyy loppua "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${_issue.includes}"`;
            if (_issue.format === "regex") {
              return `Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${_issue.pattern}`;
            }
            return `Virheellinen ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `Virheellinen luku: t\xE4ytyy olla luvun ${issue2.divisor} monikerta`;
          case "unrecognized_keys":
            return `${issue2.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return "Virheellinen avain tietueessa";
          case "invalid_union":
            return "Virheellinen unioni";
          case "invalid_element":
            return "Virheellinen arvo joukossa";
          default:
            return `Virheellinen sy\xF6te`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/fr.js
function fr_default() {
  return {
    localeError: error12()
  };
}
var error12;
var init_fr = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/fr.js"() {
    init_util2();
    error12 = () => {
      const Sizable = {
        string: { unit: "caract\xE8res", verb: "avoir" },
        file: { unit: "octets", verb: "avoir" },
        array: { unit: "\xE9l\xE9ments", verb: "avoir" },
        set: { unit: "\xE9l\xE9ments", verb: "avoir" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "nombre";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "tableau";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "entr\xE9e",
        email: "adresse e-mail",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "date et heure ISO",
        date: "date ISO",
        time: "heure ISO",
        duration: "dur\xE9e ISO",
        ipv4: "adresse IPv4",
        ipv6: "adresse IPv6",
        cidrv4: "plage IPv4",
        cidrv6: "plage IPv6",
        base64: "cha\xEEne encod\xE9e en base64",
        base64url: "cha\xEEne encod\xE9e en base64url",
        json_string: "cha\xEEne JSON",
        e164: "num\xE9ro E.164",
        jwt: "JWT",
        template_literal: "entr\xE9e"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Entr\xE9e invalide : ${issue2.expected} attendu, ${parsedType4(issue2.input)} re\xE7u`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Entr\xE9e invalide : ${stringifyPrimitive(issue2.values[0])} attendu`;
            return `Option invalide : une valeur parmi ${joinValues(issue2.values, "|")} attendue`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `Trop grand : ${issue2.origin ?? "valeur"} doit ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xE9l\xE9ment(s)"}`;
            return `Trop grand : ${issue2.origin ?? "valeur"} doit \xEAtre ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Trop petit : ${issue2.origin} doit ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `Trop petit : ${issue2.origin} doit \xEAtre ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`;
            return `${Nouns[_issue.format] ?? issue2.format} invalide`;
          }
          case "not_multiple_of":
            return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`;
          case "unrecognized_keys":
            return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Cl\xE9 invalide dans ${issue2.origin}`;
          case "invalid_union":
            return "Entr\xE9e invalide";
          case "invalid_element":
            return `Valeur invalide dans ${issue2.origin}`;
          default:
            return `Entr\xE9e invalide`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/fr-CA.js
function fr_CA_default() {
  return {
    localeError: error13()
  };
}
var error13;
var init_fr_CA = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/fr-CA.js"() {
    init_util2();
    error13 = () => {
      const Sizable = {
        string: { unit: "caract\xE8res", verb: "avoir" },
        file: { unit: "octets", verb: "avoir" },
        array: { unit: "\xE9l\xE9ments", verb: "avoir" },
        set: { unit: "\xE9l\xE9ments", verb: "avoir" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "number";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "array";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "entr\xE9e",
        email: "adresse courriel",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "date-heure ISO",
        date: "date ISO",
        time: "heure ISO",
        duration: "dur\xE9e ISO",
        ipv4: "adresse IPv4",
        ipv6: "adresse IPv6",
        cidrv4: "plage IPv4",
        cidrv6: "plage IPv6",
        base64: "cha\xEEne encod\xE9e en base64",
        base64url: "cha\xEEne encod\xE9e en base64url",
        json_string: "cha\xEEne JSON",
        e164: "num\xE9ro E.164",
        jwt: "JWT",
        template_literal: "entr\xE9e"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Entr\xE9e invalide : attendu ${issue2.expected}, re\xE7u ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Entr\xE9e invalide : attendu ${stringifyPrimitive(issue2.values[0])}`;
            return `Option invalide : attendu l'une des valeurs suivantes ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "\u2264" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} ait ${adj}${issue2.maximum.toString()} ${sizing.unit}`;
            return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} soit ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? "\u2265" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Trop petit : attendu que ${issue2.origin} ait ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `Trop petit : attendu que ${issue2.origin} soit ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with") {
              return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`;
            }
            if (_issue.format === "ends_with")
              return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `Cha\xEEne invalide : doit correspondre au motif ${_issue.pattern}`;
            return `${Nouns[_issue.format] ?? issue2.format} invalide`;
          }
          case "not_multiple_of":
            return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`;
          case "unrecognized_keys":
            return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Cl\xE9 invalide dans ${issue2.origin}`;
          case "invalid_union":
            return "Entr\xE9e invalide";
          case "invalid_element":
            return `Valeur invalide dans ${issue2.origin}`;
          default:
            return `Entr\xE9e invalide`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/he.js
function he_default() {
  return {
    localeError: error14()
  };
}
var error14;
var init_he = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/he.js"() {
    init_util2();
    error14 = () => {
      const Sizable = {
        string: { unit: "\u05D0\u05D5\u05EA\u05D9\u05D5\u05EA", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" },
        file: { unit: "\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" },
        array: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" },
        set: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "number";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "array";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "\u05E7\u05DC\u05D8",
        email: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC",
        url: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA",
        emoji: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO",
        date: "\u05EA\u05D0\u05E8\u05D9\u05DA ISO",
        time: "\u05D6\u05DE\u05DF ISO",
        duration: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO",
        ipv4: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4",
        ipv6: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6",
        cidrv4: "\u05D8\u05D5\u05D5\u05D7 IPv4",
        cidrv6: "\u05D8\u05D5\u05D5\u05D7 IPv6",
        base64: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64",
        base64url: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA",
        json_string: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON",
        e164: "\u05DE\u05E1\u05E4\u05E8 E.164",
        jwt: "JWT",
        template_literal: "\u05E7\u05DC\u05D8"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${issue2.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${parsedType4(issue2.input)}`;
          // return `Invalid input: expected ${issue.expected}, received ${util.getParsedType(issue.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${stringifyPrimitive(issue2.values[0])}`;
            return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05D0\u05D7\u05EA \u05DE\u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA  ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${issue2.origin ?? "value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`;
            return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${issue2.origin ?? "value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${issue2.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${issue2.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1"${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${_issue.pattern}`;
            return `${Nouns[_issue.format] ?? issue2.format} \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`;
          }
          case "not_multiple_of":
            return `\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${issue2.divisor}`;
          case "unrecognized_keys":
            return `\u05DE\u05E4\u05EA\u05D7${issue2.keys.length > 1 ? "\u05D5\u05EA" : ""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${issue2.keys.length > 1 ? "\u05D9\u05DD" : "\u05D4"}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `\u05DE\u05E4\u05EA\u05D7 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${issue2.origin}`;
          case "invalid_union":
            return "\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";
          case "invalid_element":
            return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${issue2.origin}`;
          default:
            return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/hu.js
function hu_default() {
  return {
    localeError: error15()
  };
}
var error15;
var init_hu = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/hu.js"() {
    init_util2();
    error15 = () => {
      const Sizable = {
        string: { unit: "karakter", verb: "legyen" },
        file: { unit: "byte", verb: "legyen" },
        array: { unit: "elem", verb: "legyen" },
        set: { unit: "elem", verb: "legyen" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "sz\xE1m";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "t\xF6mb";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "bemenet",
        email: "email c\xEDm",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO id\u0151b\xE9lyeg",
        date: "ISO d\xE1tum",
        time: "ISO id\u0151",
        duration: "ISO id\u0151intervallum",
        ipv4: "IPv4 c\xEDm",
        ipv6: "IPv6 c\xEDm",
        cidrv4: "IPv4 tartom\xE1ny",
        cidrv6: "IPv6 tartom\xE1ny",
        base64: "base64-k\xF3dolt string",
        base64url: "base64url-k\xF3dolt string",
        json_string: "JSON string",
        e164: "E.164 sz\xE1m",
        jwt: "JWT",
        template_literal: "bemenet"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${issue2.expected}, a kapott \xE9rt\xE9k ${parsedType4(issue2.input)}`;
          // return `Invalid input: expected ${issue.expected}, received ${util.getParsedType(issue.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${stringifyPrimitive(issue2.values[0])}`;
            return `\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `T\xFAl nagy: ${issue2.origin ?? "\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elem"}`;
            return `T\xFAl nagy: a bemeneti \xE9rt\xE9k ${issue2.origin ?? "\xE9rt\xE9k"} t\xFAl nagy: ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} m\xE9rete t\xFAl kicsi ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} t\xFAl kicsi ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `\xC9rv\xE9nytelen string: "${_issue.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`;
            if (_issue.format === "ends_with")
              return `\xC9rv\xE9nytelen string: "${_issue.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`;
            if (_issue.format === "includes")
              return `\xC9rv\xE9nytelen string: "${_issue.includes}" \xE9rt\xE9ket kell tartalmaznia`;
            if (_issue.format === "regex")
              return `\xC9rv\xE9nytelen string: ${_issue.pattern} mint\xE1nak kell megfelelnie`;
            return `\xC9rv\xE9nytelen ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `\xC9rv\xE9nytelen sz\xE1m: ${issue2.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;
          case "unrecognized_keys":
            return `Ismeretlen kulcs${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `\xC9rv\xE9nytelen kulcs ${issue2.origin}`;
          case "invalid_union":
            return "\xC9rv\xE9nytelen bemenet";
          case "invalid_element":
            return `\xC9rv\xE9nytelen \xE9rt\xE9k: ${issue2.origin}`;
          default:
            return `\xC9rv\xE9nytelen bemenet`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/id.js
function id_default() {
  return {
    localeError: error16()
  };
}
var error16;
var init_id = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/id.js"() {
    init_util2();
    error16 = () => {
      const Sizable = {
        string: { unit: "karakter", verb: "memiliki" },
        file: { unit: "byte", verb: "memiliki" },
        array: { unit: "item", verb: "memiliki" },
        set: { unit: "item", verb: "memiliki" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "number";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "array";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "input",
        email: "alamat email",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "tanggal dan waktu format ISO",
        date: "tanggal format ISO",
        time: "jam format ISO",
        duration: "durasi format ISO",
        ipv4: "alamat IPv4",
        ipv6: "alamat IPv6",
        cidrv4: "rentang alamat IPv4",
        cidrv6: "rentang alamat IPv6",
        base64: "string dengan enkode base64",
        base64url: "string dengan enkode base64url",
        json_string: "string JSON",
        e164: "angka E.164",
        jwt: "JWT",
        template_literal: "input"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Input tidak valid: diharapkan ${issue2.expected}, diterima ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Input tidak valid: diharapkan ${stringifyPrimitive(issue2.values[0])}`;
            return `Pilihan tidak valid: diharapkan salah satu dari ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} memiliki ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`;
            return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} menjadi ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Terlalu kecil: diharapkan ${issue2.origin} memiliki ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `Terlalu kecil: diharapkan ${issue2.origin} menjadi ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `String tidak valid: harus dimulai dengan "${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `String tidak valid: harus berakhir dengan "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `String tidak valid: harus menyertakan "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `String tidak valid: harus sesuai pola ${_issue.pattern}`;
            return `${Nouns[_issue.format] ?? issue2.format} tidak valid`;
          }
          case "not_multiple_of":
            return `Angka tidak valid: harus kelipatan dari ${issue2.divisor}`;
          case "unrecognized_keys":
            return `Kunci tidak dikenali ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Kunci tidak valid di ${issue2.origin}`;
          case "invalid_union":
            return "Input tidak valid";
          case "invalid_element":
            return `Nilai tidak valid di ${issue2.origin}`;
          default:
            return `Input tidak valid`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/it.js
function it_default() {
  return {
    localeError: error17()
  };
}
var error17;
var init_it = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/it.js"() {
    init_util2();
    error17 = () => {
      const Sizable = {
        string: { unit: "caratteri", verb: "avere" },
        file: { unit: "byte", verb: "avere" },
        array: { unit: "elementi", verb: "avere" },
        set: { unit: "elementi", verb: "avere" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "numero";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "vettore";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "input",
        email: "indirizzo email",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "data e ora ISO",
        date: "data ISO",
        time: "ora ISO",
        duration: "durata ISO",
        ipv4: "indirizzo IPv4",
        ipv6: "indirizzo IPv6",
        cidrv4: "intervallo IPv4",
        cidrv6: "intervallo IPv6",
        base64: "stringa codificata in base64",
        base64url: "URL codificata in base64",
        json_string: "stringa JSON",
        e164: "numero E.164",
        jwt: "JWT",
        template_literal: "input"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Input non valido: atteso ${issue2.expected}, ricevuto ${parsedType4(issue2.input)}`;
          // return `Input non valido: atteso ${issue.expected}, ricevuto ${util.getParsedType(issue.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Input non valido: atteso ${stringifyPrimitive(issue2.values[0])}`;
            return `Opzione non valida: atteso uno tra ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `Troppo grande: ${issue2.origin ?? "valore"} deve avere ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementi"}`;
            return `Troppo grande: ${issue2.origin ?? "valore"} deve essere ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Troppo piccolo: ${issue2.origin} deve avere ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `Troppo piccolo: ${issue2.origin} deve essere ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `Stringa non valida: deve iniziare con "${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `Stringa non valida: deve terminare con "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `Stringa non valida: deve includere "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`;
            return `Invalid ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `Numero non valido: deve essere un multiplo di ${issue2.divisor}`;
          case "unrecognized_keys":
            return `Chiav${issue2.keys.length > 1 ? "i" : "e"} non riconosciut${issue2.keys.length > 1 ? "e" : "a"}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Chiave non valida in ${issue2.origin}`;
          case "invalid_union":
            return "Input non valido";
          case "invalid_element":
            return `Valore non valido in ${issue2.origin}`;
          default:
            return `Input non valido`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ja.js
function ja_default() {
  return {
    localeError: error18()
  };
}
var error18;
var init_ja = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ja.js"() {
    init_util2();
    error18 = () => {
      const Sizable = {
        string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" },
        file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" },
        array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" },
        set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "\u6570\u5024";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "\u914D\u5217";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "\u5165\u529B\u5024",
        email: "\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9",
        url: "URL",
        emoji: "\u7D75\u6587\u5B57",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO\u65E5\u6642",
        date: "ISO\u65E5\u4ED8",
        time: "ISO\u6642\u523B",
        duration: "ISO\u671F\u9593",
        ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9",
        ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9",
        cidrv4: "IPv4\u7BC4\u56F2",
        cidrv6: "IPv6\u7BC4\u56F2",
        base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",
        base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",
        json_string: "JSON\u6587\u5B57\u5217",
        e164: "E.164\u756A\u53F7",
        jwt: "JWT",
        template_literal: "\u5165\u529B\u5024"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u7121\u52B9\u306A\u5165\u529B: ${issue2.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${parsedType4(issue2.input)}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `\u7121\u52B9\u306A\u5165\u529B: ${stringifyPrimitive(issue2.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`;
            return `\u7121\u52B9\u306A\u9078\u629E: ${joinValues(issue2.values, "\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
          case "too_big": {
            const adj = issue2.inclusive ? "\u4EE5\u4E0B\u3067\u3042\u308B" : "\u3088\u308A\u5C0F\u3055\u3044";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin ?? "\u5024"}\u306F${issue2.maximum.toString()}${sizing.unit ?? "\u8981\u7D20"}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
            return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin ?? "\u5024"}\u306F${issue2.maximum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? "\u4EE5\u4E0A\u3067\u3042\u308B" : "\u3088\u308A\u5927\u304D\u3044";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${sizing.unit}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
            return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
            if (_issue.format === "ends_with")
              return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
            if (_issue.format === "includes")
              return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
            if (_issue.format === "regex")
              return `\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${_issue.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
            return `\u7121\u52B9\u306A${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `\u7121\u52B9\u306A\u6570\u5024: ${issue2.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
          case "unrecognized_keys":
            return `\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${issue2.keys.length > 1 ? "\u7FA4" : ""}: ${joinValues(issue2.keys, "\u3001")}`;
          case "invalid_key":
            return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;
          case "invalid_union":
            return "\u7121\u52B9\u306A\u5165\u529B";
          case "invalid_element":
            return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;
          default:
            return `\u7121\u52B9\u306A\u5165\u529B`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/kh.js
function kh_default() {
  return {
    localeError: error19()
  };
}
var error19;
var init_kh = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/kh.js"() {
    init_util2();
    error19 = () => {
      const Sizable = {
        string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" },
        file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" },
        array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" },
        set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "\u1798\u17B7\u1793\u1798\u17C2\u1793\u1787\u17B6\u179B\u17C1\u1781 (NaN)" : "\u179B\u17C1\u1781";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "\u17A2\u17B6\u179A\u17C1 (Array)";
            }
            if (data === null) {
              return "\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B",
        email: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B",
        url: "URL",
        emoji: "\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO",
        date: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO",
        time: "\u1798\u17C9\u17C4\u1784 ISO",
        duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO",
        ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",
        ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",
        cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",
        cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",
        base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64",
        base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url",
        json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON",
        e164: "\u179B\u17C1\u1781 E.164",
        jwt: "JWT",
        template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${stringifyPrimitive(issue2.values[0])}`;
            return `\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u1792\u17B6\u178F\u17BB"}`;
            return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with") {
              return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${_issue.prefix}"`;
            }
            if (_issue.format === "ends_with")
              return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${_issue.pattern}`;
            return `\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${issue2.divisor}`;
          case "unrecognized_keys":
            return `\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`;
          case "invalid_union":
            return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`;
          case "invalid_element":
            return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`;
          default:
            return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ko.js
function ko_default() {
  return {
    localeError: error20()
  };
}
var error20;
var init_ko = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ko.js"() {
    init_util2();
    error20 = () => {
      const Sizable = {
        string: { unit: "\uBB38\uC790", verb: "to have" },
        file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" },
        array: { unit: "\uAC1C", verb: "to have" },
        set: { unit: "\uAC1C", verb: "to have" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "number";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "array";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "\uC785\uB825",
        email: "\uC774\uBA54\uC77C \uC8FC\uC18C",
        url: "URL",
        emoji: "\uC774\uBAA8\uC9C0",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO \uB0A0\uC9DC\uC2DC\uAC04",
        date: "ISO \uB0A0\uC9DC",
        time: "ISO \uC2DC\uAC04",
        duration: "ISO \uAE30\uAC04",
        ipv4: "IPv4 \uC8FC\uC18C",
        ipv6: "IPv6 \uC8FC\uC18C",
        cidrv4: "IPv4 \uBC94\uC704",
        cidrv6: "IPv6 \uBC94\uC704",
        base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",
        base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",
        json_string: "JSON \uBB38\uC790\uC5F4",
        e164: "E.164 \uBC88\uD638",
        jwt: "JWT",
        template_literal: "\uC785\uB825"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${issue2.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${parsedType4(issue2.input)}\uC785\uB2C8\uB2E4`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${stringifyPrimitive(issue2.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`;
            return `\uC798\uBABB\uB41C \uC635\uC158: ${joinValues(issue2.values, "\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;
          case "too_big": {
            const adj = issue2.inclusive ? "\uC774\uD558" : "\uBBF8\uB9CC";
            const suffix = adj === "\uBBF8\uB9CC" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4";
            const sizing = getSizing(issue2.origin);
            const unit = sizing?.unit ?? "\uC694\uC18C";
            if (sizing)
              return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()}${unit} ${adj}${suffix}`;
            return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()} ${adj}${suffix}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? "\uC774\uC0C1" : "\uCD08\uACFC";
            const suffix = adj === "\uC774\uC0C1" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4";
            const sizing = getSizing(issue2.origin);
            const unit = sizing?.unit ?? "\uC694\uC18C";
            if (sizing) {
              return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()}${unit} ${adj}${suffix}`;
            }
            return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()} ${adj}${suffix}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with") {
              return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`;
            }
            if (_issue.format === "ends_with")
              return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`;
            if (_issue.format === "includes")
              return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`;
            if (_issue.format === "regex")
              return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${_issue.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`;
            return `\uC798\uBABB\uB41C ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `\uC798\uBABB\uB41C \uC22B\uC790: ${issue2.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;
          case "unrecognized_keys":
            return `\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `\uC798\uBABB\uB41C \uD0A4: ${issue2.origin}`;
          case "invalid_union":
            return `\uC798\uBABB\uB41C \uC785\uB825`;
          case "invalid_element":
            return `\uC798\uBABB\uB41C \uAC12: ${issue2.origin}`;
          default:
            return `\uC798\uBABB\uB41C \uC785\uB825`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/mk.js
function mk_default() {
  return {
    localeError: error21()
  };
}
var error21;
var init_mk = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/mk.js"() {
    init_util2();
    error21 = () => {
      const Sizable = {
        string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" },
        file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" },
        array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" },
        set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "\u0431\u0440\u043E\u0458";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "\u043D\u0438\u0437\u0430";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "\u0432\u043D\u0435\u0441",
        email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430",
        url: "URL",
        emoji: "\u0435\u043C\u043E\u045F\u0438",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435",
        date: "ISO \u0434\u0430\u0442\u0443\u043C",
        time: "ISO \u0432\u0440\u0435\u043C\u0435",
        duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435",
        ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430",
        ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430",
        cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433",
        cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433",
        base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",
        base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",
        json_string: "JSON \u043D\u0438\u0437\u0430",
        e164: "E.164 \u0431\u0440\u043E\u0458",
        jwt: "JWT",
        template_literal: "\u0432\u043D\u0435\u0441"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${parsedType4(issue2.input)}`;
          // return `Invalid input: expected ${issue.expected}, received ${util.getParsedType(issue.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`;
            return `\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`;
            return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with") {
              return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${_issue.prefix}"`;
            }
            if (_issue.format === "ends_with")
              return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${_issue.pattern}`;
            return `Invalid ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${issue2.divisor}`;
          case "unrecognized_keys":
            return `${issue2.keys.length > 1 ? "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438" : "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${issue2.origin}`;
          case "invalid_union":
            return "\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";
          case "invalid_element":
            return `\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${issue2.origin}`;
          default:
            return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ms.js
function ms_default() {
  return {
    localeError: error22()
  };
}
var error22;
var init_ms = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ms.js"() {
    init_util2();
    error22 = () => {
      const Sizable = {
        string: { unit: "aksara", verb: "mempunyai" },
        file: { unit: "bait", verb: "mempunyai" },
        array: { unit: "elemen", verb: "mempunyai" },
        set: { unit: "elemen", verb: "mempunyai" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "nombor";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "array";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "input",
        email: "alamat e-mel",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "tarikh masa ISO",
        date: "tarikh ISO",
        time: "masa ISO",
        duration: "tempoh ISO",
        ipv4: "alamat IPv4",
        ipv6: "alamat IPv6",
        cidrv4: "julat IPv4",
        cidrv6: "julat IPv6",
        base64: "string dikodkan base64",
        base64url: "string dikodkan base64url",
        json_string: "string JSON",
        e164: "nombor E.164",
        jwt: "JWT",
        template_literal: "input"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Input tidak sah: dijangka ${issue2.expected}, diterima ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Input tidak sah: dijangka ${stringifyPrimitive(issue2.values[0])}`;
            return `Pilihan tidak sah: dijangka salah satu daripada ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`;
            return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} adalah ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Terlalu kecil: dijangka ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `Terlalu kecil: dijangka ${issue2.origin} adalah ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `String tidak sah: mesti bermula dengan "${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `String tidak sah: mesti berakhir dengan "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `String tidak sah: mesti mengandungi "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`;
            return `${Nouns[_issue.format] ?? issue2.format} tidak sah`;
          }
          case "not_multiple_of":
            return `Nombor tidak sah: perlu gandaan ${issue2.divisor}`;
          case "unrecognized_keys":
            return `Kunci tidak dikenali: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Kunci tidak sah dalam ${issue2.origin}`;
          case "invalid_union":
            return "Input tidak sah";
          case "invalid_element":
            return `Nilai tidak sah dalam ${issue2.origin}`;
          default:
            return `Input tidak sah`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/nl.js
function nl_default() {
  return {
    localeError: error23()
  };
}
var error23;
var init_nl = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/nl.js"() {
    init_util2();
    error23 = () => {
      const Sizable = {
        string: { unit: "tekens" },
        file: { unit: "bytes" },
        array: { unit: "elementen" },
        set: { unit: "elementen" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "getal";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "array";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "invoer",
        email: "emailadres",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO datum en tijd",
        date: "ISO datum",
        time: "ISO tijd",
        duration: "ISO duur",
        ipv4: "IPv4-adres",
        ipv6: "IPv6-adres",
        cidrv4: "IPv4-bereik",
        cidrv6: "IPv6-bereik",
        base64: "base64-gecodeerde tekst",
        base64url: "base64 URL-gecodeerde tekst",
        json_string: "JSON string",
        e164: "E.164-nummer",
        jwt: "JWT",
        template_literal: "invoer"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Ongeldige invoer: verwacht ${issue2.expected}, ontving ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Ongeldige invoer: verwacht ${stringifyPrimitive(issue2.values[0])}`;
            return `Ongeldige optie: verwacht \xE9\xE9n van ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `Te lang: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementen"} bevat`;
            return `Te lang: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} is`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Te kort: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} bevat`;
            }
            return `Te kort: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} is`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with") {
              return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`;
            }
            if (_issue.format === "ends_with")
              return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`;
            if (_issue.format === "includes")
              return `Ongeldige tekst: moet "${_issue.includes}" bevatten`;
            if (_issue.format === "regex")
              return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`;
            return `Ongeldig: ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `Ongeldig getal: moet een veelvoud van ${issue2.divisor} zijn`;
          case "unrecognized_keys":
            return `Onbekende key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Ongeldige key in ${issue2.origin}`;
          case "invalid_union":
            return "Ongeldige invoer";
          case "invalid_element":
            return `Ongeldige waarde in ${issue2.origin}`;
          default:
            return `Ongeldige invoer`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/no.js
function no_default() {
  return {
    localeError: error24()
  };
}
var error24;
var init_no = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/no.js"() {
    init_util2();
    error24 = () => {
      const Sizable = {
        string: { unit: "tegn", verb: "\xE5 ha" },
        file: { unit: "bytes", verb: "\xE5 ha" },
        array: { unit: "elementer", verb: "\xE5 inneholde" },
        set: { unit: "elementer", verb: "\xE5 inneholde" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "tall";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "liste";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "input",
        email: "e-postadresse",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO dato- og klokkeslett",
        date: "ISO-dato",
        time: "ISO-klokkeslett",
        duration: "ISO-varighet",
        ipv4: "IPv4-omr\xE5de",
        ipv6: "IPv6-omr\xE5de",
        cidrv4: "IPv4-spekter",
        cidrv6: "IPv6-spekter",
        base64: "base64-enkodet streng",
        base64url: "base64url-enkodet streng",
        json_string: "JSON-streng",
        e164: "E.164-nummer",
        jwt: "JWT",
        template_literal: "input"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Ugyldig input: forventet ${issue2.expected}, fikk ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Ugyldig verdi: forventet ${stringifyPrimitive(issue2.values[0])}`;
            return `Ugyldig valg: forventet en av ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `For stor(t): forventet ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementer"}`;
            return `For stor(t): forventet ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `Ugyldig streng: m\xE5 ende med "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `Ugyldig streng: m\xE5 inneholde "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`;
            return `Ugyldig ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `Ugyldig tall: m\xE5 v\xE6re et multiplum av ${issue2.divisor}`;
          case "unrecognized_keys":
            return `${issue2.keys.length > 1 ? "Ukjente n\xF8kler" : "Ukjent n\xF8kkel"}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Ugyldig n\xF8kkel i ${issue2.origin}`;
          case "invalid_union":
            return "Ugyldig input";
          case "invalid_element":
            return `Ugyldig verdi i ${issue2.origin}`;
          default:
            return `Ugyldig input`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ota.js
function ota_default() {
  return {
    localeError: error25()
  };
}
var error25;
var init_ota = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ota.js"() {
    init_util2();
    error25 = () => {
      const Sizable = {
        string: { unit: "harf", verb: "olmal\u0131d\u0131r" },
        file: { unit: "bayt", verb: "olmal\u0131d\u0131r" },
        array: { unit: "unsur", verb: "olmal\u0131d\u0131r" },
        set: { unit: "unsur", verb: "olmal\u0131d\u0131r" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "numara";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "saf";
            }
            if (data === null) {
              return "gayb";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "giren",
        email: "epostag\xE2h",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO heng\xE2m\u0131",
        date: "ISO tarihi",
        time: "ISO zaman\u0131",
        duration: "ISO m\xFCddeti",
        ipv4: "IPv4 ni\u015F\xE2n\u0131",
        ipv6: "IPv6 ni\u015F\xE2n\u0131",
        cidrv4: "IPv4 menzili",
        cidrv6: "IPv6 menzili",
        base64: "base64-\u015Fifreli metin",
        base64url: "base64url-\u015Fifreli metin",
        json_string: "JSON metin",
        e164: "E.164 say\u0131s\u0131",
        jwt: "JWT",
        template_literal: "giren"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `F\xE2sit giren: umulan ${issue2.expected}, al\u0131nan ${parsedType4(issue2.input)}`;
          // return `Fâsit giren: umulan ${issue.expected}, alınan ${util.getParsedType(issue.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `F\xE2sit giren: umulan ${stringifyPrimitive(issue2.values[0])}`;
            return `F\xE2sit tercih: m\xFBteberler ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `Fazla b\xFCy\xFCk: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"} sahip olmal\u0131yd\u0131.`;
            return `Fazla b\xFCy\xFCk: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} olmal\u0131yd\u0131.`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} ${sizing.unit} sahip olmal\u0131yd\u0131.`;
            }
            return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} olmal\u0131yd\u0131.`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `F\xE2sit metin: "${_issue.prefix}" ile ba\u015Flamal\u0131.`;
            if (_issue.format === "ends_with")
              return `F\xE2sit metin: "${_issue.suffix}" ile bitmeli.`;
            if (_issue.format === "includes")
              return `F\xE2sit metin: "${_issue.includes}" ihtiv\xE2 etmeli.`;
            if (_issue.format === "regex")
              return `F\xE2sit metin: ${_issue.pattern} nak\u015F\u0131na uymal\u0131.`;
            return `F\xE2sit ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `F\xE2sit say\u0131: ${issue2.divisor} kat\u0131 olmal\u0131yd\u0131.`;
          case "unrecognized_keys":
            return `Tan\u0131nmayan anahtar ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `${issue2.origin} i\xE7in tan\u0131nmayan anahtar var.`;
          case "invalid_union":
            return "Giren tan\u0131namad\u0131.";
          case "invalid_element":
            return `${issue2.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;
          default:
            return `K\u0131ymet tan\u0131namad\u0131.`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ps.js
function ps_default() {
  return {
    localeError: error26()
  };
}
var error26;
var init_ps = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ps.js"() {
    init_util2();
    error26 = () => {
      const Sizable = {
        string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" },
        file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" },
        array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" },
        set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "\u0639\u062F\u062F";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "\u0627\u0631\u06D0";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "\u0648\u0631\u0648\u062F\u064A",
        email: "\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9",
        url: "\u06CC\u0648 \u0622\u0631 \u0627\u0644",
        emoji: "\u0627\u06CC\u0645\u0648\u062C\u064A",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A",
        date: "\u0646\u06D0\u067C\u0647",
        time: "\u0648\u062E\u062A",
        duration: "\u0645\u0648\u062F\u0647",
        ipv4: "\u062F IPv4 \u067E\u062A\u0647",
        ipv6: "\u062F IPv6 \u067E\u062A\u0647",
        cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647",
        cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647",
        base64: "base64-encoded \u0645\u062A\u0646",
        base64url: "base64url-encoded \u0645\u062A\u0646",
        json_string: "JSON \u0645\u062A\u0646",
        e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647",
        jwt: "JWT",
        template_literal: "\u0648\u0631\u0648\u062F\u064A"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${issue2.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${parsedType4(issue2.input)} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`;
          case "invalid_value":
            if (issue2.values.length === 1) {
              return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${stringifyPrimitive(issue2.values[0])} \u0648\u0627\u06CC`;
            }
            return `\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${joinValues(issue2.values, "|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`;
            }
            return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0648\u064A`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0648\u0644\u0631\u064A`;
            }
            return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0648\u064A`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with") {
              return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`;
            }
            if (_issue.format === "ends_with") {
              return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`;
            }
            if (_issue.format === "includes") {
              return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${_issue.includes}" \u0648\u0644\u0631\u064A`;
            }
            if (_issue.format === "regex") {
              return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${_issue.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`;
            }
            return `${Nouns[_issue.format] ?? issue2.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`;
          }
          case "not_multiple_of":
            return `\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${issue2.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;
          case "unrecognized_keys":
            return `\u0646\u0627\u0633\u0645 ${issue2.keys.length > 1 ? "\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647" : "\u06A9\u0644\u06CC\u0689"}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`;
          case "invalid_union":
            return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`;
          case "invalid_element":
            return `\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`;
          default:
            return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/pl.js
function pl_default() {
  return {
    localeError: error27()
  };
}
var error27;
var init_pl = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/pl.js"() {
    init_util2();
    error27 = () => {
      const Sizable = {
        string: { unit: "znak\xF3w", verb: "mie\u0107" },
        file: { unit: "bajt\xF3w", verb: "mie\u0107" },
        array: { unit: "element\xF3w", verb: "mie\u0107" },
        set: { unit: "element\xF3w", verb: "mie\u0107" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "liczba";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "tablica";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "wyra\u017Cenie",
        email: "adres email",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "data i godzina w formacie ISO",
        date: "data w formacie ISO",
        time: "godzina w formacie ISO",
        duration: "czas trwania ISO",
        ipv4: "adres IPv4",
        ipv6: "adres IPv6",
        cidrv4: "zakres IPv4",
        cidrv6: "zakres IPv6",
        base64: "ci\u0105g znak\xF3w zakodowany w formacie base64",
        base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url",
        json_string: "ci\u0105g znak\xF3w w formacie JSON",
        e164: "liczba E.164",
        jwt: "JWT",
        template_literal: "wej\u015Bcie"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${issue2.expected}, otrzymano ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${stringifyPrimitive(issue2.values[0])}`;
            return `Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element\xF3w"}`;
            }
            return `Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "element\xF3w"}`;
            }
            return `Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${_issue.pattern}`;
            return `Nieprawid\u0142ow(y/a/e) ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${issue2.divisor}`;
          case "unrecognized_keys":
            return `Nierozpoznane klucze${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Nieprawid\u0142owy klucz w ${issue2.origin}`;
          case "invalid_union":
            return "Nieprawid\u0142owe dane wej\u015Bciowe";
          case "invalid_element":
            return `Nieprawid\u0142owa warto\u015B\u0107 w ${issue2.origin}`;
          default:
            return `Nieprawid\u0142owe dane wej\u015Bciowe`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/pt.js
function pt_default() {
  return {
    localeError: error28()
  };
}
var error28;
var init_pt = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/pt.js"() {
    init_util2();
    error28 = () => {
      const Sizable = {
        string: { unit: "caracteres", verb: "ter" },
        file: { unit: "bytes", verb: "ter" },
        array: { unit: "itens", verb: "ter" },
        set: { unit: "itens", verb: "ter" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "n\xFAmero";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "array";
            }
            if (data === null) {
              return "nulo";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "padr\xE3o",
        email: "endere\xE7o de e-mail",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "data e hora ISO",
        date: "data ISO",
        time: "hora ISO",
        duration: "dura\xE7\xE3o ISO",
        ipv4: "endere\xE7o IPv4",
        ipv6: "endere\xE7o IPv6",
        cidrv4: "faixa de IPv4",
        cidrv6: "faixa de IPv6",
        base64: "texto codificado em base64",
        base64url: "URL codificada em base64",
        json_string: "texto JSON",
        e164: "n\xFAmero E.164",
        jwt: "JWT",
        template_literal: "entrada"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Tipo inv\xE1lido: esperado ${issue2.expected}, recebido ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue2.values[0])}`;
            return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `Muito grande: esperado que ${issue2.origin ?? "valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`;
            return `Muito grande: esperado que ${issue2.origin ?? "valor"} fosse ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`;
            return `${Nouns[_issue.format] ?? issue2.format} inv\xE1lido`;
          }
          case "not_multiple_of":
            return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`;
          case "unrecognized_keys":
            return `Chave${issue2.keys.length > 1 ? "s" : ""} desconhecida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Chave inv\xE1lida em ${issue2.origin}`;
          case "invalid_union":
            return "Entrada inv\xE1lida";
          case "invalid_element":
            return `Valor inv\xE1lido em ${issue2.origin}`;
          default:
            return `Campo inv\xE1lido`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ru.js
function getRussianPlural(count3, one, few, many) {
  const absCount = Math.abs(count3);
  const lastDigit = absCount % 10;
  const lastTwoDigits = absCount % 100;
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
    return many;
  }
  if (lastDigit === 1) {
    return one;
  }
  if (lastDigit >= 2 && lastDigit <= 4) {
    return few;
  }
  return many;
}
function ru_default() {
  return {
    localeError: error29()
  };
}
var error29;
var init_ru = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ru.js"() {
    init_util2();
    error29 = () => {
      const Sizable = {
        string: {
          unit: {
            one: "\u0441\u0438\u043C\u0432\u043E\u043B",
            few: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430",
            many: "\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432"
          },
          verb: "\u0438\u043C\u0435\u0442\u044C"
        },
        file: {
          unit: {
            one: "\u0431\u0430\u0439\u0442",
            few: "\u0431\u0430\u0439\u0442\u0430",
            many: "\u0431\u0430\u0439\u0442"
          },
          verb: "\u0438\u043C\u0435\u0442\u044C"
        },
        array: {
          unit: {
            one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442",
            few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",
            many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"
          },
          verb: "\u0438\u043C\u0435\u0442\u044C"
        },
        set: {
          unit: {
            one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442",
            few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",
            many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"
          },
          verb: "\u0438\u043C\u0435\u0442\u044C"
        }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "\u0447\u0438\u0441\u043B\u043E";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "\u043C\u0430\u0441\u0441\u0438\u0432";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "\u0432\u0432\u043E\u0434",
        email: "email \u0430\u0434\u0440\u0435\u0441",
        url: "URL",
        emoji: "\u044D\u043C\u043E\u0434\u0437\u0438",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F",
        date: "ISO \u0434\u0430\u0442\u0430",
        time: "ISO \u0432\u0440\u0435\u043C\u044F",
        duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",
        ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441",
        ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441",
        cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",
        cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",
        base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64",
        base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url",
        json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430",
        e164: "\u043D\u043E\u043C\u0435\u0440 E.164",
        jwt: "JWT",
        template_literal: "\u0432\u0432\u043E\u0434"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${stringifyPrimitive(issue2.values[0])}`;
            return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              const maxValue = Number(issue2.maximum);
              const unit = getRussianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
              return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.maximum.toString()} ${unit}`;
            }
            return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              const minValue = Number(issue2.minimum);
              const unit = getRussianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
              return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.minimum.toString()} ${unit}`;
            }
            return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`;
            return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`;
          case "unrecognized_keys":
            return `\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${issue2.keys.length > 1 ? "\u044B\u0435" : "\u044B\u0439"} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0438" : ""}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`;
          case "invalid_union":
            return "\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435";
          case "invalid_element":
            return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${issue2.origin}`;
          default:
            return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/sl.js
function sl_default() {
  return {
    localeError: error30()
  };
}
var error30;
var init_sl = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/sl.js"() {
    init_util2();
    error30 = () => {
      const Sizable = {
        string: { unit: "znakov", verb: "imeti" },
        file: { unit: "bajtov", verb: "imeti" },
        array: { unit: "elementov", verb: "imeti" },
        set: { unit: "elementov", verb: "imeti" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "\u0161tevilo";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "tabela";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "vnos",
        email: "e-po\u0161tni naslov",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO datum in \u010Das",
        date: "ISO datum",
        time: "ISO \u010Das",
        duration: "ISO trajanje",
        ipv4: "IPv4 naslov",
        ipv6: "IPv6 naslov",
        cidrv4: "obseg IPv4",
        cidrv6: "obseg IPv6",
        base64: "base64 kodiran niz",
        base64url: "base64url kodiran niz",
        json_string: "JSON niz",
        e164: "E.164 \u0161tevilka",
        jwt: "JWT",
        template_literal: "vnos"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Neveljaven vnos: pri\u010Dakovano ${issue2.expected}, prejeto ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Neveljaven vnos: pri\u010Dakovano ${stringifyPrimitive(issue2.values[0])}`;
            return `Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `Preveliko: pri\u010Dakovano, da bo ${issue2.origin ?? "vrednost"} imelo ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementov"}`;
            return `Preveliko: pri\u010Dakovano, da bo ${issue2.origin ?? "vrednost"} ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} imelo ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with") {
              return `Neveljaven niz: mora se za\u010Deti z "${_issue.prefix}"`;
            }
            if (_issue.format === "ends_with")
              return `Neveljaven niz: mora se kon\u010Dati z "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `Neveljaven niz: mora vsebovati "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`;
            return `Neveljaven ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${issue2.divisor}`;
          case "unrecognized_keys":
            return `Neprepoznan${issue2.keys.length > 1 ? "i klju\u010Di" : " klju\u010D"}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Neveljaven klju\u010D v ${issue2.origin}`;
          case "invalid_union":
            return "Neveljaven vnos";
          case "invalid_element":
            return `Neveljavna vrednost v ${issue2.origin}`;
          default:
            return "Neveljaven vnos";
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/sv.js
function sv_default() {
  return {
    localeError: error31()
  };
}
var error31;
var init_sv = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/sv.js"() {
    init_util2();
    error31 = () => {
      const Sizable = {
        string: { unit: "tecken", verb: "att ha" },
        file: { unit: "bytes", verb: "att ha" },
        array: { unit: "objekt", verb: "att inneh\xE5lla" },
        set: { unit: "objekt", verb: "att inneh\xE5lla" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "antal";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "lista";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "regulj\xE4rt uttryck",
        email: "e-postadress",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO-datum och tid",
        date: "ISO-datum",
        time: "ISO-tid",
        duration: "ISO-varaktighet",
        ipv4: "IPv4-intervall",
        ipv6: "IPv6-intervall",
        cidrv4: "IPv4-spektrum",
        cidrv6: "IPv6-spektrum",
        base64: "base64-kodad str\xE4ng",
        base64url: "base64url-kodad str\xE4ng",
        json_string: "JSON-str\xE4ng",
        e164: "E.164-nummer",
        jwt: "JWT",
        template_literal: "mall-literal"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Ogiltig inmatning: f\xF6rv\xE4ntat ${issue2.expected}, fick ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Ogiltig inmatning: f\xF6rv\xE4ntat ${stringifyPrimitive(issue2.values[0])}`;
            return `Ogiltigt val: f\xF6rv\xE4ntade en av ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `F\xF6r stor(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`;
            }
            return `F\xF6r stor(t): f\xF6rv\xE4ntat ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with") {
              return `Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${_issue.prefix}"`;
            }
            if (_issue.format === "ends_with")
              return `Ogiltig str\xE4ng: m\xE5ste sluta med "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${_issue.pattern}"`;
            return `Ogiltig(t) ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `Ogiltigt tal: m\xE5ste vara en multipel av ${issue2.divisor}`;
          case "unrecognized_keys":
            return `${issue2.keys.length > 1 ? "Ok\xE4nda nycklar" : "Ok\xE4nd nyckel"}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Ogiltig nyckel i ${issue2.origin ?? "v\xE4rdet"}`;
          case "invalid_union":
            return "Ogiltig input";
          case "invalid_element":
            return `Ogiltigt v\xE4rde i ${issue2.origin ?? "v\xE4rdet"}`;
          default:
            return `Ogiltig input`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ta.js
function ta_default() {
  return {
    localeError: error32()
  };
}
var error32;
var init_ta = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ta.js"() {
    init_util2();
    error32 = () => {
      const Sizable = {
        string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" },
        file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" },
        array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" },
        set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "\u0B8E\u0BA3\u0BCD \u0B85\u0BB2\u0BCD\u0BB2\u0BBE\u0BA4\u0BA4\u0BC1" : "\u0B8E\u0BA3\u0BCD";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "\u0B85\u0BA3\u0BBF";
            }
            if (data === null) {
              return "\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1",
        email: "\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",
        date: "ISO \u0BA4\u0BC7\u0BA4\u0BBF",
        time: "ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",
        duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1",
        ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",
        ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",
        cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",
        cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",
        base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD",
        base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD",
        json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD",
        e164: "E.164 \u0B8E\u0BA3\u0BCD",
        jwt: "JWT",
        template_literal: "input"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${stringifyPrimitive(issue2.values[0])}`;
            return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${joinValues(issue2.values, "|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
            }
            return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
            }
            return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
            if (_issue.format === "ends_with")
              return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
            if (_issue.format === "includes")
              return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
            if (_issue.format === "regex")
              return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${_issue.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
            return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${issue2.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
          case "unrecognized_keys":
            return `\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${issue2.keys.length > 1 ? "\u0B95\u0BB3\u0BCD" : ""}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;
          case "invalid_union":
            return "\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";
          case "invalid_element":
            return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;
          default:
            return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/th.js
function th_default() {
  return {
    localeError: error33()
  };
}
var error33;
var init_th = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/th.js"() {
    init_util2();
    error33 = () => {
      const Sizable = {
        string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" },
        file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" },
        array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" },
        set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "\u0E44\u0E21\u0E48\u0E43\u0E0A\u0E48\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02 (NaN)" : "\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)";
            }
            if (data === null) {
              return "\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19",
        email: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25",
        url: "URL",
        emoji: "\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",
        date: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO",
        time: "\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",
        duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",
        ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4",
        ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6",
        cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4",
        cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6",
        base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64",
        base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL",
        json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON",
        e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)",
        jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT",
        template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${issue2.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${stringifyPrimitive(issue2.values[0])}`;
            return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19" : "\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`;
            return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? "\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22" : "\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with") {
              return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${_issue.prefix}"`;
            }
            if (_issue.format === "ends_with")
              return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${_issue.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`;
            if (_issue.format === "regex")
              return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${_issue.pattern}`;
            return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${issue2.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;
          case "unrecognized_keys":
            return `\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`;
          case "invalid_union":
            return "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49";
          case "invalid_element":
            return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`;
          default:
            return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/tr.js
function tr_default() {
  return {
    localeError: error34()
  };
}
var parsedType3, error34;
var init_tr = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/tr.js"() {
    init_util2();
    parsedType3 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "number";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "array";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    error34 = () => {
      const Sizable = {
        string: { unit: "karakter", verb: "olmal\u0131" },
        file: { unit: "bayt", verb: "olmal\u0131" },
        array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" },
        set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const Nouns = {
        regex: "girdi",
        email: "e-posta adresi",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO tarih ve saat",
        date: "ISO tarih",
        time: "ISO saat",
        duration: "ISO s\xFCre",
        ipv4: "IPv4 adresi",
        ipv6: "IPv6 adresi",
        cidrv4: "IPv4 aral\u0131\u011F\u0131",
        cidrv6: "IPv6 aral\u0131\u011F\u0131",
        base64: "base64 ile \u015Fifrelenmi\u015F metin",
        base64url: "base64url ile \u015Fifrelenmi\u015F metin",
        json_string: "JSON dizesi",
        e164: "E.164 say\u0131s\u0131",
        jwt: "JWT",
        template_literal: "\u015Eablon dizesi"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Ge\xE7ersiz de\u011Fer: beklenen ${issue2.expected}, al\u0131nan ${parsedType3(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Ge\xE7ersiz de\u011Fer: beklenen ${stringifyPrimitive(issue2.values[0])}`;
            return `Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin ?? "de\u011Fer"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xF6\u011Fe"}`;
            return `\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin ?? "de\u011Fer"} ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `Ge\xE7ersiz metin: "${_issue.prefix}" ile ba\u015Flamal\u0131`;
            if (_issue.format === "ends_with")
              return `Ge\xE7ersiz metin: "${_issue.suffix}" ile bitmeli`;
            if (_issue.format === "includes")
              return `Ge\xE7ersiz metin: "${_issue.includes}" i\xE7ermeli`;
            if (_issue.format === "regex")
              return `Ge\xE7ersiz metin: ${_issue.pattern} desenine uymal\u0131`;
            return `Ge\xE7ersiz ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `Ge\xE7ersiz say\u0131: ${issue2.divisor} ile tam b\xF6l\xFCnebilmeli`;
          case "unrecognized_keys":
            return `Tan\u0131nmayan anahtar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `${issue2.origin} i\xE7inde ge\xE7ersiz anahtar`;
          case "invalid_union":
            return "Ge\xE7ersiz de\u011Fer";
          case "invalid_element":
            return `${issue2.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;
          default:
            return `Ge\xE7ersiz de\u011Fer`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ua.js
function ua_default() {
  return {
    localeError: error35()
  };
}
var error35;
var init_ua = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ua.js"() {
    init_util2();
    error35 = () => {
      const Sizable = {
        string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" },
        file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" },
        array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" },
        set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "\u0447\u0438\u0441\u043B\u043E";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "\u043C\u0430\u0441\u0438\u0432";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456",
        email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438",
        url: "URL",
        emoji: "\u0435\u043C\u043E\u0434\u0437\u0456",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO",
        date: "\u0434\u0430\u0442\u0430 ISO",
        time: "\u0447\u0430\u0441 ISO",
        duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO",
        ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4",
        ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6",
        cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4",
        cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6",
        base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64",
        base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url",
        json_string: "\u0440\u044F\u0434\u043E\u043A JSON",
        e164: "\u043D\u043E\u043C\u0435\u0440 E.164",
        jwt: "JWT",
        template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${issue2.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${parsedType4(issue2.input)}`;
          // return `Неправильні вхідні дані: очікується ${issue.expected}, отримано ${util.getParsedType(issue.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`;
            return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`;
            return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} \u0431\u0443\u0434\u0435 ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`;
            return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${issue2.divisor}`;
          case "unrecognized_keys":
            return `\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0456" : ""}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`;
          case "invalid_union":
            return "\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";
          case "invalid_element":
            return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${issue2.origin}`;
          default:
            return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ur.js
function ur_default() {
  return {
    localeError: error36()
  };
}
var error36;
var init_ur = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ur.js"() {
    init_util2();
    error36 = () => {
      const Sizable = {
        string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" },
        file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" },
        array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" },
        set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "\u0646\u0645\u0628\u0631";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "\u0622\u0631\u06D2";
            }
            if (data === null) {
              return "\u0646\u0644";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "\u0627\u0646 \u067E\u0679",
        email: "\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633",
        url: "\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644",
        emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC",
        uuid: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",
        uuidv4: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4",
        uuidv6: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6",
        nanoid: "\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC",
        guid: "\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",
        cuid: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",
        cuid2: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2",
        ulid: "\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC",
        xid: "\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC",
        ksuid: "\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",
        datetime: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645",
        date: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E",
        time: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A",
        duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A",
        ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633",
        ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633",
        cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C",
        cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C",
        base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",
        base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",
        json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF",
        e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631",
        jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC",
        template_literal: "\u0627\u0646 \u067E\u0679"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${issue2.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${parsedType4(issue2.input)} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${stringifyPrimitive(issue2.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
            return `\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${joinValues(issue2.values, "|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;
            return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${adj}${issue2.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u06D2 ${adj}${issue2.minimum.toString()} ${sizing.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;
            }
            return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u0627 ${adj}${issue2.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with") {
              return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
            }
            if (_issue.format === "ends_with")
              return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
            if (_issue.format === "includes")
              return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
            if (_issue.format === "regex")
              return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${_issue.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
            return `\u063A\u0644\u0637 ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${issue2.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
          case "unrecognized_keys":
            return `\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${issue2.keys.length > 1 ? "\u0632" : ""}: ${joinValues(issue2.keys, "\u060C ")}`;
          case "invalid_key":
            return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;
          case "invalid_union":
            return "\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";
          case "invalid_element":
            return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;
          default:
            return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/vi.js
function vi_default() {
  return {
    localeError: error37()
  };
}
var error37;
var init_vi = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/vi.js"() {
    init_util2();
    error37 = () => {
      const Sizable = {
        string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" },
        file: { unit: "byte", verb: "c\xF3" },
        array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" },
        set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "s\u1ED1";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "m\u1EA3ng";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "\u0111\u1EA7u v\xE0o",
        email: "\u0111\u1ECBa ch\u1EC9 email",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ng\xE0y gi\u1EDD ISO",
        date: "ng\xE0y ISO",
        time: "gi\u1EDD ISO",
        duration: "kho\u1EA3ng th\u1EDDi gian ISO",
        ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4",
        ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6",
        cidrv4: "d\u1EA3i IPv4",
        cidrv6: "d\u1EA3i IPv6",
        base64: "chu\u1ED7i m\xE3 h\xF3a base64",
        base64url: "chu\u1ED7i m\xE3 h\xF3a base64url",
        json_string: "chu\u1ED7i JSON",
        e164: "s\u1ED1 E.164",
        jwt: "JWT",
        template_literal: "\u0111\u1EA7u v\xE0o"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${issue2.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${stringifyPrimitive(issue2.values[0])}`;
            return `T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin ?? "gi\xE1 tr\u1ECB"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "ph\u1EA7n t\u1EED"}`;
            return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin ?? "gi\xE1 tr\u1ECB"} ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${_issue.pattern}`;
            return `${Nouns[_issue.format] ?? issue2.format} kh\xF4ng h\u1EE3p l\u1EC7`;
          }
          case "not_multiple_of":
            return `S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${issue2.divisor}`;
          case "unrecognized_keys":
            return `Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`;
          case "invalid_union":
            return "\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7";
          case "invalid_element":
            return `Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`;
          default:
            return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/zh-CN.js
function zh_CN_default() {
  return {
    localeError: error38()
  };
}
var error38;
var init_zh_CN = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/zh-CN.js"() {
    init_util2();
    error38 = () => {
      const Sizable = {
        string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" },
        file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" },
        array: { unit: "\u9879", verb: "\u5305\u542B" },
        set: { unit: "\u9879", verb: "\u5305\u542B" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "\u975E\u6570\u5B57(NaN)" : "\u6570\u5B57";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "\u6570\u7EC4";
            }
            if (data === null) {
              return "\u7A7A\u503C(null)";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "\u8F93\u5165",
        email: "\u7535\u5B50\u90AE\u4EF6",
        url: "URL",
        emoji: "\u8868\u60C5\u7B26\u53F7",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO\u65E5\u671F\u65F6\u95F4",
        date: "ISO\u65E5\u671F",
        time: "ISO\u65F6\u95F4",
        duration: "ISO\u65F6\u957F",
        ipv4: "IPv4\u5730\u5740",
        ipv6: "IPv6\u5730\u5740",
        cidrv4: "IPv4\u7F51\u6BB5",
        cidrv6: "IPv6\u7F51\u6BB5",
        base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32",
        base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32",
        json_string: "JSON\u5B57\u7B26\u4E32",
        e164: "E.164\u53F7\u7801",
        jwt: "JWT",
        template_literal: "\u8F93\u5165"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${issue2.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${stringifyPrimitive(issue2.values[0])}`;
            return `\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin ?? "\u503C"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u4E2A\u5143\u7D20"}`;
            return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin ?? "\u503C"} ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.prefix}" \u5F00\u5934`;
            if (_issue.format === "ends_with")
              return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.suffix}" \u7ED3\u5C3E`;
            if (_issue.format === "includes")
              return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${_issue.pattern}`;
            return `\u65E0\u6548${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${issue2.divisor} \u7684\u500D\u6570`;
          case "unrecognized_keys":
            return `\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `${issue2.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;
          case "invalid_union":
            return "\u65E0\u6548\u8F93\u5165";
          case "invalid_element":
            return `${issue2.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;
          default:
            return `\u65E0\u6548\u8F93\u5165`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/zh-TW.js
function zh_TW_default() {
  return {
    localeError: error39()
  };
}
var error39;
var init_zh_TW = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/zh-TW.js"() {
    init_util2();
    error39 = () => {
      const Sizable = {
        string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" },
        file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" },
        array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" },
        set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      const parsedType4 = (data) => {
        const t = typeof data;
        switch (t) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "number";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "array";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t;
      };
      const Nouns = {
        regex: "\u8F38\u5165",
        email: "\u90F5\u4EF6\u5730\u5740",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO \u65E5\u671F\u6642\u9593",
        date: "ISO \u65E5\u671F",
        time: "ISO \u6642\u9593",
        duration: "ISO \u671F\u9593",
        ipv4: "IPv4 \u4F4D\u5740",
        ipv6: "IPv6 \u4F4D\u5740",
        cidrv4: "IPv4 \u7BC4\u570D",
        cidrv6: "IPv6 \u7BC4\u570D",
        base64: "base64 \u7DE8\u78BC\u5B57\u4E32",
        base64url: "base64url \u7DE8\u78BC\u5B57\u4E32",
        json_string: "JSON \u5B57\u4E32",
        e164: "E.164 \u6578\u503C",
        jwt: "JWT",
        template_literal: "\u8F38\u5165"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${issue2.expected}\uFF0C\u4F46\u6536\u5230 ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${stringifyPrimitive(issue2.values[0])}`;
            return `\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u500B\u5143\u7D20"}`;
            return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with") {
              return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.prefix}" \u958B\u982D`;
            }
            if (_issue.format === "ends_with")
              return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.suffix}" \u7D50\u5C3E`;
            if (_issue.format === "includes")
              return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${_issue.pattern}`;
            return `\u7121\u6548\u7684 ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${issue2.divisor} \u7684\u500D\u6578`;
          case "unrecognized_keys":
            return `\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${issue2.keys.length > 1 ? "\u5011" : ""}\uFF1A${joinValues(issue2.keys, "\u3001")}`;
          case "invalid_key":
            return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;
          case "invalid_union":
            return "\u7121\u6548\u7684\u8F38\u5165\u503C";
          case "invalid_element":
            return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;
          default:
            return `\u7121\u6548\u7684\u8F38\u5165\u503C`;
        }
      };
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/index.js
var locales_exports = {};
__export(locales_exports, {
  ar: () => ar_default,
  az: () => az_default,
  be: () => be_default,
  ca: () => ca_default,
  cs: () => cs_default,
  de: () => de_default,
  en: () => en_default2,
  eo: () => eo_default,
  es: () => es_default,
  fa: () => fa_default,
  fi: () => fi_default,
  fr: () => fr_default,
  frCA: () => fr_CA_default,
  he: () => he_default,
  hu: () => hu_default,
  id: () => id_default,
  it: () => it_default,
  ja: () => ja_default,
  kh: () => kh_default,
  ko: () => ko_default,
  mk: () => mk_default,
  ms: () => ms_default,
  nl: () => nl_default,
  no: () => no_default,
  ota: () => ota_default,
  pl: () => pl_default,
  ps: () => ps_default,
  pt: () => pt_default,
  ru: () => ru_default,
  sl: () => sl_default,
  sv: () => sv_default,
  ta: () => ta_default,
  th: () => th_default,
  tr: () => tr_default,
  ua: () => ua_default,
  ur: () => ur_default,
  vi: () => vi_default,
  zhCN: () => zh_CN_default,
  zhTW: () => zh_TW_default
});
var init_locales = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/index.js"() {
    init_ar();
    init_az();
    init_be();
    init_ca();
    init_cs();
    init_de();
    init_en2();
    init_eo();
    init_es();
    init_fa();
    init_fi();
    init_fr();
    init_fr_CA();
    init_he();
    init_hu();
    init_id();
    init_it();
    init_ja();
    init_kh();
    init_ko();
    init_mk();
    init_ms();
    init_nl();
    init_no();
    init_ota();
    init_ps();
    init_pl();
    init_pt();
    init_ru();
    init_sl();
    init_sv();
    init_ta();
    init_th();
    init_tr();
    init_ua();
    init_ur();
    init_vi();
    init_zh_CN();
    init_zh_TW();
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/registries.js
function registry() {
  return new $ZodRegistry();
}
var $output, $input, $ZodRegistry, globalRegistry;
var init_registries = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/registries.js"() {
    $output = /* @__PURE__ */ Symbol("ZodOutput");
    $input = /* @__PURE__ */ Symbol("ZodInput");
    $ZodRegistry = class {
      constructor() {
        this._map = /* @__PURE__ */ new Map();
        this._idmap = /* @__PURE__ */ new Map();
      }
      add(schema, ..._meta) {
        const meta = _meta[0];
        this._map.set(schema, meta);
        if (meta && typeof meta === "object" && "id" in meta) {
          if (this._idmap.has(meta.id)) {
            throw new Error(`ID ${meta.id} already exists in the registry`);
          }
          this._idmap.set(meta.id, schema);
        }
        return this;
      }
      clear() {
        this._map = /* @__PURE__ */ new Map();
        this._idmap = /* @__PURE__ */ new Map();
        return this;
      }
      remove(schema) {
        const meta = this._map.get(schema);
        if (meta && typeof meta === "object" && "id" in meta) {
          this._idmap.delete(meta.id);
        }
        this._map.delete(schema);
        return this;
      }
      get(schema) {
        const p = schema._zod.parent;
        if (p) {
          const pm = { ...this.get(p) ?? {} };
          delete pm.id;
          return { ...pm, ...this._map.get(schema) };
        }
        return this._map.get(schema);
      }
      has(schema) {
        return this._map.has(schema);
      }
    };
    globalRegistry = /* @__PURE__ */ registry();
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/api.js
function _string(Class2, params) {
  return new Class2({
    type: "string",
    ...normalizeParams(params)
  });
}
function _coercedString(Class2, params) {
  return new Class2({
    type: "string",
    coerce: true,
    ...normalizeParams(params)
  });
}
function _email(Class2, params) {
  return new Class2({
    type: "string",
    format: "email",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _guid(Class2, params) {
  return new Class2({
    type: "string",
    format: "guid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _uuid(Class2, params) {
  return new Class2({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _uuidv4(Class2, params) {
  return new Class2({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    version: "v4",
    ...normalizeParams(params)
  });
}
function _uuidv6(Class2, params) {
  return new Class2({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    version: "v6",
    ...normalizeParams(params)
  });
}
function _uuidv7(Class2, params) {
  return new Class2({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    version: "v7",
    ...normalizeParams(params)
  });
}
function _url(Class2, params) {
  return new Class2({
    type: "string",
    format: "url",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _emoji2(Class2, params) {
  return new Class2({
    type: "string",
    format: "emoji",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _nanoid(Class2, params) {
  return new Class2({
    type: "string",
    format: "nanoid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _cuid(Class2, params) {
  return new Class2({
    type: "string",
    format: "cuid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _cuid2(Class2, params) {
  return new Class2({
    type: "string",
    format: "cuid2",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _ulid(Class2, params) {
  return new Class2({
    type: "string",
    format: "ulid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _xid(Class2, params) {
  return new Class2({
    type: "string",
    format: "xid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _ksuid(Class2, params) {
  return new Class2({
    type: "string",
    format: "ksuid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _ipv4(Class2, params) {
  return new Class2({
    type: "string",
    format: "ipv4",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _ipv6(Class2, params) {
  return new Class2({
    type: "string",
    format: "ipv6",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _cidrv4(Class2, params) {
  return new Class2({
    type: "string",
    format: "cidrv4",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _cidrv6(Class2, params) {
  return new Class2({
    type: "string",
    format: "cidrv6",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _base64(Class2, params) {
  return new Class2({
    type: "string",
    format: "base64",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _base64url(Class2, params) {
  return new Class2({
    type: "string",
    format: "base64url",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _e164(Class2, params) {
  return new Class2({
    type: "string",
    format: "e164",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _jwt(Class2, params) {
  return new Class2({
    type: "string",
    format: "jwt",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _isoDateTime(Class2, params) {
  return new Class2({
    type: "string",
    format: "datetime",
    check: "string_format",
    offset: false,
    local: false,
    precision: null,
    ...normalizeParams(params)
  });
}
function _isoDate(Class2, params) {
  return new Class2({
    type: "string",
    format: "date",
    check: "string_format",
    ...normalizeParams(params)
  });
}
function _isoTime(Class2, params) {
  return new Class2({
    type: "string",
    format: "time",
    check: "string_format",
    precision: null,
    ...normalizeParams(params)
  });
}
function _isoDuration(Class2, params) {
  return new Class2({
    type: "string",
    format: "duration",
    check: "string_format",
    ...normalizeParams(params)
  });
}
function _number(Class2, params) {
  return new Class2({
    type: "number",
    checks: [],
    ...normalizeParams(params)
  });
}
function _coercedNumber(Class2, params) {
  return new Class2({
    type: "number",
    coerce: true,
    checks: [],
    ...normalizeParams(params)
  });
}
function _int(Class2, params) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "safeint",
    ...normalizeParams(params)
  });
}
function _float32(Class2, params) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "float32",
    ...normalizeParams(params)
  });
}
function _float64(Class2, params) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "float64",
    ...normalizeParams(params)
  });
}
function _int32(Class2, params) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "int32",
    ...normalizeParams(params)
  });
}
function _uint32(Class2, params) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "uint32",
    ...normalizeParams(params)
  });
}
function _boolean(Class2, params) {
  return new Class2({
    type: "boolean",
    ...normalizeParams(params)
  });
}
function _coercedBoolean(Class2, params) {
  return new Class2({
    type: "boolean",
    coerce: true,
    ...normalizeParams(params)
  });
}
function _bigint(Class2, params) {
  return new Class2({
    type: "bigint",
    ...normalizeParams(params)
  });
}
function _coercedBigint(Class2, params) {
  return new Class2({
    type: "bigint",
    coerce: true,
    ...normalizeParams(params)
  });
}
function _int64(Class2, params) {
  return new Class2({
    type: "bigint",
    check: "bigint_format",
    abort: false,
    format: "int64",
    ...normalizeParams(params)
  });
}
function _uint64(Class2, params) {
  return new Class2({
    type: "bigint",
    check: "bigint_format",
    abort: false,
    format: "uint64",
    ...normalizeParams(params)
  });
}
function _symbol(Class2, params) {
  return new Class2({
    type: "symbol",
    ...normalizeParams(params)
  });
}
function _undefined2(Class2, params) {
  return new Class2({
    type: "undefined",
    ...normalizeParams(params)
  });
}
function _null2(Class2, params) {
  return new Class2({
    type: "null",
    ...normalizeParams(params)
  });
}
function _any(Class2) {
  return new Class2({
    type: "any"
  });
}
function _unknown(Class2) {
  return new Class2({
    type: "unknown"
  });
}
function _never(Class2, params) {
  return new Class2({
    type: "never",
    ...normalizeParams(params)
  });
}
function _void(Class2, params) {
  return new Class2({
    type: "void",
    ...normalizeParams(params)
  });
}
function _date(Class2, params) {
  return new Class2({
    type: "date",
    ...normalizeParams(params)
  });
}
function _coercedDate(Class2, params) {
  return new Class2({
    type: "date",
    coerce: true,
    ...normalizeParams(params)
  });
}
function _nan(Class2, params) {
  return new Class2({
    type: "nan",
    ...normalizeParams(params)
  });
}
function _lt(value, params) {
  return new $ZodCheckLessThan({
    check: "less_than",
    ...normalizeParams(params),
    value,
    inclusive: false
  });
}
function _lte(value, params) {
  return new $ZodCheckLessThan({
    check: "less_than",
    ...normalizeParams(params),
    value,
    inclusive: true
  });
}
function _gt(value, params) {
  return new $ZodCheckGreaterThan({
    check: "greater_than",
    ...normalizeParams(params),
    value,
    inclusive: false
  });
}
function _gte(value, params) {
  return new $ZodCheckGreaterThan({
    check: "greater_than",
    ...normalizeParams(params),
    value,
    inclusive: true
  });
}
function _positive(params) {
  return _gt(0, params);
}
function _negative(params) {
  return _lt(0, params);
}
function _nonpositive(params) {
  return _lte(0, params);
}
function _nonnegative(params) {
  return _gte(0, params);
}
function _multipleOf(value, params) {
  return new $ZodCheckMultipleOf({
    check: "multiple_of",
    ...normalizeParams(params),
    value
  });
}
function _maxSize(maximum, params) {
  return new $ZodCheckMaxSize({
    check: "max_size",
    ...normalizeParams(params),
    maximum
  });
}
function _minSize(minimum, params) {
  return new $ZodCheckMinSize({
    check: "min_size",
    ...normalizeParams(params),
    minimum
  });
}
function _size(size, params) {
  return new $ZodCheckSizeEquals({
    check: "size_equals",
    ...normalizeParams(params),
    size
  });
}
function _maxLength(maximum, params) {
  const ch = new $ZodCheckMaxLength({
    check: "max_length",
    ...normalizeParams(params),
    maximum
  });
  return ch;
}
function _minLength(minimum, params) {
  return new $ZodCheckMinLength({
    check: "min_length",
    ...normalizeParams(params),
    minimum
  });
}
function _length(length, params) {
  return new $ZodCheckLengthEquals({
    check: "length_equals",
    ...normalizeParams(params),
    length
  });
}
function _regex(pattern, params) {
  return new $ZodCheckRegex({
    check: "string_format",
    format: "regex",
    ...normalizeParams(params),
    pattern
  });
}
function _lowercase(params) {
  return new $ZodCheckLowerCase({
    check: "string_format",
    format: "lowercase",
    ...normalizeParams(params)
  });
}
function _uppercase(params) {
  return new $ZodCheckUpperCase({
    check: "string_format",
    format: "uppercase",
    ...normalizeParams(params)
  });
}
function _includes(includes, params) {
  return new $ZodCheckIncludes({
    check: "string_format",
    format: "includes",
    ...normalizeParams(params),
    includes
  });
}
function _startsWith(prefix, params) {
  return new $ZodCheckStartsWith({
    check: "string_format",
    format: "starts_with",
    ...normalizeParams(params),
    prefix
  });
}
function _endsWith(suffix, params) {
  return new $ZodCheckEndsWith({
    check: "string_format",
    format: "ends_with",
    ...normalizeParams(params),
    suffix
  });
}
function _property(property, schema, params) {
  return new $ZodCheckProperty({
    check: "property",
    property,
    schema,
    ...normalizeParams(params)
  });
}
function _mime(types3, params) {
  return new $ZodCheckMimeType({
    check: "mime_type",
    mime: types3,
    ...normalizeParams(params)
  });
}
function _overwrite(tx) {
  return new $ZodCheckOverwrite({
    check: "overwrite",
    tx
  });
}
function _normalize(form) {
  return _overwrite((input) => input.normalize(form));
}
function _trim() {
  return _overwrite((input) => input.trim());
}
function _toLowerCase() {
  return _overwrite((input) => input.toLowerCase());
}
function _toUpperCase() {
  return _overwrite((input) => input.toUpperCase());
}
function _array(Class2, element, params) {
  return new Class2({
    type: "array",
    element,
    // get element() {
    //   return element;
    // },
    ...normalizeParams(params)
  });
}
function _union(Class2, options, params) {
  return new Class2({
    type: "union",
    options,
    ...normalizeParams(params)
  });
}
function _discriminatedUnion(Class2, discriminator, options, params) {
  return new Class2({
    type: "union",
    options,
    discriminator,
    ...normalizeParams(params)
  });
}
function _intersection(Class2, left, right) {
  return new Class2({
    type: "intersection",
    left,
    right
  });
}
function _tuple(Class2, items, _paramsOrRest, _params) {
  const hasRest = _paramsOrRest instanceof $ZodType;
  const params = hasRest ? _params : _paramsOrRest;
  const rest = hasRest ? _paramsOrRest : null;
  return new Class2({
    type: "tuple",
    items,
    rest,
    ...normalizeParams(params)
  });
}
function _record(Class2, keyType, valueType, params) {
  return new Class2({
    type: "record",
    keyType,
    valueType,
    ...normalizeParams(params)
  });
}
function _map(Class2, keyType, valueType, params) {
  return new Class2({
    type: "map",
    keyType,
    valueType,
    ...normalizeParams(params)
  });
}
function _set(Class2, valueType, params) {
  return new Class2({
    type: "set",
    valueType,
    ...normalizeParams(params)
  });
}
function _enum(Class2, values, params) {
  const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
  return new Class2({
    type: "enum",
    entries,
    ...normalizeParams(params)
  });
}
function _nativeEnum(Class2, entries, params) {
  return new Class2({
    type: "enum",
    entries,
    ...normalizeParams(params)
  });
}
function _literal(Class2, value, params) {
  return new Class2({
    type: "literal",
    values: Array.isArray(value) ? value : [value],
    ...normalizeParams(params)
  });
}
function _file(Class2, params) {
  return new Class2({
    type: "file",
    ...normalizeParams(params)
  });
}
function _transform(Class2, fn) {
  return new Class2({
    type: "transform",
    transform: fn
  });
}
function _optional(Class2, innerType) {
  return new Class2({
    type: "optional",
    innerType
  });
}
function _nullable(Class2, innerType) {
  return new Class2({
    type: "nullable",
    innerType
  });
}
function _default(Class2, innerType, defaultValue) {
  return new Class2({
    type: "default",
    innerType,
    get defaultValue() {
      return typeof defaultValue === "function" ? defaultValue() : defaultValue;
    }
  });
}
function _nonoptional(Class2, innerType, params) {
  return new Class2({
    type: "nonoptional",
    innerType,
    ...normalizeParams(params)
  });
}
function _success(Class2, innerType) {
  return new Class2({
    type: "success",
    innerType
  });
}
function _catch(Class2, innerType, catchValue) {
  return new Class2({
    type: "catch",
    innerType,
    catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
  });
}
function _pipe(Class2, in_, out) {
  return new Class2({
    type: "pipe",
    in: in_,
    out
  });
}
function _readonly(Class2, innerType) {
  return new Class2({
    type: "readonly",
    innerType
  });
}
function _templateLiteral(Class2, parts, params) {
  return new Class2({
    type: "template_literal",
    parts,
    ...normalizeParams(params)
  });
}
function _lazy(Class2, getter) {
  return new Class2({
    type: "lazy",
    getter
  });
}
function _promise(Class2, innerType) {
  return new Class2({
    type: "promise",
    innerType
  });
}
function _custom(Class2, fn, _params) {
  const norm = normalizeParams(_params);
  norm.abort ?? (norm.abort = true);
  const schema = new Class2({
    type: "custom",
    check: "custom",
    fn,
    ...norm
  });
  return schema;
}
function _refine(Class2, fn, _params) {
  const schema = new Class2({
    type: "custom",
    check: "custom",
    fn,
    ...normalizeParams(_params)
  });
  return schema;
}
function _stringbool(Classes, _params) {
  const params = normalizeParams(_params);
  let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"];
  let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"];
  if (params.case !== "sensitive") {
    truthyArray = truthyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v);
    falsyArray = falsyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v);
  }
  const truthySet = new Set(truthyArray);
  const falsySet = new Set(falsyArray);
  const _Pipe = Classes.Pipe ?? $ZodPipe;
  const _Boolean = Classes.Boolean ?? $ZodBoolean;
  const _String = Classes.String ?? $ZodString;
  const _Transform = Classes.Transform ?? $ZodTransform;
  const tx = new _Transform({
    type: "transform",
    transform: (input, payload) => {
      let data = input;
      if (params.case !== "sensitive")
        data = data.toLowerCase();
      if (truthySet.has(data)) {
        return true;
      } else if (falsySet.has(data)) {
        return false;
      } else {
        payload.issues.push({
          code: "invalid_value",
          expected: "stringbool",
          values: [...truthySet, ...falsySet],
          input: payload.value,
          inst: tx
        });
        return {};
      }
    },
    error: params.error
  });
  const innerPipe = new _Pipe({
    type: "pipe",
    in: new _String({ type: "string", error: params.error }),
    out: tx,
    error: params.error
  });
  const outerPipe = new _Pipe({
    type: "pipe",
    in: innerPipe,
    out: new _Boolean({
      type: "boolean",
      error: params.error
    }),
    error: params.error
  });
  return outerPipe;
}
function _stringFormat(Class2, format, fnOrRegex, _params = {}) {
  const params = normalizeParams(_params);
  const def = {
    ...normalizeParams(_params),
    check: "string_format",
    type: "string",
    format,
    fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val),
    ...params
  };
  if (fnOrRegex instanceof RegExp) {
    def.pattern = fnOrRegex;
  }
  const inst = new Class2(def);
  return inst;
}
var TimePrecision;
var init_api2 = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/api.js"() {
    init_checks2();
    init_schemas();
    init_util2();
    TimePrecision = {
      Any: null,
      Minute: -1,
      Second: 0,
      Millisecond: 3,
      Microsecond: 6
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/function.js
function _function(params) {
  return new $ZodFunction({
    type: "function",
    input: Array.isArray(params?.input) ? _tuple($ZodTuple, params?.input) : params?.input ?? _array($ZodArray, _unknown($ZodUnknown)),
    output: params?.output ?? _unknown($ZodUnknown)
  });
}
var $ZodFunction;
var init_function = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/function.js"() {
    init_api2();
    init_parse();
    init_schemas();
    init_schemas();
    $ZodFunction = class {
      constructor(def) {
        this._def = def;
        this.def = def;
      }
      implement(func) {
        if (typeof func !== "function") {
          throw new Error("implement() must be called with a function");
        }
        const impl = ((...args) => {
          const parsedArgs = this._def.input ? parse(this._def.input, args, void 0, { callee: impl }) : args;
          if (!Array.isArray(parsedArgs)) {
            throw new Error("Invalid arguments schema: not an array or tuple schema.");
          }
          const output = func(...parsedArgs);
          return this._def.output ? parse(this._def.output, output, void 0, { callee: impl }) : output;
        });
        return impl;
      }
      implementAsync(func) {
        if (typeof func !== "function") {
          throw new Error("implement() must be called with a function");
        }
        const impl = (async (...args) => {
          const parsedArgs = this._def.input ? await parseAsync(this._def.input, args, void 0, { callee: impl }) : args;
          if (!Array.isArray(parsedArgs)) {
            throw new Error("Invalid arguments schema: not an array or tuple schema.");
          }
          const output = await func(...parsedArgs);
          return this._def.output ? parseAsync(this._def.output, output, void 0, { callee: impl }) : output;
        });
        return impl;
      }
      input(...args) {
        const F = this.constructor;
        if (Array.isArray(args[0])) {
          return new F({
            type: "function",
            input: new $ZodTuple({
              type: "tuple",
              items: args[0],
              rest: args[1]
            }),
            output: this._def.output
          });
        }
        return new F({
          type: "function",
          input: args[0],
          output: this._def.output
        });
      }
      output(output) {
        const F = this.constructor;
        return new F({
          type: "function",
          input: this._def.input,
          output
        });
      }
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/to-json-schema.js
function toJSONSchema(input, _params) {
  if (input instanceof $ZodRegistry) {
    const gen2 = new JSONSchemaGenerator(_params);
    const defs = {};
    for (const entry of input._idmap.entries()) {
      const [_, schema] = entry;
      gen2.process(schema);
    }
    const schemas = {};
    const external = {
      registry: input,
      uri: _params?.uri,
      defs
    };
    for (const entry of input._idmap.entries()) {
      const [key, schema] = entry;
      schemas[key] = gen2.emit(schema, {
        ..._params,
        external
      });
    }
    if (Object.keys(defs).length > 0) {
      const defsSegment = gen2.target === "draft-2020-12" ? "$defs" : "definitions";
      schemas.__shared = {
        [defsSegment]: defs
      };
    }
    return { schemas };
  }
  const gen = new JSONSchemaGenerator(_params);
  gen.process(input);
  return gen.emit(input, _params);
}
function isTransforming(_schema, _ctx) {
  const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() };
  if (ctx.seen.has(_schema))
    return false;
  ctx.seen.add(_schema);
  const schema = _schema;
  const def = schema._zod.def;
  switch (def.type) {
    case "string":
    case "number":
    case "bigint":
    case "boolean":
    case "date":
    case "symbol":
    case "undefined":
    case "null":
    case "any":
    case "unknown":
    case "never":
    case "void":
    case "literal":
    case "enum":
    case "nan":
    case "file":
    case "template_literal":
      return false;
    case "array": {
      return isTransforming(def.element, ctx);
    }
    case "object": {
      for (const key in def.shape) {
        if (isTransforming(def.shape[key], ctx))
          return true;
      }
      return false;
    }
    case "union": {
      for (const option of def.options) {
        if (isTransforming(option, ctx))
          return true;
      }
      return false;
    }
    case "intersection": {
      return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);
    }
    case "tuple": {
      for (const item of def.items) {
        if (isTransforming(item, ctx))
          return true;
      }
      if (def.rest && isTransforming(def.rest, ctx))
        return true;
      return false;
    }
    case "record": {
      return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
    }
    case "map": {
      return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
    }
    case "set": {
      return isTransforming(def.valueType, ctx);
    }
    // inner types
    case "promise":
    case "optional":
    case "nonoptional":
    case "nullable":
    case "readonly":
      return isTransforming(def.innerType, ctx);
    case "lazy":
      return isTransforming(def.getter(), ctx);
    case "default": {
      return isTransforming(def.innerType, ctx);
    }
    case "prefault": {
      return isTransforming(def.innerType, ctx);
    }
    case "custom": {
      return false;
    }
    case "transform": {
      return true;
    }
    case "pipe": {
      return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);
    }
    case "success": {
      return false;
    }
    case "catch": {
      return false;
    }
    default:
      def;
  }
  throw new Error(`Unknown schema type: ${def.type}`);
}
var JSONSchemaGenerator;
var init_to_json_schema = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/to-json-schema.js"() {
    init_registries();
    init_util2();
    JSONSchemaGenerator = class {
      constructor(params) {
        this.counter = 0;
        this.metadataRegistry = params?.metadata ?? globalRegistry;
        this.target = params?.target ?? "draft-2020-12";
        this.unrepresentable = params?.unrepresentable ?? "throw";
        this.override = params?.override ?? (() => {
        });
        this.io = params?.io ?? "output";
        this.seen = /* @__PURE__ */ new Map();
      }
      process(schema, _params = { path: [], schemaPath: [] }) {
        var _a;
        const def = schema._zod.def;
        const formatMap = {
          guid: "uuid",
          url: "uri",
          datetime: "date-time",
          json_string: "json-string",
          regex: ""
          // do not set
        };
        const seen = this.seen.get(schema);
        if (seen) {
          seen.count++;
          const isCycle = _params.schemaPath.includes(schema);
          if (isCycle) {
            seen.cycle = _params.path;
          }
          return seen.schema;
        }
        const result = { schema: {}, count: 1, cycle: void 0, path: _params.path };
        this.seen.set(schema, result);
        const overrideSchema = schema._zod.toJSONSchema?.();
        if (overrideSchema) {
          result.schema = overrideSchema;
        } else {
          const params = {
            ..._params,
            schemaPath: [..._params.schemaPath, schema],
            path: _params.path
          };
          const parent = schema._zod.parent;
          if (parent) {
            result.ref = parent;
            this.process(parent, params);
            this.seen.get(parent).isParent = true;
          } else {
            const _json = result.schema;
            switch (def.type) {
              case "string": {
                const json3 = _json;
                json3.type = "string";
                const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag;
                if (typeof minimum === "number")
                  json3.minLength = minimum;
                if (typeof maximum === "number")
                  json3.maxLength = maximum;
                if (format) {
                  json3.format = formatMap[format] ?? format;
                  if (json3.format === "")
                    delete json3.format;
                }
                if (contentEncoding)
                  json3.contentEncoding = contentEncoding;
                if (patterns && patterns.size > 0) {
                  const regexes = [...patterns];
                  if (regexes.length === 1)
                    json3.pattern = regexes[0].source;
                  else if (regexes.length > 1) {
                    result.schema.allOf = [
                      ...regexes.map((regex) => ({
                        ...this.target === "draft-7" ? { type: "string" } : {},
                        pattern: regex.source
                      }))
                    ];
                  }
                }
                break;
              }
              case "number": {
                const json3 = _json;
                const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;
                if (typeof format === "string" && format.includes("int"))
                  json3.type = "integer";
                else
                  json3.type = "number";
                if (typeof exclusiveMinimum === "number")
                  json3.exclusiveMinimum = exclusiveMinimum;
                if (typeof minimum === "number") {
                  json3.minimum = minimum;
                  if (typeof exclusiveMinimum === "number") {
                    if (exclusiveMinimum >= minimum)
                      delete json3.minimum;
                    else
                      delete json3.exclusiveMinimum;
                  }
                }
                if (typeof exclusiveMaximum === "number")
                  json3.exclusiveMaximum = exclusiveMaximum;
                if (typeof maximum === "number") {
                  json3.maximum = maximum;
                  if (typeof exclusiveMaximum === "number") {
                    if (exclusiveMaximum <= maximum)
                      delete json3.maximum;
                    else
                      delete json3.exclusiveMaximum;
                  }
                }
                if (typeof multipleOf === "number")
                  json3.multipleOf = multipleOf;
                break;
              }
              case "boolean": {
                const json3 = _json;
                json3.type = "boolean";
                break;
              }
              case "bigint": {
                if (this.unrepresentable === "throw") {
                  throw new Error("BigInt cannot be represented in JSON Schema");
                }
                break;
              }
              case "symbol": {
                if (this.unrepresentable === "throw") {
                  throw new Error("Symbols cannot be represented in JSON Schema");
                }
                break;
              }
              case "null": {
                _json.type = "null";
                break;
              }
              case "any": {
                break;
              }
              case "unknown": {
                break;
              }
              case "undefined": {
                if (this.unrepresentable === "throw") {
                  throw new Error("Undefined cannot be represented in JSON Schema");
                }
                break;
              }
              case "void": {
                if (this.unrepresentable === "throw") {
                  throw new Error("Void cannot be represented in JSON Schema");
                }
                break;
              }
              case "never": {
                _json.not = {};
                break;
              }
              case "date": {
                if (this.unrepresentable === "throw") {
                  throw new Error("Date cannot be represented in JSON Schema");
                }
                break;
              }
              case "array": {
                const json3 = _json;
                const { minimum, maximum } = schema._zod.bag;
                if (typeof minimum === "number")
                  json3.minItems = minimum;
                if (typeof maximum === "number")
                  json3.maxItems = maximum;
                json3.type = "array";
                json3.items = this.process(def.element, { ...params, path: [...params.path, "items"] });
                break;
              }
              case "object": {
                const json3 = _json;
                json3.type = "object";
                json3.properties = {};
                const shape = def.shape;
                for (const key in shape) {
                  json3.properties[key] = this.process(shape[key], {
                    ...params,
                    path: [...params.path, "properties", key]
                  });
                }
                const allKeys = new Set(Object.keys(shape));
                const requiredKeys = new Set([...allKeys].filter((key) => {
                  const v = def.shape[key]._zod;
                  if (this.io === "input") {
                    return v.optin === void 0;
                  } else {
                    return v.optout === void 0;
                  }
                }));
                if (requiredKeys.size > 0) {
                  json3.required = Array.from(requiredKeys);
                }
                if (def.catchall?._zod.def.type === "never") {
                  json3.additionalProperties = false;
                } else if (!def.catchall) {
                  if (this.io === "output")
                    json3.additionalProperties = false;
                } else if (def.catchall) {
                  json3.additionalProperties = this.process(def.catchall, {
                    ...params,
                    path: [...params.path, "additionalProperties"]
                  });
                }
                break;
              }
              case "union": {
                const json3 = _json;
                json3.anyOf = def.options.map((x, i) => this.process(x, {
                  ...params,
                  path: [...params.path, "anyOf", i]
                }));
                break;
              }
              case "intersection": {
                const json3 = _json;
                const a = this.process(def.left, {
                  ...params,
                  path: [...params.path, "allOf", 0]
                });
                const b = this.process(def.right, {
                  ...params,
                  path: [...params.path, "allOf", 1]
                });
                const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1;
                const allOf = [
                  ...isSimpleIntersection(a) ? a.allOf : [a],
                  ...isSimpleIntersection(b) ? b.allOf : [b]
                ];
                json3.allOf = allOf;
                break;
              }
              case "tuple": {
                const json3 = _json;
                json3.type = "array";
                const prefixItems = def.items.map((x, i) => this.process(x, { ...params, path: [...params.path, "prefixItems", i] }));
                if (this.target === "draft-2020-12") {
                  json3.prefixItems = prefixItems;
                } else {
                  json3.items = prefixItems;
                }
                if (def.rest) {
                  const rest = this.process(def.rest, {
                    ...params,
                    path: [...params.path, "items"]
                  });
                  if (this.target === "draft-2020-12") {
                    json3.items = rest;
                  } else {
                    json3.additionalItems = rest;
                  }
                }
                if (def.rest) {
                  json3.items = this.process(def.rest, {
                    ...params,
                    path: [...params.path, "items"]
                  });
                }
                const { minimum, maximum } = schema._zod.bag;
                if (typeof minimum === "number")
                  json3.minItems = minimum;
                if (typeof maximum === "number")
                  json3.maxItems = maximum;
                break;
              }
              case "record": {
                const json3 = _json;
                json3.type = "object";
                json3.propertyNames = this.process(def.keyType, { ...params, path: [...params.path, "propertyNames"] });
                json3.additionalProperties = this.process(def.valueType, {
                  ...params,
                  path: [...params.path, "additionalProperties"]
                });
                break;
              }
              case "map": {
                if (this.unrepresentable === "throw") {
                  throw new Error("Map cannot be represented in JSON Schema");
                }
                break;
              }
              case "set": {
                if (this.unrepresentable === "throw") {
                  throw new Error("Set cannot be represented in JSON Schema");
                }
                break;
              }
              case "enum": {
                const json3 = _json;
                const values = getEnumValues(def.entries);
                if (values.every((v) => typeof v === "number"))
                  json3.type = "number";
                if (values.every((v) => typeof v === "string"))
                  json3.type = "string";
                json3.enum = values;
                break;
              }
              case "literal": {
                const json3 = _json;
                const vals = [];
                for (const val of def.values) {
                  if (val === void 0) {
                    if (this.unrepresentable === "throw") {
                      throw new Error("Literal `undefined` cannot be represented in JSON Schema");
                    } else {
                    }
                  } else if (typeof val === "bigint") {
                    if (this.unrepresentable === "throw") {
                      throw new Error("BigInt literals cannot be represented in JSON Schema");
                    } else {
                      vals.push(Number(val));
                    }
                  } else {
                    vals.push(val);
                  }
                }
                if (vals.length === 0) {
                } else if (vals.length === 1) {
                  const val = vals[0];
                  json3.type = val === null ? "null" : typeof val;
                  json3.const = val;
                } else {
                  if (vals.every((v) => typeof v === "number"))
                    json3.type = "number";
                  if (vals.every((v) => typeof v === "string"))
                    json3.type = "string";
                  if (vals.every((v) => typeof v === "boolean"))
                    json3.type = "string";
                  if (vals.every((v) => v === null))
                    json3.type = "null";
                  json3.enum = vals;
                }
                break;
              }
              case "file": {
                const json3 = _json;
                const file2 = {
                  type: "string",
                  format: "binary",
                  contentEncoding: "binary"
                };
                const { minimum, maximum, mime } = schema._zod.bag;
                if (minimum !== void 0)
                  file2.minLength = minimum;
                if (maximum !== void 0)
                  file2.maxLength = maximum;
                if (mime) {
                  if (mime.length === 1) {
                    file2.contentMediaType = mime[0];
                    Object.assign(json3, file2);
                  } else {
                    json3.anyOf = mime.map((m) => {
                      const mFile = { ...file2, contentMediaType: m };
                      return mFile;
                    });
                  }
                } else {
                  Object.assign(json3, file2);
                }
                break;
              }
              case "transform": {
                if (this.unrepresentable === "throw") {
                  throw new Error("Transforms cannot be represented in JSON Schema");
                }
                break;
              }
              case "nullable": {
                const inner = this.process(def.innerType, params);
                _json.anyOf = [inner, { type: "null" }];
                break;
              }
              case "nonoptional": {
                this.process(def.innerType, params);
                result.ref = def.innerType;
                break;
              }
              case "success": {
                const json3 = _json;
                json3.type = "boolean";
                break;
              }
              case "default": {
                this.process(def.innerType, params);
                result.ref = def.innerType;
                _json.default = JSON.parse(JSON.stringify(def.defaultValue));
                break;
              }
              case "prefault": {
                this.process(def.innerType, params);
                result.ref = def.innerType;
                if (this.io === "input")
                  _json._prefault = JSON.parse(JSON.stringify(def.defaultValue));
                break;
              }
              case "catch": {
                this.process(def.innerType, params);
                result.ref = def.innerType;
                let catchValue;
                try {
                  catchValue = def.catchValue(void 0);
                } catch {
                  throw new Error("Dynamic catch values are not supported in JSON Schema");
                }
                _json.default = catchValue;
                break;
              }
              case "nan": {
                if (this.unrepresentable === "throw") {
                  throw new Error("NaN cannot be represented in JSON Schema");
                }
                break;
              }
              case "template_literal": {
                const json3 = _json;
                const pattern = schema._zod.pattern;
                if (!pattern)
                  throw new Error("Pattern not found in template literal");
                json3.type = "string";
                json3.pattern = pattern.source;
                break;
              }
              case "pipe": {
                const innerType = this.io === "input" ? def.in._zod.def.type === "transform" ? def.out : def.in : def.out;
                this.process(innerType, params);
                result.ref = innerType;
                break;
              }
              case "readonly": {
                this.process(def.innerType, params);
                result.ref = def.innerType;
                _json.readOnly = true;
                break;
              }
              // passthrough types
              case "promise": {
                this.process(def.innerType, params);
                result.ref = def.innerType;
                break;
              }
              case "optional": {
                this.process(def.innerType, params);
                result.ref = def.innerType;
                break;
              }
              case "lazy": {
                const innerType = schema._zod.innerType;
                this.process(innerType, params);
                result.ref = innerType;
                break;
              }
              case "custom": {
                if (this.unrepresentable === "throw") {
                  throw new Error("Custom types cannot be represented in JSON Schema");
                }
                break;
              }
              default: {
                def;
              }
            }
          }
        }
        const meta = this.metadataRegistry.get(schema);
        if (meta)
          Object.assign(result.schema, meta);
        if (this.io === "input" && isTransforming(schema)) {
          delete result.schema.examples;
          delete result.schema.default;
        }
        if (this.io === "input" && result.schema._prefault)
          (_a = result.schema).default ?? (_a.default = result.schema._prefault);
        delete result.schema._prefault;
        const _result = this.seen.get(schema);
        return _result.schema;
      }
      emit(schema, _params) {
        const params = {
          cycles: _params?.cycles ?? "ref",
          reused: _params?.reused ?? "inline",
          // unrepresentable: _params?.unrepresentable ?? "throw",
          // uri: _params?.uri ?? ((id) => `${id}`),
          external: _params?.external ?? void 0
        };
        const root = this.seen.get(schema);
        if (!root)
          throw new Error("Unprocessed schema. This is a bug in Zod.");
        const makeURI = (entry) => {
          const defsSegment = this.target === "draft-2020-12" ? "$defs" : "definitions";
          if (params.external) {
            const externalId = params.external.registry.get(entry[0])?.id;
            const uriGenerator = params.external.uri ?? ((id2) => id2);
            if (externalId) {
              return { ref: uriGenerator(externalId) };
            }
            const id = entry[1].defId ?? entry[1].schema.id ?? `schema${this.counter++}`;
            entry[1].defId = id;
            return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` };
          }
          if (entry[1] === root) {
            return { ref: "#" };
          }
          const uriPrefix = `#`;
          const defUriPrefix = `${uriPrefix}/${defsSegment}/`;
          const defId = entry[1].schema.id ?? `__schema${this.counter++}`;
          return { defId, ref: defUriPrefix + defId };
        };
        const extractToDef = (entry) => {
          if (entry[1].schema.$ref) {
            return;
          }
          const seen = entry[1];
          const { ref, defId } = makeURI(entry);
          seen.def = { ...seen.schema };
          if (defId)
            seen.defId = defId;
          const schema2 = seen.schema;
          for (const key in schema2) {
            delete schema2[key];
          }
          schema2.$ref = ref;
        };
        if (params.cycles === "throw") {
          for (const entry of this.seen.entries()) {
            const seen = entry[1];
            if (seen.cycle) {
              throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/<root>

Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`);
            }
          }
        }
        for (const entry of this.seen.entries()) {
          const seen = entry[1];
          if (schema === entry[0]) {
            extractToDef(entry);
            continue;
          }
          if (params.external) {
            const ext = params.external.registry.get(entry[0])?.id;
            if (schema !== entry[0] && ext) {
              extractToDef(entry);
              continue;
            }
          }
          const id = this.metadataRegistry.get(entry[0])?.id;
          if (id) {
            extractToDef(entry);
            continue;
          }
          if (seen.cycle) {
            extractToDef(entry);
            continue;
          }
          if (seen.count > 1) {
            if (params.reused === "ref") {
              extractToDef(entry);
              continue;
            }
          }
        }
        const flattenRef = (zodSchema, params2) => {
          const seen = this.seen.get(zodSchema);
          const schema2 = seen.def ?? seen.schema;
          const _cached = { ...schema2 };
          if (seen.ref === null) {
            return;
          }
          const ref = seen.ref;
          seen.ref = null;
          if (ref) {
            flattenRef(ref, params2);
            const refSchema = this.seen.get(ref).schema;
            if (refSchema.$ref && params2.target === "draft-7") {
              schema2.allOf = schema2.allOf ?? [];
              schema2.allOf.push(refSchema);
            } else {
              Object.assign(schema2, refSchema);
              Object.assign(schema2, _cached);
            }
          }
          if (!seen.isParent)
            this.override({
              zodSchema,
              jsonSchema: schema2,
              path: seen.path ?? []
            });
        };
        for (const entry of [...this.seen.entries()].reverse()) {
          flattenRef(entry[0], { target: this.target });
        }
        const result = {};
        if (this.target === "draft-2020-12") {
          result.$schema = "https://json-schema.org/draft/2020-12/schema";
        } else if (this.target === "draft-7") {
          result.$schema = "http://json-schema.org/draft-07/schema#";
        } else {
          console.warn(`Invalid target: ${this.target}`);
        }
        if (params.external?.uri) {
          const id = params.external.registry.get(schema)?.id;
          if (!id)
            throw new Error("Schema is missing an `id` property");
          result.$id = params.external.uri(id);
        }
        Object.assign(result, root.def);
        const defs = params.external?.defs ?? {};
        for (const entry of this.seen.entries()) {
          const seen = entry[1];
          if (seen.def && seen.defId) {
            defs[seen.defId] = seen.def;
          }
        }
        if (params.external) {
        } else {
          if (Object.keys(defs).length > 0) {
            if (this.target === "draft-2020-12") {
              result.$defs = defs;
            } else {
              result.definitions = defs;
            }
          }
        }
        try {
          return JSON.parse(JSON.stringify(result));
        } catch (_err) {
          throw new Error("Error converting schema to JSON.");
        }
      }
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/json-schema.js
var json_schema_exports = {};
var init_json_schema = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/json-schema.js"() {
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/index.js
var core_exports2 = {};
__export(core_exports2, {
  $ZodAny: () => $ZodAny,
  $ZodArray: () => $ZodArray,
  $ZodAsyncError: () => $ZodAsyncError,
  $ZodBase64: () => $ZodBase64,
  $ZodBase64URL: () => $ZodBase64URL,
  $ZodBigInt: () => $ZodBigInt,
  $ZodBigIntFormat: () => $ZodBigIntFormat,
  $ZodBoolean: () => $ZodBoolean,
  $ZodCIDRv4: () => $ZodCIDRv4,
  $ZodCIDRv6: () => $ZodCIDRv6,
  $ZodCUID: () => $ZodCUID,
  $ZodCUID2: () => $ZodCUID2,
  $ZodCatch: () => $ZodCatch,
  $ZodCheck: () => $ZodCheck,
  $ZodCheckBigIntFormat: () => $ZodCheckBigIntFormat,
  $ZodCheckEndsWith: () => $ZodCheckEndsWith,
  $ZodCheckGreaterThan: () => $ZodCheckGreaterThan,
  $ZodCheckIncludes: () => $ZodCheckIncludes,
  $ZodCheckLengthEquals: () => $ZodCheckLengthEquals,
  $ZodCheckLessThan: () => $ZodCheckLessThan,
  $ZodCheckLowerCase: () => $ZodCheckLowerCase,
  $ZodCheckMaxLength: () => $ZodCheckMaxLength,
  $ZodCheckMaxSize: () => $ZodCheckMaxSize,
  $ZodCheckMimeType: () => $ZodCheckMimeType,
  $ZodCheckMinLength: () => $ZodCheckMinLength,
  $ZodCheckMinSize: () => $ZodCheckMinSize,
  $ZodCheckMultipleOf: () => $ZodCheckMultipleOf,
  $ZodCheckNumberFormat: () => $ZodCheckNumberFormat,
  $ZodCheckOverwrite: () => $ZodCheckOverwrite,
  $ZodCheckProperty: () => $ZodCheckProperty,
  $ZodCheckRegex: () => $ZodCheckRegex,
  $ZodCheckSizeEquals: () => $ZodCheckSizeEquals,
  $ZodCheckStartsWith: () => $ZodCheckStartsWith,
  $ZodCheckStringFormat: () => $ZodCheckStringFormat,
  $ZodCheckUpperCase: () => $ZodCheckUpperCase,
  $ZodCustom: () => $ZodCustom,
  $ZodCustomStringFormat: () => $ZodCustomStringFormat,
  $ZodDate: () => $ZodDate,
  $ZodDefault: () => $ZodDefault,
  $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion,
  $ZodE164: () => $ZodE164,
  $ZodEmail: () => $ZodEmail,
  $ZodEmoji: () => $ZodEmoji,
  $ZodEnum: () => $ZodEnum,
  $ZodError: () => $ZodError,
  $ZodFile: () => $ZodFile,
  $ZodFunction: () => $ZodFunction,
  $ZodGUID: () => $ZodGUID,
  $ZodIPv4: () => $ZodIPv4,
  $ZodIPv6: () => $ZodIPv6,
  $ZodISODate: () => $ZodISODate,
  $ZodISODateTime: () => $ZodISODateTime,
  $ZodISODuration: () => $ZodISODuration,
  $ZodISOTime: () => $ZodISOTime,
  $ZodIntersection: () => $ZodIntersection,
  $ZodJWT: () => $ZodJWT,
  $ZodKSUID: () => $ZodKSUID,
  $ZodLazy: () => $ZodLazy,
  $ZodLiteral: () => $ZodLiteral,
  $ZodMap: () => $ZodMap,
  $ZodNaN: () => $ZodNaN,
  $ZodNanoID: () => $ZodNanoID,
  $ZodNever: () => $ZodNever,
  $ZodNonOptional: () => $ZodNonOptional,
  $ZodNull: () => $ZodNull,
  $ZodNullable: () => $ZodNullable,
  $ZodNumber: () => $ZodNumber,
  $ZodNumberFormat: () => $ZodNumberFormat,
  $ZodObject: () => $ZodObject,
  $ZodOptional: () => $ZodOptional,
  $ZodPipe: () => $ZodPipe,
  $ZodPrefault: () => $ZodPrefault,
  $ZodPromise: () => $ZodPromise,
  $ZodReadonly: () => $ZodReadonly,
  $ZodRealError: () => $ZodRealError,
  $ZodRecord: () => $ZodRecord,
  $ZodRegistry: () => $ZodRegistry,
  $ZodSet: () => $ZodSet,
  $ZodString: () => $ZodString,
  $ZodStringFormat: () => $ZodStringFormat,
  $ZodSuccess: () => $ZodSuccess,
  $ZodSymbol: () => $ZodSymbol,
  $ZodTemplateLiteral: () => $ZodTemplateLiteral,
  $ZodTransform: () => $ZodTransform,
  $ZodTuple: () => $ZodTuple,
  $ZodType: () => $ZodType,
  $ZodULID: () => $ZodULID,
  $ZodURL: () => $ZodURL,
  $ZodUUID: () => $ZodUUID,
  $ZodUndefined: () => $ZodUndefined,
  $ZodUnion: () => $ZodUnion,
  $ZodUnknown: () => $ZodUnknown,
  $ZodVoid: () => $ZodVoid,
  $ZodXID: () => $ZodXID,
  $brand: () => $brand,
  $constructor: () => $constructor,
  $input: () => $input,
  $output: () => $output,
  Doc: () => Doc,
  JSONSchema: () => json_schema_exports,
  JSONSchemaGenerator: () => JSONSchemaGenerator,
  NEVER: () => NEVER2,
  TimePrecision: () => TimePrecision,
  _any: () => _any,
  _array: () => _array,
  _base64: () => _base64,
  _base64url: () => _base64url,
  _bigint: () => _bigint,
  _boolean: () => _boolean,
  _catch: () => _catch,
  _cidrv4: () => _cidrv4,
  _cidrv6: () => _cidrv6,
  _coercedBigint: () => _coercedBigint,
  _coercedBoolean: () => _coercedBoolean,
  _coercedDate: () => _coercedDate,
  _coercedNumber: () => _coercedNumber,
  _coercedString: () => _coercedString,
  _cuid: () => _cuid,
  _cuid2: () => _cuid2,
  _custom: () => _custom,
  _date: () => _date,
  _default: () => _default,
  _discriminatedUnion: () => _discriminatedUnion,
  _e164: () => _e164,
  _email: () => _email,
  _emoji: () => _emoji2,
  _endsWith: () => _endsWith,
  _enum: () => _enum,
  _file: () => _file,
  _float32: () => _float32,
  _float64: () => _float64,
  _gt: () => _gt,
  _gte: () => _gte,
  _guid: () => _guid,
  _includes: () => _includes,
  _int: () => _int,
  _int32: () => _int32,
  _int64: () => _int64,
  _intersection: () => _intersection,
  _ipv4: () => _ipv4,
  _ipv6: () => _ipv6,
  _isoDate: () => _isoDate,
  _isoDateTime: () => _isoDateTime,
  _isoDuration: () => _isoDuration,
  _isoTime: () => _isoTime,
  _jwt: () => _jwt,
  _ksuid: () => _ksuid,
  _lazy: () => _lazy,
  _length: () => _length,
  _literal: () => _literal,
  _lowercase: () => _lowercase,
  _lt: () => _lt,
  _lte: () => _lte,
  _map: () => _map,
  _max: () => _lte,
  _maxLength: () => _maxLength,
  _maxSize: () => _maxSize,
  _mime: () => _mime,
  _min: () => _gte,
  _minLength: () => _minLength,
  _minSize: () => _minSize,
  _multipleOf: () => _multipleOf,
  _nan: () => _nan,
  _nanoid: () => _nanoid,
  _nativeEnum: () => _nativeEnum,
  _negative: () => _negative,
  _never: () => _never,
  _nonnegative: () => _nonnegative,
  _nonoptional: () => _nonoptional,
  _nonpositive: () => _nonpositive,
  _normalize: () => _normalize,
  _null: () => _null2,
  _nullable: () => _nullable,
  _number: () => _number,
  _optional: () => _optional,
  _overwrite: () => _overwrite,
  _parse: () => _parse,
  _parseAsync: () => _parseAsync,
  _pipe: () => _pipe,
  _positive: () => _positive,
  _promise: () => _promise,
  _property: () => _property,
  _readonly: () => _readonly,
  _record: () => _record,
  _refine: () => _refine,
  _regex: () => _regex,
  _safeParse: () => _safeParse,
  _safeParseAsync: () => _safeParseAsync,
  _set: () => _set,
  _size: () => _size,
  _startsWith: () => _startsWith,
  _string: () => _string,
  _stringFormat: () => _stringFormat,
  _stringbool: () => _stringbool,
  _success: () => _success,
  _symbol: () => _symbol,
  _templateLiteral: () => _templateLiteral,
  _toLowerCase: () => _toLowerCase,
  _toUpperCase: () => _toUpperCase,
  _transform: () => _transform,
  _trim: () => _trim,
  _tuple: () => _tuple,
  _uint32: () => _uint32,
  _uint64: () => _uint64,
  _ulid: () => _ulid,
  _undefined: () => _undefined2,
  _union: () => _union,
  _unknown: () => _unknown,
  _uppercase: () => _uppercase,
  _url: () => _url,
  _uuid: () => _uuid,
  _uuidv4: () => _uuidv4,
  _uuidv6: () => _uuidv6,
  _uuidv7: () => _uuidv7,
  _void: () => _void,
  _xid: () => _xid,
  clone: () => clone,
  config: () => config,
  flattenError: () => flattenError,
  formatError: () => formatError,
  function: () => _function,
  globalConfig: () => globalConfig,
  globalRegistry: () => globalRegistry,
  isValidBase64: () => isValidBase64,
  isValidBase64URL: () => isValidBase64URL,
  isValidJWT: () => isValidJWT2,
  locales: () => locales_exports,
  parse: () => parse,
  parseAsync: () => parseAsync,
  prettifyError: () => prettifyError,
  regexes: () => regexes_exports,
  registry: () => registry,
  safeParse: () => safeParse,
  safeParseAsync: () => safeParseAsync,
  toDotPath: () => toDotPath,
  toJSONSchema: () => toJSONSchema,
  treeifyError: () => treeifyError,
  util: () => util_exports,
  version: () => version2
});
var init_core3 = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/index.js"() {
    init_core2();
    init_parse();
    init_errors3();
    init_schemas();
    init_checks2();
    init_versions();
    init_util2();
    init_regexes();
    init_locales();
    init_registries();
    init_doc();
    init_function();
    init_api2();
    init_to_json_schema();
    init_json_schema();
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/checks.js
var init_checks3 = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/checks.js"() {
    init_core3();
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/iso.js
var iso_exports = {};
__export(iso_exports, {
  ZodISODate: () => ZodISODate,
  ZodISODateTime: () => ZodISODateTime,
  ZodISODuration: () => ZodISODuration,
  ZodISOTime: () => ZodISOTime,
  date: () => date3,
  datetime: () => datetime2,
  duration: () => duration2,
  time: () => time3
});
function datetime2(params) {
  return _isoDateTime(ZodISODateTime, params);
}
function date3(params) {
  return _isoDate(ZodISODate, params);
}
function time3(params) {
  return _isoTime(ZodISOTime, params);
}
function duration2(params) {
  return _isoDuration(ZodISODuration, params);
}
var ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration;
var init_iso = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/iso.js"() {
    init_core3();
    init_schemas2();
    ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => {
      $ZodISODateTime.init(inst, def);
      ZodStringFormat.init(inst, def);
    });
    ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => {
      $ZodISODate.init(inst, def);
      ZodStringFormat.init(inst, def);
    });
    ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => {
      $ZodISOTime.init(inst, def);
      ZodStringFormat.init(inst, def);
    });
    ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => {
      $ZodISODuration.init(inst, def);
      ZodStringFormat.init(inst, def);
    });
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/errors.js
var initializer2, ZodError2, ZodRealError;
var init_errors4 = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/errors.js"() {
    init_core3();
    init_core3();
    initializer2 = (inst, issues) => {
      $ZodError.init(inst, issues);
      inst.name = "ZodError";
      Object.defineProperties(inst, {
        format: {
          value: (mapper) => formatError(inst, mapper)
          // enumerable: false,
        },
        flatten: {
          value: (mapper) => flattenError(inst, mapper)
          // enumerable: false,
        },
        addIssue: {
          value: (issue2) => inst.issues.push(issue2)
          // enumerable: false,
        },
        addIssues: {
          value: (issues2) => inst.issues.push(...issues2)
          // enumerable: false,
        },
        isEmpty: {
          get() {
            return inst.issues.length === 0;
          }
          // enumerable: false,
        }
      });
    };
    ZodError2 = $constructor("ZodError", initializer2);
    ZodRealError = $constructor("ZodError", initializer2, {
      Parent: Error
    });
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/parse.js
var parse2, parseAsync2, safeParse2, safeParseAsync2;
var init_parse2 = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/parse.js"() {
    init_core3();
    init_errors4();
    parse2 = /* @__PURE__ */ _parse(ZodRealError);
    parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError);
    safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError);
    safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError);
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/schemas.js
function string2(params) {
  return _string(ZodString2, params);
}
function email2(params) {
  return _email(ZodEmail, params);
}
function guid2(params) {
  return _guid(ZodGUID, params);
}
function uuid3(params) {
  return _uuid(ZodUUID, params);
}
function uuidv4(params) {
  return _uuidv4(ZodUUID, params);
}
function uuidv6(params) {
  return _uuidv6(ZodUUID, params);
}
function uuidv7(params) {
  return _uuidv7(ZodUUID, params);
}
function url(params) {
  return _url(ZodURL, params);
}
function emoji2(params) {
  return _emoji2(ZodEmoji, params);
}
function nanoid2(params) {
  return _nanoid(ZodNanoID, params);
}
function cuid3(params) {
  return _cuid(ZodCUID, params);
}
function cuid22(params) {
  return _cuid2(ZodCUID2, params);
}
function ulid2(params) {
  return _ulid(ZodULID, params);
}
function xid2(params) {
  return _xid(ZodXID, params);
}
function ksuid2(params) {
  return _ksuid(ZodKSUID, params);
}
function ipv42(params) {
  return _ipv4(ZodIPv4, params);
}
function ipv62(params) {
  return _ipv6(ZodIPv6, params);
}
function cidrv42(params) {
  return _cidrv4(ZodCIDRv4, params);
}
function cidrv62(params) {
  return _cidrv6(ZodCIDRv6, params);
}
function base642(params) {
  return _base64(ZodBase64, params);
}
function base64url2(params) {
  return _base64url(ZodBase64URL, params);
}
function e1642(params) {
  return _e164(ZodE164, params);
}
function jwt(params) {
  return _jwt(ZodJWT, params);
}
function stringFormat(format, fnOrRegex, _params = {}) {
  return _stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params);
}
function number2(params) {
  return _number(ZodNumber2, params);
}
function int(params) {
  return _int(ZodNumberFormat, params);
}
function float32(params) {
  return _float32(ZodNumberFormat, params);
}
function float64(params) {
  return _float64(ZodNumberFormat, params);
}
function int32(params) {
  return _int32(ZodNumberFormat, params);
}
function uint32(params) {
  return _uint32(ZodNumberFormat, params);
}
function boolean3(params) {
  return _boolean(ZodBoolean2, params);
}
function bigint3(params) {
  return _bigint(ZodBigInt2, params);
}
function int64(params) {
  return _int64(ZodBigIntFormat, params);
}
function uint64(params) {
  return _uint64(ZodBigIntFormat, params);
}
function symbol(params) {
  return _symbol(ZodSymbol2, params);
}
function _undefined3(params) {
  return _undefined2(ZodUndefined2, params);
}
function _null3(params) {
  return _null2(ZodNull2, params);
}
function any() {
  return _any(ZodAny2);
}
function unknown() {
  return _unknown(ZodUnknown2);
}
function never(params) {
  return _never(ZodNever2, params);
}
function _void2(params) {
  return _void(ZodVoid2, params);
}
function date4(params) {
  return _date(ZodDate2, params);
}
function array(element, params) {
  return _array(ZodArray2, element, params);
}
function keyof(schema) {
  const shape = schema._zod.def.shape;
  return literal(Object.keys(shape));
}
function object(shape, params) {
  const def = {
    type: "object",
    get shape() {
      util_exports.assignProp(this, "shape", { ...shape });
      return this.shape;
    },
    ...util_exports.normalizeParams(params)
  };
  return new ZodObject2(def);
}
function strictObject(shape, params) {
  return new ZodObject2({
    type: "object",
    get shape() {
      util_exports.assignProp(this, "shape", { ...shape });
      return this.shape;
    },
    catchall: never(),
    ...util_exports.normalizeParams(params)
  });
}
function looseObject(shape, params) {
  return new ZodObject2({
    type: "object",
    get shape() {
      util_exports.assignProp(this, "shape", { ...shape });
      return this.shape;
    },
    catchall: unknown(),
    ...util_exports.normalizeParams(params)
  });
}
function union2(options, params) {
  return new ZodUnion2({
    type: "union",
    options,
    ...util_exports.normalizeParams(params)
  });
}
function discriminatedUnion(discriminator, options, params) {
  return new ZodDiscriminatedUnion2({
    type: "union",
    options,
    discriminator,
    ...util_exports.normalizeParams(params)
  });
}
function intersection(left, right) {
  return new ZodIntersection2({
    type: "intersection",
    left,
    right
  });
}
function tuple(items, _paramsOrRest, _params) {
  const hasRest = _paramsOrRest instanceof $ZodType;
  const params = hasRest ? _params : _paramsOrRest;
  const rest = hasRest ? _paramsOrRest : null;
  return new ZodTuple2({
    type: "tuple",
    items,
    rest,
    ...util_exports.normalizeParams(params)
  });
}
function record(keyType, valueType, params) {
  return new ZodRecord2({
    type: "record",
    keyType,
    valueType,
    ...util_exports.normalizeParams(params)
  });
}
function partialRecord(keyType, valueType, params) {
  return new ZodRecord2({
    type: "record",
    keyType: union2([keyType, never()]),
    valueType,
    ...util_exports.normalizeParams(params)
  });
}
function map(keyType, valueType, params) {
  return new ZodMap2({
    type: "map",
    keyType,
    valueType,
    ...util_exports.normalizeParams(params)
  });
}
function set(valueType, params) {
  return new ZodSet2({
    type: "set",
    valueType,
    ...util_exports.normalizeParams(params)
  });
}
function _enum2(values, params) {
  const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
  return new ZodEnum2({
    type: "enum",
    entries,
    ...util_exports.normalizeParams(params)
  });
}
function nativeEnum(entries, params) {
  return new ZodEnum2({
    type: "enum",
    entries,
    ...util_exports.normalizeParams(params)
  });
}
function literal(value, params) {
  return new ZodLiteral2({
    type: "literal",
    values: Array.isArray(value) ? value : [value],
    ...util_exports.normalizeParams(params)
  });
}
function file(params) {
  return _file(ZodFile, params);
}
function transform(fn) {
  return new ZodTransform({
    type: "transform",
    transform: fn
  });
}
function optional(innerType) {
  return new ZodOptional2({
    type: "optional",
    innerType
  });
}
function nullable(innerType) {
  return new ZodNullable2({
    type: "nullable",
    innerType
  });
}
function nullish2(innerType) {
  return optional(nullable(innerType));
}
function _default2(innerType, defaultValue) {
  return new ZodDefault2({
    type: "default",
    innerType,
    get defaultValue() {
      return typeof defaultValue === "function" ? defaultValue() : defaultValue;
    }
  });
}
function prefault(innerType, defaultValue) {
  return new ZodPrefault({
    type: "prefault",
    innerType,
    get defaultValue() {
      return typeof defaultValue === "function" ? defaultValue() : defaultValue;
    }
  });
}
function nonoptional(innerType, params) {
  return new ZodNonOptional({
    type: "nonoptional",
    innerType,
    ...util_exports.normalizeParams(params)
  });
}
function success(innerType) {
  return new ZodSuccess({
    type: "success",
    innerType
  });
}
function _catch2(innerType, catchValue) {
  return new ZodCatch2({
    type: "catch",
    innerType,
    catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
  });
}
function nan(params) {
  return _nan(ZodNaN2, params);
}
function pipe(in_, out) {
  return new ZodPipe({
    type: "pipe",
    in: in_,
    out
    // ...util.normalizeParams(params),
  });
}
function readonly(innerType) {
  return new ZodReadonly2({
    type: "readonly",
    innerType
  });
}
function templateLiteral(parts, params) {
  return new ZodTemplateLiteral({
    type: "template_literal",
    parts,
    ...util_exports.normalizeParams(params)
  });
}
function lazy(getter) {
  return new ZodLazy2({
    type: "lazy",
    getter
  });
}
function promise(innerType) {
  return new ZodPromise2({
    type: "promise",
    innerType
  });
}
function check(fn) {
  const ch = new $ZodCheck({
    check: "custom"
    // ...util.normalizeParams(params),
  });
  ch._zod.check = fn;
  return ch;
}
function custom2(fn, _params) {
  return _custom(ZodCustom, fn ?? (() => true), _params);
}
function refine(fn, _params = {}) {
  return _refine(ZodCustom, fn, _params);
}
function superRefine(fn) {
  const ch = check((payload) => {
    payload.addIssue = (issue2) => {
      if (typeof issue2 === "string") {
        payload.issues.push(util_exports.issue(issue2, payload.value, ch._zod.def));
      } else {
        const _issue = issue2;
        if (_issue.fatal)
          _issue.continue = false;
        _issue.code ?? (_issue.code = "custom");
        _issue.input ?? (_issue.input = payload.value);
        _issue.inst ?? (_issue.inst = ch);
        _issue.continue ?? (_issue.continue = !ch._zod.def.abort);
        payload.issues.push(util_exports.issue(_issue));
      }
    };
    return fn(payload.value, payload);
  });
  return ch;
}
function _instanceof(cls, params = {
  error: `Input not instance of ${cls.name}`
}) {
  const inst = new ZodCustom({
    type: "custom",
    check: "custom",
    fn: (data) => data instanceof cls,
    abort: true,
    ...util_exports.normalizeParams(params)
  });
  inst._zod.bag.Class = cls;
  return inst;
}
function json2(params) {
  const jsonSchema2 = lazy(() => {
    return union2([string2(params), number2(), boolean3(), _null3(), array(jsonSchema2), record(string2(), jsonSchema2)]);
  });
  return jsonSchema2;
}
function preprocess(fn, schema) {
  return pipe(transform(fn), schema);
}
var ZodType2, _ZodString, ZodString2, ZodStringFormat, ZodEmail, ZodGUID, ZodUUID, ZodURL, ZodEmoji, ZodNanoID, ZodCUID, ZodCUID2, ZodULID, ZodXID, ZodKSUID, ZodIPv4, ZodIPv6, ZodCIDRv4, ZodCIDRv6, ZodBase64, ZodBase64URL, ZodE164, ZodJWT, ZodCustomStringFormat, ZodNumber2, ZodNumberFormat, ZodBoolean2, ZodBigInt2, ZodBigIntFormat, ZodSymbol2, ZodUndefined2, ZodNull2, ZodAny2, ZodUnknown2, ZodNever2, ZodVoid2, ZodDate2, ZodArray2, ZodObject2, ZodUnion2, ZodDiscriminatedUnion2, ZodIntersection2, ZodTuple2, ZodRecord2, ZodMap2, ZodSet2, ZodEnum2, ZodLiteral2, ZodFile, ZodTransform, ZodOptional2, ZodNullable2, ZodDefault2, ZodPrefault, ZodNonOptional, ZodSuccess, ZodCatch2, ZodNaN2, ZodPipe, ZodReadonly2, ZodTemplateLiteral, ZodLazy2, ZodPromise2, ZodCustom, stringbool;
var init_schemas2 = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/schemas.js"() {
    init_core3();
    init_core3();
    init_checks3();
    init_iso();
    init_parse2();
    ZodType2 = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
      $ZodType.init(inst, def);
      inst.def = def;
      Object.defineProperty(inst, "_def", { value: def });
      inst.check = (...checks) => {
        return inst.clone(
          {
            ...def,
            checks: [
              ...def.checks ?? [],
              ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch)
            ]
          }
          // { parent: true }
        );
      };
      inst.clone = (def2, params) => clone(inst, def2, params);
      inst.brand = () => inst;
      inst.register = ((reg, meta) => {
        reg.add(inst, meta);
        return inst;
      });
      inst.parse = (data, params) => parse2(inst, data, params, { callee: inst.parse });
      inst.safeParse = (data, params) => safeParse2(inst, data, params);
      inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync });
      inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params);
      inst.spa = inst.safeParseAsync;
      inst.refine = (check2, params) => inst.check(refine(check2, params));
      inst.superRefine = (refinement) => inst.check(superRefine(refinement));
      inst.overwrite = (fn) => inst.check(_overwrite(fn));
      inst.optional = () => optional(inst);
      inst.nullable = () => nullable(inst);
      inst.nullish = () => optional(nullable(inst));
      inst.nonoptional = (params) => nonoptional(inst, params);
      inst.array = () => array(inst);
      inst.or = (arg) => union2([inst, arg]);
      inst.and = (arg) => intersection(inst, arg);
      inst.transform = (tx) => pipe(inst, transform(tx));
      inst.default = (def2) => _default2(inst, def2);
      inst.prefault = (def2) => prefault(inst, def2);
      inst.catch = (params) => _catch2(inst, params);
      inst.pipe = (target) => pipe(inst, target);
      inst.readonly = () => readonly(inst);
      inst.describe = (description) => {
        const cl = inst.clone();
        globalRegistry.add(cl, { description });
        return cl;
      };
      Object.defineProperty(inst, "description", {
        get() {
          return globalRegistry.get(inst)?.description;
        },
        configurable: true
      });
      inst.meta = (...args) => {
        if (args.length === 0) {
          return globalRegistry.get(inst);
        }
        const cl = inst.clone();
        globalRegistry.add(cl, args[0]);
        return cl;
      };
      inst.isOptional = () => inst.safeParse(void 0).success;
      inst.isNullable = () => inst.safeParse(null).success;
      return inst;
    });
    _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => {
      $ZodString.init(inst, def);
      ZodType2.init(inst, def);
      const bag = inst._zod.bag;
      inst.format = bag.format ?? null;
      inst.minLength = bag.minimum ?? null;
      inst.maxLength = bag.maximum ?? null;
      inst.regex = (...args) => inst.check(_regex(...args));
      inst.includes = (...args) => inst.check(_includes(...args));
      inst.startsWith = (...args) => inst.check(_startsWith(...args));
      inst.endsWith = (...args) => inst.check(_endsWith(...args));
      inst.min = (...args) => inst.check(_minLength(...args));
      inst.max = (...args) => inst.check(_maxLength(...args));
      inst.length = (...args) => inst.check(_length(...args));
      inst.nonempty = (...args) => inst.check(_minLength(1, ...args));
      inst.lowercase = (params) => inst.check(_lowercase(params));
      inst.uppercase = (params) => inst.check(_uppercase(params));
      inst.trim = () => inst.check(_trim());
      inst.normalize = (...args) => inst.check(_normalize(...args));
      inst.toLowerCase = () => inst.check(_toLowerCase());
      inst.toUpperCase = () => inst.check(_toUpperCase());
    });
    ZodString2 = /* @__PURE__ */ $constructor("ZodString", (inst, def) => {
      $ZodString.init(inst, def);
      _ZodString.init(inst, def);
      inst.email = (params) => inst.check(_email(ZodEmail, params));
      inst.url = (params) => inst.check(_url(ZodURL, params));
      inst.jwt = (params) => inst.check(_jwt(ZodJWT, params));
      inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params));
      inst.guid = (params) => inst.check(_guid(ZodGUID, params));
      inst.uuid = (params) => inst.check(_uuid(ZodUUID, params));
      inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params));
      inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params));
      inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params));
      inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params));
      inst.guid = (params) => inst.check(_guid(ZodGUID, params));
      inst.cuid = (params) => inst.check(_cuid(ZodCUID, params));
      inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params));
      inst.ulid = (params) => inst.check(_ulid(ZodULID, params));
      inst.base64 = (params) => inst.check(_base64(ZodBase64, params));
      inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params));
      inst.xid = (params) => inst.check(_xid(ZodXID, params));
      inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params));
      inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params));
      inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params));
      inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params));
      inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params));
      inst.e164 = (params) => inst.check(_e164(ZodE164, params));
      inst.datetime = (params) => inst.check(datetime2(params));
      inst.date = (params) => inst.check(date3(params));
      inst.time = (params) => inst.check(time3(params));
      inst.duration = (params) => inst.check(duration2(params));
    });
    ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => {
      $ZodStringFormat.init(inst, def);
      _ZodString.init(inst, def);
    });
    ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => {
      $ZodEmail.init(inst, def);
      ZodStringFormat.init(inst, def);
    });
    ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => {
      $ZodGUID.init(inst, def);
      ZodStringFormat.init(inst, def);
    });
    ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => {
      $ZodUUID.init(inst, def);
      ZodStringFormat.init(inst, def);
    });
    ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => {
      $ZodURL.init(inst, def);
      ZodStringFormat.init(inst, def);
    });
    ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => {
      $ZodEmoji.init(inst, def);
      ZodStringFormat.init(inst, def);
    });
    ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => {
      $ZodNanoID.init(inst, def);
      ZodStringFormat.init(inst, def);
    });
    ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => {
      $ZodCUID.init(inst, def);
      ZodStringFormat.init(inst, def);
    });
    ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => {
      $ZodCUID2.init(inst, def);
      ZodStringFormat.init(inst, def);
    });
    ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => {
      $ZodULID.init(inst, def);
      ZodStringFormat.init(inst, def);
    });
    ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => {
      $ZodXID.init(inst, def);
      ZodStringFormat.init(inst, def);
    });
    ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => {
      $ZodKSUID.init(inst, def);
      ZodStringFormat.init(inst, def);
    });
    ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => {
      $ZodIPv4.init(inst, def);
      ZodStringFormat.init(inst, def);
    });
    ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => {
      $ZodIPv6.init(inst, def);
      ZodStringFormat.init(inst, def);
    });
    ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => {
      $ZodCIDRv4.init(inst, def);
      ZodStringFormat.init(inst, def);
    });
    ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => {
      $ZodCIDRv6.init(inst, def);
      ZodStringFormat.init(inst, def);
    });
    ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => {
      $ZodBase64.init(inst, def);
      ZodStringFormat.init(inst, def);
    });
    ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => {
      $ZodBase64URL.init(inst, def);
      ZodStringFormat.init(inst, def);
    });
    ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => {
      $ZodE164.init(inst, def);
      ZodStringFormat.init(inst, def);
    });
    ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => {
      $ZodJWT.init(inst, def);
      ZodStringFormat.init(inst, def);
    });
    ZodCustomStringFormat = /* @__PURE__ */ $constructor("ZodCustomStringFormat", (inst, def) => {
      $ZodCustomStringFormat.init(inst, def);
      ZodStringFormat.init(inst, def);
    });
    ZodNumber2 = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => {
      $ZodNumber.init(inst, def);
      ZodType2.init(inst, def);
      inst.gt = (value, params) => inst.check(_gt(value, params));
      inst.gte = (value, params) => inst.check(_gte(value, params));
      inst.min = (value, params) => inst.check(_gte(value, params));
      inst.lt = (value, params) => inst.check(_lt(value, params));
      inst.lte = (value, params) => inst.check(_lte(value, params));
      inst.max = (value, params) => inst.check(_lte(value, params));
      inst.int = (params) => inst.check(int(params));
      inst.safe = (params) => inst.check(int(params));
      inst.positive = (params) => inst.check(_gt(0, params));
      inst.nonnegative = (params) => inst.check(_gte(0, params));
      inst.negative = (params) => inst.check(_lt(0, params));
      inst.nonpositive = (params) => inst.check(_lte(0, params));
      inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params));
      inst.step = (value, params) => inst.check(_multipleOf(value, params));
      inst.finite = () => inst;
      const bag = inst._zod.bag;
      inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;
      inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;
      inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5);
      inst.isFinite = true;
      inst.format = bag.format ?? null;
    });
    ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => {
      $ZodNumberFormat.init(inst, def);
      ZodNumber2.init(inst, def);
    });
    ZodBoolean2 = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => {
      $ZodBoolean.init(inst, def);
      ZodType2.init(inst, def);
    });
    ZodBigInt2 = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => {
      $ZodBigInt.init(inst, def);
      ZodType2.init(inst, def);
      inst.gte = (value, params) => inst.check(_gte(value, params));
      inst.min = (value, params) => inst.check(_gte(value, params));
      inst.gt = (value, params) => inst.check(_gt(value, params));
      inst.gte = (value, params) => inst.check(_gte(value, params));
      inst.min = (value, params) => inst.check(_gte(value, params));
      inst.lt = (value, params) => inst.check(_lt(value, params));
      inst.lte = (value, params) => inst.check(_lte(value, params));
      inst.max = (value, params) => inst.check(_lte(value, params));
      inst.positive = (params) => inst.check(_gt(BigInt(0), params));
      inst.negative = (params) => inst.check(_lt(BigInt(0), params));
      inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params));
      inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params));
      inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params));
      const bag = inst._zod.bag;
      inst.minValue = bag.minimum ?? null;
      inst.maxValue = bag.maximum ?? null;
      inst.format = bag.format ?? null;
    });
    ZodBigIntFormat = /* @__PURE__ */ $constructor("ZodBigIntFormat", (inst, def) => {
      $ZodBigIntFormat.init(inst, def);
      ZodBigInt2.init(inst, def);
    });
    ZodSymbol2 = /* @__PURE__ */ $constructor("ZodSymbol", (inst, def) => {
      $ZodSymbol.init(inst, def);
      ZodType2.init(inst, def);
    });
    ZodUndefined2 = /* @__PURE__ */ $constructor("ZodUndefined", (inst, def) => {
      $ZodUndefined.init(inst, def);
      ZodType2.init(inst, def);
    });
    ZodNull2 = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => {
      $ZodNull.init(inst, def);
      ZodType2.init(inst, def);
    });
    ZodAny2 = /* @__PURE__ */ $constructor("ZodAny", (inst, def) => {
      $ZodAny.init(inst, def);
      ZodType2.init(inst, def);
    });
    ZodUnknown2 = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => {
      $ZodUnknown.init(inst, def);
      ZodType2.init(inst, def);
    });
    ZodNever2 = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => {
      $ZodNever.init(inst, def);
      ZodType2.init(inst, def);
    });
    ZodVoid2 = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => {
      $ZodVoid.init(inst, def);
      ZodType2.init(inst, def);
    });
    ZodDate2 = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => {
      $ZodDate.init(inst, def);
      ZodType2.init(inst, def);
      inst.min = (value, params) => inst.check(_gte(value, params));
      inst.max = (value, params) => inst.check(_lte(value, params));
      const c = inst._zod.bag;
      inst.minDate = c.minimum ? new Date(c.minimum) : null;
      inst.maxDate = c.maximum ? new Date(c.maximum) : null;
    });
    ZodArray2 = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => {
      $ZodArray.init(inst, def);
      ZodType2.init(inst, def);
      inst.element = def.element;
      inst.min = (minLength, params) => inst.check(_minLength(minLength, params));
      inst.nonempty = (params) => inst.check(_minLength(1, params));
      inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params));
      inst.length = (len, params) => inst.check(_length(len, params));
      inst.unwrap = () => inst.element;
    });
    ZodObject2 = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => {
      $ZodObject.init(inst, def);
      ZodType2.init(inst, def);
      util_exports.defineLazy(inst, "shape", () => def.shape);
      inst.keyof = () => _enum2(Object.keys(inst._zod.def.shape));
      inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall });
      inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() });
      inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() });
      inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() });
      inst.strip = () => inst.clone({ ...inst._zod.def, catchall: void 0 });
      inst.extend = (incoming) => {
        return util_exports.extend(inst, incoming);
      };
      inst.merge = (other) => util_exports.merge(inst, other);
      inst.pick = (mask) => util_exports.pick(inst, mask);
      inst.omit = (mask) => util_exports.omit(inst, mask);
      inst.partial = (...args) => util_exports.partial(ZodOptional2, inst, args[0]);
      inst.required = (...args) => util_exports.required(ZodNonOptional, inst, args[0]);
    });
    ZodUnion2 = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => {
      $ZodUnion.init(inst, def);
      ZodType2.init(inst, def);
      inst.options = def.options;
    });
    ZodDiscriminatedUnion2 = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => {
      ZodUnion2.init(inst, def);
      $ZodDiscriminatedUnion.init(inst, def);
    });
    ZodIntersection2 = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => {
      $ZodIntersection.init(inst, def);
      ZodType2.init(inst, def);
    });
    ZodTuple2 = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => {
      $ZodTuple.init(inst, def);
      ZodType2.init(inst, def);
      inst.rest = (rest) => inst.clone({
        ...inst._zod.def,
        rest
      });
    });
    ZodRecord2 = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => {
      $ZodRecord.init(inst, def);
      ZodType2.init(inst, def);
      inst.keyType = def.keyType;
      inst.valueType = def.valueType;
    });
    ZodMap2 = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => {
      $ZodMap.init(inst, def);
      ZodType2.init(inst, def);
      inst.keyType = def.keyType;
      inst.valueType = def.valueType;
    });
    ZodSet2 = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => {
      $ZodSet.init(inst, def);
      ZodType2.init(inst, def);
      inst.min = (...args) => inst.check(_minSize(...args));
      inst.nonempty = (params) => inst.check(_minSize(1, params));
      inst.max = (...args) => inst.check(_maxSize(...args));
      inst.size = (...args) => inst.check(_size(...args));
    });
    ZodEnum2 = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => {
      $ZodEnum.init(inst, def);
      ZodType2.init(inst, def);
      inst.enum = def.entries;
      inst.options = Object.values(def.entries);
      const keys = new Set(Object.keys(def.entries));
      inst.extract = (values, params) => {
        const newEntries = {};
        for (const value of values) {
          if (keys.has(value)) {
            newEntries[value] = def.entries[value];
          } else
            throw new Error(`Key ${value} not found in enum`);
        }
        return new ZodEnum2({
          ...def,
          checks: [],
          ...util_exports.normalizeParams(params),
          entries: newEntries
        });
      };
      inst.exclude = (values, params) => {
        const newEntries = { ...def.entries };
        for (const value of values) {
          if (keys.has(value)) {
            delete newEntries[value];
          } else
            throw new Error(`Key ${value} not found in enum`);
        }
        return new ZodEnum2({
          ...def,
          checks: [],
          ...util_exports.normalizeParams(params),
          entries: newEntries
        });
      };
    });
    ZodLiteral2 = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => {
      $ZodLiteral.init(inst, def);
      ZodType2.init(inst, def);
      inst.values = new Set(def.values);
      Object.defineProperty(inst, "value", {
        get() {
          if (def.values.length > 1) {
            throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");
          }
          return def.values[0];
        }
      });
    });
    ZodFile = /* @__PURE__ */ $constructor("ZodFile", (inst, def) => {
      $ZodFile.init(inst, def);
      ZodType2.init(inst, def);
      inst.min = (size, params) => inst.check(_minSize(size, params));
      inst.max = (size, params) => inst.check(_maxSize(size, params));
      inst.mime = (types3, params) => inst.check(_mime(Array.isArray(types3) ? types3 : [types3], params));
    });
    ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
      $ZodTransform.init(inst, def);
      ZodType2.init(inst, def);
      inst._zod.parse = (payload, _ctx) => {
        payload.addIssue = (issue2) => {
          if (typeof issue2 === "string") {
            payload.issues.push(util_exports.issue(issue2, payload.value, def));
          } else {
            const _issue = issue2;
            if (_issue.fatal)
              _issue.continue = false;
            _issue.code ?? (_issue.code = "custom");
            _issue.input ?? (_issue.input = payload.value);
            _issue.inst ?? (_issue.inst = inst);
            _issue.continue ?? (_issue.continue = true);
            payload.issues.push(util_exports.issue(_issue));
          }
        };
        const output = def.transform(payload.value, payload);
        if (output instanceof Promise) {
          return output.then((output2) => {
            payload.value = output2;
            return payload;
          });
        }
        payload.value = output;
        return payload;
      };
    });
    ZodOptional2 = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => {
      $ZodOptional.init(inst, def);
      ZodType2.init(inst, def);
      inst.unwrap = () => inst._zod.def.innerType;
    });
    ZodNullable2 = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => {
      $ZodNullable.init(inst, def);
      ZodType2.init(inst, def);
      inst.unwrap = () => inst._zod.def.innerType;
    });
    ZodDefault2 = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => {
      $ZodDefault.init(inst, def);
      ZodType2.init(inst, def);
      inst.unwrap = () => inst._zod.def.innerType;
      inst.removeDefault = inst.unwrap;
    });
    ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => {
      $ZodPrefault.init(inst, def);
      ZodType2.init(inst, def);
      inst.unwrap = () => inst._zod.def.innerType;
    });
    ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => {
      $ZodNonOptional.init(inst, def);
      ZodType2.init(inst, def);
      inst.unwrap = () => inst._zod.def.innerType;
    });
    ZodSuccess = /* @__PURE__ */ $constructor("ZodSuccess", (inst, def) => {
      $ZodSuccess.init(inst, def);
      ZodType2.init(inst, def);
      inst.unwrap = () => inst._zod.def.innerType;
    });
    ZodCatch2 = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => {
      $ZodCatch.init(inst, def);
      ZodType2.init(inst, def);
      inst.unwrap = () => inst._zod.def.innerType;
      inst.removeCatch = inst.unwrap;
    });
    ZodNaN2 = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => {
      $ZodNaN.init(inst, def);
      ZodType2.init(inst, def);
    });
    ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => {
      $ZodPipe.init(inst, def);
      ZodType2.init(inst, def);
      inst.in = def.in;
      inst.out = def.out;
    });
    ZodReadonly2 = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => {
      $ZodReadonly.init(inst, def);
      ZodType2.init(inst, def);
    });
    ZodTemplateLiteral = /* @__PURE__ */ $constructor("ZodTemplateLiteral", (inst, def) => {
      $ZodTemplateLiteral.init(inst, def);
      ZodType2.init(inst, def);
    });
    ZodLazy2 = /* @__PURE__ */ $constructor("ZodLazy", (inst, def) => {
      $ZodLazy.init(inst, def);
      ZodType2.init(inst, def);
      inst.unwrap = () => inst._zod.def.getter();
    });
    ZodPromise2 = /* @__PURE__ */ $constructor("ZodPromise", (inst, def) => {
      $ZodPromise.init(inst, def);
      ZodType2.init(inst, def);
      inst.unwrap = () => inst._zod.def.innerType;
    });
    ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => {
      $ZodCustom.init(inst, def);
      ZodType2.init(inst, def);
    });
    stringbool = (...args) => _stringbool({
      Pipe: ZodPipe,
      Boolean: ZodBoolean2,
      String: ZodString2,
      Transform: ZodTransform
    }, ...args);
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/compat.js
function setErrorMap2(map2) {
  config({
    customError: map2
  });
}
function getErrorMap2() {
  return config().customError;
}
var ZodIssueCode2;
var init_compat = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/compat.js"() {
    init_core3();
    ZodIssueCode2 = {
      invalid_type: "invalid_type",
      too_big: "too_big",
      too_small: "too_small",
      invalid_format: "invalid_format",
      not_multiple_of: "not_multiple_of",
      unrecognized_keys: "unrecognized_keys",
      invalid_union: "invalid_union",
      invalid_key: "invalid_key",
      invalid_element: "invalid_element",
      invalid_value: "invalid_value",
      custom: "custom"
    };
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/coerce.js
var coerce_exports = {};
__export(coerce_exports, {
  bigint: () => bigint4,
  boolean: () => boolean4,
  date: () => date5,
  number: () => number3,
  string: () => string3
});
function string3(params) {
  return _coercedString(ZodString2, params);
}
function number3(params) {
  return _coercedNumber(ZodNumber2, params);
}
function boolean4(params) {
  return _coercedBoolean(ZodBoolean2, params);
}
function bigint4(params) {
  return _coercedBigint(ZodBigInt2, params);
}
function date5(params) {
  return _coercedDate(ZodDate2, params);
}
var init_coerce = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/coerce.js"() {
    init_core3();
    init_schemas2();
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/external.js
var external_exports2 = {};
__export(external_exports2, {
  $brand: () => $brand,
  $input: () => $input,
  $output: () => $output,
  NEVER: () => NEVER2,
  TimePrecision: () => TimePrecision,
  ZodAny: () => ZodAny2,
  ZodArray: () => ZodArray2,
  ZodBase64: () => ZodBase64,
  ZodBase64URL: () => ZodBase64URL,
  ZodBigInt: () => ZodBigInt2,
  ZodBigIntFormat: () => ZodBigIntFormat,
  ZodBoolean: () => ZodBoolean2,
  ZodCIDRv4: () => ZodCIDRv4,
  ZodCIDRv6: () => ZodCIDRv6,
  ZodCUID: () => ZodCUID,
  ZodCUID2: () => ZodCUID2,
  ZodCatch: () => ZodCatch2,
  ZodCustom: () => ZodCustom,
  ZodCustomStringFormat: () => ZodCustomStringFormat,
  ZodDate: () => ZodDate2,
  ZodDefault: () => ZodDefault2,
  ZodDiscriminatedUnion: () => ZodDiscriminatedUnion2,
  ZodE164: () => ZodE164,
  ZodEmail: () => ZodEmail,
  ZodEmoji: () => ZodEmoji,
  ZodEnum: () => ZodEnum2,
  ZodError: () => ZodError2,
  ZodFile: () => ZodFile,
  ZodGUID: () => ZodGUID,
  ZodIPv4: () => ZodIPv4,
  ZodIPv6: () => ZodIPv6,
  ZodISODate: () => ZodISODate,
  ZodISODateTime: () => ZodISODateTime,
  ZodISODuration: () => ZodISODuration,
  ZodISOTime: () => ZodISOTime,
  ZodIntersection: () => ZodIntersection2,
  ZodIssueCode: () => ZodIssueCode2,
  ZodJWT: () => ZodJWT,
  ZodKSUID: () => ZodKSUID,
  ZodLazy: () => ZodLazy2,
  ZodLiteral: () => ZodLiteral2,
  ZodMap: () => ZodMap2,
  ZodNaN: () => ZodNaN2,
  ZodNanoID: () => ZodNanoID,
  ZodNever: () => ZodNever2,
  ZodNonOptional: () => ZodNonOptional,
  ZodNull: () => ZodNull2,
  ZodNullable: () => ZodNullable2,
  ZodNumber: () => ZodNumber2,
  ZodNumberFormat: () => ZodNumberFormat,
  ZodObject: () => ZodObject2,
  ZodOptional: () => ZodOptional2,
  ZodPipe: () => ZodPipe,
  ZodPrefault: () => ZodPrefault,
  ZodPromise: () => ZodPromise2,
  ZodReadonly: () => ZodReadonly2,
  ZodRealError: () => ZodRealError,
  ZodRecord: () => ZodRecord2,
  ZodSet: () => ZodSet2,
  ZodString: () => ZodString2,
  ZodStringFormat: () => ZodStringFormat,
  ZodSuccess: () => ZodSuccess,
  ZodSymbol: () => ZodSymbol2,
  ZodTemplateLiteral: () => ZodTemplateLiteral,
  ZodTransform: () => ZodTransform,
  ZodTuple: () => ZodTuple2,
  ZodType: () => ZodType2,
  ZodULID: () => ZodULID,
  ZodURL: () => ZodURL,
  ZodUUID: () => ZodUUID,
  ZodUndefined: () => ZodUndefined2,
  ZodUnion: () => ZodUnion2,
  ZodUnknown: () => ZodUnknown2,
  ZodVoid: () => ZodVoid2,
  ZodXID: () => ZodXID,
  _ZodString: () => _ZodString,
  _default: () => _default2,
  any: () => any,
  array: () => array,
  base64: () => base642,
  base64url: () => base64url2,
  bigint: () => bigint3,
  boolean: () => boolean3,
  catch: () => _catch2,
  check: () => check,
  cidrv4: () => cidrv42,
  cidrv6: () => cidrv62,
  clone: () => clone,
  coerce: () => coerce_exports,
  config: () => config,
  core: () => core_exports2,
  cuid: () => cuid3,
  cuid2: () => cuid22,
  custom: () => custom2,
  date: () => date4,
  discriminatedUnion: () => discriminatedUnion,
  e164: () => e1642,
  email: () => email2,
  emoji: () => emoji2,
  endsWith: () => _endsWith,
  enum: () => _enum2,
  file: () => file,
  flattenError: () => flattenError,
  float32: () => float32,
  float64: () => float64,
  formatError: () => formatError,
  function: () => _function,
  getErrorMap: () => getErrorMap2,
  globalRegistry: () => globalRegistry,
  gt: () => _gt,
  gte: () => _gte,
  guid: () => guid2,
  includes: () => _includes,
  instanceof: () => _instanceof,
  int: () => int,
  int32: () => int32,
  int64: () => int64,
  intersection: () => intersection,
  ipv4: () => ipv42,
  ipv6: () => ipv62,
  iso: () => iso_exports,
  json: () => json2,
  jwt: () => jwt,
  keyof: () => keyof,
  ksuid: () => ksuid2,
  lazy: () => lazy,
  length: () => _length,
  literal: () => literal,
  locales: () => locales_exports,
  looseObject: () => looseObject,
  lowercase: () => _lowercase,
  lt: () => _lt,
  lte: () => _lte,
  map: () => map,
  maxLength: () => _maxLength,
  maxSize: () => _maxSize,
  mime: () => _mime,
  minLength: () => _minLength,
  minSize: () => _minSize,
  multipleOf: () => _multipleOf,
  nan: () => nan,
  nanoid: () => nanoid2,
  nativeEnum: () => nativeEnum,
  negative: () => _negative,
  never: () => never,
  nonnegative: () => _nonnegative,
  nonoptional: () => nonoptional,
  nonpositive: () => _nonpositive,
  normalize: () => _normalize,
  null: () => _null3,
  nullable: () => nullable,
  nullish: () => nullish2,
  number: () => number2,
  object: () => object,
  optional: () => optional,
  overwrite: () => _overwrite,
  parse: () => parse2,
  parseAsync: () => parseAsync2,
  partialRecord: () => partialRecord,
  pipe: () => pipe,
  positive: () => _positive,
  prefault: () => prefault,
  preprocess: () => preprocess,
  prettifyError: () => prettifyError,
  promise: () => promise,
  property: () => _property,
  readonly: () => readonly,
  record: () => record,
  refine: () => refine,
  regex: () => _regex,
  regexes: () => regexes_exports,
  registry: () => registry,
  safeParse: () => safeParse2,
  safeParseAsync: () => safeParseAsync2,
  set: () => set,
  setErrorMap: () => setErrorMap2,
  size: () => _size,
  startsWith: () => _startsWith,
  strictObject: () => strictObject,
  string: () => string2,
  stringFormat: () => stringFormat,
  stringbool: () => stringbool,
  success: () => success,
  superRefine: () => superRefine,
  symbol: () => symbol,
  templateLiteral: () => templateLiteral,
  toJSONSchema: () => toJSONSchema,
  toLowerCase: () => _toLowerCase,
  toUpperCase: () => _toUpperCase,
  transform: () => transform,
  treeifyError: () => treeifyError,
  trim: () => _trim,
  tuple: () => tuple,
  uint32: () => uint32,
  uint64: () => uint64,
  ulid: () => ulid2,
  undefined: () => _undefined3,
  union: () => union2,
  unknown: () => unknown,
  uppercase: () => _uppercase,
  url: () => url,
  uuid: () => uuid3,
  uuidv4: () => uuidv4,
  uuidv6: () => uuidv6,
  uuidv7: () => uuidv7,
  void: () => _void2,
  xid: () => xid2
});
var init_external2 = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/external.js"() {
    init_core3();
    init_schemas2();
    init_checks3();
    init_errors4();
    init_parse2();
    init_compat();
    init_core3();
    init_en2();
    init_core3();
    init_locales();
    init_iso();
    init_iso();
    init_coerce();
    config(en_default2());
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/index.js
var init_classic = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/index.js"() {
    init_external2();
    init_external2();
  }
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/index.js
var init_v4 = __esm({
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/index.js"() {
    init_classic();
  }
});

// ../../node_modules/.pnpm/drizzle-zod@0.8.3_drizzle-o_388078da7d074fc4ad4cae0eacfc8b59/node_modules/drizzle-zod/index.mjs
function isColumnType(column, columnTypes) {
  return columnTypes.includes(column.columnType);
}
function isWithEnum(column) {
  return "enumValues" in column && Array.isArray(column.enumValues) && column.enumValues.length > 0;
}
function columnToSchema(column, factory) {
  const z$1 = factory?.zodInstance ?? external_exports2;
  const coerce2 = factory?.coerce ?? {};
  let schema;
  if (isWithEnum(column)) {
    schema = column.enumValues.length ? z$1.enum(column.enumValues) : z$1.string();
  }
  if (!schema) {
    if (isColumnType(column, ["PgGeometry", "PgPointTuple"])) {
      schema = z$1.tuple([z$1.number(), z$1.number()]);
    } else if (isColumnType(column, ["PgGeometryObject", "PgPointObject"])) {
      schema = z$1.object({ x: z$1.number(), y: z$1.number() });
    } else if (isColumnType(column, ["PgHalfVector", "PgVector"])) {
      schema = z$1.array(z$1.number());
      schema = column.dimensions ? schema.length(column.dimensions) : schema;
    } else if (isColumnType(column, ["PgLine"])) {
      schema = z$1.tuple([z$1.number(), z$1.number(), z$1.number()]);
    } else if (isColumnType(column, ["PgLineABC"])) {
      schema = z$1.object({
        a: z$1.number(),
        b: z$1.number(),
        c: z$1.number()
      });
    } else if (isColumnType(column, ["PgArray"])) {
      schema = z$1.array(columnToSchema(column.baseColumn, factory));
      schema = column.size ? schema.length(column.size) : schema;
    } else if (column.dataType === "array") {
      schema = z$1.array(z$1.any());
    } else if (column.dataType === "number") {
      schema = numberColumnToSchema(column, z$1, coerce2);
    } else if (column.dataType === "bigint") {
      schema = bigintColumnToSchema(column, z$1, coerce2);
    } else if (column.dataType === "boolean") {
      schema = coerce2 === true || coerce2.boolean ? z$1.coerce.boolean() : z$1.boolean();
    } else if (column.dataType === "date") {
      schema = coerce2 === true || coerce2.date ? z$1.coerce.date() : z$1.date();
    } else if (column.dataType === "string") {
      schema = stringColumnToSchema(column, z$1, coerce2);
    } else if (column.dataType === "json") {
      schema = jsonSchema;
    } else if (column.dataType === "custom") {
      schema = z$1.any();
    } else if (column.dataType === "buffer") {
      schema = bufferSchema;
    }
  }
  if (!schema) {
    schema = z$1.any();
  }
  return schema;
}
function numberColumnToSchema(column, z, coerce2) {
  let unsigned = column.getSQLType().includes("unsigned");
  let min;
  let max;
  let integer3 = false;
  if (isColumnType(column, ["MySqlTinyInt", "SingleStoreTinyInt"])) {
    min = unsigned ? 0 : CONSTANTS.INT8_MIN;
    max = unsigned ? CONSTANTS.INT8_UNSIGNED_MAX : CONSTANTS.INT8_MAX;
    integer3 = true;
  } else if (isColumnType(column, [
    "PgSmallInt",
    "PgSmallSerial",
    "MySqlSmallInt",
    "SingleStoreSmallInt"
  ])) {
    min = unsigned ? 0 : CONSTANTS.INT16_MIN;
    max = unsigned ? CONSTANTS.INT16_UNSIGNED_MAX : CONSTANTS.INT16_MAX;
    integer3 = true;
  } else if (isColumnType(column, [
    "PgReal",
    "MySqlFloat",
    "MySqlMediumInt",
    "SingleStoreMediumInt",
    "SingleStoreFloat"
  ])) {
    min = unsigned ? 0 : CONSTANTS.INT24_MIN;
    max = unsigned ? CONSTANTS.INT24_UNSIGNED_MAX : CONSTANTS.INT24_MAX;
    integer3 = isColumnType(column, ["MySqlMediumInt", "SingleStoreMediumInt"]);
  } else if (isColumnType(column, [
    "PgInteger",
    "PgSerial",
    "MySqlInt",
    "SingleStoreInt"
  ])) {
    min = unsigned ? 0 : CONSTANTS.INT32_MIN;
    max = unsigned ? CONSTANTS.INT32_UNSIGNED_MAX : CONSTANTS.INT32_MAX;
    integer3 = true;
  } else if (isColumnType(column, [
    "PgDoublePrecision",
    "MySqlReal",
    "MySqlDouble",
    "SingleStoreReal",
    "SingleStoreDouble",
    "SQLiteReal"
  ])) {
    min = unsigned ? 0 : CONSTANTS.INT48_MIN;
    max = unsigned ? CONSTANTS.INT48_UNSIGNED_MAX : CONSTANTS.INT48_MAX;
  } else if (isColumnType(column, [
    "PgBigInt53",
    "PgBigSerial53",
    "MySqlBigInt53",
    "MySqlSerial",
    "SingleStoreBigInt53",
    "SingleStoreSerial",
    "SQLiteInteger"
  ])) {
    unsigned = unsigned || isColumnType(column, ["MySqlSerial", "SingleStoreSerial"]);
    min = unsigned ? 0 : Number.MIN_SAFE_INTEGER;
    max = Number.MAX_SAFE_INTEGER;
    integer3 = true;
  } else if (isColumnType(column, ["MySqlYear", "SingleStoreYear"])) {
    min = 1901;
    max = 2155;
    integer3 = true;
  } else {
    min = Number.MIN_SAFE_INTEGER;
    max = Number.MAX_SAFE_INTEGER;
  }
  let schema = coerce2 === true || coerce2?.number ? integer3 ? z.coerce.number() : z.coerce.number().int() : integer3 ? z.int() : z.number();
  schema = schema.gte(min).lte(max);
  return schema;
}
function bigintColumnToSchema(column, z, coerce2) {
  const unsigned = column.getSQLType().includes("unsigned");
  const min = unsigned ? 0n : CONSTANTS.INT64_MIN;
  const max = unsigned ? CONSTANTS.INT64_UNSIGNED_MAX : CONSTANTS.INT64_MAX;
  const schema = coerce2 === true || coerce2?.bigint ? z.coerce.bigint() : z.bigint();
  return schema.gte(min).lte(max);
}
function stringColumnToSchema(column, z, coerce2) {
  if (isColumnType(column, ["PgUUID"])) {
    return z.uuid();
  }
  let max;
  let regex;
  let fixed = false;
  if (isColumnType(column, ["PgVarchar", "SQLiteText"])) {
    max = column.length;
  } else if (isColumnType(column, ["MySqlVarChar", "SingleStoreVarChar"])) {
    max = column.length ?? CONSTANTS.INT16_UNSIGNED_MAX;
  } else if (isColumnType(column, ["MySqlText", "SingleStoreText"])) {
    if (column.textType === "longtext") {
      max = CONSTANTS.INT32_UNSIGNED_MAX;
    } else if (column.textType === "mediumtext") {
      max = CONSTANTS.INT24_UNSIGNED_MAX;
    } else if (column.textType === "text") {
      max = CONSTANTS.INT16_UNSIGNED_MAX;
    } else {
      max = CONSTANTS.INT8_UNSIGNED_MAX;
    }
  }
  if (isColumnType(column, [
    "PgChar",
    "MySqlChar",
    "SingleStoreChar"
  ])) {
    max = column.length;
    fixed = true;
  }
  if (isColumnType(column, ["PgBinaryVector"])) {
    regex = /^[01]+$/;
    max = column.dimensions;
  }
  let schema = coerce2 === true || coerce2?.string ? z.coerce.string() : z.string();
  schema = regex ? schema.regex(regex) : schema;
  return max && fixed ? schema.length(max) : max ? schema.max(max) : schema;
}
function getColumns(tableLike) {
  return isTable(tableLike) ? getTableColumns(tableLike) : getViewSelectedFields(tableLike);
}
function handleColumns(columns, refinements, conditions, factory) {
  const columnSchemas = {};
  for (const [key, selected] of Object.entries(columns)) {
    if (!is(selected, Column) && !is(selected, SQL) && !is(selected, SQL.Aliased) && typeof selected === "object") {
      const columns2 = isTable(selected) || isView(selected) ? getColumns(selected) : selected;
      columnSchemas[key] = handleColumns(columns2, refinements[key] ?? {}, conditions, factory);
      continue;
    }
    const refinement = refinements[key];
    if (refinement !== void 0 && typeof refinement !== "function") {
      columnSchemas[key] = refinement;
      continue;
    }
    const column = is(selected, Column) ? selected : void 0;
    const schema = column ? columnToSchema(column, factory) : external_exports2.any();
    const refined = typeof refinement === "function" ? refinement(schema) : schema;
    if (conditions.never(column)) {
      continue;
    } else {
      columnSchemas[key] = refined;
    }
    if (column) {
      if (conditions.nullable(column)) {
        columnSchemas[key] = columnSchemas[key].nullable();
      }
      if (conditions.optional(column)) {
        columnSchemas[key] = columnSchemas[key].optional();
      }
    }
  }
  return external_exports2.object(columnSchemas);
}
var CONSTANTS, literalSchema, jsonSchema, bufferSchema, insertConditions, createInsertSchema;
var init_drizzle_zod = __esm({
  "../../node_modules/.pnpm/drizzle-zod@0.8.3_drizzle-o_388078da7d074fc4ad4cae0eacfc8b59/node_modules/drizzle-zod/index.mjs"() {
    init_v4();
    init_drizzle_orm();
    CONSTANTS = {
      INT8_MIN: -128,
      INT8_MAX: 127,
      INT8_UNSIGNED_MAX: 255,
      INT16_MIN: -32768,
      INT16_MAX: 32767,
      INT16_UNSIGNED_MAX: 65535,
      INT24_MIN: -8388608,
      INT24_MAX: 8388607,
      INT24_UNSIGNED_MAX: 16777215,
      INT32_MIN: -2147483648,
      INT32_MAX: 2147483647,
      INT32_UNSIGNED_MAX: 4294967295,
      INT48_MIN: -140737488355328,
      INT48_MAX: 140737488355327,
      INT48_UNSIGNED_MAX: 281474976710655,
      INT64_MIN: -9223372036854775808n,
      INT64_MAX: 9223372036854775807n,
      INT64_UNSIGNED_MAX: 18446744073709551615n
    };
    literalSchema = external_exports2.union([external_exports2.string(), external_exports2.number(), external_exports2.boolean(), external_exports2.null()]);
    jsonSchema = external_exports2.union([
      literalSchema,
      external_exports2.record(external_exports2.string(), external_exports2.any()),
      external_exports2.array(external_exports2.any())
    ]);
    bufferSchema = external_exports2.custom((v) => v instanceof Buffer);
    insertConditions = {
      never: (column) => column?.generated?.type === "always" || column?.generatedIdentity?.type === "always",
      optional: (column) => !column.notNull || column.notNull && column.hasDefault,
      nullable: (column) => !column.notNull
    };
    createInsertSchema = (entity, refine2) => {
      const columns = getColumns(entity);
      return handleColumns(columns, refine2 ?? {}, insertConditions);
    };
  }
});

// ../../lib/db/src/schema/index.ts
var schema_exports = {};
__export(schema_exports, {
  academyCategoriesTable: () => academyCategoriesTable,
  academyCoursesTable: () => academyCoursesTable,
  announcementsTable: () => announcementsTable,
  ascaContributionStatusEnum: () => ascaContributionStatusEnum,
  ascaContributionsTable: () => ascaContributionsTable,
  ascaMemberStatusEnum: () => ascaMemberStatusEnum,
  ascaMembersTable: () => ascaMembersTable,
  ascaStatusEnum: () => ascaStatusEnum,
  ascaTypeEnum: () => ascaTypeEnum,
  ascasTable: () => ascasTable,
  bankSetupTable: () => bankSetupTable,
  circleMembershipsTable: () => circleMembershipsTable,
  circlePayoutsTable: () => circlePayoutsTable,
  circleStatusEnum: () => circleStatusEnum,
  commitmentStatusEnum: () => commitmentStatusEnum,
  communityCommentsTable: () => communityCommentsTable,
  communityEventsTable: () => communityEventsTable,
  communityForumsTable: () => communityForumsTable,
  communityPostTypeEnum: () => communityPostTypeEnum,
  communityPostsTable: () => communityPostsTable,
  communityProfilesTable: () => communityProfilesTable,
  communityReactionsTable: () => communityReactionsTable,
  contributionFrequencyEnum: () => contributionFrequencyEnum,
  contributionStatusEnum: () => contributionStatusEnum,
  courseInterestsTable: () => courseInterestsTable,
  creditScoreFactorsTable: () => creditScoreFactorsTable,
  directMessagesTable: () => directMessagesTable,
  discussionRepliesTable: () => discussionRepliesTable,
  discussionsTable: () => discussionsTable,
  eventRsvpsTable: () => eventRsvpsTable,
  eventTypeEnum: () => eventTypeEnum,
  forumThreadsTable: () => forumThreadsTable,
  helpingHandApplicationsTable: () => helpingHandApplicationsTable,
  helpingHandRepaymentsTable: () => helpingHandRepaymentsTable,
  helpingHandStatusEnum: () => helpingHandStatusEnum,
  insertUserSchema: () => insertUserSchema,
  intakeStatusEnum: () => intakeStatusEnum,
  investmentCategoryEnum: () => investmentCategoryEnum,
  investmentIntentReservationStatusEnum: () => investmentIntentReservationStatusEnum,
  investmentIntentReservationsTable: () => investmentIntentReservationsTable,
  investmentInterestStatusEnum: () => investmentInterestStatusEnum,
  investmentInterestsTable: () => investmentInterestsTable,
  investmentOpportunitiesTable: () => investmentOpportunitiesTable,
  investmentOpportunityStatusEnum: () => investmentOpportunityStatusEnum,
  investmentTransactionsTable: () => investmentTransactionsTable,
  investorCategoryEnum: () => investorCategoryEnum,
  invoiceStatusEnum: () => invoiceStatusEnum,
  invoicesTable: () => invoicesTable,
  kycStatusEnum: () => kycStatusEnum,
  lendingCommitmentsTable: () => lendingCommitmentsTable,
  lendingLoanTypeEnum: () => lendingLoanTypeEnum,
  lendingMinAppreciationTypeEnum: () => lendingMinAppreciationTypeEnum,
  lendingOpportunitiesTable: () => lendingOpportunitiesTable,
  lendingOpportunityReturnAllocationsTable: () => lendingOpportunityReturnAllocationsTable,
  lendingOpportunityReturnEventsTable: () => lendingOpportunityReturnEventsTable,
  lendingPoolReturnModelEnum: () => lendingPoolReturnModelEnum,
  lendingPoolStatusEnum: () => lendingPoolStatusEnum,
  lendingRepaymentFrequencyEnum: () => lendingRepaymentFrequencyEnum,
  lendingTemplatesTable: () => lendingTemplatesTable,
  loanApplicationStatusEnum: () => loanApplicationStatusEnum,
  loanApplicationsTable: () => loanApplicationsTable,
  loanRepaymentsTable: () => loanRepaymentsTable,
  memberSpotlightsTable: () => memberSpotlightsTable,
  membershipIdSettingsTable: () => membershipIdSettingsTable,
  membershipPlanTierEnum: () => membershipPlanTierEnum,
  membershipPlansTable: () => membershipPlansTable,
  membershipStatusEnum: () => membershipStatusEnum,
  membershipSubscriptionsTable: () => membershipSubscriptionsTable,
  membershipTypeEnum: () => membershipTypeEnum,
  messageThreadParticipantsTable: () => messageThreadParticipantsTable,
  messageThreadsTable: () => messageThreadsTable,
  notificationCategoryEnum: () => notificationCategoryEnum,
  notificationChannelEnum: () => notificationChannelEnum,
  notificationDeliveriesTable: () => notificationDeliveriesTable,
  notificationDeliveryStatusEnum: () => notificationDeliveryStatusEnum,
  notificationSeverityEnum: () => notificationSeverityEnum,
  notificationsTable: () => notificationsTable,
  onboardingActivityProgressTable: () => onboardingActivityProgressTable,
  onboardingActivityStatusEnum: () => onboardingActivityStatusEnum,
  onboardingActivityTypeEnum: () => onboardingActivityTypeEnum,
  onboardingEnrollmentsTable: () => onboardingEnrollmentsTable,
  onboardingProgramDurationUnitEnum: () => onboardingProgramDurationUnitEnum,
  onboardingProgramStatusEnum: () => onboardingProgramStatusEnum,
  onboardingProgramWeeksTable: () => onboardingProgramWeeksTable,
  onboardingProgramsTable: () => onboardingProgramsTable,
  onboardingSlidesTable: () => onboardingSlidesTable,
  onboardingWeekActivitiesTable: () => onboardingWeekActivitiesTable,
  orgLendingPoolFunderUsesTable: () => orgLendingPoolFunderUsesTable,
  orgLendingPoolsTable: () => orgLendingPoolsTable,
  orgMemberRoleEnum: () => orgMemberRoleEnum,
  organizationBankSettingsTable: () => organizationBankSettingsTable,
  organizationIntakesTable: () => organizationIntakesTable,
  organizationInvitationStatusEnum: () => organizationInvitationStatusEnum,
  organizationInvitationsTable: () => organizationInvitationsTable,
  organizationMemberObligationKindEnum: () => organizationMemberObligationKindEnum,
  organizationMemberObligationStatusEnum: () => organizationMemberObligationStatusEnum,
  organizationMemberObligationsTable: () => organizationMemberObligationsTable,
  organizationMemberStatusEnum: () => organizationMemberStatusEnum,
  organizationMembersTable: () => organizationMembersTable,
  organizationMembershipIdSettingsTable: () => organizationMembershipIdSettingsTable,
  organizationOperationalStatusEnum: () => organizationOperationalStatusEnum,
  organizationSubscriptionsTable: () => organizationSubscriptionsTable,
  organizationTypeEnum: () => organizationTypeEnum,
  organizationsTable: () => organizationsTable,
  passwordResetTokensTable: () => passwordResetTokensTable,
  paymentMethodEnum: () => paymentMethodEnum,
  paymentProviderEnum: () => paymentProviderEnum,
  paymentStatusEnum: () => paymentStatusEnum,
  paymentWebhookEventsTable: () => paymentWebhookEventsTable,
  paymentsTable: () => paymentsTable,
  payoutStatusEnum: () => payoutStatusEnum,
  planBillingCycleEnum: () => planBillingCycleEnum,
  planBillingModeEnum: () => planBillingModeEnum,
  pushPlatformEnum: () => pushPlatformEnum,
  repaymentStatusEnum: () => repaymentStatusEnum,
  resourceCategoriesTable: () => resourceCategoriesTable,
  resourceFileTypeEnum: () => resourceFileTypeEnum,
  resourceKindEnum: () => resourceKindEnum,
  resourcesTable: () => resourcesTable,
  riskLevelEnum: () => riskLevelEnum,
  rsvpStatusEnum: () => rsvpStatusEnum,
  savingsCirclesTable: () => savingsCirclesTable,
  savingsContributionsTable: () => savingsContributionsTable,
  userNotificationPreferencesTable: () => userNotificationPreferencesTable,
  userPushTokensTable: () => userPushTokensTable,
  userRoleEnum: () => userRoleEnum,
  userSegmentEnum: () => userSegmentEnum,
  usersTable: () => usersTable,
  verificationTokensTable: () => verificationTokensTable,
  walletOwnerTypeEnum: () => walletOwnerTypeEnum,
  walletPaymentIntentStatusEnum: () => walletPaymentIntentStatusEnum,
  walletPaymentIntentTypeEnum: () => walletPaymentIntentTypeEnum,
  walletPaymentIntentsTable: () => walletPaymentIntentsTable,
  walletTransactionTypeEnum: () => walletTransactionTypeEnum,
  walletTransactionsTable: () => walletTransactionsTable,
  walletsTable: () => walletsTable,
  webhookEventStatusEnum: () => webhookEventStatusEnum,
  wwnCreditScoresTable: () => wwnCreditScoresTable
});
var userRoleEnum, userSegmentEnum, membershipTypeEnum, membershipStatusEnum, membershipPlanTierEnum, investorCategoryEnum, planBillingModeEnum, planBillingCycleEnum, contributionFrequencyEnum, lendingRepaymentFrequencyEnum, contributionStatusEnum, paymentMethodEnum, paymentStatusEnum, invoiceStatusEnum, circleStatusEnum, payoutStatusEnum, walletOwnerTypeEnum, walletTransactionTypeEnum, paymentProviderEnum, walletPaymentIntentTypeEnum, walletPaymentIntentStatusEnum, webhookEventStatusEnum, helpingHandStatusEnum, loanApplicationStatusEnum, repaymentStatusEnum, investmentCategoryEnum, investmentOpportunityStatusEnum, investmentInterestStatusEnum, investmentIntentReservationStatusEnum, riskLevelEnum, lendingPoolStatusEnum, commitmentStatusEnum, lendingPoolReturnModelEnum, lendingMinAppreciationTypeEnum, lendingLoanTypeEnum, kycStatusEnum, eventTypeEnum, rsvpStatusEnum, notificationCategoryEnum, notificationSeverityEnum, pushPlatformEnum, notificationChannelEnum, notificationDeliveryStatusEnum, resourceFileTypeEnum, resourceKindEnum, orgMemberRoleEnum, organizationMemberStatusEnum, intakeStatusEnum, organizationTypeEnum, organizationOperationalStatusEnum, organizationInvitationStatusEnum, organizationMemberObligationStatusEnum, organizationMemberObligationKindEnum, onboardingProgramStatusEnum, onboardingProgramDurationUnitEnum, onboardingActivityTypeEnum, onboardingActivityStatusEnum, ascaTypeEnum, ascaStatusEnum, ascaMemberStatusEnum, ascaContributionStatusEnum, organizationsTable, usersTable, verificationTokensTable, passwordResetTokensTable, organizationMembersTable, organizationInvitationsTable, organizationIntakesTable, organizationMemberObligationsTable, organizationBankSettingsTable, organizationMembershipIdSettingsTable, membershipPlansTable, membershipSubscriptionsTable, organizationSubscriptionsTable, invoicesTable, paymentsTable, academyCategoriesTable, academyCoursesTable, courseInterestsTable, savingsCirclesTable, circleMembershipsTable, savingsContributionsTable, circlePayoutsTable, walletsTable, walletTransactionsTable, walletPaymentIntentsTable, bankSetupTable, membershipIdSettingsTable, paymentWebhookEventsTable, wwnCreditScoresTable, creditScoreFactorsTable, helpingHandApplicationsTable, helpingHandRepaymentsTable, investmentOpportunitiesTable, investmentInterestsTable, investmentIntentReservationsTable, investmentTransactionsTable, lendingTemplatesTable, lendingOpportunitiesTable, lendingCommitmentsTable, loanApplicationsTable, loanRepaymentsTable, orgLendingPoolsTable, orgLendingPoolFunderUsesTable, lendingOpportunityReturnEventsTable, lendingOpportunityReturnAllocationsTable, notificationsTable, userPushTokensTable, userNotificationPreferencesTable, notificationDeliveriesTable, announcementsTable, communityEventsTable, eventRsvpsTable, discussionsTable, discussionRepliesTable, memberSpotlightsTable, communityPostTypeEnum, communityProfilesTable, communityPostsTable, communityCommentsTable, communityReactionsTable, communityForumsTable, forumThreadsTable, messageThreadsTable, messageThreadParticipantsTable, directMessagesTable, resourceCategoriesTable, resourcesTable, onboardingSlidesTable, onboardingProgramsTable, onboardingProgramWeeksTable, onboardingWeekActivitiesTable, onboardingEnrollmentsTable, onboardingActivityProgressTable, ascasTable, ascaMembersTable, ascaContributionsTable, insertUserSchema;
var init_schema2 = __esm({
  "../../lib/db/src/schema/index.ts"() {
    "use strict";
    init_pg_core();
    init_drizzle_orm();
    init_drizzle_zod();
    userRoleEnum = pgEnum("user_role_enum", [
      "MEMBER",
      "ADMIN",
      "SUPER_ADMIN"
    ]);
    userSegmentEnum = pgEnum("user_segment_enum", [
      "PROFESSIONAL",
      "ENTREPRENEUR",
      "YOUTH",
      "SCHOOL",
      "INSTITUTION"
    ]);
    membershipTypeEnum = pgEnum("membership_type_enum", [
      "INDIVIDUAL",
      "ORGANIZATION",
      "INVESTOR"
    ]);
    membershipStatusEnum = pgEnum("membership_status_enum", [
      "PENDING",
      "ACTIVE",
      "SUSPENDED",
      "EXPIRED",
      "CANCELLED"
    ]);
    membershipPlanTierEnum = pgEnum("membership_plan_tier_enum", [
      "STARTER",
      "PROFESSIONAL",
      "ELITE",
      "ENTREPRENEUR",
      "YOUTH",
      "COMMUNITY",
      "EDUCATION",
      "GRASSROOT",
      "WORKER",
      "IMPACT",
      "SPONSOR"
    ]);
    investorCategoryEnum = pgEnum("investor_category_enum", [
      "WORKER_OWNER",
      "COMMUNITY_SPONSOR",
      "IMPACT_INVESTOR"
    ]);
    planBillingModeEnum = pgEnum("plan_billing_mode_enum", [
      "ONE_TIME",
      "RECURRING"
    ]);
    planBillingCycleEnum = pgEnum("plan_billing_cycle_enum", [
      "MONTHLY",
      "ANNUAL"
    ]);
    contributionFrequencyEnum = pgEnum("contribution_frequency_enum", [
      "WEEKLY",
      "BIWEEKLY",
      "MONTHLY"
    ]);
    lendingRepaymentFrequencyEnum = pgEnum(
      "lending_repayment_frequency_enum",
      ["WEEKLY", "BIWEEKLY", "MONTHLY"]
    );
    contributionStatusEnum = pgEnum("contribution_status_enum", [
      "PAID",
      "PENDING",
      "MISSED",
      "WAIVED"
    ]);
    paymentMethodEnum = pgEnum("payment_method_enum", [
      "STRIPE",
      "EFT",
      "INTERAC",
      "WIRE",
      "WALLET"
    ]);
    paymentStatusEnum = pgEnum("payment_status_enum", [
      "PENDING",
      "COMPLETED",
      "FAILED",
      "REFUNDED"
    ]);
    invoiceStatusEnum = pgEnum("invoice_status_enum", [
      "DRAFT",
      "SENT",
      "PAID",
      "OVERDUE",
      "CANCELLED"
    ]);
    circleStatusEnum = pgEnum("circle_status_enum", [
      "FORMING",
      "UPCOMING",
      "ACTIVE",
      "COMPLETED",
      "CANCELLED"
    ]);
    payoutStatusEnum = pgEnum("payout_status_enum", [
      "PENDING",
      "PAID",
      "SKIPPED"
    ]);
    walletOwnerTypeEnum = pgEnum("wallet_owner_type_enum", [
      "USER",
      "ORGANIZATION",
      "SUSU",
      "INVESTMENT",
      "CIRCLE",
      "LENDING_POOL",
      "LENDING_MASTER",
      "PLATFORM",
      "ASCA"
    ]);
    walletTransactionTypeEnum = pgEnum(
      "wallet_transaction_type_enum",
      [
        "TOP_UP",
        "CASH_OUT",
        "REFUND",
        "CONTRIBUTION",
        "PAYOUT",
        "ADJUSTMENT",
        "INVESTMENT_PURCHASE",
        "INVESTMENT_PRINCIPAL_PAYOUT",
        "INVESTMENT_RETURN_PAYOUT",
        "LENDING_PRINCIPAL_PAYOUT",
        "LENDING_RETURN_PAYOUT",
        "LOAN_DISBURSEMENT",
        "LOAN_REPAYMENT",
        "HELPING_HAND_DISBURSEMENT",
        "HELPING_HAND_REPAYMENT",
        "ASCA_CONTRIBUTION",
        "ASCA_REFUND",
        "ASCA_INVESTMENT",
        "ASCA_OFFLINE_WITHDRAWAL"
      ]
    );
    paymentProviderEnum = pgEnum("payment_provider_enum", [
      "STRIPE",
      "INTERAC",
      "MANUAL"
    ]);
    walletPaymentIntentTypeEnum = pgEnum(
      "wallet_payment_intent_type_enum",
      ["TOP_UP", "CASH_OUT", "REFUND"]
    );
    walletPaymentIntentStatusEnum = pgEnum(
      "wallet_payment_intent_status_enum",
      ["CREATED", "PENDING", "SUCCEEDED", "FAILED", "CANCELLED"]
    );
    webhookEventStatusEnum = pgEnum("webhook_event_status_enum", [
      "PENDING",
      "PROCESSED",
      "FAILED"
    ]);
    helpingHandStatusEnum = pgEnum("helping_hand_status_enum", [
      "DRAFT",
      "SUBMITTED",
      "UNDER_REVIEW",
      "APPROVED",
      "REJECTED",
      "FUNDED",
      "REPAYING",
      "CLOSED"
    ]);
    loanApplicationStatusEnum = pgEnum(
      "loan_application_status_enum",
      [
        "DRAFT",
        "SUBMITTED",
        "WAITLISTED",
        "UNDER_REVIEW",
        "APPROVED",
        "APPROVED_RESERVED",
        "REJECTED",
        "CANCELLED",
        "FUNDED",
        "REPAYING",
        "CLOSED"
      ]
    );
    repaymentStatusEnum = pgEnum("repayment_status_enum", [
      "PENDING",
      "PAID",
      "LATE",
      "WAIVED"
    ]);
    investmentCategoryEnum = pgEnum("investment_category_enum", [
      "REAL_ESTATE",
      "AGRICULTURE",
      "SMALL_BUSINESS",
      "COMMUNITY_DEVELOPMENT",
      "BONDS",
      "OTHER"
    ]);
    investmentOpportunityStatusEnum = pgEnum(
      "investment_opportunity_status_enum",
      ["DRAFT", "OPEN", "FUNDED", "CLOSED"]
    );
    investmentInterestStatusEnum = pgEnum(
      "investment_interest_status_enum",
      ["PENDING", "CONFIRMED", "CANCELLED"]
    );
    investmentIntentReservationStatusEnum = pgEnum(
      "investment_intent_reservation_status_enum",
      ["RESERVED", "FINALIZED", "RELEASED"]
    );
    riskLevelEnum = pgEnum("risk_level_enum", [
      "LOW",
      "MEDIUM",
      "HIGH"
    ]);
    lendingPoolStatusEnum = pgEnum("lending_pool_status_enum", [
      "DRAFT",
      "OPEN",
      "PAUSED",
      "CLOSED"
    ]);
    commitmentStatusEnum = pgEnum("commitment_status_enum", [
      "PENDING",
      "CONFIRMED",
      "CANCELLED"
    ]);
    lendingPoolReturnModelEnum = pgEnum(
      "lending_pool_return_model_enum",
      ["FIXED_SIMPLE"]
    );
    lendingMinAppreciationTypeEnum = pgEnum(
      "lending_min_appreciation_type_enum",
      ["NONE", "FIXED", "PCT_OF_PRINCIPAL", "TERM_TIERED"]
    );
    lendingLoanTypeEnum = pgEnum("lending_loan_type_enum", [
      "COMMUNITY_LENDING",
      "P2P_LENDING"
    ]);
    kycStatusEnum = pgEnum("kyc_status_enum", [
      "PENDING",
      "APPROVED",
      "REJECTED"
    ]);
    eventTypeEnum = pgEnum("event_type_enum", [
      "VIRTUAL",
      "IN_PERSON",
      "HYBRID"
    ]);
    rsvpStatusEnum = pgEnum("rsvp_status_enum", [
      "GOING",
      "WAITLISTED",
      "CANCELLED"
    ]);
    notificationCategoryEnum = pgEnum("notification_category_enum", [
      "SYSTEM",
      "MEMBERSHIP",
      "SAVINGS",
      "LENDING",
      "INVESTMENT",
      "ACADEMY",
      "PAYMENT",
      "COMMUNITY"
    ]);
    notificationSeverityEnum = pgEnum("notification_severity_enum", [
      "INFO",
      "SUCCESS",
      "WARNING",
      "ERROR"
    ]);
    pushPlatformEnum = pgEnum("push_platform_enum", ["EXPO"]);
    notificationChannelEnum = pgEnum("notification_channel_enum", [
      "PUSH",
      "EMAIL"
    ]);
    notificationDeliveryStatusEnum = pgEnum(
      "notification_delivery_status_enum",
      ["SENT", "FAILED", "SKIPPED"]
    );
    resourceFileTypeEnum = pgEnum("resource_file_type_enum", [
      "PDF",
      "VIDEO",
      "DOCUMENT",
      "SPREADSHEET",
      "IMAGE",
      "LINK",
      "OTHER"
    ]);
    resourceKindEnum = pgEnum("resource_kind_enum", [
      "FILE",
      "ARTICLE"
    ]);
    orgMemberRoleEnum = pgEnum("org_member_role_enum", [
      "OWNER",
      "ADMIN",
      "MEMBER"
    ]);
    organizationMemberStatusEnum = pgEnum(
      "organization_member_status_enum",
      ["PENDING", "ACTIVE"]
    );
    intakeStatusEnum = pgEnum("intake_status_enum", [
      "PENDING",
      "IN_REVIEW",
      "QUOTED",
      "ACCEPTED",
      "COMPLETED",
      "CANCELLED"
    ]);
    organizationTypeEnum = pgEnum("organization_type_enum", [
      "SCHOOL",
      "GRASSROOTS_ROSCA",
      "NFP_ALUMNI_FAITH"
    ]);
    organizationOperationalStatusEnum = pgEnum(
      "organization_operational_status_enum",
      ["PENDING", "ACTIVE", "SUSPENDED", "ARCHIVED"]
    );
    organizationInvitationStatusEnum = pgEnum(
      "organization_invitation_status_enum",
      ["PENDING", "ACCEPTED", "CANCELLED", "EXPIRED"]
    );
    organizationMemberObligationStatusEnum = pgEnum(
      "organization_member_obligation_status_enum",
      ["PENDING", "PAID", "CANCELLED"]
    );
    organizationMemberObligationKindEnum = pgEnum(
      "organization_member_obligation_kind_enum",
      ["TREASURY", "ORG_SUSU"]
    );
    onboardingProgramStatusEnum = pgEnum(
      "onboarding_program_status_enum",
      ["DRAFT", "PUBLISHED", "ARCHIVED"]
    );
    onboardingProgramDurationUnitEnum = pgEnum(
      "onboarding_program_duration_unit_enum",
      ["WEEK", "DAY"]
    );
    onboardingActivityTypeEnum = pgEnum(
      "onboarding_activity_type_enum",
      [
        "VIDEO",
        "FILE",
        "RICH_TEXT",
        "EXTERNAL_LINK",
        "QUIZ",
        "CHECKLIST",
        "SURVEY"
      ]
    );
    onboardingActivityStatusEnum = pgEnum(
      "onboarding_activity_status_enum",
      ["NOT_STARTED", "IN_PROGRESS", "COMPLETED"]
    );
    ascaTypeEnum = pgEnum("asca_type_enum", ["GENERAL", "INVESTMENT"]);
    ascaStatusEnum = pgEnum("asca_status_enum", [
      "DRAFT",
      "FUNDING",
      "READY",
      "PENDING_INVESTMENT",
      "INVESTED",
      "MATURED",
      "CLOSED",
      "CANCELLED"
    ]);
    ascaMemberStatusEnum = pgEnum("asca_member_status_enum", [
      "ACTIVE",
      "DEFAULTED",
      "WITHDRAWN"
    ]);
    ascaContributionStatusEnum = pgEnum(
      "asca_contribution_status_enum",
      ["PENDING", "PAID", "LATE", "REFUNDED"]
    );
    organizationsTable = pgTable("organizations", {
      id: serial("id").primaryKey(),
      name: text("name").notNull(),
      type: text("type").notNull(),
      organizationType: organizationTypeEnum("organization_type"),
      operationalStatus: organizationOperationalStatusEnum("operational_status").notNull().default("PENDING"),
      description: text("description"),
      website: text("website"),
      contactName: text("contact_name"),
      contactTitle: text("contact_title"),
      businessType: text("business_type"),
      yearsInBusiness: text("years_in_business"),
      annualRevenue: text("annual_revenue"),
      province: text("province"),
      city: text("city"),
      createdAt: timestamp("created_at").notNull().defaultNow(),
      updatedAt: timestamp("updated_at").notNull().defaultNow()
    });
    usersTable = pgTable(
      "users",
      {
        id: serial("id").primaryKey(),
        email: text("email").notNull().unique(),
        username: text("username").unique(),
        phone: text("phone"),
        passwordHash: text("password_hash").notNull(),
        firstName: text("first_name").notNull(),
        lastName: text("last_name"),
        segment: userSegmentEnum("segment"),
        membershipType: membershipTypeEnum("membership_type"),
        membershipStatus: membershipStatusEnum("membership_status").notNull().default("PENDING"),
        role: text("role").default("member"),
        userRole: userRoleEnum("user_role").notNull().default("MEMBER"),
        isEmailVerified: boolean("is_email_verified").notNull().default(false),
        bio: text("bio"),
        avatarUrl: text("avatar_url"),
        city: text("city"),
        province: text("province"),
        contactAddress: text("contact_address"),
        contactStreet: text("contact_street"),
        contactPostalCode: text("contact_postal_code"),
        contactCountryIso2: text("contact_country_iso2"),
        ageRange: text("age_range"),
        occupation: text("occupation"),
        employmentEmployed: boolean("employment_employed"),
        employmentStatus: text("employment_status"),
        employerName: text("employer_name"),
        employerAddress: text("employer_address"),
        employmentPosition: text("employment_position"),
        businessName: text("business_name"),
        businessType: text("business_type"),
        yearsInBusiness: text("years_in_business"),
        annualRevenue: text("annual_revenue"),
        howHeard: text("how_heard"),
        referrerName: text("referrer_name"),
        referrerPhone: text("referrer_phone"),
        referrerWwnId: text("referrer_wwn_id"),
        referrerAddress: text("referrer_address"),
        referrerStreet: text("referrer_street"),
        referrerCity: text("referrer_city"),
        referrerPostalCode: text("referrer_postal_code"),
        goals: text("goals"),
        consentAccepted: boolean("consent_accepted").notNull().default(false),
        consentAcceptedAt: timestamp("consent_accepted_at"),
        nextOfKinFirstName: text("next_of_kin_first_name"),
        nextOfKinLastName: text("next_of_kin_last_name"),
        nextOfKinOtherNames: text("next_of_kin_other_names"),
        nextOfKinGender: text("next_of_kin_gender"),
        nextOfKinResidentialAddress: text("next_of_kin_residential_address"),
        nextOfKinStreet: text("next_of_kin_street"),
        nextOfKinCity: text("next_of_kin_city"),
        nextOfKinPostalCode: text("next_of_kin_postal_code"),
        nextOfKinEmail: text("next_of_kin_email"),
        nextOfKinPhone: text("next_of_kin_phone"),
        nextOfKinRelationship: text("next_of_kin_relationship"),
        nextOfKinOccupation: text("next_of_kin_occupation"),
        kycIdFrontUrl: text("kyc_id_front_url"),
        kycIdBackUrl: text("kyc_id_back_url"),
        kycSelfieUrl: text("kyc_selfie_url"),
        kycStatus: kycStatusEnum("kyc_status"),
        kycSubmittedAt: timestamp("kyc_submitted_at"),
        kycReviewedAt: timestamp("kyc_reviewed_at"),
        kycReviewedByUserId: integer("kyc_reviewed_by_user_id"),
        kycRejectionReason: text("kyc_rejection_reason"),
        investorCategory: investorCategoryEnum("investor_category"),
        organizationId: integer("organization_id").references(
          () => organizationsTable.id
        ),
        onboardingCompletedAt: timestamp("onboarding_completed_at"),
        lastLoginAt: timestamp("last_login_at"),
        authTokenVersion: integer("auth_token_version").notNull().default(0),
        membershipRegistrationId: text("membership_registration_id"),
        deletedAt: timestamp("deleted_at"),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        index("users_membership_created_idx").on(
          t.membershipStatus,
          t.membershipType,
          t.createdAt
        ),
        uniqueIndex("users_membership_registration_id_uidx").on(
          t.membershipRegistrationId
        )
      ]
    );
    verificationTokensTable = pgTable("verification_tokens", {
      id: serial("id").primaryKey(),
      userId: integer("user_id").notNull().references(() => usersTable.id, { onDelete: "cascade" }),
      codeHash: text("code_hash").notNull(),
      expiresAt: timestamp("expires_at").notNull(),
      attempts: integer("attempts").notNull().default(0),
      createdAt: timestamp("created_at").notNull().defaultNow()
    });
    passwordResetTokensTable = pgTable("password_reset_tokens", {
      id: serial("id").primaryKey(),
      userId: integer("user_id").notNull().references(() => usersTable.id, { onDelete: "cascade" }),
      tokenHash: text("token_hash").notNull(),
      expiresAt: timestamp("expires_at").notNull(),
      attempts: integer("attempts").notNull().default(0),
      isExchangeToken: boolean("is_exchange_token").notNull().default(false),
      used: boolean("used").notNull().default(false),
      createdAt: timestamp("created_at").notNull().defaultNow()
    });
    organizationMembersTable = pgTable(
      "organization_members",
      {
        id: serial("id").primaryKey(),
        organizationId: integer("organization_id").notNull().references(() => organizationsTable.id, { onDelete: "cascade" }),
        userId: integer("user_id").notNull().references(() => usersTable.id, { onDelete: "cascade" }),
        role: orgMemberRoleEnum("role").notNull().default("MEMBER"),
        status: organizationMemberStatusEnum("status").notNull().default("ACTIVE"),
        joinedAt: timestamp("joined_at").notNull().defaultNow()
      },
      (t) => [
        uniqueIndex("org_members_org_user_uidx").on(t.organizationId, t.userId)
      ]
    );
    organizationInvitationsTable = pgTable(
      "organization_invitations",
      {
        id: serial("id").primaryKey(),
        organizationId: integer("organization_id").notNull().references(() => organizationsTable.id, { onDelete: "cascade" }),
        email: text("email").notNull(),
        firstName: text("first_name"),
        lastName: text("last_name"),
        role: orgMemberRoleEnum("role").notNull().default("MEMBER"),
        invitedByUserId: integer("invited_by_user_id").references(
          () => usersTable.id,
          {
            onDelete: "set null"
          }
        ),
        tokenHash: text("token_hash").notNull().unique(),
        status: organizationInvitationStatusEnum("status").notNull().default("PENDING"),
        expiresAt: timestamp("expires_at").notNull(),
        acceptedAt: timestamp("accepted_at"),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        index("org_invites_org_status_created_idx").on(
          t.organizationId,
          t.status,
          t.createdAt
        ),
        uniqueIndex("org_invites_org_email_pending_uidx").on(t.organizationId, t.email).where(sql`${t.status} = 'PENDING'`)
      ]
    );
    organizationIntakesTable = pgTable(
      "organization_intakes",
      {
        id: serial("id").primaryKey(),
        organizationId: integer("organization_id").notNull().references(() => organizationsTable.id, { onDelete: "cascade" }),
        programInterests: text("program_interests"),
        annualBudget: text("annual_budget"),
        staffCount: text("staff_count"),
        goals: text("goals"),
        additionalNotes: text("additional_notes"),
        status: intakeStatusEnum("status").notNull().default("PENDING"),
        quoteAmount: numeric("quote_amount", { precision: 12, scale: 2 }),
        quoteNote: text("quote_note"),
        quoteLink: text("quote_link"),
        reviewedByAdminId: integer("reviewed_by_admin_id"),
        reviewedAt: timestamp("reviewed_at"),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        index("org_intakes_org_created_idx").on(t.organizationId, t.createdAt),
        index("org_intakes_org_updated_idx").on(t.organizationId, t.updatedAt)
      ]
    );
    organizationMemberObligationsTable = pgTable(
      "organization_member_obligations",
      {
        id: serial("id").primaryKey(),
        organizationId: integer("organization_id").notNull().references(() => organizationsTable.id, { onDelete: "cascade" }),
        memberUserId: integer("member_user_id").notNull().references(() => usersTable.id, { onDelete: "cascade" }),
        assignedByUserId: integer("assigned_by_user_id").references(
          () => usersTable.id,
          {
            onDelete: "set null"
          }
        ),
        kind: organizationMemberObligationKindEnum("kind").notNull().default("TREASURY"),
        title: text("title").notNull(),
        description: text("description"),
        amount: numeric("amount", { precision: 12, scale: 2 }).notNull(),
        currency: text("currency").notNull().default("CAD"),
        status: organizationMemberObligationStatusEnum("status").notNull().default("PENDING"),
        dueDate: timestamp("due_date"),
        paidAt: timestamp("paid_at"),
        walletTransactionId: integer("wallet_transaction_id"),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        index("org_member_obligation_org_member_status_idx").on(
          t.organizationId,
          t.memberUserId,
          t.status
        ),
        index("org_member_obligation_org_created_idx").on(
          t.organizationId,
          t.createdAt
        )
      ]
    );
    organizationBankSettingsTable = pgTable(
      "organization_bank_settings",
      {
        id: serial("id").primaryKey(),
        organizationId: integer("organization_id").notNull().unique().references(() => organizationsTable.id, { onDelete: "cascade" }),
        eftAccountName: text("eft_account_name").notNull(),
        eftInstitutionNumber: text("eft_institution_number").notNull(),
        eftTransitNumber: text("eft_transit_number").notNull(),
        eftAccountNumber: text("eft_account_number").notNull(),
        interacRecipientName: text("interac_recipient_name").notNull(),
        interacEmail: text("interac_email").notNull(),
        cashoutMinAmount: numeric("cashout_min_amount", {
          precision: 12,
          scale: 2
        }).notNull(),
        cashoutFeePct: numeric("cashout_fee_pct", {
          precision: 6,
          scale: 3
        }).notNull(),
        cashoutFeeFixed: numeric("cashout_fee_fixed", {
          precision: 12,
          scale: 2
        }).notNull(),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        index("org_bank_settings_org_updated_idx").on(
          t.organizationId,
          t.updatedAt
        )
      ]
    );
    organizationMembershipIdSettingsTable = pgTable(
      "organization_membership_id_settings",
      {
        id: serial("id").primaryKey(),
        organizationId: integer("organization_id").notNull().unique().references(() => organizationsTable.id, { onDelete: "cascade" }),
        prefix: text("prefix").notNull().default("WWN"),
        digits: integer("digits").notNull().default(7),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        index("org_membership_id_settings_org_updated_idx").on(
          t.organizationId,
          t.updatedAt
        )
      ]
    );
    membershipPlansTable = pgTable("membership_plans", {
      id: serial("id").primaryKey(),
      membershipType: membershipTypeEnum("membership_type").notNull(),
      organizationType: organizationTypeEnum("organization_type"),
      tier: membershipPlanTierEnum("tier").notNull(),
      name: text("name").notNull(),
      description: text("description"),
      priceMonthly: numeric("price_monthly", {
        precision: 10,
        scale: 2
      }).notNull(),
      priceAnnual: numeric("price_annual", { precision: 10, scale: 2 }).notNull(),
      currency: text("currency").notNull().default("CAD"),
      features: json("features").notNull().default([]),
      entitlements: json("entitlements").$type().notNull().default({}),
      isActive: boolean("is_active").notNull().default(true),
      sortOrder: integer("sort_order").notNull().default(0),
      billingMode: planBillingModeEnum("billing_mode").notNull().default("RECURRING"),
      defaultBillingCycle: planBillingCycleEnum("default_billing_cycle").notNull().default("ANNUAL"),
      createdAt: timestamp("created_at").notNull().defaultNow(),
      updatedAt: timestamp("updated_at").notNull().defaultNow()
    });
    membershipSubscriptionsTable = pgTable(
      "membership_subscriptions",
      {
        id: serial("id").primaryKey(),
        userId: integer("user_id").notNull().references(() => usersTable.id, { onDelete: "cascade" }),
        planId: integer("plan_id").notNull().references(() => membershipPlansTable.id),
        status: membershipStatusEnum("status").notNull().default("PENDING"),
        startDate: timestamp("start_date"),
        endDate: timestamp("end_date"),
        renewsAt: timestamp("renews_at"),
        cancelledAt: timestamp("cancelled_at"),
        stripeCustomerId: text("stripe_customer_id"),
        stripeSubscriptionId: text("stripe_subscription_id"),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        index("member_sub_user_status_created_idx").on(
          t.userId,
          t.status,
          t.createdAt
        ),
        uniqueIndex("member_sub_user_active_uidx").on(t.userId).where(sql`${t.status} in ('PENDING', 'ACTIVE')`)
      ]
    );
    organizationSubscriptionsTable = pgTable(
      "organization_subscriptions",
      {
        id: serial("id").primaryKey(),
        organizationId: integer("organization_id").notNull().references(() => organizationsTable.id, { onDelete: "cascade" }),
        planId: integer("plan_id").notNull().references(() => membershipPlansTable.id),
        status: membershipStatusEnum("status").notNull().default("PENDING"),
        startDate: timestamp("start_date"),
        endDate: timestamp("end_date"),
        renewsAt: timestamp("renews_at"),
        cancelledAt: timestamp("cancelled_at"),
        stripeCustomerId: text("stripe_customer_id"),
        stripeSubscriptionId: text("stripe_subscription_id"),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        index("org_sub_org_status_created_idx").on(
          t.organizationId,
          t.status,
          t.createdAt
        ),
        uniqueIndex("org_sub_org_active_uidx").on(t.organizationId).where(sql`${t.status} in ('PENDING', 'ACTIVE')`)
      ]
    );
    invoicesTable = pgTable(
      "invoices",
      {
        id: serial("id").primaryKey(),
        userId: integer("user_id").notNull().references(() => usersTable.id),
        subscriptionId: integer("subscription_id").references(
          () => membershipSubscriptionsTable.id
        ),
        invoiceNumber: text("invoice_number").notNull().unique(),
        amount: numeric("amount", { precision: 12, scale: 2 }).notNull(),
        currency: text("currency").notNull().default("CAD"),
        status: invoiceStatusEnum("status").notNull().default("DRAFT"),
        dueDate: timestamp("due_date").notNull(),
        paidAt: timestamp("paid_at"),
        pdfUrl: text("pdf_url"),
        lineItems: json("line_items").notNull().default([]),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        index("invoices_user_created_idx").on(t.userId, t.createdAt),
        index("invoices_sub_created_idx").on(t.subscriptionId, t.createdAt)
      ]
    );
    paymentsTable = pgTable(
      "payments",
      {
        id: serial("id").primaryKey(),
        userId: integer("user_id").notNull().references(() => usersTable.id),
        amount: numeric("amount", { precision: 12, scale: 2 }).notNull(),
        currency: text("currency").notNull().default("CAD"),
        method: paymentMethodEnum("method").notNull(),
        status: paymentStatusEnum("status").notNull().default("PENDING"),
        reference: text("reference"),
        description: text("description"),
        metadata: json("metadata"),
        invoiceId: integer("invoice_id").references(() => invoicesTable.id),
        processedAt: timestamp("processed_at"),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        index("payments_invoice_created_idx").on(t.invoiceId, t.createdAt),
        index("payments_user_created_idx").on(t.userId, t.createdAt),
        index("payments_status_created_idx").on(t.status, t.createdAt)
      ]
    );
    academyCategoriesTable = pgTable("academy_categories", {
      id: serial("id").primaryKey(),
      name: text("name").notNull().unique(),
      slug: text("slug").notNull().unique(),
      sortOrder: integer("sort_order").notNull().default(0)
    });
    academyCoursesTable = pgTable("academy_courses", {
      id: serial("id").primaryKey(),
      title: text("title").notNull(),
      slug: text("slug").notNull().unique(),
      description: text("description").notNull(),
      thumbnailUrl: text("thumbnail_url"),
      categoryId: integer("category_id").notNull().references(() => academyCategoriesTable.id),
      instructor: text("instructor").notNull(),
      duration: text("duration").notNull(),
      level: text("level").notNull(),
      rating: numeric("rating", { precision: 3, scale: 1 }),
      enrolledCount: integer("enrolled_count").notNull().default(0),
      externalUrl: text("external_url").notNull(),
      tags: json("tags").notNull().default([]),
      isPublished: boolean("is_published").notNull().default(true),
      sortOrder: integer("sort_order").notNull().default(0),
      createdAt: timestamp("created_at").notNull().defaultNow(),
      updatedAt: timestamp("updated_at").notNull().defaultNow()
    });
    courseInterestsTable = pgTable(
      "course_interests",
      {
        id: serial("id").primaryKey(),
        userId: integer("user_id").notNull().references(() => usersTable.id, { onDelete: "cascade" }),
        courseId: integer("course_id").notNull().references(() => academyCoursesTable.id, { onDelete: "cascade" }),
        createdAt: timestamp("created_at").notNull().defaultNow()
      },
      (t) => [
        uniqueIndex("course_interests_user_course_uidx").on(t.userId, t.courseId)
      ]
    );
    savingsCirclesTable = pgTable(
      "savings_circles",
      {
        id: serial("id").primaryKey(),
        name: text("name").notNull(),
        description: text("description"),
        termsHtml: text("terms_html"),
        contributionAmount: numeric("contribution_amount", {
          precision: 10,
          scale: 2
        }).notNull(),
        frequency: contributionFrequencyEnum("frequency").notNull().default("MONTHLY"),
        helpingHandMultiplier: numeric("helping_hand_multiplier", {
          precision: 6,
          scale: 2
        }),
        orgAutoDeductEnabled: boolean("org_auto_deduct_enabled").notNull().default(false),
        isFreeToJoin: boolean("is_free_to_join").notNull().default(false),
        maxMembers: integer("max_members").notNull(),
        formingTimeoutDays: integer("forming_timeout_days").notNull().default(14),
        status: circleStatusEnum("status").notNull().default("UPCOMING"),
        startDate: timestamp("start_date"),
        endDate: timestamp("end_date"),
        organizationId: integer("organization_id").references(
          () => organizationsTable.id,
          { onDelete: "cascade" }
        ),
        createdByAdminId: integer("created_by_admin_id"),
        createdByOrganizationMemberUserId: integer(
          "created_by_organization_member_user_id"
        ).references(() => usersTable.id, { onDelete: "set null" }),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        index("savings_circles_org_idx").on(t.organizationId, t.createdAt),
        index("savings_circles_org_status_idx").on(t.organizationId, t.status)
      ]
    );
    circleMembershipsTable = pgTable(
      "circle_memberships",
      {
        id: serial("id").primaryKey(),
        circleId: integer("circle_id").notNull().references(() => savingsCirclesTable.id, { onDelete: "cascade" }),
        userId: integer("user_id").notNull().references(() => usersTable.id, { onDelete: "cascade" }),
        position: integer("position").notNull(),
        memberAutoDeductEnabled: boolean("member_auto_deduct_enabled").notNull().default(false),
        joinedAt: timestamp("joined_at").notNull().defaultNow()
      },
      (t) => [
        uniqueIndex("circle_memberships_circle_user_uidx").on(t.circleId, t.userId),
        uniqueIndex("circle_memberships_circle_pos_uidx").on(
          t.circleId,
          t.position
        ),
        index("circle_memberships_user_idx").on(t.userId)
      ]
    );
    savingsContributionsTable = pgTable(
      "savings_contributions",
      {
        id: serial("id").primaryKey(),
        circleId: integer("circle_id").notNull().references(() => savingsCirclesTable.id),
        userId: integer("user_id").notNull().references(() => usersTable.id),
        dueDate: timestamp("due_date").notNull(),
        paidAt: timestamp("paid_at"),
        amount: numeric("amount", { precision: 10, scale: 2 }).notNull(),
        status: contributionStatusEnum("status").notNull().default("PENDING"),
        method: paymentMethodEnum("method"),
        receiptRef: text("receipt_ref"),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        uniqueIndex("savings_contributions_circle_user_due_uidx").on(
          t.circleId,
          t.userId,
          t.dueDate
        ),
        index("savings_contrib_circle_status_due_idx").on(
          t.circleId,
          t.status,
          t.dueDate
        ),
        index("savings_contrib_user_due_idx").on(t.userId, t.dueDate)
      ]
    );
    circlePayoutsTable = pgTable(
      "circle_payouts",
      {
        id: serial("id").primaryKey(),
        circleId: integer("circle_id").notNull().references(() => savingsCirclesTable.id),
        userId: integer("user_id").notNull(),
        position: integer("position").notNull(),
        scheduledDate: timestamp("scheduled_date").notNull(),
        paidDate: timestamp("paid_date"),
        amount: numeric("amount", { precision: 12, scale: 2 }).notNull(),
        status: payoutStatusEnum("status").notNull().default("PENDING"),
        createdAt: timestamp("created_at").notNull().defaultNow()
      },
      (t) => [
        uniqueIndex("circle_payouts_circle_user_pos_uidx").on(
          t.circleId,
          t.userId,
          t.position
        ),
        index("circle_payouts_circle_status_sched_idx").on(
          t.circleId,
          t.status,
          t.scheduledDate
        )
      ]
    );
    walletsTable = pgTable(
      "wallets",
      {
        id: serial("id").primaryKey(),
        ownerType: walletOwnerTypeEnum("owner_type").notNull(),
        ownerId: integer("owner_id").notNull(),
        currency: text("currency").notNull().default("CAD"),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [uniqueIndex("wallets_owner_uidx").on(t.ownerType, t.ownerId)]
    );
    walletTransactionsTable = pgTable(
      "wallet_transactions",
      {
        id: serial("id").primaryKey(),
        type: walletTransactionTypeEnum("type").notNull(),
        idempotencyKey: text("idempotency_key"),
        fromWalletId: integer("from_wallet_id").references(() => walletsTable.id),
        toWalletId: integer("to_wallet_id").references(() => walletsTable.id),
        amount: numeric("amount", { precision: 12, scale: 2 }).notNull(),
        metadata: json("metadata").notNull().default({}),
        createdAt: timestamp("created_at").notNull().defaultNow()
      },
      (t) => [
        uniqueIndex("wallet_transactions_idempotency_uidx").on(t.idempotencyKey),
        index("wallet_txs_from_created_idx").on(t.fromWalletId, t.createdAt),
        index("wallet_txs_to_created_idx").on(t.toWalletId, t.createdAt),
        index("wallet_txs_type_wallets_idx").on(
          t.type,
          t.fromWalletId,
          t.toWalletId
        )
      ]
    );
    walletPaymentIntentsTable = pgTable(
      "wallet_payment_intents",
      {
        id: serial("id").primaryKey(),
        userId: integer("user_id").notNull().references(() => usersTable.id, { onDelete: "cascade" }),
        walletId: integer("wallet_id").notNull().references(() => walletsTable.id, { onDelete: "cascade" }),
        provider: paymentProviderEnum("provider").notNull().default("MANUAL"),
        type: walletPaymentIntentTypeEnum("type").notNull(),
        amount: numeric("amount", { precision: 12, scale: 2 }).notNull(),
        currency: text("currency").notNull().default("CAD"),
        status: walletPaymentIntentStatusEnum("status").notNull().default("CREATED"),
        providerReference: text("provider_reference"),
        metadata: json("metadata").notNull().default({}),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        uniqueIndex("wallet_payment_intents_provider_ref_uidx").on(
          t.provider,
          t.providerReference
        ),
        index("wallet_intents_user_created_idx").on(t.userId, t.createdAt),
        index("wallet_intents_wallet_status_idx").on(
          t.walletId,
          t.status,
          t.createdAt
        )
      ]
    );
    bankSetupTable = pgTable("bank_setup", {
      id: serial("id").primaryKey(),
      eftAccountName: text("eft_account_name").notNull(),
      eftInstitutionNumber: text("eft_institution_number").notNull(),
      eftTransitNumber: text("eft_transit_number").notNull(),
      eftAccountNumber: text("eft_account_number").notNull(),
      interacRecipientName: text("interac_recipient_name").notNull(),
      interacEmail: text("interac_email").notNull(),
      cashoutMinAmount: numeric("cashout_min_amount", {
        precision: 12,
        scale: 2
      }).notNull(),
      cashoutFeePct: numeric("cashout_fee_pct", {
        precision: 6,
        scale: 3
      }).notNull(),
      cashoutFeeFixed: numeric("cashout_fee_fixed", {
        precision: 12,
        scale: 2
      }).notNull(),
      createdAt: timestamp("created_at").notNull().defaultNow(),
      updatedAt: timestamp("updated_at").notNull().defaultNow()
    });
    membershipIdSettingsTable = pgTable("membership_id_settings", {
      id: integer("id").primaryKey(),
      prefix: text("prefix").notNull().default("WWN"),
      digits: integer("digits").notNull().default(7),
      createdAt: timestamp("created_at").notNull().defaultNow(),
      updatedAt: timestamp("updated_at").notNull().defaultNow()
    });
    paymentWebhookEventsTable = pgTable(
      "payment_webhook_events",
      {
        id: serial("id").primaryKey(),
        provider: paymentProviderEnum("provider").notNull(),
        eventId: text("event_id").notNull(),
        eventType: text("event_type").notNull(),
        payload: json("payload").notNull(),
        status: webhookEventStatusEnum("status").notNull().default("PENDING"),
        error: text("error"),
        attempts: integer("attempts").notNull().default(0),
        receivedAt: timestamp("received_at").notNull().defaultNow(),
        processedAt: timestamp("processed_at")
      },
      (t) => [
        uniqueIndex("payment_webhook_events_provider_event_uidx").on(
          t.provider,
          t.eventId
        ),
        index("webhook_events_status_received_idx").on(t.status, t.receivedAt)
      ]
    );
    wwnCreditScoresTable = pgTable("wwn_credit_scores", {
      id: serial("id").primaryKey(),
      userId: integer("user_id").notNull().unique().references(() => usersTable.id, { onDelete: "cascade" }),
      score: integer("score").notNull(),
      computedAt: timestamp("computed_at").notNull().defaultNow()
    });
    creditScoreFactorsTable = pgTable("credit_score_factors", {
      id: serial("id").primaryKey(),
      creditScoreId: integer("credit_score_id").notNull().references(() => wwnCreditScoresTable.id, { onDelete: "cascade" }),
      factorName: text("factor_name").notNull(),
      score: integer("score").notNull(),
      weight: text("weight").notNull()
    });
    helpingHandApplicationsTable = pgTable(
      "helping_hand_applications",
      {
        id: serial("id").primaryKey(),
        userId: integer("user_id").notNull().references(() => usersTable.id),
        requestedAmount: numeric("requested_amount", {
          precision: 10,
          scale: 2
        }).notNull(),
        purpose: text("purpose").notNull(),
        term: text("term").notNull(),
        repaymentSchedule: text("repayment_schedule").notNull(),
        notes: text("notes"),
        status: helpingHandStatusEnum("status").notNull().default("DRAFT"),
        reviewedByAdminId: integer("reviewed_by_admin_id"),
        reviewedAt: timestamp("reviewed_at"),
        reviewNote: text("review_note"),
        qualifyingCircleId: integer("qualifying_circle_id").references(
          () => savingsCirclesTable.id
        ),
        qualifyingPayoutId: integer("qualifying_payout_id").references(
          () => circlePayoutsTable.id
        ),
        qualifyingPayoutAmount: numeric("qualifying_payout_amount", {
          precision: 12,
          scale: 2
        }),
        qualifyingMultiplier: numeric("qualifying_multiplier", {
          precision: 6,
          scale: 2
        }),
        approvedAmount: numeric("approved_amount", { precision: 10, scale: 2 }),
        disbursedAmount: numeric("disbursed_amount", { precision: 10, scale: 2 }),
        disbursementTransactionId: integer(
          "disbursement_transaction_id"
        ).references(() => walletTransactionsTable.id),
        disbursedAt: timestamp("disbursed_at"),
        organizationId: integer("organization_id").references(() => organizationsTable.id),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        index("hh_apps_user_created_idx").on(t.userId, t.createdAt),
        index("hh_apps_status_created_idx").on(t.status, t.createdAt),
        index("hh_apps_org_created_idx").on(t.organizationId, t.createdAt)
      ]
    );
    helpingHandRepaymentsTable = pgTable(
      "helping_hand_repayments",
      {
        id: serial("id").primaryKey(),
        helpingHandApplicationId: integer("helping_hand_application_id").notNull().references(() => helpingHandApplicationsTable.id),
        dueDate: timestamp("due_date").notNull(),
        amount: numeric("amount", { precision: 10, scale: 2 }).notNull(),
        paidAmount: numeric("paid_amount", { precision: 10, scale: 2 }),
        paidAt: timestamp("paid_at"),
        status: repaymentStatusEnum("status").notNull().default("PENDING"),
        method: paymentMethodEnum("method"),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow(),
        organizationId: integer("organization_id").references(() => organizationsTable.id)
      },
      (t) => [
        index("hh_repayments_app_due_idx").on(
          t.helpingHandApplicationId,
          t.dueDate
        ),
        index("hh_repayments_status_due_idx").on(t.status, t.dueDate),
        index("hh_repayments_org_due_idx").on(t.organizationId, t.status, t.dueDate)
      ]
    );
    investmentOpportunitiesTable = pgTable(
      "investment_opportunities",
      {
        id: serial("id").primaryKey(),
        title: text("title").notNull(),
        slug: text("slug").notNull().unique(),
        description: text("description").notNull(),
        termsHtml: text("terms_html"),
        category: investmentCategoryEnum("category").notNull(),
        expectedReturnPct: integer("expected_return_pct").notNull(),
        minInvestment: numeric("min_investment", {
          precision: 10,
          scale: 2
        }).notNull(),
        targetAmount: numeric("target_amount", {
          precision: 12,
          scale: 2
        }).notNull(),
        raisedAmount: numeric("raised_amount", { precision: 12, scale: 2 }).notNull().default("0"),
        deadline: timestamp("deadline").notNull(),
        riskLevel: riskLevelEnum("risk_level").notNull().default("MEDIUM"),
        status: investmentOpportunityStatusEnum("status").notNull().default("DRAFT"),
        featured: boolean("featured").notNull().default(false),
        fundingModel: text("funding_model").$type().notNull().default("CROWD"),
        eligibleInvestorTiers: json("eligible_investor_tiers").$type().notNull().default([]),
        organizationId: integer("organization_id").references(
          () => organizationsTable.id
        ),
        videoUrl: text("video_url"),
        academyLink: text("academy_link"),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        index("invest_opps_status_featured_deadline_idx").on(
          t.status,
          t.featured,
          t.deadline
        )
      ]
    );
    investmentInterestsTable = pgTable(
      "investment_interests",
      {
        id: serial("id").primaryKey(),
        userId: integer("user_id").notNull().references(() => usersTable.id),
        opportunityId: integer("opportunity_id").notNull().references(() => investmentOpportunitiesTable.id),
        amount: numeric("amount", { precision: 10, scale: 2 }).notNull(),
        notes: text("notes"),
        status: investmentInterestStatusEnum("status").notNull().default("PENDING"),
        confirmedAt: timestamp("confirmed_at"),
        cancelledAt: timestamp("cancelled_at"),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        uniqueIndex("investment_interests_user_opp_uidx").on(
          t.userId,
          t.opportunityId
        ),
        index("invest_interests_opp_status_idx").on(t.opportunityId, t.status),
        index("invest_interests_user_created_idx").on(t.userId, t.createdAt)
      ]
    );
    investmentIntentReservationsTable = pgTable(
      "investment_intent_reservations",
      {
        id: serial("id").primaryKey(),
        interestId: integer("interest_id").notNull().references(() => investmentInterestsTable.id, { onDelete: "cascade" }),
        walletId: integer("wallet_id").notNull().references(() => walletsTable.id, { onDelete: "cascade" }),
        amount: numeric("amount", { precision: 10, scale: 2 }).notNull(),
        status: investmentIntentReservationStatusEnum("status").notNull().default("RESERVED"),
        finalizedTransactionId: integer("finalized_transaction_id").references(
          () => walletTransactionsTable.id
        ),
        reservedAt: timestamp("reserved_at").notNull().defaultNow(),
        finalizedAt: timestamp("finalized_at"),
        releasedAt: timestamp("released_at"),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        uniqueIndex("investment_intent_reservations_interest_uidx").on(
          t.interestId
        ),
        index("invest_reservations_wallet_status_idx").on(t.walletId, t.status),
        index("invest_reservations_status_created_idx").on(t.status, t.createdAt)
      ]
    );
    investmentTransactionsTable = pgTable(
      "investment_transactions",
      {
        id: serial("id").primaryKey(),
        userId: integer("user_id").notNull().references(() => usersTable.id),
        opportunityId: integer("opportunity_id").notNull().references(() => investmentOpportunitiesTable.id),
        amount: numeric("amount", { precision: 10, scale: 2 }).notNull(),
        type: text("type").notNull(),
        description: text("description"),
        processedAt: timestamp("processed_at").notNull().defaultNow(),
        createdAt: timestamp("created_at").notNull().defaultNow()
      },
      (t) => [
        index("invest_txs_user_processed_idx").on(t.userId, t.processedAt),
        index("invest_txs_user_opp_type_idx").on(t.userId, t.opportunityId, t.type)
      ]
    );
    lendingTemplatesTable = pgTable(
      "lending_templates",
      {
        id: serial("id").primaryKey(),
        legacyPoolId: integer("legacy_pool_id").unique(),
        sourceOpportunityId: integer("source_opportunity_id").unique(),
        loanType: lendingLoanTypeEnum("loan_type").notNull().default("P2P_LENDING"),
        title: text("title").notNull(),
        description: text("description").notNull(),
        termsHtml: text("terms_html"),
        status: lendingPoolStatusEnum("status").notNull().default("OPEN"),
        isSnapshot: boolean("is_snapshot").notNull().default(false),
        minCommitment: numeric("min_commitment", {
          precision: 10,
          scale: 2
        }).notNull(),
        minRequestAmount: numeric("min_request_amount", {
          precision: 10,
          scale: 2
        }).notNull().default("500.00"),
        maxRequestAmount: numeric("max_request_amount", {
          precision: 12,
          scale: 2
        }).notNull().default("25000.00"),
        borrowerAppreciationAmount: numeric("borrower_appreciation_amount", {
          precision: 10,
          scale: 2
        }).notNull().default("0.00"),
        borrowerTermMonths: integer("borrower_term_months").notNull().default(12),
        repaymentFrequency: lendingRepaymentFrequencyEnum("repayment_frequency").notNull().default("MONTHLY"),
        processingFeePct: numeric("processing_fee_pct", {
          precision: 5,
          scale: 2
        }),
        wwnMarginPct: numeric("wwn_margin_pct", {
          precision: 5,
          scale: 2
        }).notNull().default("0.00"),
        reserveContributionPct: numeric("reserve_contribution_pct", {
          precision: 5,
          scale: 2
        }).notNull().default("0.00"),
        platformAppreciationSharePct: numeric("platform_appreciation_share_pct", {
          precision: 5,
          scale: 2
        }).notNull().default("0.00"),
        minAppreciationType: lendingMinAppreciationTypeEnum("min_appreciation_type").notNull().default("NONE"),
        minAppreciationValue: numeric("min_appreciation_value", {
          precision: 10,
          scale: 2
        }).notNull().default("0.00"),
        minAppreciationTiers: json("min_appreciation_tiers"),
        economicsUpdatedAt: timestamp("economics_updated_at"),
        economicsUpdatedByAdminId: integer(
          "economics_updated_by_admin_id"
        ).references(() => usersTable.id),
        economicsUpdateReason: text("economics_update_reason"),
        expectedReturnPct: numeric("expected_return_pct", {
          precision: 5,
          scale: 2
        }).notNull().default("8.00"),
        termMonths: integer("term_months").notNull().default(12),
        returnModel: lendingPoolReturnModelEnum("return_model").notNull().default("FIXED_SIMPLE"),
        expectedReturn: text("expected_return").notNull(),
        term: text("term").notNull(),
        minBorrowerPlanTier: membershipPlanTierEnum("min_borrower_plan_tier").notNull().default("STARTER"),
        borrowerType: text("borrower_type"),
        organizationId: integer("organization_id").references(
          () => organizationsTable.id
        ),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        index("lending_templates_status_created_idx").on(t.status, t.createdAt),
        index("idx_lending_templates_org_status_created").on(
          t.organizationId,
          t.status,
          t.createdAt
        )
      ]
    );
    lendingOpportunitiesTable = pgTable(
      "lending_opportunities",
      {
        id: serial("id").primaryKey(),
        legacyPoolId: integer("legacy_pool_id").unique(),
        templateId: integer("template_id").references(
          () => lendingTemplatesTable.id
        ),
        applicationId: integer("application_id").unique(),
        loanType: lendingLoanTypeEnum("loan_type").notNull().default("P2P_LENDING"),
        title: text("title").notNull(),
        description: text("description").notNull(),
        status: lendingPoolStatusEnum("status").notNull().default("DRAFT"),
        targetAmount: numeric("target_amount", {
          precision: 12,
          scale: 2
        }).notNull(),
        committedAmount: numeric("committed_amount", { precision: 12, scale: 2 }).notNull().default("0"),
        minCommitment: numeric("min_commitment", {
          precision: 10,
          scale: 2
        }).notNull(),
        borrowerAppreciationAmount: numeric("borrower_appreciation_amount", {
          precision: 10,
          scale: 2
        }).notNull().default("0.00"),
        borrowerTermMonths: integer("borrower_term_months").notNull().default(12),
        repaymentFrequency: lendingRepaymentFrequencyEnum("repayment_frequency").notNull().default("MONTHLY"),
        processingFeePct: numeric("processing_fee_pct", {
          precision: 5,
          scale: 2
        }),
        wwnMarginPct: numeric("wwn_margin_pct", {
          precision: 5,
          scale: 2
        }).notNull().default("0.00"),
        reserveContributionPct: numeric("reserve_contribution_pct", {
          precision: 5,
          scale: 2
        }).notNull().default("0.00"),
        platformAppreciationSharePct: numeric("platform_appreciation_share_pct", {
          precision: 5,
          scale: 2
        }).notNull().default("0.00"),
        minAppreciationType: lendingMinAppreciationTypeEnum("min_appreciation_type").notNull().default("NONE"),
        minAppreciationValue: numeric("min_appreciation_value", {
          precision: 10,
          scale: 2
        }).notNull().default("0.00"),
        minAppreciationTiers: json("min_appreciation_tiers"),
        expectedReturnPct: numeric("expected_return_pct", {
          precision: 5,
          scale: 2
        }).notNull().default("8.00"),
        termMonths: integer("term_months").notNull().default(12),
        returnModel: lendingPoolReturnModelEnum("return_model").notNull().default("FIXED_SIMPLE"),
        expectedReturn: text("expected_return").notNull(),
        term: text("term").notNull(),
        minBorrowerPlanTier: membershipPlanTierEnum("min_borrower_plan_tier").notNull().default("STARTER"),
        borrowerType: text("borrower_type"),
        organizationId: integer("organization_id").references(
          () => organizationsTable.id
        ),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        index("lending_opps_status_created_idx").on(t.status, t.createdAt),
        index("lending_opps_template_status_created_idx").on(
          t.templateId,
          t.status,
          t.createdAt
        ),
        index("idx_lending_opps_org_status_created").on(
          t.organizationId,
          t.status,
          t.createdAt
        )
      ]
    );
    lendingCommitmentsTable = pgTable(
      "lending_commitments",
      {
        id: serial("id").primaryKey(),
        userId: integer("user_id").notNull().references(() => usersTable.id),
        opportunityId: integer("opportunity_id").notNull().references(() => lendingOpportunitiesTable.id),
        amount: numeric("amount", { precision: 10, scale: 2 }).notNull(),
        status: commitmentStatusEnum("status").notNull().default("PENDING"),
        confirmedAt: timestamp("confirmed_at"),
        statusChangedAt: timestamp("status_changed_at"),
        statusChangedByAdminId: integer("status_changed_by_admin_id").references(
          () => usersTable.id
        ),
        reviewNote: text("review_note"),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        index("lend_commit_opp_status_created_idx").on(
          t.opportunityId,
          t.status,
          t.createdAt
        ),
        index("lend_commit_user_status_created_idx").on(
          t.userId,
          t.status,
          t.createdAt
        ),
        uniqueIndex("lend_commit_user_opp_active_uidx").on(t.userId, t.opportunityId).where(sql`${t.status} in ('PENDING', 'CONFIRMED')`)
      ]
    );
    loanApplicationsTable = pgTable(
      "loan_applications",
      {
        id: serial("id").primaryKey(),
        ascaId: integer("asca_id").references(() => ascasTable.id),
        borrowerId: integer("borrower_id").notNull().references(() => usersTable.id),
        templateId: integer("template_id").references(
          () => lendingTemplatesTable.id
        ),
        opportunityId: integer("opportunity_id"),
        loanType: lendingLoanTypeEnum("loan_type").notNull().default("P2P_LENDING"),
        requestedAmount: numeric("requested_amount", {
          precision: 10,
          scale: 2
        }).notNull(),
        purpose: text("purpose").notNull(),
        term: text("term").notNull(),
        repaymentSchedule: text("repayment_schedule").notNull(),
        termMonths: integer("term_months").notNull().default(12),
        borrowerAppreciationAmount: numeric("borrower_appreciation_amount", {
          precision: 10,
          scale: 2
        }).notNull().default("0.00"),
        repaymentFrequency: lendingRepaymentFrequencyEnum("repayment_frequency").notNull().default("MONTHLY"),
        processingFeePct: numeric("processing_fee_pct", {
          precision: 5,
          scale: 2
        }),
        wwnMarginPct: numeric("wwn_margin_pct", {
          precision: 5,
          scale: 2
        }).notNull().default("0.00"),
        reserveContributionPct: numeric("reserve_contribution_pct", {
          precision: 5,
          scale: 2
        }).notNull().default("0.00"),
        platformAppreciationSharePct: numeric("platform_appreciation_share_pct", {
          precision: 5,
          scale: 2
        }).notNull().default("0.00"),
        pricingLockedAt: timestamp("pricing_locked_at"),
        totalRepayableAmount: numeric("total_repayable_amount", {
          precision: 10,
          scale: 2
        }).notNull().default("0"),
        estimatedInstallmentAmount: numeric("estimated_installment_amount", {
          precision: 10,
          scale: 2
        }).notNull().default("0"),
        funderOpportunityTitle: text("funder_opportunity_title"),
        notes: text("notes"),
        status: loanApplicationStatusEnum("status").notNull().default("DRAFT"),
        poolAssignedAt: timestamp("pool_assigned_at"),
        poolAssignedByAdminId: integer("pool_assigned_by_admin_id").references(
          () => usersTable.id
        ),
        poolReassignedAt: timestamp("pool_reassigned_at"),
        poolReassignedByAdminId: integer("pool_reassigned_by_admin_id").references(
          () => usersTable.id
        ),
        poolReassignmentNote: text("pool_reassignment_note"),
        reviewedByAdminId: integer("reviewed_by_admin_id"),
        reviewedAt: timestamp("reviewed_at"),
        reviewNote: text("review_note"),
        approvedAmount: numeric("approved_amount", { precision: 10, scale: 2 }),
        reservedAt: timestamp("reserved_at"),
        reservedByAdminId: integer("reserved_by_admin_id").references(
          () => usersTable.id
        ),
        disbursedAt: timestamp("disbursed_at"),
        disbursedAmount: numeric("disbursed_amount", { precision: 10, scale: 2 }),
        disbursementTransactionId: integer(
          "disbursement_transaction_id"
        ).references(() => walletTransactionsTable.id),
        organizationId: integer("organization_id").references(
          () => organizationsTable.id
        ),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        index("loan_apps_borrower_created_idx").on(t.borrowerId, t.createdAt),
        index("loan_apps_asca_status_created_idx").on(t.ascaId, t.status, t.createdAt),
        index("loan_apps_opp_status_created_idx").on(
          t.opportunityId,
          t.status,
          t.createdAt
        ),
        index("idx_loan_apps_org_status_created").on(
          t.organizationId,
          t.status,
          t.createdAt
        ),
        uniqueIndex("loan_apps_borrower_active_uidx").on(t.borrowerId).where(
          sql`${t.status} in ('DRAFT', 'SUBMITTED', 'WAITLISTED', 'UNDER_REVIEW', 'APPROVED', 'APPROVED_RESERVED', 'FUNDED', 'REPAYING')`
        )
      ]
    );
    loanRepaymentsTable = pgTable(
      "loan_repayments",
      {
        id: serial("id").primaryKey(),
        loanApplicationId: integer("loan_application_id").notNull().references(() => loanApplicationsTable.id),
        dueDate: timestamp("due_date").notNull(),
        amount: numeric("amount", { precision: 10, scale: 2 }).notNull(),
        paidAmount: numeric("paid_amount", { precision: 10, scale: 2 }),
        principalPaidAmount: numeric("principal_paid_amount", {
          precision: 10,
          scale: 2
        }).notNull().default("0"),
        returnPaidAmount: numeric("return_paid_amount", {
          precision: 10,
          scale: 2
        }).notNull().default("0"),
        feePaidAmount: numeric("fee_paid_amount", {
          precision: 10,
          scale: 2
        }).notNull().default("0"),
        creditedToPoolAmount: numeric("credited_to_pool_amount", {
          precision: 10,
          scale: 2
        }).notNull().default("0"),
        paidAt: timestamp("paid_at"),
        status: repaymentStatusEnum("status").notNull().default("PENDING"),
        method: paymentMethodEnum("method"),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        index("loan_repayments_app_due_idx").on(t.loanApplicationId, t.dueDate),
        index("loan_repayments_status_due_idx").on(t.status, t.dueDate)
      ]
    );
    orgLendingPoolsTable = pgTable(
      "org_lending_pools",
      {
        id: serial("id").primaryKey(),
        organizationId: integer("organization_id").notNull().references(() => organizationsTable.id, { onDelete: "cascade" }),
        templateId: integer("template_id").references(() => lendingTemplatesTable.id),
        name: text("name").notNull(),
        description: text("description"),
        eligibilityMode: text("eligibility_mode").$type().notNull().default("CONTRIBUTORS_ONLY"),
        status: text("status").$type().notNull().default("DRAFT"),
        minRequestAmount: numeric("min_request_amount", {
          precision: 10,
          scale: 2
        }).notNull().default("500.00"),
        maxRequestAmount: numeric("max_request_amount", {
          precision: 12,
          scale: 2
        }).notNull().default("25000.00"),
        defaultTermMonths: integer("default_term_months").notNull().default(12),
        defaultRepaymentFrequency: lendingRepaymentFrequencyEnum(
          "default_repayment_frequency"
        ).notNull().default("MONTHLY"),
        defaultBorrowerAppreciationPct: numeric(
          "default_borrower_appreciation_pct",
          { precision: 5, scale: 2 }
        ).notNull().default("0.00"),
        defaultProcessingFeePct: numeric("default_processing_fee_pct", {
          precision: 5,
          scale: 2
        }).notNull().default("0.00"),
        notes: text("notes"),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        index("org_lending_pools_org_status_created_idx").on(
          t.organizationId,
          t.status,
          t.createdAt
        ),
        uniqueIndex("org_lending_pools_org_template_uniq_idx").on(t.organizationId, t.templateId).where(sql`${t.templateId} IS NOT NULL`)
      ]
    );
    orgLendingPoolFunderUsesTable = pgTable(
      "org_lending_pool_funder_uses",
      {
        id: serial("id").primaryKey(),
        organizationId: integer("organization_id").notNull().references(() => organizationsTable.id, { onDelete: "cascade" }),
        poolId: integer("pool_id").notNull().references(() => orgLendingPoolsTable.id, { onDelete: "cascade" }),
        loanApplicationId: integer("loan_application_id").notNull().references(() => loanApplicationsTable.id, { onDelete: "cascade" }),
        ascaId: integer("asca_id").notNull().references(() => ascasTable.id, { onDelete: "cascade" }),
        fundedAmount: numeric("funded_amount", { precision: 12, scale: 2 }).notNull(),
        createdAt: timestamp("created_at").notNull().defaultNow()
      },
      (t) => [
        uniqueIndex("org_lending_pool_funder_uses_org_pool_app_asca_uq").on(
          t.organizationId,
          t.poolId,
          t.loanApplicationId,
          t.ascaId
        ),
        index("org_lending_pool_funder_uses_org_created_idx").on(
          t.organizationId,
          t.createdAt
        ),
        index("org_lending_pool_funder_uses_pool_created_idx").on(
          t.poolId,
          t.createdAt
        ),
        index("org_lending_pool_funder_uses_asca_idx").on(t.ascaId),
        index("org_lending_pool_funder_uses_loan_app_idx").on(t.loanApplicationId)
      ]
    );
    lendingOpportunityReturnEventsTable = pgTable(
      "lending_opportunity_return_events",
      {
        id: serial("id").primaryKey(),
        legacyReturnEventId: integer("legacy_return_event_id").unique(),
        opportunityId: integer("opportunity_id").notNull().references(() => lendingOpportunitiesTable.id),
        repaymentId: integer("repayment_id").notNull().references(() => loanRepaymentsTable.id),
        loanApplicationId: integer("loan_application_id").notNull().references(() => loanApplicationsTable.id),
        walletTransactionId: integer("wallet_transaction_id").references(
          () => walletTransactionsTable.id
        ),
        grossAmount: numeric("gross_amount", { precision: 10, scale: 2 }).notNull().default("0"),
        principalAmount: numeric("principal_amount", { precision: 10, scale: 2 }).notNull().default("0"),
        returnAmount: numeric("return_amount", { precision: 10, scale: 2 }).notNull().default("0"),
        allocatedReturnAmount: numeric("allocated_return_amount", {
          precision: 10,
          scale: 2
        }).notNull().default("0"),
        occurredAt: timestamp("occurred_at").notNull().defaultNow(),
        createdAt: timestamp("created_at").notNull().defaultNow()
      },
      (t) => [
        uniqueIndex("lending_opportunity_return_events_repayment_wallet_uidx").on(
          t.repaymentId,
          t.walletTransactionId
        )
      ]
    );
    lendingOpportunityReturnAllocationsTable = pgTable(
      "lending_opportunity_return_allocations",
      {
        id: serial("id").primaryKey(),
        returnEventId: integer("return_event_id").notNull().references(() => lendingOpportunityReturnEventsTable.id),
        commitmentId: integer("commitment_id").notNull().references(() => lendingCommitmentsTable.id),
        opportunityId: integer("opportunity_id").notNull().references(() => lendingOpportunitiesTable.id),
        userId: integer("user_id").notNull().references(() => usersTable.id),
        commitmentAmountSnapshot: numeric("commitment_amount_snapshot", {
          precision: 10,
          scale: 2
        }).notNull().default("0"),
        ownershipPctSnapshot: numeric("ownership_pct_snapshot", {
          precision: 8,
          scale: 6
        }).notNull().default("0"),
        allocatedReturnAmount: numeric("allocated_return_amount", {
          precision: 10,
          scale: 2
        }).notNull().default("0"),
        occurredAt: timestamp("occurred_at").notNull().defaultNow(),
        createdAt: timestamp("created_at").notNull().defaultNow()
      },
      (t) => [
        uniqueIndex(
          "lending_opportunity_return_allocations_event_commitment_uidx"
        ).on(t.returnEventId, t.commitmentId)
      ]
    );
    notificationsTable = pgTable(
      "notifications",
      {
        id: serial("id").primaryKey(),
        userId: integer("user_id").notNull().references(() => usersTable.id, { onDelete: "cascade" }),
        category: notificationCategoryEnum("category").notNull().default("SYSTEM"),
        severity: notificationSeverityEnum("severity").notNull().default("INFO"),
        title: text("title").notNull(),
        body: text("body").notNull(),
        read: boolean("read").notNull().default(false),
        readAt: timestamp("read_at"),
        actionLabel: text("action_label"),
        actionHref: text("action_href"),
        createdAt: timestamp("created_at").notNull().defaultNow()
      },
      (t) => [
        index("notifications_user_read_created_idx").on(
          t.userId,
          t.read,
          t.createdAt,
          t.id
        ),
        index("notifications_user_created_idx").on(t.userId, t.createdAt, t.id),
        index("notifications_created_idx").on(t.createdAt),
        index("notifications_read_read_at_idx").on(t.read, t.readAt)
      ]
    );
    userPushTokensTable = pgTable(
      "user_push_tokens",
      {
        id: serial("id").primaryKey(),
        userId: integer("user_id").notNull().references(() => usersTable.id, { onDelete: "cascade" }),
        platform: pushPlatformEnum("platform").notNull().default("EXPO"),
        token: text("token").notNull().unique(),
        deviceName: text("device_name"),
        deviceId: text("device_id"),
        isEnabled: boolean("is_enabled").notNull().default(true),
        lastSeenAt: timestamp("last_seen_at").notNull().defaultNow(),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [index("push_tokens_user_enabled_idx").on(t.userId, t.isEnabled)]
    );
    userNotificationPreferencesTable = pgTable(
      "user_notification_preferences",
      {
        id: serial("id").primaryKey(),
        userId: integer("user_id").notNull().references(() => usersTable.id, { onDelete: "cascade" }),
        channel: notificationChannelEnum("channel").notNull(),
        category: notificationCategoryEnum("category").notNull(),
        enabled: boolean("enabled").notNull(),
        updatedAt: timestamp("updated_at").notNull().defaultNow(),
        createdAt: timestamp("created_at").notNull().defaultNow()
      },
      (t) => [
        uniqueIndex("user_notification_prefs_user_channel_category_uidx").on(
          t.userId,
          t.channel,
          t.category
        )
      ]
    );
    notificationDeliveriesTable = pgTable(
      "notification_deliveries",
      {
        id: serial("id").primaryKey(),
        userId: integer("user_id").notNull().references(() => usersTable.id, { onDelete: "cascade" }),
        channel: notificationChannelEnum("channel").notNull(),
        category: notificationCategoryEnum("category").notNull(),
        status: notificationDeliveryStatusEnum("status").notNull(),
        idempotencyKey: text("idempotency_key").notNull().unique(),
        notificationId: integer("notification_id").references(
          () => notificationsTable.id,
          { onDelete: "set null" }
        ),
        provider: text("provider"),
        errorMessage: text("error_message"),
        metadata: json("metadata").notNull().default({}),
        occurredAt: timestamp("occurred_at").notNull().defaultNow(),
        createdAt: timestamp("created_at").notNull().defaultNow()
      },
      (t) => [
        index("notification_deliveries_user_occurred_idx").on(
          t.userId,
          t.occurredAt
        ),
        index("notification_deliveries_occurred_idx").on(t.occurredAt)
      ]
    );
    announcementsTable = pgTable("announcements", {
      id: serial("id").primaryKey(),
      title: text("title").notNull(),
      body: text("body").notNull(),
      category: text("category").notNull(),
      pinned: boolean("pinned").notNull().default(false),
      publishedBy: integer("published_by"),
      publishedAt: timestamp("published_at").notNull().defaultNow(),
      createdAt: timestamp("created_at").notNull().defaultNow(),
      updatedAt: timestamp("updated_at").notNull().defaultNow()
    });
    communityEventsTable = pgTable("community_events", {
      id: serial("id").primaryKey(),
      title: text("title").notNull(),
      description: text("description").notNull(),
      date: timestamp("date").notNull(),
      startTime: text("start_time").notNull(),
      endTime: text("end_time"),
      location: text("location").notNull(),
      type: eventTypeEnum("type").notNull().default("VIRTUAL"),
      maxAttendees: integer("max_attendees"),
      organizerId: integer("organizer_id"),
      coverImageUrl: text("cover_image_url"),
      createdAt: timestamp("created_at").notNull().defaultNow(),
      updatedAt: timestamp("updated_at").notNull().defaultNow()
    });
    eventRsvpsTable = pgTable(
      "event_rsvps",
      {
        id: serial("id").primaryKey(),
        userId: integer("user_id").notNull().references(() => usersTable.id, { onDelete: "cascade" }),
        eventId: integer("event_id").notNull().references(() => communityEventsTable.id, { onDelete: "cascade" }),
        status: rsvpStatusEnum("status").notNull().default("GOING"),
        createdAt: timestamp("created_at").notNull().defaultNow()
      },
      (t) => [uniqueIndex("event_rsvps_user_event_uidx").on(t.userId, t.eventId)]
    );
    discussionsTable = pgTable("discussions", {
      id: serial("id").primaryKey(),
      authorId: integer("author_id").notNull().references(() => usersTable.id),
      title: text("title").notNull(),
      body: text("body").notNull(),
      category: text("category").notNull(),
      pinned: boolean("pinned").notNull().default(false),
      viewCount: integer("view_count").notNull().default(0),
      createdAt: timestamp("created_at").notNull().defaultNow(),
      updatedAt: timestamp("updated_at").notNull().defaultNow()
    });
    discussionRepliesTable = pgTable("discussion_replies", {
      id: serial("id").primaryKey(),
      discussionId: integer("discussion_id").notNull().references(() => discussionsTable.id, { onDelete: "cascade" }),
      authorId: integer("author_id").notNull().references(() => usersTable.id),
      body: text("body").notNull(),
      createdAt: timestamp("created_at").notNull().defaultNow(),
      updatedAt: timestamp("updated_at").notNull().defaultNow()
    });
    memberSpotlightsTable = pgTable("member_spotlights", {
      id: serial("id").primaryKey(),
      userId: integer("user_id").notNull().unique().references(() => usersTable.id, { onDelete: "cascade" }),
      achievement: text("achievement").notNull(),
      featured: boolean("featured").notNull().default(false),
      approvedAt: timestamp("approved_at"),
      createdAt: timestamp("created_at").notNull().defaultNow()
    });
    communityPostTypeEnum = pgEnum("community_post_type", [
      "USER_UPDATE",
      "MILESTONE",
      "ADMIN_STORY",
      "RESOURCE_SHARE"
    ]);
    communityProfilesTable = pgTable("community_profiles", {
      id: serial("id").primaryKey(),
      userId: integer("user_id").unique().references(() => usersTable.id, { onDelete: "cascade" }),
      organizationId: integer("organization_id").unique().references(() => organizationsTable.id, { onDelete: "cascade" }),
      bio: text("bio"),
      location: text("location"),
      interests: text("interests").array(),
      badges: text("badges").array(),
      createdAt: timestamp("created_at").notNull().defaultNow(),
      updatedAt: timestamp("updated_at").notNull().defaultNow()
    }, (t) => [
      index("community_profiles_user_idx").on(t.userId),
      index("community_profiles_org_idx").on(t.organizationId)
    ]);
    communityPostsTable = pgTable("community_posts", {
      id: serial("id").primaryKey(),
      postType: communityPostTypeEnum("post_type").notNull().default("USER_UPDATE"),
      authorId: integer("author_id").references(() => usersTable.id),
      // For USER_UPDATE / ADMIN_STORY
      organizationId: integer("organization_id").references(() => organizationsTable.id),
      // If an Org posts
      title: text("title"),
      // Required for ADMIN_STORY
      slug: text("slug").unique(),
      // For ADMIN_STORY permalinks
      excerpt: text("excerpt"),
      // For ADMIN_STORY
      contentHtml: text("content_html").notNull(),
      coverImageUrl: text("cover_image_url"),
      // Visibility Flags (Primarily used for ADMIN_STORY)
      showToIndividuals: boolean("show_to_individuals").notNull().default(true),
      showToInvestors: boolean("show_to_investors").notNull().default(true),
      showToOrganizations: boolean("show_to_organizations").notNull().default(true),
      isPublished: boolean("is_published").notNull().default(true),
      publishedAt: timestamp("published_at").defaultNow(),
      createdAt: timestamp("created_at").notNull().defaultNow(),
      updatedAt: timestamp("updated_at").notNull().defaultNow()
    }, (t) => [
      index("community_posts_type_published_idx").on(t.postType, t.isPublished, t.publishedAt)
    ]);
    communityCommentsTable = pgTable("community_comments", {
      id: serial("id").primaryKey(),
      postId: integer("post_id").notNull().references(() => communityPostsTable.id, { onDelete: "cascade" }),
      authorId: integer("author_id").notNull().references(() => usersTable.id),
      parentId: integer("parent_id"),
      // Self-referencing for threaded replies. Can't use references() inline due to Drizzle circular dep limits without explicit relations
      contentHtml: text("content_html").notNull(),
      createdAt: timestamp("created_at").notNull().defaultNow(),
      updatedAt: timestamp("updated_at").notNull().defaultNow()
    }, (t) => [
      index("community_comments_post_idx").on(t.postId, t.createdAt)
    ]);
    communityReactionsTable = pgTable("community_reactions", {
      id: serial("id").primaryKey(),
      postId: integer("post_id").references(() => communityPostsTable.id, { onDelete: "cascade" }),
      commentId: integer("comment_id").references(() => communityCommentsTable.id, { onDelete: "cascade" }),
      userId: integer("user_id").notNull().references(() => usersTable.id),
      reactionType: text("reaction_type").notNull().default("LIKE"),
      createdAt: timestamp("created_at").notNull().defaultNow()
    }, (t) => [
      uniqueIndex("community_reactions_post_user_uidx").on(t.postId, t.userId),
      uniqueIndex("community_reactions_comment_user_uidx").on(t.commentId, t.userId)
    ]);
    communityForumsTable = pgTable("community_forums", {
      id: serial("id").primaryKey(),
      name: text("name").notNull().unique(),
      slug: text("slug").notNull().unique(),
      description: text("description"),
      sortOrder: integer("sort_order").notNull().default(0),
      isRestricted: boolean("is_restricted").notNull().default(false),
      createdAt: timestamp("created_at").notNull().defaultNow(),
      updatedAt: timestamp("updated_at").notNull().defaultNow()
    });
    forumThreadsTable = pgTable("forum_threads", {
      id: serial("id").primaryKey(),
      forumId: integer("forum_id").notNull().references(() => communityForumsTable.id, { onDelete: "cascade" }),
      authorId: integer("author_id").notNull().references(() => usersTable.id),
      title: text("title").notNull(),
      slug: text("slug").notNull().unique(),
      contentHtml: text("content_html").notNull(),
      isPinned: boolean("is_pinned").notNull().default(false),
      isLocked: boolean("is_locked").notNull().default(false),
      viewCount: integer("view_count").notNull().default(0),
      lastActivityAt: timestamp("last_activity_at").notNull().defaultNow(),
      createdAt: timestamp("created_at").notNull().defaultNow(),
      updatedAt: timestamp("updated_at").notNull().defaultNow()
    }, (t) => [
      index("forum_threads_forum_idx").on(t.forumId, t.lastActivityAt)
    ]);
    messageThreadsTable = pgTable("message_threads", {
      id: serial("id").primaryKey(),
      isGroup: boolean("is_group").notNull().default(false),
      name: text("name"),
      // For group chats
      ascaId: integer("asca_id").references(() => ascasTable.id),
      // Link to a Savings Circle
      createdAt: timestamp("created_at").notNull().defaultNow(),
      updatedAt: timestamp("updated_at").notNull().defaultNow()
    });
    messageThreadParticipantsTable = pgTable("message_thread_participants", {
      id: serial("id").primaryKey(),
      threadId: integer("thread_id").notNull().references(() => messageThreadsTable.id, { onDelete: "cascade" }),
      userId: integer("user_id").notNull().references(() => usersTable.id, { onDelete: "cascade" }),
      lastReadAt: timestamp("last_read_at"),
      joinedAt: timestamp("joined_at").notNull().defaultNow()
    }, (t) => [
      uniqueIndex("message_thread_participants_uidx").on(t.threadId, t.userId)
    ]);
    directMessagesTable = pgTable("direct_messages", {
      id: serial("id").primaryKey(),
      threadId: integer("thread_id").notNull().references(() => messageThreadsTable.id, { onDelete: "cascade" }),
      senderId: integer("sender_id").notNull().references(() => usersTable.id),
      content: text("content").notNull(),
      createdAt: timestamp("created_at").notNull().defaultNow(),
      updatedAt: timestamp("updated_at").notNull().defaultNow()
    }, (t) => [
      index("direct_messages_thread_idx").on(t.threadId, t.createdAt)
    ]);
    resourceCategoriesTable = pgTable("resource_categories", {
      id: serial("id").primaryKey(),
      name: text("name").notNull().unique(),
      slug: text("slug").notNull().unique(),
      sortOrder: integer("sort_order").notNull().default(0)
    });
    resourcesTable = pgTable("resources", {
      id: serial("id").primaryKey(),
      title: text("title").notNull(),
      slug: text("slug").notNull().unique(),
      description: text("description"),
      resourceKind: resourceKindEnum("resource_kind").notNull().default("FILE"),
      categoryId: integer("category_id").notNull().references(() => resourceCategoriesTable.id),
      fileUrl: text("file_url"),
      fileType: resourceFileTypeEnum("file_type").notNull().default("PDF"),
      fileSize: integer("file_size"),
      coverImageUrl: text("cover_image_url"),
      authorName: text("author_name"),
      contentHtml: text("content_html"),
      showToIndividuals: boolean("show_to_individuals").notNull().default(false),
      showToInvestors: boolean("show_to_investors").notNull().default(true),
      showToOrganizations: boolean("show_to_organizations").notNull().default(true),
      uploadedById: integer("uploaded_by_id"),
      isPublished: boolean("is_published").notNull().default(false),
      publishedAt: timestamp("published_at"),
      downloads: integer("downloads").notNull().default(0),
      createdAt: timestamp("created_at").notNull().defaultNow(),
      updatedAt: timestamp("updated_at").notNull().defaultNow()
    });
    onboardingSlidesTable = pgTable("onboarding_slides", {
      id: serial("id").primaryKey(),
      title: text("title").notNull(),
      subtitle: text("subtitle"),
      body: text("body"),
      illustrationIcon: text("illustration_icon").notNull().default("diamond-stone"),
      illustrationUrl: text("illustration_url"),
      accentColor: text("accent_color").notNull().default("#f27a4a"),
      sortOrder: integer("sort_order").notNull().default(0),
      isActive: boolean("is_active").notNull().default(true),
      createdAt: timestamp("created_at").defaultNow(),
      updatedAt: timestamp("updated_at").defaultNow()
    });
    onboardingProgramsTable = pgTable(
      "onboarding_programs",
      {
        id: serial("id").primaryKey(),
        title: text("title").notNull(),
        description: text("description"),
        targetMembershipType: membershipTypeEnum("target_membership_type").notNull().default("INDIVIDUAL"),
        numberOfWeeks: integer("number_of_weeks").notNull(),
        durationUnit: onboardingProgramDurationUnitEnum("duration_unit").notNull().default("WEEK"),
        startDate: timestamp("start_date"),
        endDate: timestamp("end_date"),
        status: onboardingProgramStatusEnum("status").notNull().default("DRAFT"),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        index("onboarding_programs_status_idx").on(t.status),
        index("onboarding_programs_target_membership_idx").on(
          t.targetMembershipType
        ),
        index("onboarding_programs_created_idx").on(t.createdAt)
      ]
    );
    onboardingProgramWeeksTable = pgTable(
      "onboarding_program_weeks",
      {
        id: serial("id").primaryKey(),
        programId: integer("program_id").notNull().references(() => onboardingProgramsTable.id, { onDelete: "cascade" }),
        weekNumber: integer("week_number").notNull(),
        title: text("title").notNull(),
        description: text("description"),
        sortOrder: integer("sort_order").notNull().default(0),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        uniqueIndex("onboarding_program_weeks_unique_idx").on(
          t.programId,
          t.weekNumber
        ),
        index("onboarding_program_weeks_order_idx").on(t.programId, t.sortOrder)
      ]
    );
    onboardingWeekActivitiesTable = pgTable(
      "onboarding_week_activities",
      {
        id: serial("id").primaryKey(),
        weekId: integer("week_id").notNull().references(() => onboardingProgramWeeksTable.id, {
          onDelete: "cascade"
        }),
        title: text("title").notNull(),
        description: text("description"),
        durationMinutes: integer("duration_minutes"),
        type: onboardingActivityTypeEnum("type").notNull(),
        content: json("content").$type(),
        sortOrder: integer("sort_order").notNull().default(0),
        isRequired: boolean("is_required").notNull().default(true),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        index("onboarding_week_activities_order_idx").on(t.weekId, t.sortOrder),
        uniqueIndex("onboarding_week_activities_unique_title_idx").on(
          t.weekId,
          t.title
        )
      ]
    );
    onboardingEnrollmentsTable = pgTable(
      "onboarding_enrollments",
      {
        id: serial("id").primaryKey(),
        userId: integer("user_id").notNull().references(() => usersTable.id, { onDelete: "cascade" }),
        programId: integer("program_id").notNull().references(() => onboardingProgramsTable.id, { onDelete: "restrict" }),
        enrolledAt: timestamp("enrolled_at").notNull().defaultNow(),
        completedAt: timestamp("completed_at"),
        lastActivityAt: timestamp("last_activity_at"),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        uniqueIndex("onboarding_enrollments_user_program_unique_idx").on(
          t.userId,
          t.programId
        ),
        index("onboarding_enrollments_user_idx").on(t.userId),
        index("onboarding_enrollments_program_idx").on(t.programId)
      ]
    );
    onboardingActivityProgressTable = pgTable(
      "onboarding_activity_progress",
      {
        id: serial("id").primaryKey(),
        enrollmentId: integer("enrollment_id").notNull().references(() => onboardingEnrollmentsTable.id, { onDelete: "cascade" }),
        activityId: integer("activity_id").notNull().references(() => onboardingWeekActivitiesTable.id, {
          onDelete: "cascade"
        }),
        status: onboardingActivityStatusEnum("status").notNull().default("NOT_STARTED"),
        startedAt: timestamp("started_at"),
        completedAt: timestamp("completed_at"),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        uniqueIndex("onboarding_activity_progress_unique_idx").on(
          t.enrollmentId,
          t.activityId
        ),
        index("onboarding_activity_progress_enrollment_idx").on(t.enrollmentId)
      ]
    );
    ascasTable = pgTable(
      "ascas",
      {
        id: serial("id").primaryKey(),
        name: text("name").notNull(),
        description: text("description"),
        termsHtml: text("terms_html"),
        organizationId: integer("organization_id").references(
          () => organizationsTable.id
        ),
        type: ascaTypeEnum("type").notNull().default("GENERAL"),
        status: ascaStatusEnum("status").notNull().default("DRAFT"),
        investmentId: integer("investment_id").references(
          () => investmentOpportunitiesTable.id
        ),
        escrowWalletId: integer("escrow_wallet_id").references(
          () => walletsTable.id
        ),
        targetAmount: numeric("target_amount", { precision: 12, scale: 2 }),
        currentAmount: numeric("current_amount", { precision: 12, scale: 2 }).notNull().default("0"),
        fundingStartAt: timestamp("funding_start_at"),
        fundingEndAt: timestamp("funding_end_at"),
        constitution: json("constitution").$type().notNull().default({}),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        index("ascas_status_idx").on(t.status),
        index("ascas_type_idx").on(t.type),
        index("ascas_investment_idx").on(t.investmentId),
        index("ascas_org_status_idx").on(t.organizationId, t.status)
      ]
    );
    ascaMembersTable = pgTable(
      "asca_members",
      {
        id: serial("id").primaryKey(),
        ascaId: integer("asca_id").notNull().references(() => ascasTable.id, { onDelete: "cascade" }),
        userId: integer("user_id").notNull().references(() => usersTable.id, { onDelete: "cascade" }),
        targetContribution: numeric("target_contribution", {
          precision: 12,
          scale: 2
        }).notNull(),
        contributedAmount: numeric("contributed_amount", {
          precision: 12,
          scale: 2
        }).notNull().default("0"),
        status: ascaMemberStatusEnum("status").notNull().default("ACTIVE"),
        joinedAt: timestamp("joined_at").notNull().defaultNow(),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        uniqueIndex("asca_members_asca_user_idx").on(t.ascaId, t.userId),
        index("asca_members_user_idx").on(t.userId)
      ]
    );
    ascaContributionsTable = pgTable(
      "asca_contributions",
      {
        id: serial("id").primaryKey(),
        ascaId: integer("asca_id").notNull().references(() => ascasTable.id, { onDelete: "cascade" }),
        memberId: integer("member_id").notNull().references(() => ascaMembersTable.id, { onDelete: "cascade" }),
        amount: numeric("amount", { precision: 12, scale: 2 }).notNull(),
        status: ascaContributionStatusEnum("status").notNull().default("PENDING"),
        dueDate: timestamp("due_date"),
        paidAt: timestamp("paid_at"),
        transactionId: integer("transaction_id").references(
          () => walletTransactionsTable.id
        ),
        createdAt: timestamp("created_at").notNull().defaultNow(),
        updatedAt: timestamp("updated_at").notNull().defaultNow()
      },
      (t) => [
        index("asca_contributions_member_idx").on(t.memberId),
        index("asca_contributions_asca_idx").on(t.ascaId),
        index("asca_contributions_status_idx").on(t.status)
      ]
    );
    insertUserSchema = createInsertSchema(usersTable).omit({
      id: true,
      createdAt: true,
      updatedAt: true
    });
  }
});

// ../../lib/db/src/index.ts
import { existsSync } from "node:fs";
import { readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
function parsePositiveInteger(value, fallback, minimum = 1) {
  if (!value) return fallback;
  const parsed = Number(value.trim());
  if (!Number.isFinite(parsed)) return fallback;
  const normalized = Math.floor(parsed);
  return normalized >= minimum ? normalized : fallback;
}
var Pool3, databaseUrl, nodeEnv, poolMax, connectionTimeoutMillis, idleTimeoutMillis, maxLifetimeSeconds, applicationName, pool, db;
var init_src2 = __esm({
  "../../lib/db/src/index.ts"() {
    "use strict";
    init_node_postgres();
    init_esm();
    init_schema2();
    init_schema2();
    ({ Pool: Pool3 } = esm_default);
    if (!process.env.DATABASE_URL) {
      const nodeEnv5 = process.env.NODE_ENV ?? "development";
      const moduleDir2 = path.dirname(fileURLToPath(import.meta.url));
      const repoRoot2 = path.resolve(moduleDir2, "../../..");
      const envPath2 = path.resolve(repoRoot2, ".env");
      if (nodeEnv5 !== "production" && existsSync(envPath2)) {
        const raw = readFileSync(envPath2, "utf8");
        for (const line2 of raw.split(/\r?\n/)) {
          const trimmed = line2.trim();
          if (!trimmed || trimmed.startsWith("#")) continue;
          const eqIndex = trimmed.indexOf("=");
          if (eqIndex <= 0) continue;
          const key = trimmed.slice(0, eqIndex).trim();
          let value = trimmed.slice(eqIndex + 1).trim();
          if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
            value = value.slice(1, -1);
          }
          if (process.env[key] === void 0) {
            process.env[key] = value;
          }
        }
      }
    }
    databaseUrl = process.env.DATABASE_URL;
    nodeEnv = process.env.NODE_ENV ?? "development";
    if (!databaseUrl) {
      throw new Error(
        "DATABASE_URL must be set. Did you forget to provision a database?"
      );
    }
    poolMax = parsePositiveInteger(
      process.env.DB_POOL_MAX,
      nodeEnv === "production" ? 5 : 10
    );
    connectionTimeoutMillis = parsePositiveInteger(
      process.env.DB_CONNECTION_TIMEOUT_MS,
      1e4
    );
    idleTimeoutMillis = parsePositiveInteger(
      process.env.DB_IDLE_TIMEOUT_MS,
      1e4
    );
    maxLifetimeSeconds = parsePositiveInteger(
      process.env.DB_MAX_LIFETIME_SECONDS,
      300
    );
    applicationName = process.env.DB_APPLICATION_NAME?.trim() || `wwn-${nodeEnv === "production" ? "prod" : "dev"}`;
    pool = new Pool3({
      connectionString: databaseUrl,
      max: poolMax,
      connectionTimeoutMillis,
      idleTimeoutMillis,
      maxLifetimeSeconds,
      application_name: applicationName,
      keepAlive: true
    });
    db = drizzle(pool, { schema: schema_exports });
  }
});

// src/config.ts
import fs from "fs";
import path2 from "path";
function loadEnvFile(filePath) {
  if (!fs.existsSync(filePath)) return;
  const content = fs.readFileSync(filePath, "utf8");
  const lines = content.split(/\r?\n/);
  for (const line2 of lines) {
    const normalized = line2.trim();
    if (!normalized || normalized.startsWith("#")) continue;
    const eqIndex = normalized.indexOf("=");
    if (eqIndex <= 0) continue;
    const key = normalized.slice(0, eqIndex).trim();
    if (!key) continue;
    if (process.env[key] !== void 0) continue;
    let value = normalized.slice(eqIndex + 1).trim();
    if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
      value = value.slice(1, -1);
    }
    process.env[key] = value;
  }
}
function parseBoolean(value, fallback) {
  if (!value) return fallback;
  switch (value.trim().toLowerCase()) {
    case "1":
    case "true":
    case "yes":
    case "on":
      return true;
    case "0":
    case "false":
    case "no":
    case "off":
      return false;
    default:
      return fallback;
  }
}
function parsePositiveInteger2(value, fallback, minimum = 1) {
  if (!value) return fallback;
  const parsed = Number(value.trim());
  if (!Number.isFinite(parsed)) return fallback;
  const normalized = Math.floor(parsed);
  return normalized >= minimum ? normalized : fallback;
}
function parseTrustProxy(value) {
  if (!value) {
    return nodeEnv2 === "production" ? 1 : false;
  }
  const normalized = value.trim().toLowerCase();
  if (["true", "yes", "on"].includes(normalized)) return true;
  if (["false", "no", "off"].includes(normalized)) return false;
  if (/^\d+$/.test(value.trim())) return Number(value.trim());
  return value.trim();
}
var nodeEnv2, effectiveNodeEnv, rawJwtSecret, JWT_SECRET, TRUST_PROXY, rawCorsOrigin, CORS_ORIGIN, rawCookieSameSite, COOKIE_SAME_SITE, COOKIE_SECURE, rawCookieDomain, COOKIE_DOMAIN, ENABLE_BACKGROUND_JOBS, BACKGROUND_JOBS_LEADER_RETRY_MS, ENABLE_SUSU_SCHEDULER, SUSU_SCHEDULER_INTERVAL_MS, SUSU_SCHEDULER_RUN_ON_STARTUP, SUSU_SCHEDULER_STARTUP_DELAY_MS, ENABLE_INVESTMENT_RETURN_SCHEDULER, INVESTMENT_RETURN_SCHEDULER_INTERVAL_MS, INVESTMENT_RETURN_SCHEDULER_RUN_ON_STARTUP, INVESTMENT_RETURN_SCHEDULER_STARTUP_DELAY_MS, ENABLE_NOTIFICATION_SCHEDULER, NOTIFICATION_SCHEDULER_INTERVAL_MS, NOTIFICATION_SCHEDULER_RUN_ON_STARTUP, NOTIFICATION_SCHEDULER_STARTUP_DELAY_MS, NOTIFICATION_SCHEDULER_TIMEZONE, NOTIFICATION_DELIVERIES_RETENTION_DAYS, NOTIFICATIONS_RETENTION_DAYS, NOTIFICATIONS_READ_RETENTION_DAYS, STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET;
var init_config = __esm({
  "src/config.ts"() {
    "use strict";
    nodeEnv2 = process.env.NODE_ENV ?? "development";
    if (nodeEnv2 !== "production") {
      const root = process.cwd();
      loadEnvFile(path2.join(root, ".env"));
      loadEnvFile(path2.join(root, `.env.${nodeEnv2}`));
    }
    effectiveNodeEnv = process.env.NODE_ENV ?? "development";
    rawJwtSecret = process.env.JWT_SECRET;
    if (!rawJwtSecret && effectiveNodeEnv === "production") {
      throw new Error("JWT_SECRET environment variable is required but not set.");
    }
    JWT_SECRET = rawJwtSecret ?? "dev-jwt-secret-change-me";
    TRUST_PROXY = parseTrustProxy(process.env.TRUST_PROXY);
    rawCorsOrigin = process.env.CORS_ORIGIN;
    CORS_ORIGIN = rawCorsOrigin ? rawCorsOrigin.includes(",") ? rawCorsOrigin.split(",").map((s) => s.trim()).filter(Boolean) : rawCorsOrigin.trim() : ["http://localhost:5173", "http://localhost:19006"];
    rawCookieSameSite = process.env.COOKIE_SAME_SITE?.trim().toLowerCase();
    COOKIE_SAME_SITE = rawCookieSameSite === "strict" || rawCookieSameSite === "none" ? rawCookieSameSite : "lax";
    COOKIE_SECURE = parseBoolean(
      process.env.COOKIE_SECURE,
      effectiveNodeEnv === "production" || !!process.env.REPLIT_DEV_DOMAIN || COOKIE_SAME_SITE === "none"
    );
    rawCookieDomain = process.env.COOKIE_DOMAIN?.trim();
    COOKIE_DOMAIN = rawCookieDomain ? rawCookieDomain : void 0;
    ENABLE_BACKGROUND_JOBS = parseBoolean(
      process.env.ENABLE_BACKGROUND_JOBS,
      true
    );
    BACKGROUND_JOBS_LEADER_RETRY_MS = parsePositiveInteger2(
      process.env.BACKGROUND_JOBS_LEADER_RETRY_MS,
      6e4,
      5e3
    );
    ENABLE_SUSU_SCHEDULER = parseBoolean(
      process.env.ENABLE_SUSU_SCHEDULER,
      effectiveNodeEnv !== "test"
    );
    SUSU_SCHEDULER_INTERVAL_MS = parsePositiveInteger2(
      process.env.SUSU_SCHEDULER_INTERVAL_MS,
      6e4,
      5e3
    );
    SUSU_SCHEDULER_RUN_ON_STARTUP = parseBoolean(
      process.env.SUSU_SCHEDULER_RUN_ON_STARTUP,
      effectiveNodeEnv === "production"
    );
    SUSU_SCHEDULER_STARTUP_DELAY_MS = parsePositiveInteger2(
      process.env.SUSU_SCHEDULER_STARTUP_DELAY_MS,
      5e3,
      0
    );
    ENABLE_INVESTMENT_RETURN_SCHEDULER = parseBoolean(
      process.env.ENABLE_INVESTMENT_RETURN_SCHEDULER,
      effectiveNodeEnv !== "test"
    );
    INVESTMENT_RETURN_SCHEDULER_INTERVAL_MS = parsePositiveInteger2(
      process.env.INVESTMENT_RETURN_SCHEDULER_INTERVAL_MS,
      6e4,
      5e3
    );
    INVESTMENT_RETURN_SCHEDULER_RUN_ON_STARTUP = parseBoolean(
      process.env.INVESTMENT_RETURN_SCHEDULER_RUN_ON_STARTUP,
      effectiveNodeEnv === "production"
    );
    INVESTMENT_RETURN_SCHEDULER_STARTUP_DELAY_MS = parsePositiveInteger2(
      process.env.INVESTMENT_RETURN_SCHEDULER_STARTUP_DELAY_MS,
      7500,
      0
    );
    ENABLE_NOTIFICATION_SCHEDULER = parseBoolean(
      process.env.ENABLE_NOTIFICATION_SCHEDULER,
      effectiveNodeEnv !== "test"
    );
    NOTIFICATION_SCHEDULER_INTERVAL_MS = parsePositiveInteger2(
      process.env.NOTIFICATION_SCHEDULER_INTERVAL_MS,
      3e5,
      6e4
    );
    NOTIFICATION_SCHEDULER_RUN_ON_STARTUP = parseBoolean(
      process.env.NOTIFICATION_SCHEDULER_RUN_ON_STARTUP,
      effectiveNodeEnv === "production"
    );
    NOTIFICATION_SCHEDULER_STARTUP_DELAY_MS = parsePositiveInteger2(
      process.env.NOTIFICATION_SCHEDULER_STARTUP_DELAY_MS,
      1e4,
      0
    );
    NOTIFICATION_SCHEDULER_TIMEZONE = process.env.NOTIFICATION_SCHEDULER_TIMEZONE?.trim() || "UTC";
    NOTIFICATION_DELIVERIES_RETENTION_DAYS = parsePositiveInteger2(
      process.env.NOTIFICATION_DELIVERIES_RETENTION_DAYS,
      90,
      1
    );
    NOTIFICATIONS_RETENTION_DAYS = parsePositiveInteger2(
      process.env.NOTIFICATIONS_RETENTION_DAYS,
      365,
      1
    );
    NOTIFICATIONS_READ_RETENTION_DAYS = parsePositiveInteger2(
      process.env.NOTIFICATIONS_READ_RETENTION_DAYS,
      180,
      1
    );
    STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY?.trim() || "";
    STRIPE_WEBHOOK_SECRET = process.env.STRIPE_WEBHOOK_SECRET?.trim() || "";
  }
});

// src/lib/mailer.ts
import nodemailer from "nodemailer";
function escapeHtml(value) {
  return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
}
function getRecipientName(firstName) {
  const trimmed = firstName?.trim();
  return trimmed && trimmed.length > 0 ? trimmed : "there";
}
function getPublicWebBaseUrl() {
  const raw = process.env.PUBLIC_WEB_URL?.trim() ?? process.env.WEB_BASE_URL?.trim() ?? null;
  if (raw && /^https?:\/\//i.test(raw)) {
    return raw.replace(/\/+$/, "");
  }
  const origin = Array.isArray(CORS_ORIGIN) ? CORS_ORIGIN[0] : CORS_ORIGIN;
  if (typeof origin === "string" && /^https?:\/\//i.test(origin)) {
    return origin.replace(/\/+$/, "");
  }
  return null;
}
function normalizeEmailActionHref(value) {
  const trimmed = value.trim();
  if (!trimmed) return null;
  if (/^https?:\/\//i.test(trimmed)) return trimmed;
  if (trimmed.startsWith("//")) return null;
  if (!trimmed.startsWith("/")) return null;
  const base = getPublicWebBaseUrl();
  if (!base) return null;
  return `${base}${trimmed}`;
}
function formatMembershipType(membershipType) {
  switch (membershipType) {
    case "INDIVIDUAL":
      return "Individual";
    case "ORGANIZATION":
      return "Organization";
    case "INVESTOR":
      return "Investor";
    default:
      return "member";
  }
}
function renderEmailShell(input) {
  return `<!doctype html>
<html lang="en">
  <body style="margin:0;padding:0;background:#f7efe8;font-family:Arial,sans-serif;color:#4a2242;">
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f7efe8;padding:32px 16px;">
      <tr>
        <td align="center">
          <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:600px;background:#fffdfb;border:1px solid #eadacf;border-radius:24px;overflow:hidden;">
            <tr>
              <td style="padding:32px 32px 8px;">
                <p style="margin:0 0 12px;font-size:12px;line-height:18px;letter-spacing:0.18em;text-transform:uppercase;color:#c6683c;font-weight:700;">${escapeHtml(input.eyebrow)}</p>
                <h1 style="margin:0 0 14px;font-size:30px;line-height:38px;color:#4a2242;">${escapeHtml(input.title)}</h1>
                <p style="margin:0 0 6px;font-size:16px;line-height:26px;color:#6d5650;">${escapeHtml(input.greeting)}</p>
                <p style="margin:0;font-size:16px;line-height:26px;color:#6d5650;">${escapeHtml(input.intro)}</p>
              </td>
            </tr>
            <tr>
              <td style="padding:24px 32px 8px;">
                ${input.bodyHtml}
              </td>
            </tr>
            <tr>
              <td style="padding:8px 32px 32px;">
                <p style="margin:0 0 16px;font-size:15px;line-height:25px;color:#6d5650;">${escapeHtml(input.closing)}</p>
                <p style="margin:0;font-size:15px;line-height:24px;color:#4a2242;font-weight:700;">With warmth,<br />The Whole Woman Network Team</p>
              </td>
            </tr>
            <tr>
              <td style="padding:18px 32px;background:#fbf6f1;border-top:1px solid #eadacf;">
                <p style="margin:0;font-size:13px;line-height:20px;color:#8b6c63;">
                  Need help? Reply to this email or reach us at
                  <a href="mailto:${SUPPORT_EMAIL}" style="color:#c6683c;text-decoration:none;">${SUPPORT_EMAIL}</a>.
                </p>
              </td>
            </tr>
          </table>
        </td>
      </tr>
    </table>
  </body>
</html>`;
}
function createVerificationCodeEmail(input) {
  const greeting = `Hi ${getRecipientName(input.firstName)},`;
  const subject = "Your WWN verification code";
  const text2 = [
    greeting,
    "Welcome to Whole Woman Network. We are glad you are here.",
    `Your verification code is ${input.code}.`,
    `It expires in ${input.expiresInMinutes} minutes.`,
    "",
    "Take your time, and if you need support, just reply to this email.",
    "",
    "With warmth,",
    "The Whole Woman Network Team"
  ].join("\n");
  const html = renderEmailShell({
    eyebrow: "Account Verification",
    title: "Here is your code",
    greeting,
    intro: "Welcome to Whole Woman Network. We are happy to have you here and ready to help you get started.",
    bodyHtml: `
      <div style="margin:0 0 18px;padding:20px;border-radius:20px;background:#fdf6f0;border:1px solid #f1ddd0;text-align:center;">
        <p style="margin:0 0 10px;font-size:13px;line-height:18px;letter-spacing:0.12em;text-transform:uppercase;color:#9b7c72;font-weight:700;">One-time verification code</p>
        <p style="margin:0;font-size:34px;line-height:40px;letter-spacing:0.28em;color:#4a2242;font-weight:700;">${escapeHtml(input.code)}</p>
      </div>
      <p style="margin:0 0 14px;font-size:15px;line-height:25px;color:#6d5650;">
        This code stays active for <strong style="color:#4a2242;">${input.expiresInMinutes} minutes</strong>.
        When you enter it, your account will be verified and ready to go.
      </p>
      <p style="margin:0;font-size:15px;line-height:25px;color:#6d5650;">
        We know first steps matter. If anything feels unclear, just reply and our team will gladly support you.
      </p>`,
    closing: "Thank you for joining us. We are looking forward to supporting your journey."
  });
  return { subject, text: text2, html };
}
function createWelcomeEmail(input) {
  const greeting = `Hi ${getRecipientName(input.firstName)},`;
  const membershipLabel = formatMembershipType(input.membershipType);
  const subject = "Welcome to Whole Woman Network";
  const text2 = [
    greeting,
    "Welcome to Whole Woman Network. Your email has been verified and your account is now active.",
    `We are grateful to welcome you as an ${membershipLabel.toLowerCase()} member.`,
    "You do not have to figure everything out alone. We are here to support you as you get settled in.",
    "",
    `If you need help at any point, reply to this email or contact ${SUPPORT_EMAIL}.`,
    "",
    "With warmth,",
    "The Whole Woman Network Team"
  ].join("\n");
  const html = renderEmailShell({
    eyebrow: "Welcome To WWN",
    title: "Your account is ready",
    greeting,
    intro: "Your email has been verified and we are truly glad to welcome you to Whole Woman Network.",
    bodyHtml: `
      <div style="margin:0 0 18px;padding:20px;border-radius:20px;background:#fff6ef;border:1px solid #f1ddd0;">
        <p style="margin:0 0 10px;font-size:15px;line-height:24px;color:#6d5650;">
          You are now set up as an <strong style="color:#4a2242;">${escapeHtml(membershipLabel)}</strong> member.
        </p>
        <p style="margin:0;font-size:15px;line-height:24px;color:#6d5650;">
          We want your experience to feel supported, clear, and encouraging from day one.
        </p>
      </div>
      <p style="margin:0 0 14px;font-size:15px;line-height:25px;color:#6d5650;">
        Thank you for choosing to be part of this community. Whether you are here to learn, build, invest, or grow with others, we are honored to walk alongside you.
      </p>
      <p style="margin:0;font-size:15px;line-height:25px;color:#6d5650;">
        If you ever need guidance, reassurance, or a quick answer, reply to this email and we will be here for you.
      </p>`,
    closing: "You are warmly welcomed here, and we look forward to supporting you every step of the way."
  });
  return { subject, text: text2, html };
}
function createMembershipActivatedEmail(input) {
  const greeting = `Hi ${getRecipientName(input.firstName)},`;
  const renewal = input.renewalDate.toLocaleDateString("en-CA", {
    year: "numeric",
    month: "long",
    day: "numeric"
  });
  const amountLabel = new Intl.NumberFormat("en-CA", {
    style: "currency",
    currency: input.currency,
    maximumFractionDigits: 2
  }).format(input.amount);
  const subject = "Your WWN membership is active";
  const text2 = [
    greeting,
    `Thank you for activating your ${input.planName} membership.`,
    `We have received your payment of ${amountLabel} and your access is now active.`,
    `Your next renewal date is ${renewal}.`,
    "",
    "If you need anything at all, reply to this email and we will support you.",
    "",
    "With warmth,",
    "The Whole Woman Network Team"
  ].join("\n");
  const html = renderEmailShell({
    eyebrow: "Membership Confirmed",
    title: "You are officially active",
    greeting,
    intro: `Your ${input.planName} membership has been activated and you now have full access to WWN.`,
    bodyHtml: `
      <div style="margin:0 0 18px;padding:20px;border-radius:20px;background:#fff6ef;border:1px solid #f1ddd0;">
        <p style="margin:0 0 10px;font-size:15px;line-height:24px;color:#6d5650;">
          Payment received: <strong style="color:#4a2242;">${escapeHtml(amountLabel)}</strong>
        </p>
        <p style="margin:0 0 10px;font-size:15px;line-height:24px;color:#6d5650;">
          Billing: <strong style="color:#4a2242;">Yearly (billed annually)</strong>
        </p>
        <p style="margin:0;font-size:15px;line-height:24px;color:#6d5650;">
          Next renewal: <strong style="color:#4a2242;">${escapeHtml(renewal)}</strong>
        </p>
      </div>
      <p style="margin:0;font-size:15px;line-height:25px;color:#6d5650;">
        If you have questions about billing, invoices, or your membership benefits, reply to this email and we will take care of you.
      </p>`,
    closing: "We are glad you are here. Thank you for investing in your growth with us."
  });
  return { subject, text: text2, html };
}
function createReminderEmail(input) {
  const subject = input.title;
  const recipientName = getRecipientName(input.firstName);
  const greeting = `Hi ${recipientName},`;
  const safeActionHref = input.actionLabel && input.actionHref ? normalizeEmailActionHref(input.actionHref) : null;
  const text2 = [
    greeting,
    input.intro,
    "",
    ...input.lines,
    "",
    input.actionLabel && safeActionHref ? `${input.actionLabel}: ${safeActionHref}` : "",
    "",
    "With warmth,",
    "The Whole Woman Network Team"
  ].filter((line2) => line2.trim() !== "").join("\n");
  const actionHtml = input.actionLabel && safeActionHref ? `<div style="margin:18px 0 0;">
          <a href="${escapeHtml(safeActionHref)}" style="display:inline-block;background:#c6683c;color:#fff;text-decoration:none;padding:12px 18px;border-radius:999px;font-size:14px;font-weight:700;">
            ${escapeHtml(input.actionLabel)}
          </a>
        </div>` : "";
  const html = renderEmailShell({
    eyebrow: input.eyebrow,
    title: input.title,
    greeting,
    intro: input.intro,
    bodyHtml: `
      <div style="margin:0 0 18px;padding:20px;border-radius:20px;background:#fff6ef;border:1px solid #f1ddd0;">
        ${input.lines.map(
      (line2) => `<p style="margin:0 0 10px;font-size:15px;line-height:24px;color:#6d5650;">${escapeHtml(line2)}</p>`
    ).join("")}
        ${actionHtml}
      </div>`,
    closing: "If you have questions or need support, reply to this email and we will help you."
  });
  return { subject, text: text2, html };
}
function createPasswordResetEmail(input) {
  const greeting = `Hi ${getRecipientName(input.firstName)},`;
  const subject = "Your WWN password reset code";
  const text2 = [
    greeting,
    `Your password reset code is ${input.code}.`,
    `It expires in ${input.expiresInMinutes} minutes.`,
    "",
    "If you did not request this change, you can safely ignore this email.",
    "",
    "With warmth,",
    "The Whole Woman Network Team"
  ].join("\n");
  const html = renderEmailShell({
    eyebrow: "Password Reset",
    title: "Here is your reset code",
    greeting,
    intro: "We received a request to reset your password.",
    bodyHtml: `
      <div style="margin:0 0 18px;padding:22px;border-radius:20px;background:#ffffff;border:1px solid #f1ddd0;text-align:center;box-shadow:0 14px 30px rgba(74,34,66,0.10);">
        <p style="margin:0 0 10px;font-size:13px;line-height:18px;letter-spacing:0.12em;text-transform:uppercase;color:#9b7c72;font-weight:700;">Password reset code</p>
        <p style="margin:0;font-size:34px;line-height:40px;letter-spacing:0.28em;color:#4a2242;font-weight:700;">${escapeHtml(input.code)}</p>
      </div>
      <p style="margin:0 0 14px;font-size:15px;line-height:25px;color:#6d5650;">
        This code stays active for <strong style="color:#4a2242;">${input.expiresInMinutes} minutes</strong>.
      </p>
      <p style="margin:0;font-size:15px;line-height:25px;color:#6d5650;">
        If you did not request this change, you can safely ignore this email.
      </p>`,
    closing: "If you need support, reply to this email and we will help you."
  });
  return { subject, text: text2, html };
}
function createOrganizationInvitationEmail(input) {
  const greeting = `Hi ${getRecipientName(input.firstName)},`;
  const inviteHref = normalizeEmailActionHref(input.inviteLink);
  const subject = `You have been invited to join ${input.organizationName} on WWN`;
  const invitedByLine = input.invitedByName?.trim() ? `${input.invitedByName.trim()} invited you to join ${input.organizationName} as ${input.roleLabel}.` : `You have been invited to join ${input.organizationName} as ${input.roleLabel}.`;
  const text2 = [
    greeting,
    invitedByLine,
    `This invitation expires on ${input.expiresOnLabel}.`,
    inviteHref ? `Accept your invitation here: ${inviteHref}` : "Sign in or create your WWN account to accept this invitation.",
    "",
    `If you need help, reply to this email or contact ${SUPPORT_EMAIL}.`,
    "",
    "With warmth,",
    "The Whole Woman Network Team"
  ].join("\n");
  const actionHtml = inviteHref ? `<p style="margin:18px 0 0;">
        <a href="${escapeHtml(inviteHref)}" style="display:inline-flex;align-items:center;justify-content:center;padding:12px 18px;border-radius:999px;background:#4a2242;color:#fffdfb;text-decoration:none;font-size:14px;font-weight:700;">
          Review invitation
        </a>
      </p>` : "";
  const html = renderEmailShell({
    eyebrow: "Organization Invitation",
    title: `You are invited to join ${input.organizationName}`,
    greeting,
    intro: "Your organization team is ready to bring you into their WWN workspace.",
    bodyHtml: `
      <div style="margin:0 0 18px;padding:20px;border-radius:20px;background:#fff6ef;border:1px solid #f1ddd0;">
        <p style="margin:0 0 10px;font-size:15px;line-height:24px;color:#6d5650;">
          Organization: <strong style="color:#4a2242;">${escapeHtml(input.organizationName)}</strong>
        </p>
        <p style="margin:0 0 10px;font-size:15px;line-height:24px;color:#6d5650;">
          Role: <strong style="color:#4a2242;">${escapeHtml(input.roleLabel)}</strong>
        </p>
        <p style="margin:0;font-size:15px;line-height:24px;color:#6d5650;">
          Invitation expires on <strong style="color:#4a2242;">${escapeHtml(input.expiresOnLabel)}</strong>.
        </p>
      </div>
      <p style="margin:0 0 14px;font-size:15px;line-height:25px;color:#6d5650;">
        ${escapeHtml(invitedByLine)}
      </p>
      <p style="margin:0;font-size:15px;line-height:25px;color:#6d5650;">
        Create your WWN account with this same email address, or sign in if you already have one, to join the organization workspace.
      </p>
      ${actionHtml}`,
    closing: "We are looking forward to welcoming you into your organization's WWN experience."
  });
  return { subject, text: text2, html };
}
async function sendMail({
  to,
  subject,
  text: text2,
  html
}) {
  const from = EMAIL_FROM || DEFAULT_FROM;
  if (!transporter) {
    throw new Error(
      "SMTP is not configured. Set SMTP_USER/SMTP_PASS (or SMTP_USERNAME/SMTP_PASSWORD) to enable email delivery."
    );
  }
  await transporter.sendMail({ to, from, subject, text: text2, html });
}
var SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS, EMAIL_FROM, DEFAULT_FROM, isSmtpConfigured, SUPPORT_EMAIL, transporter;
var init_mailer = __esm({
  "src/lib/mailer.ts"() {
    "use strict";
    init_config();
    SMTP_HOST = process.env.SMTP_HOST?.trim() || "smtp.gmail.com";
    SMTP_PORT = process.env.SMTP_PORT?.trim() || "587";
    SMTP_USER = process.env.SMTP_USER?.trim() || process.env.SMTP_USERNAME?.trim() || process.env.SMTP_LOGIN?.trim() || "";
    SMTP_PASS = process.env.SMTP_PASS?.trim() || process.env.SMTP_PASSWORD?.trim() || process.env.SMTP_APP_PASSWORD?.trim() || "";
    EMAIL_FROM = process.env.EMAIL_FROM?.trim() || "";
    DEFAULT_FROM = "WWN <noreply@wwncoop.com>";
    isSmtpConfigured = Boolean(SMTP_USER && SMTP_PASS);
    SUPPORT_EMAIL = "admin@wwncoop.com";
    transporter = isSmtpConfigured ? nodemailer.createTransport({
      host: SMTP_HOST,
      port: Number(SMTP_PORT),
      secure: Number(SMTP_PORT) === 465,
      auth: { user: SMTP_USER, pass: SMTP_PASS }
    }) : null;
  }
});

// ../../node_modules/.pnpm/jws@4.0.1/node_modules/jws/lib/data-stream.js
var require_data_stream = __commonJS({
  "../../node_modules/.pnpm/jws@4.0.1/node_modules/jws/lib/data-stream.js"(exports, module) {
    var Buffer3 = require_safe_buffer().Buffer;
    var Stream = __require("stream");
    var util2 = __require("util");
    function DataStream(data) {
      this.buffer = null;
      this.writable = true;
      this.readable = true;
      if (!data) {
        this.buffer = Buffer3.alloc(0);
        return this;
      }
      if (typeof data.pipe === "function") {
        this.buffer = Buffer3.alloc(0);
        data.pipe(this);
        return this;
      }
      if (data.length || typeof data === "object") {
        this.buffer = data;
        this.writable = false;
        process.nextTick(function() {
          this.emit("end", data);
          this.readable = false;
          this.emit("close");
        }.bind(this));
        return this;
      }
      throw new TypeError("Unexpected data type (" + typeof data + ")");
    }
    util2.inherits(DataStream, Stream);
    DataStream.prototype.write = function write(data) {
      this.buffer = Buffer3.concat([this.buffer, Buffer3.from(data)]);
      this.emit("data", data);
    };
    DataStream.prototype.end = function end(data) {
      if (data)
        this.write(data);
      this.emit("end", data);
      this.emit("close");
      this.writable = false;
      this.readable = false;
    };
    module.exports = DataStream;
  }
});

// ../../node_modules/.pnpm/ecdsa-sig-formatter@1.0.11/node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js
var require_param_bytes_for_alg = __commonJS({
  "../../node_modules/.pnpm/ecdsa-sig-formatter@1.0.11/node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js"(exports, module) {
    "use strict";
    function getParamSize(keySize) {
      var result = (keySize / 8 | 0) + (keySize % 8 === 0 ? 0 : 1);
      return result;
    }
    var paramBytesForAlg = {
      ES256: getParamSize(256),
      ES384: getParamSize(384),
      ES512: getParamSize(521)
    };
    function getParamBytesForAlg(alg) {
      var paramBytes = paramBytesForAlg[alg];
      if (paramBytes) {
        return paramBytes;
      }
      throw new Error('Unknown algorithm "' + alg + '"');
    }
    module.exports = getParamBytesForAlg;
  }
});

// ../../node_modules/.pnpm/ecdsa-sig-formatter@1.0.11/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js
var require_ecdsa_sig_formatter = __commonJS({
  "../../node_modules/.pnpm/ecdsa-sig-formatter@1.0.11/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js"(exports, module) {
    "use strict";
    var Buffer3 = require_safe_buffer().Buffer;
    var getParamBytesForAlg = require_param_bytes_for_alg();
    var MAX_OCTET = 128;
    var CLASS_UNIVERSAL = 0;
    var PRIMITIVE_BIT = 32;
    var TAG_SEQ = 16;
    var TAG_INT = 2;
    var ENCODED_TAG_SEQ = TAG_SEQ | PRIMITIVE_BIT | CLASS_UNIVERSAL << 6;
    var ENCODED_TAG_INT = TAG_INT | CLASS_UNIVERSAL << 6;
    function base64Url(base643) {
      return base643.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
    }
    function signatureAsBuffer(signature) {
      if (Buffer3.isBuffer(signature)) {
        return signature;
      } else if ("string" === typeof signature) {
        return Buffer3.from(signature, "base64");
      }
      throw new TypeError("ECDSA signature must be a Base64 string or a Buffer");
    }
    function derToJose(signature, alg) {
      signature = signatureAsBuffer(signature);
      var paramBytes = getParamBytesForAlg(alg);
      var maxEncodedParamLength = paramBytes + 1;
      var inputLength = signature.length;
      var offset = 0;
      if (signature[offset++] !== ENCODED_TAG_SEQ) {
        throw new Error('Could not find expected "seq"');
      }
      var seqLength = signature[offset++];
      if (seqLength === (MAX_OCTET | 1)) {
        seqLength = signature[offset++];
      }
      if (inputLength - offset < seqLength) {
        throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining');
      }
      if (signature[offset++] !== ENCODED_TAG_INT) {
        throw new Error('Could not find expected "int" for "r"');
      }
      var rLength = signature[offset++];
      if (inputLength - offset - 2 < rLength) {
        throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available');
      }
      if (maxEncodedParamLength < rLength) {
        throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable');
      }
      var rOffset = offset;
      offset += rLength;
      if (signature[offset++] !== ENCODED_TAG_INT) {
        throw new Error('Could not find expected "int" for "s"');
      }
      var sLength = signature[offset++];
      if (inputLength - offset !== sLength) {
        throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"');
      }
      if (maxEncodedParamLength < sLength) {
        throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable');
      }
      var sOffset = offset;
      offset += sLength;
      if (offset !== inputLength) {
        throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain');
      }
      var rPadding = paramBytes - rLength, sPadding = paramBytes - sLength;
      var dst = Buffer3.allocUnsafe(rPadding + rLength + sPadding + sLength);
      for (offset = 0; offset < rPadding; ++offset) {
        dst[offset] = 0;
      }
      signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength);
      offset = paramBytes;
      for (var o = offset; offset < o + sPadding; ++offset) {
        dst[offset] = 0;
      }
      signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength);
      dst = dst.toString("base64");
      dst = base64Url(dst);
      return dst;
    }
    function countPadding(buf, start, stop) {
      var padding = 0;
      while (start + padding < stop && buf[start + padding] === 0) {
        ++padding;
      }
      var needsSign = buf[start + padding] >= MAX_OCTET;
      if (needsSign) {
        --padding;
      }
      return padding;
    }
    function joseToDer(signature, alg) {
      signature = signatureAsBuffer(signature);
      var paramBytes = getParamBytesForAlg(alg);
      var signatureBytes = signature.length;
      if (signatureBytes !== paramBytes * 2) {
        throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"');
      }
      var rPadding = countPadding(signature, 0, paramBytes);
      var sPadding = countPadding(signature, paramBytes, signature.length);
      var rLength = paramBytes - rPadding;
      var sLength = paramBytes - sPadding;
      var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength;
      var shortLength = rsBytes < MAX_OCTET;
      var dst = Buffer3.allocUnsafe((shortLength ? 2 : 3) + rsBytes);
      var offset = 0;
      dst[offset++] = ENCODED_TAG_SEQ;
      if (shortLength) {
        dst[offset++] = rsBytes;
      } else {
        dst[offset++] = MAX_OCTET | 1;
        dst[offset++] = rsBytes & 255;
      }
      dst[offset++] = ENCODED_TAG_INT;
      dst[offset++] = rLength;
      if (rPadding < 0) {
        dst[offset++] = 0;
        offset += signature.copy(dst, offset, 0, paramBytes);
      } else {
        offset += signature.copy(dst, offset, rPadding, paramBytes);
      }
      dst[offset++] = ENCODED_TAG_INT;
      dst[offset++] = sLength;
      if (sPadding < 0) {
        dst[offset++] = 0;
        signature.copy(dst, offset, paramBytes);
      } else {
        signature.copy(dst, offset, paramBytes + sPadding);
      }
      return dst;
    }
    module.exports = {
      derToJose,
      joseToDer
    };
  }
});

// ../../node_modules/.pnpm/buffer-equal-constant-time@1.0.1/node_modules/buffer-equal-constant-time/index.js
var require_buffer_equal_constant_time = __commonJS({
  "../../node_modules/.pnpm/buffer-equal-constant-time@1.0.1/node_modules/buffer-equal-constant-time/index.js"(exports, module) {
    "use strict";
    var Buffer3 = __require("buffer").Buffer;
    var SlowBuffer = __require("buffer").SlowBuffer;
    module.exports = bufferEq;
    function bufferEq(a, b) {
      if (!Buffer3.isBuffer(a) || !Buffer3.isBuffer(b)) {
        return false;
      }
      if (a.length !== b.length) {
        return false;
      }
      var c = 0;
      for (var i = 0; i < a.length; i++) {
        c |= a[i] ^ b[i];
      }
      return c === 0;
    }
    bufferEq.install = function() {
      Buffer3.prototype.equal = SlowBuffer.prototype.equal = function equal(that) {
        return bufferEq(this, that);
      };
    };
    var origBufEqual = Buffer3.prototype.equal;
    var origSlowBufEqual = SlowBuffer.prototype.equal;
    bufferEq.restore = function() {
      Buffer3.prototype.equal = origBufEqual;
      SlowBuffer.prototype.equal = origSlowBufEqual;
    };
  }
});

// ../../node_modules/.pnpm/jwa@2.0.1/node_modules/jwa/index.js
var require_jwa = __commonJS({
  "../../node_modules/.pnpm/jwa@2.0.1/node_modules/jwa/index.js"(exports, module) {
    var Buffer3 = require_safe_buffer().Buffer;
    var crypto4 = __require("crypto");
    var formatEcdsa = require_ecdsa_sig_formatter();
    var util2 = __require("util");
    var MSG_INVALID_ALGORITHM = '"%s" is not a valid algorithm.\n  Supported algorithms are:\n  "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".';
    var MSG_INVALID_SECRET = "secret must be a string or buffer";
    var MSG_INVALID_VERIFIER_KEY = "key must be a string or a buffer";
    var MSG_INVALID_SIGNER_KEY = "key must be a string, a buffer or an object";
    var supportsKeyObjects = typeof crypto4.createPublicKey === "function";
    if (supportsKeyObjects) {
      MSG_INVALID_VERIFIER_KEY += " or a KeyObject";
      MSG_INVALID_SECRET += "or a KeyObject";
    }
    function checkIsPublicKey(key) {
      if (Buffer3.isBuffer(key)) {
        return;
      }
      if (typeof key === "string") {
        return;
      }
      if (!supportsKeyObjects) {
        throw typeError(MSG_INVALID_VERIFIER_KEY);
      }
      if (typeof key !== "object") {
        throw typeError(MSG_INVALID_VERIFIER_KEY);
      }
      if (typeof key.type !== "string") {
        throw typeError(MSG_INVALID_VERIFIER_KEY);
      }
      if (typeof key.asymmetricKeyType !== "string") {
        throw typeError(MSG_INVALID_VERIFIER_KEY);
      }
      if (typeof key.export !== "function") {
        throw typeError(MSG_INVALID_VERIFIER_KEY);
      }
    }
    function checkIsPrivateKey(key) {
      if (Buffer3.isBuffer(key)) {
        return;
      }
      if (typeof key === "string") {
        return;
      }
      if (typeof key === "object") {
        return;
      }
      throw typeError(MSG_INVALID_SIGNER_KEY);
    }
    function checkIsSecretKey(key) {
      if (Buffer3.isBuffer(key)) {
        return;
      }
      if (typeof key === "string") {
        return key;
      }
      if (!supportsKeyObjects) {
        throw typeError(MSG_INVALID_SECRET);
      }
      if (typeof key !== "object") {
        throw typeError(MSG_INVALID_SECRET);
      }
      if (key.type !== "secret") {
        throw typeError(MSG_INVALID_SECRET);
      }
      if (typeof key.export !== "function") {
        throw typeError(MSG_INVALID_SECRET);
      }
    }
    function fromBase64(base643) {
      return base643.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
    }
    function toBase64(base64url3) {
      base64url3 = base64url3.toString();
      var padding = 4 - base64url3.length % 4;
      if (padding !== 4) {
        for (var i = 0; i < padding; ++i) {
          base64url3 += "=";
        }
      }
      return base64url3.replace(/\-/g, "+").replace(/_/g, "/");
    }
    function typeError(template) {
      var args = [].slice.call(arguments, 1);
      var errMsg = util2.format.bind(util2, template).apply(null, args);
      return new TypeError(errMsg);
    }
    function bufferOrString(obj) {
      return Buffer3.isBuffer(obj) || typeof obj === "string";
    }
    function normalizeInput(thing) {
      if (!bufferOrString(thing))
        thing = JSON.stringify(thing);
      return thing;
    }
    function createHmacSigner(bits) {
      return function sign(thing, secret) {
        checkIsSecretKey(secret);
        thing = normalizeInput(thing);
        var hmac = crypto4.createHmac("sha" + bits, secret);
        var sig = (hmac.update(thing), hmac.digest("base64"));
        return fromBase64(sig);
      };
    }
    var bufferEqual;
    var timingSafeEqual3 = "timingSafeEqual" in crypto4 ? function timingSafeEqual4(a, b) {
      if (a.byteLength !== b.byteLength) {
        return false;
      }
      return crypto4.timingSafeEqual(a, b);
    } : function timingSafeEqual4(a, b) {
      if (!bufferEqual) {
        bufferEqual = require_buffer_equal_constant_time();
      }
      return bufferEqual(a, b);
    };
    function createHmacVerifier(bits) {
      return function verify(thing, signature, secret) {
        var computedSig = createHmacSigner(bits)(thing, secret);
        return timingSafeEqual3(Buffer3.from(signature), Buffer3.from(computedSig));
      };
    }
    function createKeySigner(bits) {
      return function sign(thing, privateKey) {
        checkIsPrivateKey(privateKey);
        thing = normalizeInput(thing);
        var signer = crypto4.createSign("RSA-SHA" + bits);
        var sig = (signer.update(thing), signer.sign(privateKey, "base64"));
        return fromBase64(sig);
      };
    }
    function createKeyVerifier(bits) {
      return function verify(thing, signature, publicKey) {
        checkIsPublicKey(publicKey);
        thing = normalizeInput(thing);
        signature = toBase64(signature);
        var verifier = crypto4.createVerify("RSA-SHA" + bits);
        verifier.update(thing);
        return verifier.verify(publicKey, signature, "base64");
      };
    }
    function createPSSKeySigner(bits) {
      return function sign(thing, privateKey) {
        checkIsPrivateKey(privateKey);
        thing = normalizeInput(thing);
        var signer = crypto4.createSign("RSA-SHA" + bits);
        var sig = (signer.update(thing), signer.sign({
          key: privateKey,
          padding: crypto4.constants.RSA_PKCS1_PSS_PADDING,
          saltLength: crypto4.constants.RSA_PSS_SALTLEN_DIGEST
        }, "base64"));
        return fromBase64(sig);
      };
    }
    function createPSSKeyVerifier(bits) {
      return function verify(thing, signature, publicKey) {
        checkIsPublicKey(publicKey);
        thing = normalizeInput(thing);
        signature = toBase64(signature);
        var verifier = crypto4.createVerify("RSA-SHA" + bits);
        verifier.update(thing);
        return verifier.verify({
          key: publicKey,
          padding: crypto4.constants.RSA_PKCS1_PSS_PADDING,
          saltLength: crypto4.constants.RSA_PSS_SALTLEN_DIGEST
        }, signature, "base64");
      };
    }
    function createECDSASigner(bits) {
      var inner = createKeySigner(bits);
      return function sign() {
        var signature = inner.apply(null, arguments);
        signature = formatEcdsa.derToJose(signature, "ES" + bits);
        return signature;
      };
    }
    function createECDSAVerifer(bits) {
      var inner = createKeyVerifier(bits);
      return function verify(thing, signature, publicKey) {
        signature = formatEcdsa.joseToDer(signature, "ES" + bits).toString("base64");
        var result = inner(thing, signature, publicKey);
        return result;
      };
    }
    function createNoneSigner() {
      return function sign() {
        return "";
      };
    }
    function createNoneVerifier() {
      return function verify(thing, signature) {
        return signature === "";
      };
    }
    module.exports = function jwa(algorithm) {
      var signerFactories = {
        hs: createHmacSigner,
        rs: createKeySigner,
        ps: createPSSKeySigner,
        es: createECDSASigner,
        none: createNoneSigner
      };
      var verifierFactories = {
        hs: createHmacVerifier,
        rs: createKeyVerifier,
        ps: createPSSKeyVerifier,
        es: createECDSAVerifer,
        none: createNoneVerifier
      };
      var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);
      if (!match)
        throw typeError(MSG_INVALID_ALGORITHM, algorithm);
      var algo = (match[1] || match[3]).toLowerCase();
      var bits = match[2];
      return {
        sign: signerFactories[algo](bits),
        verify: verifierFactories[algo](bits)
      };
    };
  }
});

// ../../node_modules/.pnpm/jws@4.0.1/node_modules/jws/lib/tostring.js
var require_tostring = __commonJS({
  "../../node_modules/.pnpm/jws@4.0.1/node_modules/jws/lib/tostring.js"(exports, module) {
    var Buffer3 = __require("buffer").Buffer;
    module.exports = function toString(obj) {
      if (typeof obj === "string")
        return obj;
      if (typeof obj === "number" || Buffer3.isBuffer(obj))
        return obj.toString();
      return JSON.stringify(obj);
    };
  }
});

// ../../node_modules/.pnpm/jws@4.0.1/node_modules/jws/lib/sign-stream.js
var require_sign_stream = __commonJS({
  "../../node_modules/.pnpm/jws@4.0.1/node_modules/jws/lib/sign-stream.js"(exports, module) {
    var Buffer3 = require_safe_buffer().Buffer;
    var DataStream = require_data_stream();
    var jwa = require_jwa();
    var Stream = __require("stream");
    var toString = require_tostring();
    var util2 = __require("util");
    function base64url3(string4, encoding) {
      return Buffer3.from(string4, encoding).toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
    }
    function jwsSecuredInput(header, payload, encoding) {
      encoding = encoding || "utf8";
      var encodedHeader = base64url3(toString(header), "binary");
      var encodedPayload = base64url3(toString(payload), encoding);
      return util2.format("%s.%s", encodedHeader, encodedPayload);
    }
    function jwsSign(opts) {
      var header = opts.header;
      var payload = opts.payload;
      var secretOrKey = opts.secret || opts.privateKey;
      var encoding = opts.encoding;
      var algo = jwa(header.alg);
      var securedInput = jwsSecuredInput(header, payload, encoding);
      var signature = algo.sign(securedInput, secretOrKey);
      return util2.format("%s.%s", securedInput, signature);
    }
    function SignStream(opts) {
      var secret = opts.secret;
      secret = secret == null ? opts.privateKey : secret;
      secret = secret == null ? opts.key : secret;
      if (/^hs/i.test(opts.header.alg) === true && secret == null) {
        throw new TypeError("secret must be a string or buffer or a KeyObject");
      }
      var secretStream = new DataStream(secret);
      this.readable = true;
      this.header = opts.header;
      this.encoding = opts.encoding;
      this.secret = this.privateKey = this.key = secretStream;
      this.payload = new DataStream(opts.payload);
      this.secret.once("close", function() {
        if (!this.payload.writable && this.readable)
          this.sign();
      }.bind(this));
      this.payload.once("close", function() {
        if (!this.secret.writable && this.readable)
          this.sign();
      }.bind(this));
    }
    util2.inherits(SignStream, Stream);
    SignStream.prototype.sign = function sign() {
      try {
        var signature = jwsSign({
          header: this.header,
          payload: this.payload.buffer,
          secret: this.secret.buffer,
          encoding: this.encoding
        });
        this.emit("done", signature);
        this.emit("data", signature);
        this.emit("end");
        this.readable = false;
        return signature;
      } catch (e) {
        this.readable = false;
        this.emit("error", e);
        this.emit("close");
      }
    };
    SignStream.sign = jwsSign;
    module.exports = SignStream;
  }
});

// ../../node_modules/.pnpm/jws@4.0.1/node_modules/jws/lib/verify-stream.js
var require_verify_stream = __commonJS({
  "../../node_modules/.pnpm/jws@4.0.1/node_modules/jws/lib/verify-stream.js"(exports, module) {
    var Buffer3 = require_safe_buffer().Buffer;
    var DataStream = require_data_stream();
    var jwa = require_jwa();
    var Stream = __require("stream");
    var toString = require_tostring();
    var util2 = __require("util");
    var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;
    function isObject3(thing) {
      return Object.prototype.toString.call(thing) === "[object Object]";
    }
    function safeJsonParse(thing) {
      if (isObject3(thing))
        return thing;
      try {
        return JSON.parse(thing);
      } catch (e) {
        return void 0;
      }
    }
    function headerFromJWS(jwsSig) {
      var encodedHeader = jwsSig.split(".", 1)[0];
      return safeJsonParse(Buffer3.from(encodedHeader, "base64").toString("binary"));
    }
    function securedInputFromJWS(jwsSig) {
      return jwsSig.split(".", 2).join(".");
    }
    function signatureFromJWS(jwsSig) {
      return jwsSig.split(".")[2];
    }
    function payloadFromJWS(jwsSig, encoding) {
      encoding = encoding || "utf8";
      var payload = jwsSig.split(".")[1];
      return Buffer3.from(payload, "base64").toString(encoding);
    }
    function isValidJws(string4) {
      return JWS_REGEX.test(string4) && !!headerFromJWS(string4);
    }
    function jwsVerify(jwsSig, algorithm, secretOrKey) {
      if (!algorithm) {
        var err = new Error("Missing algorithm parameter for jws.verify");
        err.code = "MISSING_ALGORITHM";
        throw err;
      }
      jwsSig = toString(jwsSig);
      var signature = signatureFromJWS(jwsSig);
      var securedInput = securedInputFromJWS(jwsSig);
      var algo = jwa(algorithm);
      return algo.verify(securedInput, signature, secretOrKey);
    }
    function jwsDecode(jwsSig, opts) {
      opts = opts || {};
      jwsSig = toString(jwsSig);
      if (!isValidJws(jwsSig))
        return null;
      var header = headerFromJWS(jwsSig);
      if (!header)
        return null;
      var payload = payloadFromJWS(jwsSig);
      if (header.typ === "JWT" || opts.json)
        payload = JSON.parse(payload, opts.encoding);
      return {
        header,
        payload,
        signature: signatureFromJWS(jwsSig)
      };
    }
    function VerifyStream(opts) {
      opts = opts || {};
      var secretOrKey = opts.secret;
      secretOrKey = secretOrKey == null ? opts.publicKey : secretOrKey;
      secretOrKey = secretOrKey == null ? opts.key : secretOrKey;
      if (/^hs/i.test(opts.algorithm) === true && secretOrKey == null) {
        throw new TypeError("secret must be a string or buffer or a KeyObject");
      }
      var secretStream = new DataStream(secretOrKey);
      this.readable = true;
      this.algorithm = opts.algorithm;
      this.encoding = opts.encoding;
      this.secret = this.publicKey = this.key = secretStream;
      this.signature = new DataStream(opts.signature);
      this.secret.once("close", function() {
        if (!this.signature.writable && this.readable)
          this.verify();
      }.bind(this));
      this.signature.once("close", function() {
        if (!this.secret.writable && this.readable)
          this.verify();
      }.bind(this));
    }
    util2.inherits(VerifyStream, Stream);
    VerifyStream.prototype.verify = function verify() {
      try {
        var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer);
        var obj = jwsDecode(this.signature.buffer, this.encoding);
        this.emit("done", valid, obj);
        this.emit("data", valid);
        this.emit("end");
        this.readable = false;
        return valid;
      } catch (e) {
        this.readable = false;
        this.emit("error", e);
        this.emit("close");
      }
    };
    VerifyStream.decode = jwsDecode;
    VerifyStream.isValid = isValidJws;
    VerifyStream.verify = jwsVerify;
    module.exports = VerifyStream;
  }
});

// ../../node_modules/.pnpm/jws@4.0.1/node_modules/jws/index.js
var require_jws = __commonJS({
  "../../node_modules/.pnpm/jws@4.0.1/node_modules/jws/index.js"(exports) {
    var SignStream = require_sign_stream();
    var VerifyStream = require_verify_stream();
    var ALGORITHMS = [
      "HS256",
      "HS384",
      "HS512",
      "RS256",
      "RS384",
      "RS512",
      "PS256",
      "PS384",
      "PS512",
      "ES256",
      "ES384",
      "ES512"
    ];
    exports.ALGORITHMS = ALGORITHMS;
    exports.sign = SignStream.sign;
    exports.verify = VerifyStream.verify;
    exports.decode = VerifyStream.decode;
    exports.isValid = VerifyStream.isValid;
    exports.createSign = function createSign(opts) {
      return new SignStream(opts);
    };
    exports.createVerify = function createVerify(opts) {
      return new VerifyStream(opts);
    };
  }
});

// ../../node_modules/.pnpm/jsonwebtoken@9.0.3/node_modules/jsonwebtoken/decode.js
var require_decode = __commonJS({
  "../../node_modules/.pnpm/jsonwebtoken@9.0.3/node_modules/jsonwebtoken/decode.js"(exports, module) {
    var jws = require_jws();
    module.exports = function(jwt3, options) {
      options = options || {};
      var decoded = jws.decode(jwt3, options);
      if (!decoded) {
        return null;
      }
      var payload = decoded.payload;
      if (typeof payload === "string") {
        try {
          var obj = JSON.parse(payload);
          if (obj !== null && typeof obj === "object") {
            payload = obj;
          }
        } catch (e) {
        }
      }
      if (options.complete === true) {
        return {
          header: decoded.header,
          payload,
          signature: decoded.signature
        };
      }
      return payload;
    };
  }
});

// ../../node_modules/.pnpm/jsonwebtoken@9.0.3/node_modules/jsonwebtoken/lib/JsonWebTokenError.js
var require_JsonWebTokenError = __commonJS({
  "../../node_modules/.pnpm/jsonwebtoken@9.0.3/node_modules/jsonwebtoken/lib/JsonWebTokenError.js"(exports, module) {
    var JsonWebTokenError = function(message, error40) {
      Error.call(this, message);
      if (Error.captureStackTrace) {
        Error.captureStackTrace(this, this.constructor);
      }
      this.name = "JsonWebTokenError";
      this.message = message;
      if (error40) this.inner = error40;
    };
    JsonWebTokenError.prototype = Object.create(Error.prototype);
    JsonWebTokenError.prototype.constructor = JsonWebTokenError;
    module.exports = JsonWebTokenError;
  }
});

// ../../node_modules/.pnpm/jsonwebtoken@9.0.3/node_modules/jsonwebtoken/lib/NotBeforeError.js
var require_NotBeforeError = __commonJS({
  "../../node_modules/.pnpm/jsonwebtoken@9.0.3/node_modules/jsonwebtoken/lib/NotBeforeError.js"(exports, module) {
    var JsonWebTokenError = require_JsonWebTokenError();
    var NotBeforeError = function(message, date6) {
      JsonWebTokenError.call(this, message);
      this.name = "NotBeforeError";
      this.date = date6;
    };
    NotBeforeError.prototype = Object.create(JsonWebTokenError.prototype);
    NotBeforeError.prototype.constructor = NotBeforeError;
    module.exports = NotBeforeError;
  }
});

// ../../node_modules/.pnpm/jsonwebtoken@9.0.3/node_modules/jsonwebtoken/lib/TokenExpiredError.js
var require_TokenExpiredError = __commonJS({
  "../../node_modules/.pnpm/jsonwebtoken@9.0.3/node_modules/jsonwebtoken/lib/TokenExpiredError.js"(exports, module) {
    var JsonWebTokenError = require_JsonWebTokenError();
    var TokenExpiredError = function(message, expiredAt) {
      JsonWebTokenError.call(this, message);
      this.name = "TokenExpiredError";
      this.expiredAt = expiredAt;
    };
    TokenExpiredError.prototype = Object.create(JsonWebTokenError.prototype);
    TokenExpiredError.prototype.constructor = TokenExpiredError;
    module.exports = TokenExpiredError;
  }
});

// ../../node_modules/.pnpm/jsonwebtoken@9.0.3/node_modules/jsonwebtoken/lib/timespan.js
var require_timespan = __commonJS({
  "../../node_modules/.pnpm/jsonwebtoken@9.0.3/node_modules/jsonwebtoken/lib/timespan.js"(exports, module) {
    var ms = require_ms2();
    module.exports = function(time4, iat) {
      var timestamp2 = iat || Math.floor(Date.now() / 1e3);
      if (typeof time4 === "string") {
        var milliseconds = ms(time4);
        if (typeof milliseconds === "undefined") {
          return;
        }
        return Math.floor(timestamp2 + milliseconds / 1e3);
      } else if (typeof time4 === "number") {
        return timestamp2 + time4;
      } else {
        return;
      }
    };
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/internal/constants.js
var require_constants4 = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/internal/constants.js"(exports, module) {
    "use strict";
    var SEMVER_SPEC_VERSION = "2.0.0";
    var MAX_LENGTH = 256;
    var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */
    9007199254740991;
    var MAX_SAFE_COMPONENT_LENGTH = 16;
    var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6;
    var RELEASE_TYPES = [
      "major",
      "premajor",
      "minor",
      "preminor",
      "patch",
      "prepatch",
      "prerelease"
    ];
    module.exports = {
      MAX_LENGTH,
      MAX_SAFE_COMPONENT_LENGTH,
      MAX_SAFE_BUILD_LENGTH,
      MAX_SAFE_INTEGER,
      RELEASE_TYPES,
      SEMVER_SPEC_VERSION,
      FLAG_INCLUDE_PRERELEASE: 1,
      FLAG_LOOSE: 2
    };
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/internal/debug.js
var require_debug2 = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/internal/debug.js"(exports, module) {
    "use strict";
    var debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => {
    };
    module.exports = debug;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/internal/re.js
var require_re = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/internal/re.js"(exports, module) {
    "use strict";
    var {
      MAX_SAFE_COMPONENT_LENGTH,
      MAX_SAFE_BUILD_LENGTH,
      MAX_LENGTH
    } = require_constants4();
    var debug = require_debug2();
    exports = module.exports = {};
    var re = exports.re = [];
    var safeRe = exports.safeRe = [];
    var src = exports.src = [];
    var safeSrc = exports.safeSrc = [];
    var t = exports.t = {};
    var R = 0;
    var LETTERDASHNUMBER = "[a-zA-Z0-9-]";
    var safeRegexReplacements = [
      ["\\s", 1],
      ["\\d", MAX_LENGTH],
      [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH]
    ];
    var makeSafeRegex = (value) => {
      for (const [token, max] of safeRegexReplacements) {
        value = value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`);
      }
      return value;
    };
    var createToken = (name, value, isGlobal) => {
      const safe = makeSafeRegex(value);
      const index2 = R++;
      debug(name, index2, value);
      t[name] = index2;
      src[index2] = value;
      safeSrc[index2] = safe;
      re[index2] = new RegExp(value, isGlobal ? "g" : void 0);
      safeRe[index2] = new RegExp(safe, isGlobal ? "g" : void 0);
    };
    createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*");
    createToken("NUMERICIDENTIFIERLOOSE", "\\d+");
    createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`);
    createToken("MAINVERSION", `(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})`);
    createToken("MAINVERSIONLOOSE", `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})`);
    createToken("PRERELEASEIDENTIFIER", `(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIER]})`);
    createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIERLOOSE]})`);
    createToken("PRERELEASE", `(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`);
    createToken("PRERELEASELOOSE", `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`);
    createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`);
    createToken("BUILD", `(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`);
    createToken("FULLPLAIN", `v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`);
    createToken("FULL", `^${src[t.FULLPLAIN]}$`);
    createToken("LOOSEPLAIN", `[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`);
    createToken("LOOSE", `^${src[t.LOOSEPLAIN]}$`);
    createToken("GTLT", "((?:<|>)?=?)");
    createToken("XRANGEIDENTIFIERLOOSE", `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
    createToken("XRANGEIDENTIFIER", `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`);
    createToken("XRANGEPLAIN", `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?)?)?`);
    createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?)?)?`);
    createToken("XRANGE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`);
    createToken("XRANGELOOSE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`);
    createToken("COERCEPLAIN", `${"(^|[^\\d])(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`);
    createToken("COERCE", `${src[t.COERCEPLAIN]}(?:$|[^\\d])`);
    createToken("COERCEFULL", src[t.COERCEPLAIN] + `(?:${src[t.PRERELEASE]})?(?:${src[t.BUILD]})?(?:$|[^\\d])`);
    createToken("COERCERTL", src[t.COERCE], true);
    createToken("COERCERTLFULL", src[t.COERCEFULL], true);
    createToken("LONETILDE", "(?:~>?)");
    createToken("TILDETRIM", `(\\s*)${src[t.LONETILDE]}\\s+`, true);
    exports.tildeTrimReplace = "$1~";
    createToken("TILDE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);
    createToken("TILDELOOSE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`);
    createToken("LONECARET", "(?:\\^)");
    createToken("CARETTRIM", `(\\s*)${src[t.LONECARET]}\\s+`, true);
    exports.caretTrimReplace = "$1^";
    createToken("CARET", `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);
    createToken("CARETLOOSE", `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`);
    createToken("COMPARATORLOOSE", `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`);
    createToken("COMPARATOR", `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`);
    createToken("COMPARATORTRIM", `(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true);
    exports.comparatorTrimReplace = "$1$2$3";
    createToken("HYPHENRANGE", `^\\s*(${src[t.XRANGEPLAIN]})\\s+-\\s+(${src[t.XRANGEPLAIN]})\\s*$`);
    createToken("HYPHENRANGELOOSE", `^\\s*(${src[t.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t.XRANGEPLAINLOOSE]})\\s*$`);
    createToken("STAR", "(<|>)?=?\\s*\\*");
    createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$");
    createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$");
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/internal/parse-options.js
var require_parse_options = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/internal/parse-options.js"(exports, module) {
    "use strict";
    var looseOption = Object.freeze({ loose: true });
    var emptyOpts = Object.freeze({});
    var parseOptions2 = (options) => {
      if (!options) {
        return emptyOpts;
      }
      if (typeof options !== "object") {
        return looseOption;
      }
      return options;
    };
    module.exports = parseOptions2;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/internal/identifiers.js
var require_identifiers = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/internal/identifiers.js"(exports, module) {
    "use strict";
    var numeric2 = /^[0-9]+$/;
    var compareIdentifiers = (a, b) => {
      if (typeof a === "number" && typeof b === "number") {
        return a === b ? 0 : a < b ? -1 : 1;
      }
      const anum = numeric2.test(a);
      const bnum = numeric2.test(b);
      if (anum && bnum) {
        a = +a;
        b = +b;
      }
      return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
    };
    var rcompareIdentifiers = (a, b) => compareIdentifiers(b, a);
    module.exports = {
      compareIdentifiers,
      rcompareIdentifiers
    };
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/classes/semver.js
var require_semver = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/classes/semver.js"(exports, module) {
    "use strict";
    var debug = require_debug2();
    var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants4();
    var { safeRe: re, t } = require_re();
    var parseOptions2 = require_parse_options();
    var { compareIdentifiers } = require_identifiers();
    var SemVer = class _SemVer {
      constructor(version3, options) {
        options = parseOptions2(options);
        if (version3 instanceof _SemVer) {
          if (version3.loose === !!options.loose && version3.includePrerelease === !!options.includePrerelease) {
            return version3;
          } else {
            version3 = version3.version;
          }
        } else if (typeof version3 !== "string") {
          throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version3}".`);
        }
        if (version3.length > MAX_LENGTH) {
          throw new TypeError(
            `version is longer than ${MAX_LENGTH} characters`
          );
        }
        debug("SemVer", version3, options);
        this.options = options;
        this.loose = !!options.loose;
        this.includePrerelease = !!options.includePrerelease;
        const m = version3.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);
        if (!m) {
          throw new TypeError(`Invalid Version: ${version3}`);
        }
        this.raw = version3;
        this.major = +m[1];
        this.minor = +m[2];
        this.patch = +m[3];
        if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
          throw new TypeError("Invalid major version");
        }
        if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
          throw new TypeError("Invalid minor version");
        }
        if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
          throw new TypeError("Invalid patch version");
        }
        if (!m[4]) {
          this.prerelease = [];
        } else {
          this.prerelease = m[4].split(".").map((id) => {
            if (/^[0-9]+$/.test(id)) {
              const num = +id;
              if (num >= 0 && num < MAX_SAFE_INTEGER) {
                return num;
              }
            }
            return id;
          });
        }
        this.build = m[5] ? m[5].split(".") : [];
        this.format();
      }
      format() {
        this.version = `${this.major}.${this.minor}.${this.patch}`;
        if (this.prerelease.length) {
          this.version += `-${this.prerelease.join(".")}`;
        }
        return this.version;
      }
      toString() {
        return this.version;
      }
      compare(other) {
        debug("SemVer.compare", this.version, this.options, other);
        if (!(other instanceof _SemVer)) {
          if (typeof other === "string" && other === this.version) {
            return 0;
          }
          other = new _SemVer(other, this.options);
        }
        if (other.version === this.version) {
          return 0;
        }
        return this.compareMain(other) || this.comparePre(other);
      }
      compareMain(other) {
        if (!(other instanceof _SemVer)) {
          other = new _SemVer(other, this.options);
        }
        if (this.major < other.major) {
          return -1;
        }
        if (this.major > other.major) {
          return 1;
        }
        if (this.minor < other.minor) {
          return -1;
        }
        if (this.minor > other.minor) {
          return 1;
        }
        if (this.patch < other.patch) {
          return -1;
        }
        if (this.patch > other.patch) {
          return 1;
        }
        return 0;
      }
      comparePre(other) {
        if (!(other instanceof _SemVer)) {
          other = new _SemVer(other, this.options);
        }
        if (this.prerelease.length && !other.prerelease.length) {
          return -1;
        } else if (!this.prerelease.length && other.prerelease.length) {
          return 1;
        } else if (!this.prerelease.length && !other.prerelease.length) {
          return 0;
        }
        let i = 0;
        do {
          const a = this.prerelease[i];
          const b = other.prerelease[i];
          debug("prerelease compare", i, a, b);
          if (a === void 0 && b === void 0) {
            return 0;
          } else if (b === void 0) {
            return 1;
          } else if (a === void 0) {
            return -1;
          } else if (a === b) {
            continue;
          } else {
            return compareIdentifiers(a, b);
          }
        } while (++i);
      }
      compareBuild(other) {
        if (!(other instanceof _SemVer)) {
          other = new _SemVer(other, this.options);
        }
        let i = 0;
        do {
          const a = this.build[i];
          const b = other.build[i];
          debug("build compare", i, a, b);
          if (a === void 0 && b === void 0) {
            return 0;
          } else if (b === void 0) {
            return 1;
          } else if (a === void 0) {
            return -1;
          } else if (a === b) {
            continue;
          } else {
            return compareIdentifiers(a, b);
          }
        } while (++i);
      }
      // preminor will bump the version up to the next minor release, and immediately
      // down to pre-release. premajor and prepatch work the same way.
      inc(release, identifier, identifierBase) {
        if (release.startsWith("pre")) {
          if (!identifier && identifierBase === false) {
            throw new Error("invalid increment argument: identifier is empty");
          }
          if (identifier) {
            const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]);
            if (!match || match[1] !== identifier) {
              throw new Error(`invalid identifier: ${identifier}`);
            }
          }
        }
        switch (release) {
          case "premajor":
            this.prerelease.length = 0;
            this.patch = 0;
            this.minor = 0;
            this.major++;
            this.inc("pre", identifier, identifierBase);
            break;
          case "preminor":
            this.prerelease.length = 0;
            this.patch = 0;
            this.minor++;
            this.inc("pre", identifier, identifierBase);
            break;
          case "prepatch":
            this.prerelease.length = 0;
            this.inc("patch", identifier, identifierBase);
            this.inc("pre", identifier, identifierBase);
            break;
          // If the input is a non-prerelease version, this acts the same as
          // prepatch.
          case "prerelease":
            if (this.prerelease.length === 0) {
              this.inc("patch", identifier, identifierBase);
            }
            this.inc("pre", identifier, identifierBase);
            break;
          case "release":
            if (this.prerelease.length === 0) {
              throw new Error(`version ${this.raw} is not a prerelease`);
            }
            this.prerelease.length = 0;
            break;
          case "major":
            if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
              this.major++;
            }
            this.minor = 0;
            this.patch = 0;
            this.prerelease = [];
            break;
          case "minor":
            if (this.patch !== 0 || this.prerelease.length === 0) {
              this.minor++;
            }
            this.patch = 0;
            this.prerelease = [];
            break;
          case "patch":
            if (this.prerelease.length === 0) {
              this.patch++;
            }
            this.prerelease = [];
            break;
          // This probably shouldn't be used publicly.
          // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
          case "pre": {
            const base = Number(identifierBase) ? 1 : 0;
            if (this.prerelease.length === 0) {
              this.prerelease = [base];
            } else {
              let i = this.prerelease.length;
              while (--i >= 0) {
                if (typeof this.prerelease[i] === "number") {
                  this.prerelease[i]++;
                  i = -2;
                }
              }
              if (i === -1) {
                if (identifier === this.prerelease.join(".") && identifierBase === false) {
                  throw new Error("invalid increment argument: identifier already exists");
                }
                this.prerelease.push(base);
              }
            }
            if (identifier) {
              let prerelease = [identifier, base];
              if (identifierBase === false) {
                prerelease = [identifier];
              }
              if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
                if (isNaN(this.prerelease[1])) {
                  this.prerelease = prerelease;
                }
              } else {
                this.prerelease = prerelease;
              }
            }
            break;
          }
          default:
            throw new Error(`invalid increment argument: ${release}`);
        }
        this.raw = this.format();
        if (this.build.length) {
          this.raw += `+${this.build.join(".")}`;
        }
        return this;
      }
    };
    module.exports = SemVer;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/parse.js
var require_parse2 = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/parse.js"(exports, module) {
    "use strict";
    var SemVer = require_semver();
    var parse3 = (version3, options, throwErrors = false) => {
      if (version3 instanceof SemVer) {
        return version3;
      }
      try {
        return new SemVer(version3, options);
      } catch (er) {
        if (!throwErrors) {
          return null;
        }
        throw er;
      }
    };
    module.exports = parse3;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/valid.js
var require_valid = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/valid.js"(exports, module) {
    "use strict";
    var parse3 = require_parse2();
    var valid = (version3, options) => {
      const v = parse3(version3, options);
      return v ? v.version : null;
    };
    module.exports = valid;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/clean.js
var require_clean = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/clean.js"(exports, module) {
    "use strict";
    var parse3 = require_parse2();
    var clean = (version3, options) => {
      const s = parse3(version3.trim().replace(/^[=v]+/, ""), options);
      return s ? s.version : null;
    };
    module.exports = clean;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/inc.js
var require_inc = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/inc.js"(exports, module) {
    "use strict";
    var SemVer = require_semver();
    var inc = (version3, release, options, identifier, identifierBase) => {
      if (typeof options === "string") {
        identifierBase = identifier;
        identifier = options;
        options = void 0;
      }
      try {
        return new SemVer(
          version3 instanceof SemVer ? version3.version : version3,
          options
        ).inc(release, identifier, identifierBase).version;
      } catch (er) {
        return null;
      }
    };
    module.exports = inc;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/diff.js
var require_diff = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/diff.js"(exports, module) {
    "use strict";
    var parse3 = require_parse2();
    var diff = (version1, version22) => {
      const v1 = parse3(version1, null, true);
      const v2 = parse3(version22, null, true);
      const comparison = v1.compare(v2);
      if (comparison === 0) {
        return null;
      }
      const v1Higher = comparison > 0;
      const highVersion = v1Higher ? v1 : v2;
      const lowVersion = v1Higher ? v2 : v1;
      const highHasPre = !!highVersion.prerelease.length;
      const lowHasPre = !!lowVersion.prerelease.length;
      if (lowHasPre && !highHasPre) {
        if (!lowVersion.patch && !lowVersion.minor) {
          return "major";
        }
        if (lowVersion.compareMain(highVersion) === 0) {
          if (lowVersion.minor && !lowVersion.patch) {
            return "minor";
          }
          return "patch";
        }
      }
      const prefix = highHasPre ? "pre" : "";
      if (v1.major !== v2.major) {
        return prefix + "major";
      }
      if (v1.minor !== v2.minor) {
        return prefix + "minor";
      }
      if (v1.patch !== v2.patch) {
        return prefix + "patch";
      }
      return "prerelease";
    };
    module.exports = diff;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/major.js
var require_major = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/major.js"(exports, module) {
    "use strict";
    var SemVer = require_semver();
    var major = (a, loose) => new SemVer(a, loose).major;
    module.exports = major;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/minor.js
var require_minor = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/minor.js"(exports, module) {
    "use strict";
    var SemVer = require_semver();
    var minor = (a, loose) => new SemVer(a, loose).minor;
    module.exports = minor;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/patch.js
var require_patch = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/patch.js"(exports, module) {
    "use strict";
    var SemVer = require_semver();
    var patch = (a, loose) => new SemVer(a, loose).patch;
    module.exports = patch;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/prerelease.js
var require_prerelease = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/prerelease.js"(exports, module) {
    "use strict";
    var parse3 = require_parse2();
    var prerelease = (version3, options) => {
      const parsed = parse3(version3, options);
      return parsed && parsed.prerelease.length ? parsed.prerelease : null;
    };
    module.exports = prerelease;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/compare.js
var require_compare = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/compare.js"(exports, module) {
    "use strict";
    var SemVer = require_semver();
    var compare2 = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose));
    module.exports = compare2;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/rcompare.js
var require_rcompare = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/rcompare.js"(exports, module) {
    "use strict";
    var compare2 = require_compare();
    var rcompare = (a, b, loose) => compare2(b, a, loose);
    module.exports = rcompare;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/compare-loose.js
var require_compare_loose = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/compare-loose.js"(exports, module) {
    "use strict";
    var compare2 = require_compare();
    var compareLoose = (a, b) => compare2(a, b, true);
    module.exports = compareLoose;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/compare-build.js
var require_compare_build = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/compare-build.js"(exports, module) {
    "use strict";
    var SemVer = require_semver();
    var compareBuild = (a, b, loose) => {
      const versionA = new SemVer(a, loose);
      const versionB = new SemVer(b, loose);
      return versionA.compare(versionB) || versionA.compareBuild(versionB);
    };
    module.exports = compareBuild;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/sort.js
var require_sort = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/sort.js"(exports, module) {
    "use strict";
    var compareBuild = require_compare_build();
    var sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose));
    module.exports = sort;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/rsort.js
var require_rsort = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/rsort.js"(exports, module) {
    "use strict";
    var compareBuild = require_compare_build();
    var rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose));
    module.exports = rsort;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/gt.js
var require_gt = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/gt.js"(exports, module) {
    "use strict";
    var compare2 = require_compare();
    var gt2 = (a, b, loose) => compare2(a, b, loose) > 0;
    module.exports = gt2;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/lt.js
var require_lt = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/lt.js"(exports, module) {
    "use strict";
    var compare2 = require_compare();
    var lt3 = (a, b, loose) => compare2(a, b, loose) < 0;
    module.exports = lt3;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/eq.js
var require_eq = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/eq.js"(exports, module) {
    "use strict";
    var compare2 = require_compare();
    var eq2 = (a, b, loose) => compare2(a, b, loose) === 0;
    module.exports = eq2;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/neq.js
var require_neq = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/neq.js"(exports, module) {
    "use strict";
    var compare2 = require_compare();
    var neq = (a, b, loose) => compare2(a, b, loose) !== 0;
    module.exports = neq;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/gte.js
var require_gte = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/gte.js"(exports, module) {
    "use strict";
    var compare2 = require_compare();
    var gte4 = (a, b, loose) => compare2(a, b, loose) >= 0;
    module.exports = gte4;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/lte.js
var require_lte = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/lte.js"(exports, module) {
    "use strict";
    var compare2 = require_compare();
    var lte2 = (a, b, loose) => compare2(a, b, loose) <= 0;
    module.exports = lte2;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/cmp.js
var require_cmp = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/cmp.js"(exports, module) {
    "use strict";
    var eq2 = require_eq();
    var neq = require_neq();
    var gt2 = require_gt();
    var gte4 = require_gte();
    var lt3 = require_lt();
    var lte2 = require_lte();
    var cmp = (a, op, b, loose) => {
      switch (op) {
        case "===":
          if (typeof a === "object") {
            a = a.version;
          }
          if (typeof b === "object") {
            b = b.version;
          }
          return a === b;
        case "!==":
          if (typeof a === "object") {
            a = a.version;
          }
          if (typeof b === "object") {
            b = b.version;
          }
          return a !== b;
        case "":
        case "=":
        case "==":
          return eq2(a, b, loose);
        case "!=":
          return neq(a, b, loose);
        case ">":
          return gt2(a, b, loose);
        case ">=":
          return gte4(a, b, loose);
        case "<":
          return lt3(a, b, loose);
        case "<=":
          return lte2(a, b, loose);
        default:
          throw new TypeError(`Invalid operator: ${op}`);
      }
    };
    module.exports = cmp;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/coerce.js
var require_coerce = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/coerce.js"(exports, module) {
    "use strict";
    var SemVer = require_semver();
    var parse3 = require_parse2();
    var { safeRe: re, t } = require_re();
    var coerce2 = (version3, options) => {
      if (version3 instanceof SemVer) {
        return version3;
      }
      if (typeof version3 === "number") {
        version3 = String(version3);
      }
      if (typeof version3 !== "string") {
        return null;
      }
      options = options || {};
      let match = null;
      if (!options.rtl) {
        match = version3.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]);
      } else {
        const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL];
        let next;
        while ((next = coerceRtlRegex.exec(version3)) && (!match || match.index + match[0].length !== version3.length)) {
          if (!match || next.index + next[0].length !== match.index + match[0].length) {
            match = next;
          }
          coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length;
        }
        coerceRtlRegex.lastIndex = -1;
      }
      if (match === null) {
        return null;
      }
      const major = match[2];
      const minor = match[3] || "0";
      const patch = match[4] || "0";
      const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : "";
      const build = options.includePrerelease && match[6] ? `+${match[6]}` : "";
      return parse3(`${major}.${minor}.${patch}${prerelease}${build}`, options);
    };
    module.exports = coerce2;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/truncate.js
var require_truncate = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/truncate.js"(exports, module) {
    "use strict";
    var parse3 = require_parse2();
    var constants = require_constants4();
    var SemVer = require_semver();
    var truncate = (version3, truncation, options) => {
      if (!constants.RELEASE_TYPES.includes(truncation)) {
        return null;
      }
      const clonedVersion = cloneInputVersion(version3, options);
      return clonedVersion && doTruncation(clonedVersion, truncation);
    };
    var cloneInputVersion = (version3, options) => {
      const versionStringToParse = version3 instanceof SemVer ? version3.version : version3;
      return parse3(versionStringToParse, options);
    };
    var doTruncation = (version3, truncation) => {
      if (isPrerelease(truncation)) {
        return version3.version;
      }
      version3.prerelease = [];
      switch (truncation) {
        case "major":
          version3.minor = 0;
          version3.patch = 0;
          break;
        case "minor":
          version3.patch = 0;
          break;
      }
      return version3.format();
    };
    var isPrerelease = (type) => {
      return type.startsWith("pre");
    };
    module.exports = truncate;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/internal/lrucache.js
var require_lrucache = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/internal/lrucache.js"(exports, module) {
    "use strict";
    var LRUCache = class {
      constructor() {
        this.max = 1e3;
        this.map = /* @__PURE__ */ new Map();
      }
      get(key) {
        const value = this.map.get(key);
        if (value === void 0) {
          return void 0;
        } else {
          this.map.delete(key);
          this.map.set(key, value);
          return value;
        }
      }
      delete(key) {
        return this.map.delete(key);
      }
      set(key, value) {
        const deleted = this.delete(key);
        if (!deleted && value !== void 0) {
          if (this.map.size >= this.max) {
            const firstKey = this.map.keys().next().value;
            this.delete(firstKey);
          }
          this.map.set(key, value);
        }
        return this;
      }
    };
    module.exports = LRUCache;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/classes/range.js
var require_range2 = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/classes/range.js"(exports, module) {
    "use strict";
    var SPACE_CHARACTERS = /\s+/g;
    var Range = class _Range {
      constructor(range, options) {
        options = parseOptions2(options);
        if (range instanceof _Range) {
          if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
            return range;
          } else {
            return new _Range(range.raw, options);
          }
        }
        if (range instanceof Comparator) {
          this.raw = range.value;
          this.set = [[range]];
          this.formatted = void 0;
          return this;
        }
        this.options = options;
        this.loose = !!options.loose;
        this.includePrerelease = !!options.includePrerelease;
        this.raw = range.trim().replace(SPACE_CHARACTERS, " ");
        this.set = this.raw.split("||").map((r) => this.parseRange(r.trim())).filter((c) => c.length);
        if (!this.set.length) {
          throw new TypeError(`Invalid SemVer Range: ${this.raw}`);
        }
        if (this.set.length > 1) {
          const first = this.set[0];
          this.set = this.set.filter((c) => !isNullSet(c[0]));
          if (this.set.length === 0) {
            this.set = [first];
          } else if (this.set.length > 1) {
            for (const c of this.set) {
              if (c.length === 1 && isAny(c[0])) {
                this.set = [c];
                break;
              }
            }
          }
        }
        this.formatted = void 0;
      }
      get range() {
        if (this.formatted === void 0) {
          this.formatted = "";
          for (let i = 0; i < this.set.length; i++) {
            if (i > 0) {
              this.formatted += "||";
            }
            const comps = this.set[i];
            for (let k = 0; k < comps.length; k++) {
              if (k > 0) {
                this.formatted += " ";
              }
              this.formatted += comps[k].toString().trim();
            }
          }
        }
        return this.formatted;
      }
      format() {
        return this.range;
      }
      toString() {
        return this.range;
      }
      parseRange(range) {
        range = range.replace(BUILDSTRIPRE, "");
        const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE);
        const memoKey = memoOpts + ":" + range;
        const cached2 = cache.get(memoKey);
        if (cached2) {
          return cached2;
        }
        const loose = this.options.loose;
        const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE];
        range = range.replace(hr, hyphenReplace(this.options.includePrerelease));
        debug("hyphen replace", range);
        range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace);
        debug("comparator trim", range);
        range = range.replace(re[t.TILDETRIM], tildeTrimReplace);
        debug("tilde trim", range);
        range = range.replace(re[t.CARETTRIM], caretTrimReplace);
        debug("caret trim", range);
        let rangeList = range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options));
        if (loose) {
          rangeList = rangeList.filter((comp) => {
            debug("loose invalid filter", comp, this.options);
            return !!comp.match(re[t.COMPARATORLOOSE]);
          });
        }
        debug("range list", rangeList);
        const rangeMap = /* @__PURE__ */ new Map();
        const comparators = rangeList.map((comp) => new Comparator(comp, this.options));
        for (const comp of comparators) {
          if (isNullSet(comp)) {
            return [comp];
          }
          rangeMap.set(comp.value, comp);
        }
        if (rangeMap.size > 1 && rangeMap.has("")) {
          rangeMap.delete("");
        }
        const result = [...rangeMap.values()];
        cache.set(memoKey, result);
        return result;
      }
      intersects(range, options) {
        if (!(range instanceof _Range)) {
          throw new TypeError("a Range is required");
        }
        return this.set.some((thisComparators) => {
          return isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => {
            return isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => {
              return rangeComparators.every((rangeComparator) => {
                return thisComparator.intersects(rangeComparator, options);
              });
            });
          });
        });
      }
      // if ANY of the sets match ALL of its comparators, then pass
      test(version3) {
        if (!version3) {
          return false;
        }
        if (typeof version3 === "string") {
          try {
            version3 = new SemVer(version3, this.options);
          } catch (er) {
            return false;
          }
        }
        for (let i = 0; i < this.set.length; i++) {
          if (testSet(this.set[i], version3, this.options)) {
            return true;
          }
        }
        return false;
      }
    };
    module.exports = Range;
    var LRU = require_lrucache();
    var cache = new LRU();
    var parseOptions2 = require_parse_options();
    var Comparator = require_comparator();
    var debug = require_debug2();
    var SemVer = require_semver();
    var {
      safeRe: re,
      src,
      t,
      comparatorTrimReplace,
      tildeTrimReplace,
      caretTrimReplace
    } = require_re();
    var { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants4();
    var BUILDSTRIPRE = new RegExp(src[t.BUILD], "g");
    var isNullSet = (c) => c.value === "<0.0.0-0";
    var isAny = (c) => c.value === "";
    var isSatisfiable = (comparators, options) => {
      let result = true;
      const remainingComparators = comparators.slice();
      let testComparator = remainingComparators.pop();
      while (result && remainingComparators.length) {
        result = remainingComparators.every((otherComparator) => {
          return testComparator.intersects(otherComparator, options);
        });
        testComparator = remainingComparators.pop();
      }
      return result;
    };
    var parseComparator = (comp, options) => {
      comp = comp.replace(re[t.BUILD], "");
      debug("comp", comp, options);
      comp = replaceCarets(comp, options);
      debug("caret", comp);
      comp = replaceTildes(comp, options);
      debug("tildes", comp);
      comp = replaceXRanges(comp, options);
      debug("xrange", comp);
      comp = replaceStars(comp, options);
      debug("stars", comp);
      return comp;
    };
    var isX = (id) => !id || id.toLowerCase() === "x" || id === "*";
    var replaceTildes = (comp, options) => {
      return comp.trim().split(/\s+/).map((c) => replaceTilde(c, options)).join(" ");
    };
    var replaceTilde = (comp, options) => {
      const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE];
      return comp.replace(r, (_, M, m, p, pr) => {
        debug("tilde", comp, _, M, m, p, pr);
        let ret;
        if (isX(M)) {
          ret = "";
        } else if (isX(m)) {
          ret = `>=${M}.0.0 <${+M + 1}.0.0-0`;
        } else if (isX(p)) {
          ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`;
        } else if (pr) {
          debug("replaceTilde pr", pr);
          ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
        } else {
          ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`;
        }
        debug("tilde return", ret);
        return ret;
      });
    };
    var replaceCarets = (comp, options) => {
      return comp.trim().split(/\s+/).map((c) => replaceCaret(c, options)).join(" ");
    };
    var replaceCaret = (comp, options) => {
      debug("caret", comp, options);
      const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET];
      const z = options.includePrerelease ? "-0" : "";
      return comp.replace(r, (_, M, m, p, pr) => {
        debug("caret", comp, _, M, m, p, pr);
        let ret;
        if (isX(M)) {
          ret = "";
        } else if (isX(m)) {
          ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`;
        } else if (isX(p)) {
          if (M === "0") {
            ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`;
          } else {
            ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`;
          }
        } else if (pr) {
          debug("replaceCaret pr", pr);
          if (M === "0") {
            if (m === "0") {
              ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`;
            } else {
              ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
            }
          } else {
            ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`;
          }
        } else {
          debug("no pr");
          if (M === "0") {
            if (m === "0") {
              ret = `>=${M}.${m}.${p}${z} <${M}.${m}.${+p + 1}-0`;
            } else {
              ret = `>=${M}.${m}.${p}${z} <${M}.${+m + 1}.0-0`;
            }
          } else {
            ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`;
          }
        }
        debug("caret return", ret);
        return ret;
      });
    };
    var replaceXRanges = (comp, options) => {
      debug("replaceXRanges", comp, options);
      return comp.split(/\s+/).map((c) => replaceXRange(c, options)).join(" ");
    };
    var replaceXRange = (comp, options) => {
      comp = comp.trim();
      const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE];
      return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
        debug("xRange", comp, ret, gtlt, M, m, p, pr);
        const xM = isX(M);
        const xm = xM || isX(m);
        const xp = xm || isX(p);
        const anyX = xp;
        if (gtlt === "=" && anyX) {
          gtlt = "";
        }
        pr = options.includePrerelease ? "-0" : "";
        if (xM) {
          if (gtlt === ">" || gtlt === "<") {
            ret = "<0.0.0-0";
          } else {
            ret = "*";
          }
        } else if (gtlt && anyX) {
          if (xm) {
            m = 0;
          }
          p = 0;
          if (gtlt === ">") {
            gtlt = ">=";
            if (xm) {
              M = +M + 1;
              m = 0;
              p = 0;
            } else {
              m = +m + 1;
              p = 0;
            }
          } else if (gtlt === "<=") {
            gtlt = "<";
            if (xm) {
              M = +M + 1;
            } else {
              m = +m + 1;
            }
          }
          if (gtlt === "<") {
            pr = "-0";
          }
          ret = `${gtlt + M}.${m}.${p}${pr}`;
        } else if (xm) {
          ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;
        } else if (xp) {
          ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`;
        }
        debug("xRange return", ret);
        return ret;
      });
    };
    var replaceStars = (comp, options) => {
      debug("replaceStars", comp, options);
      return comp.trim().replace(re[t.STAR], "");
    };
    var replaceGTE0 = (comp, options) => {
      debug("replaceGTE0", comp, options);
      return comp.trim().replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], "");
    };
    var hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => {
      if (isX(fM)) {
        from = "";
      } else if (isX(fm)) {
        from = `>=${fM}.0.0${incPr ? "-0" : ""}`;
      } else if (isX(fp)) {
        from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`;
      } else if (fpr) {
        from = `>=${from}`;
      } else {
        from = `>=${from}${incPr ? "-0" : ""}`;
      }
      if (isX(tM)) {
        to = "";
      } else if (isX(tm)) {
        to = `<${+tM + 1}.0.0-0`;
      } else if (isX(tp)) {
        to = `<${tM}.${+tm + 1}.0-0`;
      } else if (tpr) {
        to = `<=${tM}.${tm}.${tp}-${tpr}`;
      } else if (incPr) {
        to = `<${tM}.${tm}.${+tp + 1}-0`;
      } else {
        to = `<=${to}`;
      }
      return `${from} ${to}`.trim();
    };
    var testSet = (set2, version3, options) => {
      for (let i = 0; i < set2.length; i++) {
        if (!set2[i].test(version3)) {
          return false;
        }
      }
      if (version3.prerelease.length && !options.includePrerelease) {
        for (let i = 0; i < set2.length; i++) {
          debug(set2[i].semver);
          if (set2[i].semver === Comparator.ANY) {
            continue;
          }
          if (set2[i].semver.prerelease.length > 0) {
            const allowed = set2[i].semver;
            if (allowed.major === version3.major && allowed.minor === version3.minor && allowed.patch === version3.patch) {
              return true;
            }
          }
        }
        return false;
      }
      return true;
    };
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/classes/comparator.js
var require_comparator = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/classes/comparator.js"(exports, module) {
    "use strict";
    var ANY = /* @__PURE__ */ Symbol("SemVer ANY");
    var Comparator = class _Comparator {
      static get ANY() {
        return ANY;
      }
      constructor(comp, options) {
        options = parseOptions2(options);
        if (comp instanceof _Comparator) {
          if (comp.loose === !!options.loose) {
            return comp;
          } else {
            comp = comp.value;
          }
        }
        comp = comp.trim().split(/\s+/).join(" ");
        debug("comparator", comp, options);
        this.options = options;
        this.loose = !!options.loose;
        this.parse(comp);
        if (this.semver === ANY) {
          this.value = "";
        } else {
          this.value = this.operator + this.semver.version;
        }
        debug("comp", this);
      }
      parse(comp) {
        const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
        const m = comp.match(r);
        if (!m) {
          throw new TypeError(`Invalid comparator: ${comp}`);
        }
        this.operator = m[1] !== void 0 ? m[1] : "";
        if (this.operator === "=") {
          this.operator = "";
        }
        if (!m[2]) {
          this.semver = ANY;
        } else {
          this.semver = new SemVer(m[2], this.options.loose);
        }
      }
      toString() {
        return this.value;
      }
      test(version3) {
        debug("Comparator.test", version3, this.options.loose);
        if (this.semver === ANY || version3 === ANY) {
          return true;
        }
        if (typeof version3 === "string") {
          try {
            version3 = new SemVer(version3, this.options);
          } catch (er) {
            return false;
          }
        }
        return cmp(version3, this.operator, this.semver, this.options);
      }
      intersects(comp, options) {
        if (!(comp instanceof _Comparator)) {
          throw new TypeError("a Comparator is required");
        }
        if (this.operator === "") {
          if (this.value === "") {
            return true;
          }
          return new Range(comp.value, options).test(this.value);
        } else if (comp.operator === "") {
          if (comp.value === "") {
            return true;
          }
          return new Range(this.value, options).test(comp.semver);
        }
        options = parseOptions2(options);
        if (options.includePrerelease && (this.value === "<0.0.0-0" || comp.value === "<0.0.0-0")) {
          return false;
        }
        if (!options.includePrerelease && (this.value.startsWith("<0.0.0") || comp.value.startsWith("<0.0.0"))) {
          return false;
        }
        if (this.operator.startsWith(">") && comp.operator.startsWith(">")) {
          return true;
        }
        if (this.operator.startsWith("<") && comp.operator.startsWith("<")) {
          return true;
        }
        if (this.semver.version === comp.semver.version && this.operator.includes("=") && comp.operator.includes("=")) {
          return true;
        }
        if (cmp(this.semver, "<", comp.semver, options) && this.operator.startsWith(">") && comp.operator.startsWith("<")) {
          return true;
        }
        if (cmp(this.semver, ">", comp.semver, options) && this.operator.startsWith("<") && comp.operator.startsWith(">")) {
          return true;
        }
        return false;
      }
    };
    module.exports = Comparator;
    var parseOptions2 = require_parse_options();
    var { safeRe: re, t } = require_re();
    var cmp = require_cmp();
    var debug = require_debug2();
    var SemVer = require_semver();
    var Range = require_range2();
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/satisfies.js
var require_satisfies = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/functions/satisfies.js"(exports, module) {
    "use strict";
    var Range = require_range2();
    var satisfies = (version3, range, options) => {
      try {
        range = new Range(range, options);
      } catch (er) {
        return false;
      }
      return range.test(version3);
    };
    module.exports = satisfies;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/ranges/to-comparators.js
var require_to_comparators = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/ranges/to-comparators.js"(exports, module) {
    "use strict";
    var Range = require_range2();
    var toComparators = (range, options) => new Range(range, options).set.map((comp) => comp.map((c) => c.value).join(" ").trim().split(" "));
    module.exports = toComparators;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/ranges/max-satisfying.js
var require_max_satisfying = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/ranges/max-satisfying.js"(exports, module) {
    "use strict";
    var SemVer = require_semver();
    var Range = require_range2();
    var maxSatisfying = (versions, range, options) => {
      let max = null;
      let maxSV = null;
      let rangeObj = null;
      try {
        rangeObj = new Range(range, options);
      } catch (er) {
        return null;
      }
      versions.forEach((v) => {
        if (rangeObj.test(v)) {
          if (!max || maxSV.compare(v) === -1) {
            max = v;
            maxSV = new SemVer(max, options);
          }
        }
      });
      return max;
    };
    module.exports = maxSatisfying;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/ranges/min-satisfying.js
var require_min_satisfying = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/ranges/min-satisfying.js"(exports, module) {
    "use strict";
    var SemVer = require_semver();
    var Range = require_range2();
    var minSatisfying = (versions, range, options) => {
      let min = null;
      let minSV = null;
      let rangeObj = null;
      try {
        rangeObj = new Range(range, options);
      } catch (er) {
        return null;
      }
      versions.forEach((v) => {
        if (rangeObj.test(v)) {
          if (!min || minSV.compare(v) === 1) {
            min = v;
            minSV = new SemVer(min, options);
          }
        }
      });
      return min;
    };
    module.exports = minSatisfying;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/ranges/min-version.js
var require_min_version = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/ranges/min-version.js"(exports, module) {
    "use strict";
    var SemVer = require_semver();
    var Range = require_range2();
    var gt2 = require_gt();
    var minVersion = (range, loose) => {
      range = new Range(range, loose);
      let minver = new SemVer("0.0.0");
      if (range.test(minver)) {
        return minver;
      }
      minver = new SemVer("0.0.0-0");
      if (range.test(minver)) {
        return minver;
      }
      minver = null;
      for (let i = 0; i < range.set.length; ++i) {
        const comparators = range.set[i];
        let setMin = null;
        comparators.forEach((comparator) => {
          const compver = new SemVer(comparator.semver.version);
          switch (comparator.operator) {
            case ">":
              if (compver.prerelease.length === 0) {
                compver.patch++;
              } else {
                compver.prerelease.push(0);
              }
              compver.raw = compver.format();
            /* fallthrough */
            case "":
            case ">=":
              if (!setMin || gt2(compver, setMin)) {
                setMin = compver;
              }
              break;
            case "<":
            case "<=":
              break;
            /* istanbul ignore next */
            default:
              throw new Error(`Unexpected operation: ${comparator.operator}`);
          }
        });
        if (setMin && (!minver || gt2(minver, setMin))) {
          minver = setMin;
        }
      }
      if (minver && range.test(minver)) {
        return minver;
      }
      return null;
    };
    module.exports = minVersion;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/ranges/valid.js
var require_valid2 = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/ranges/valid.js"(exports, module) {
    "use strict";
    var Range = require_range2();
    var validRange = (range, options) => {
      try {
        return new Range(range, options).range || "*";
      } catch (er) {
        return null;
      }
    };
    module.exports = validRange;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/ranges/outside.js
var require_outside = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/ranges/outside.js"(exports, module) {
    "use strict";
    var SemVer = require_semver();
    var Comparator = require_comparator();
    var { ANY } = Comparator;
    var Range = require_range2();
    var satisfies = require_satisfies();
    var gt2 = require_gt();
    var lt3 = require_lt();
    var lte2 = require_lte();
    var gte4 = require_gte();
    var outside = (version3, range, hilo, options) => {
      version3 = new SemVer(version3, options);
      range = new Range(range, options);
      let gtfn, ltefn, ltfn, comp, ecomp;
      switch (hilo) {
        case ">":
          gtfn = gt2;
          ltefn = lte2;
          ltfn = lt3;
          comp = ">";
          ecomp = ">=";
          break;
        case "<":
          gtfn = lt3;
          ltefn = gte4;
          ltfn = gt2;
          comp = "<";
          ecomp = "<=";
          break;
        default:
          throw new TypeError('Must provide a hilo val of "<" or ">"');
      }
      if (satisfies(version3, range, options)) {
        return false;
      }
      for (let i = 0; i < range.set.length; ++i) {
        const comparators = range.set[i];
        let high = null;
        let low = null;
        comparators.forEach((comparator) => {
          if (comparator.semver === ANY) {
            comparator = new Comparator(">=0.0.0");
          }
          high = high || comparator;
          low = low || comparator;
          if (gtfn(comparator.semver, high.semver, options)) {
            high = comparator;
          } else if (ltfn(comparator.semver, low.semver, options)) {
            low = comparator;
          }
        });
        if (high.operator === comp || high.operator === ecomp) {
          return false;
        }
        if ((!low.operator || low.operator === comp) && ltefn(version3, low.semver)) {
          return false;
        } else if (low.operator === ecomp && ltfn(version3, low.semver)) {
          return false;
        }
      }
      return true;
    };
    module.exports = outside;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/ranges/gtr.js
var require_gtr = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/ranges/gtr.js"(exports, module) {
    "use strict";
    var outside = require_outside();
    var gtr = (version3, range, options) => outside(version3, range, ">", options);
    module.exports = gtr;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/ranges/ltr.js
var require_ltr = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/ranges/ltr.js"(exports, module) {
    "use strict";
    var outside = require_outside();
    var ltr = (version3, range, options) => outside(version3, range, "<", options);
    module.exports = ltr;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/ranges/intersects.js
var require_intersects = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/ranges/intersects.js"(exports, module) {
    "use strict";
    var Range = require_range2();
    var intersects = (r1, r2, options) => {
      r1 = new Range(r1, options);
      r2 = new Range(r2, options);
      return r1.intersects(r2, options);
    };
    module.exports = intersects;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/ranges/simplify.js
var require_simplify = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/ranges/simplify.js"(exports, module) {
    "use strict";
    var satisfies = require_satisfies();
    var compare2 = require_compare();
    module.exports = (versions, range, options) => {
      const set2 = [];
      let first = null;
      let prev = null;
      const v = versions.sort((a, b) => compare2(a, b, options));
      for (const version3 of v) {
        const included = satisfies(version3, range, options);
        if (included) {
          prev = version3;
          if (!first) {
            first = version3;
          }
        } else {
          if (prev) {
            set2.push([first, prev]);
          }
          prev = null;
          first = null;
        }
      }
      if (first) {
        set2.push([first, null]);
      }
      const ranges = [];
      for (const [min, max] of set2) {
        if (min === max) {
          ranges.push(min);
        } else if (!max && min === v[0]) {
          ranges.push("*");
        } else if (!max) {
          ranges.push(`>=${min}`);
        } else if (min === v[0]) {
          ranges.push(`<=${max}`);
        } else {
          ranges.push(`${min} - ${max}`);
        }
      }
      const simplified = ranges.join(" || ");
      const original = typeof range.raw === "string" ? range.raw : String(range);
      return simplified.length < original.length ? simplified : range;
    };
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/ranges/subset.js
var require_subset = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/ranges/subset.js"(exports, module) {
    "use strict";
    var Range = require_range2();
    var Comparator = require_comparator();
    var { ANY } = Comparator;
    var satisfies = require_satisfies();
    var compare2 = require_compare();
    var subset = (sub, dom, options = {}) => {
      if (sub === dom) {
        return true;
      }
      sub = new Range(sub, options);
      dom = new Range(dom, options);
      let sawNonNull = false;
      OUTER: for (const simpleSub of sub.set) {
        for (const simpleDom of dom.set) {
          const isSub = simpleSubset(simpleSub, simpleDom, options);
          sawNonNull = sawNonNull || isSub !== null;
          if (isSub) {
            continue OUTER;
          }
        }
        if (sawNonNull) {
          return false;
        }
      }
      return true;
    };
    var minimumVersionWithPreRelease = [new Comparator(">=0.0.0-0")];
    var minimumVersion = [new Comparator(">=0.0.0")];
    var simpleSubset = (sub, dom, options) => {
      if (sub === dom) {
        return true;
      }
      if (sub.length === 1 && sub[0].semver === ANY) {
        if (dom.length === 1 && dom[0].semver === ANY) {
          return true;
        } else if (options.includePrerelease) {
          sub = minimumVersionWithPreRelease;
        } else {
          sub = minimumVersion;
        }
      }
      if (dom.length === 1 && dom[0].semver === ANY) {
        if (options.includePrerelease) {
          return true;
        } else {
          dom = minimumVersion;
        }
      }
      const eqSet = /* @__PURE__ */ new Set();
      let gt2, lt3;
      for (const c of sub) {
        if (c.operator === ">" || c.operator === ">=") {
          gt2 = higherGT(gt2, c, options);
        } else if (c.operator === "<" || c.operator === "<=") {
          lt3 = lowerLT(lt3, c, options);
        } else {
          eqSet.add(c.semver);
        }
      }
      if (eqSet.size > 1) {
        return null;
      }
      let gtltComp;
      if (gt2 && lt3) {
        gtltComp = compare2(gt2.semver, lt3.semver, options);
        if (gtltComp > 0) {
          return null;
        } else if (gtltComp === 0 && (gt2.operator !== ">=" || lt3.operator !== "<=")) {
          return null;
        }
      }
      for (const eq2 of eqSet) {
        if (gt2 && !satisfies(eq2, String(gt2), options)) {
          return null;
        }
        if (lt3 && !satisfies(eq2, String(lt3), options)) {
          return null;
        }
        for (const c of dom) {
          if (!satisfies(eq2, String(c), options)) {
            return false;
          }
        }
        return true;
      }
      let higher, lower;
      let hasDomLT, hasDomGT;
      let needDomLTPre = lt3 && !options.includePrerelease && lt3.semver.prerelease.length ? lt3.semver : false;
      let needDomGTPre = gt2 && !options.includePrerelease && gt2.semver.prerelease.length ? gt2.semver : false;
      if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt3.operator === "<" && needDomLTPre.prerelease[0] === 0) {
        needDomLTPre = false;
      }
      for (const c of dom) {
        hasDomGT = hasDomGT || c.operator === ">" || c.operator === ">=";
        hasDomLT = hasDomLT || c.operator === "<" || c.operator === "<=";
        if (gt2) {
          if (needDomGTPre) {
            if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) {
              needDomGTPre = false;
            }
          }
          if (c.operator === ">" || c.operator === ">=") {
            higher = higherGT(gt2, c, options);
            if (higher === c && higher !== gt2) {
              return false;
            }
          } else if (gt2.operator === ">=" && !c.test(gt2.semver)) {
            return false;
          }
        }
        if (lt3) {
          if (needDomLTPre) {
            if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) {
              needDomLTPre = false;
            }
          }
          if (c.operator === "<" || c.operator === "<=") {
            lower = lowerLT(lt3, c, options);
            if (lower === c && lower !== lt3) {
              return false;
            }
          } else if (lt3.operator === "<=" && !c.test(lt3.semver)) {
            return false;
          }
        }
        if (!c.operator && (lt3 || gt2) && gtltComp !== 0) {
          return false;
        }
      }
      if (gt2 && hasDomLT && !lt3 && gtltComp !== 0) {
        return false;
      }
      if (lt3 && hasDomGT && !gt2 && gtltComp !== 0) {
        return false;
      }
      if (needDomGTPre || needDomLTPre) {
        return false;
      }
      return true;
    };
    var higherGT = (a, b, options) => {
      if (!a) {
        return b;
      }
      const comp = compare2(a.semver, b.semver, options);
      return comp > 0 ? a : comp < 0 ? b : b.operator === ">" && a.operator === ">=" ? b : a;
    };
    var lowerLT = (a, b, options) => {
      if (!a) {
        return b;
      }
      const comp = compare2(a.semver, b.semver, options);
      return comp < 0 ? a : comp > 0 ? b : b.operator === "<" && a.operator === "<=" ? b : a;
    };
    module.exports = subset;
  }
});

// ../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/index.js
var require_semver2 = __commonJS({
  "../../node_modules/.pnpm/semver@7.8.1/node_modules/semver/index.js"(exports, module) {
    "use strict";
    var internalRe = require_re();
    var constants = require_constants4();
    var SemVer = require_semver();
    var identifiers = require_identifiers();
    var parse3 = require_parse2();
    var valid = require_valid();
    var clean = require_clean();
    var inc = require_inc();
    var diff = require_diff();
    var major = require_major();
    var minor = require_minor();
    var patch = require_patch();
    var prerelease = require_prerelease();
    var compare2 = require_compare();
    var rcompare = require_rcompare();
    var compareLoose = require_compare_loose();
    var compareBuild = require_compare_build();
    var sort = require_sort();
    var rsort = require_rsort();
    var gt2 = require_gt();
    var lt3 = require_lt();
    var eq2 = require_eq();
    var neq = require_neq();
    var gte4 = require_gte();
    var lte2 = require_lte();
    var cmp = require_cmp();
    var coerce2 = require_coerce();
    var truncate = require_truncate();
    var Comparator = require_comparator();
    var Range = require_range2();
    var satisfies = require_satisfies();
    var toComparators = require_to_comparators();
    var maxSatisfying = require_max_satisfying();
    var minSatisfying = require_min_satisfying();
    var minVersion = require_min_version();
    var validRange = require_valid2();
    var outside = require_outside();
    var gtr = require_gtr();
    var ltr = require_ltr();
    var intersects = require_intersects();
    var simplifyRange = require_simplify();
    var subset = require_subset();
    module.exports = {
      parse: parse3,
      valid,
      clean,
      inc,
      diff,
      major,
      minor,
      patch,
      prerelease,
      compare: compare2,
      rcompare,
      compareLoose,
      compareBuild,
      sort,
      rsort,
      gt: gt2,
      lt: lt3,
      eq: eq2,
      neq,
      gte: gte4,
      lte: lte2,
      cmp,
      coerce: coerce2,
      truncate,
      Comparator,
      Range,
      satisfies,
      toComparators,
      maxSatisfying,
      minSatisfying,
      minVersion,
      validRange,
      outside,
      gtr,
      ltr,
      intersects,
      simplifyRange,
      subset,
      SemVer,
      re: internalRe.re,
      src: internalRe.src,
      tokens: internalRe.t,
      SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,
      RELEASE_TYPES: constants.RELEASE_TYPES,
      compareIdentifiers: identifiers.compareIdentifiers,
      rcompareIdentifiers: identifiers.rcompareIdentifiers
    };
  }
});

// ../../node_modules/.pnpm/jsonwebtoken@9.0.3/node_modules/jsonwebtoken/lib/asymmetricKeyDetailsSupported.js
var require_asymmetricKeyDetailsSupported = __commonJS({
  "../../node_modules/.pnpm/jsonwebtoken@9.0.3/node_modules/jsonwebtoken/lib/asymmetricKeyDetailsSupported.js"(exports, module) {
    var semver = require_semver2();
    module.exports = semver.satisfies(process.version, ">=15.7.0");
  }
});

// ../../node_modules/.pnpm/jsonwebtoken@9.0.3/node_modules/jsonwebtoken/lib/rsaPssKeyDetailsSupported.js
var require_rsaPssKeyDetailsSupported = __commonJS({
  "../../node_modules/.pnpm/jsonwebtoken@9.0.3/node_modules/jsonwebtoken/lib/rsaPssKeyDetailsSupported.js"(exports, module) {
    var semver = require_semver2();
    module.exports = semver.satisfies(process.version, ">=16.9.0");
  }
});

// ../../node_modules/.pnpm/jsonwebtoken@9.0.3/node_modules/jsonwebtoken/lib/validateAsymmetricKey.js
var require_validateAsymmetricKey = __commonJS({
  "../../node_modules/.pnpm/jsonwebtoken@9.0.3/node_modules/jsonwebtoken/lib/validateAsymmetricKey.js"(exports, module) {
    var ASYMMETRIC_KEY_DETAILS_SUPPORTED = require_asymmetricKeyDetailsSupported();
    var RSA_PSS_KEY_DETAILS_SUPPORTED = require_rsaPssKeyDetailsSupported();
    var allowedAlgorithmsForKeys = {
      "ec": ["ES256", "ES384", "ES512"],
      "rsa": ["RS256", "PS256", "RS384", "PS384", "RS512", "PS512"],
      "rsa-pss": ["PS256", "PS384", "PS512"]
    };
    var allowedCurves = {
      ES256: "prime256v1",
      ES384: "secp384r1",
      ES512: "secp521r1"
    };
    module.exports = function(algorithm, key) {
      if (!algorithm || !key) return;
      const keyType = key.asymmetricKeyType;
      if (!keyType) return;
      const allowedAlgorithms = allowedAlgorithmsForKeys[keyType];
      if (!allowedAlgorithms) {
        throw new Error(`Unknown key type "${keyType}".`);
      }
      if (!allowedAlgorithms.includes(algorithm)) {
        throw new Error(`"alg" parameter for "${keyType}" key type must be one of: ${allowedAlgorithms.join(", ")}.`);
      }
      if (ASYMMETRIC_KEY_DETAILS_SUPPORTED) {
        switch (keyType) {
          case "ec":
            const keyCurve = key.asymmetricKeyDetails.namedCurve;
            const allowedCurve = allowedCurves[algorithm];
            if (keyCurve !== allowedCurve) {
              throw new Error(`"alg" parameter "${algorithm}" requires curve "${allowedCurve}".`);
            }
            break;
          case "rsa-pss":
            if (RSA_PSS_KEY_DETAILS_SUPPORTED) {
              const length = parseInt(algorithm.slice(-3), 10);
              const { hashAlgorithm, mgf1HashAlgorithm, saltLength } = key.asymmetricKeyDetails;
              if (hashAlgorithm !== `sha${length}` || mgf1HashAlgorithm !== hashAlgorithm) {
                throw new Error(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${algorithm}.`);
              }
              if (saltLength !== void 0 && saltLength > length >> 3) {
                throw new Error(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${algorithm}.`);
              }
            }
            break;
        }
      }
    };
  }
});

// ../../node_modules/.pnpm/jsonwebtoken@9.0.3/node_modules/jsonwebtoken/lib/psSupported.js
var require_psSupported = __commonJS({
  "../../node_modules/.pnpm/jsonwebtoken@9.0.3/node_modules/jsonwebtoken/lib/psSupported.js"(exports, module) {
    var semver = require_semver2();
    module.exports = semver.satisfies(process.version, "^6.12.0 || >=8.0.0");
  }
});

// ../../node_modules/.pnpm/jsonwebtoken@9.0.3/node_modules/jsonwebtoken/verify.js
var require_verify = __commonJS({
  "../../node_modules/.pnpm/jsonwebtoken@9.0.3/node_modules/jsonwebtoken/verify.js"(exports, module) {
    var JsonWebTokenError = require_JsonWebTokenError();
    var NotBeforeError = require_NotBeforeError();
    var TokenExpiredError = require_TokenExpiredError();
    var decode = require_decode();
    var timespan = require_timespan();
    var validateAsymmetricKey = require_validateAsymmetricKey();
    var PS_SUPPORTED = require_psSupported();
    var jws = require_jws();
    var { KeyObject, createSecretKey, createPublicKey } = __require("crypto");
    var PUB_KEY_ALGS = ["RS256", "RS384", "RS512"];
    var EC_KEY_ALGS = ["ES256", "ES384", "ES512"];
    var RSA_KEY_ALGS = ["RS256", "RS384", "RS512"];
    var HS_ALGS = ["HS256", "HS384", "HS512"];
    if (PS_SUPPORTED) {
      PUB_KEY_ALGS.splice(PUB_KEY_ALGS.length, 0, "PS256", "PS384", "PS512");
      RSA_KEY_ALGS.splice(RSA_KEY_ALGS.length, 0, "PS256", "PS384", "PS512");
    }
    module.exports = function(jwtString, secretOrPublicKey, options, callback) {
      if (typeof options === "function" && !callback) {
        callback = options;
        options = {};
      }
      if (!options) {
        options = {};
      }
      options = Object.assign({}, options);
      let done;
      if (callback) {
        done = callback;
      } else {
        done = function(err, data) {
          if (err) throw err;
          return data;
        };
      }
      if (options.clockTimestamp && typeof options.clockTimestamp !== "number") {
        return done(new JsonWebTokenError("clockTimestamp must be a number"));
      }
      if (options.nonce !== void 0 && (typeof options.nonce !== "string" || options.nonce.trim() === "")) {
        return done(new JsonWebTokenError("nonce must be a non-empty string"));
      }
      if (options.allowInvalidAsymmetricKeyTypes !== void 0 && typeof options.allowInvalidAsymmetricKeyTypes !== "boolean") {
        return done(new JsonWebTokenError("allowInvalidAsymmetricKeyTypes must be a boolean"));
      }
      const clockTimestamp = options.clockTimestamp || Math.floor(Date.now() / 1e3);
      if (!jwtString) {
        return done(new JsonWebTokenError("jwt must be provided"));
      }
      if (typeof jwtString !== "string") {
        return done(new JsonWebTokenError("jwt must be a string"));
      }
      const parts = jwtString.split(".");
      if (parts.length !== 3) {
        return done(new JsonWebTokenError("jwt malformed"));
      }
      let decodedToken;
      try {
        decodedToken = decode(jwtString, { complete: true });
      } catch (err) {
        return done(err);
      }
      if (!decodedToken) {
        return done(new JsonWebTokenError("invalid token"));
      }
      const header = decodedToken.header;
      let getSecret;
      if (typeof secretOrPublicKey === "function") {
        if (!callback) {
          return done(new JsonWebTokenError("verify must be called asynchronous if secret or public key is provided as a callback"));
        }
        getSecret = secretOrPublicKey;
      } else {
        getSecret = function(header2, secretCallback) {
          return secretCallback(null, secretOrPublicKey);
        };
      }
      return getSecret(header, function(err, secretOrPublicKey2) {
        if (err) {
          return done(new JsonWebTokenError("error in secret or public key callback: " + err.message));
        }
        const hasSignature = parts[2].trim() !== "";
        if (!hasSignature && secretOrPublicKey2) {
          return done(new JsonWebTokenError("jwt signature is required"));
        }
        if (hasSignature && !secretOrPublicKey2) {
          return done(new JsonWebTokenError("secret or public key must be provided"));
        }
        if (!hasSignature && !options.algorithms) {
          return done(new JsonWebTokenError('please specify "none" in "algorithms" to verify unsigned tokens'));
        }
        if (secretOrPublicKey2 != null && !(secretOrPublicKey2 instanceof KeyObject)) {
          try {
            secretOrPublicKey2 = createPublicKey(secretOrPublicKey2);
          } catch (_) {
            try {
              secretOrPublicKey2 = createSecretKey(typeof secretOrPublicKey2 === "string" ? Buffer.from(secretOrPublicKey2) : secretOrPublicKey2);
            } catch (_2) {
              return done(new JsonWebTokenError("secretOrPublicKey is not valid key material"));
            }
          }
        }
        if (!options.algorithms) {
          if (secretOrPublicKey2.type === "secret") {
            options.algorithms = HS_ALGS;
          } else if (["rsa", "rsa-pss"].includes(secretOrPublicKey2.asymmetricKeyType)) {
            options.algorithms = RSA_KEY_ALGS;
          } else if (secretOrPublicKey2.asymmetricKeyType === "ec") {
            options.algorithms = EC_KEY_ALGS;
          } else {
            options.algorithms = PUB_KEY_ALGS;
          }
        }
        if (options.algorithms.indexOf(decodedToken.header.alg) === -1) {
          return done(new JsonWebTokenError("invalid algorithm"));
        }
        if (header.alg.startsWith("HS") && secretOrPublicKey2.type !== "secret") {
          return done(new JsonWebTokenError(`secretOrPublicKey must be a symmetric key when using ${header.alg}`));
        } else if (/^(?:RS|PS|ES)/.test(header.alg) && secretOrPublicKey2.type !== "public") {
          return done(new JsonWebTokenError(`secretOrPublicKey must be an asymmetric key when using ${header.alg}`));
        }
        if (!options.allowInvalidAsymmetricKeyTypes) {
          try {
            validateAsymmetricKey(header.alg, secretOrPublicKey2);
          } catch (e) {
            return done(e);
          }
        }
        let valid;
        try {
          valid = jws.verify(jwtString, decodedToken.header.alg, secretOrPublicKey2);
        } catch (e) {
          return done(e);
        }
        if (!valid) {
          return done(new JsonWebTokenError("invalid signature"));
        }
        const payload = decodedToken.payload;
        if (typeof payload.nbf !== "undefined" && !options.ignoreNotBefore) {
          if (typeof payload.nbf !== "number") {
            return done(new JsonWebTokenError("invalid nbf value"));
          }
          if (payload.nbf > clockTimestamp + (options.clockTolerance || 0)) {
            return done(new NotBeforeError("jwt not active", new Date(payload.nbf * 1e3)));
          }
        }
        if (typeof payload.exp !== "undefined" && !options.ignoreExpiration) {
          if (typeof payload.exp !== "number") {
            return done(new JsonWebTokenError("invalid exp value"));
          }
          if (clockTimestamp >= payload.exp + (options.clockTolerance || 0)) {
            return done(new TokenExpiredError("jwt expired", new Date(payload.exp * 1e3)));
          }
        }
        if (options.audience) {
          const audiences = Array.isArray(options.audience) ? options.audience : [options.audience];
          const target = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
          const match = target.some(function(targetAudience) {
            return audiences.some(function(audience) {
              return audience instanceof RegExp ? audience.test(targetAudience) : audience === targetAudience;
            });
          });
          if (!match) {
            return done(new JsonWebTokenError("jwt audience invalid. expected: " + audiences.join(" or ")));
          }
        }
        if (options.issuer) {
          const invalid_issuer = typeof options.issuer === "string" && payload.iss !== options.issuer || Array.isArray(options.issuer) && options.issuer.indexOf(payload.iss) === -1;
          if (invalid_issuer) {
            return done(new JsonWebTokenError("jwt issuer invalid. expected: " + options.issuer));
          }
        }
        if (options.subject) {
          if (payload.sub !== options.subject) {
            return done(new JsonWebTokenError("jwt subject invalid. expected: " + options.subject));
          }
        }
        if (options.jwtid) {
          if (payload.jti !== options.jwtid) {
            return done(new JsonWebTokenError("jwt jwtid invalid. expected: " + options.jwtid));
          }
        }
        if (options.nonce) {
          if (payload.nonce !== options.nonce) {
            return done(new JsonWebTokenError("jwt nonce invalid. expected: " + options.nonce));
          }
        }
        if (options.maxAge) {
          if (typeof payload.iat !== "number") {
            return done(new JsonWebTokenError("iat required when maxAge is specified"));
          }
          const maxAgeTimestamp = timespan(options.maxAge, payload.iat);
          if (typeof maxAgeTimestamp === "undefined") {
            return done(new JsonWebTokenError('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));
          }
          if (clockTimestamp >= maxAgeTimestamp + (options.clockTolerance || 0)) {
            return done(new TokenExpiredError("maxAge exceeded", new Date(maxAgeTimestamp * 1e3)));
          }
        }
        if (options.complete === true) {
          const signature = decodedToken.signature;
          return done(null, {
            header,
            payload,
            signature
          });
        }
        return done(null, payload);
      });
    };
  }
});

// ../../node_modules/.pnpm/lodash.includes@4.3.0/node_modules/lodash.includes/index.js
var require_lodash = __commonJS({
  "../../node_modules/.pnpm/lodash.includes@4.3.0/node_modules/lodash.includes/index.js"(exports, module) {
    var INFINITY = 1 / 0;
    var MAX_SAFE_INTEGER = 9007199254740991;
    var MAX_INTEGER = 17976931348623157e292;
    var NAN = 0 / 0;
    var argsTag = "[object Arguments]";
    var funcTag = "[object Function]";
    var genTag = "[object GeneratorFunction]";
    var stringTag = "[object String]";
    var symbolTag = "[object Symbol]";
    var reTrim = /^\s+|\s+$/g;
    var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
    var reIsBinary = /^0b[01]+$/i;
    var reIsOctal = /^0o[0-7]+$/i;
    var reIsUint = /^(?:0|[1-9]\d*)$/;
    var freeParseInt = parseInt;
    function arrayMap(array2, iteratee) {
      var index2 = -1, length = array2 ? array2.length : 0, result = Array(length);
      while (++index2 < length) {
        result[index2] = iteratee(array2[index2], index2, array2);
      }
      return result;
    }
    function baseFindIndex(array2, predicate, fromIndex, fromRight) {
      var length = array2.length, index2 = fromIndex + (fromRight ? 1 : -1);
      while (fromRight ? index2-- : ++index2 < length) {
        if (predicate(array2[index2], index2, array2)) {
          return index2;
        }
      }
      return -1;
    }
    function baseIndexOf(array2, value, fromIndex) {
      if (value !== value) {
        return baseFindIndex(array2, baseIsNaN, fromIndex);
      }
      var index2 = fromIndex - 1, length = array2.length;
      while (++index2 < length) {
        if (array2[index2] === value) {
          return index2;
        }
      }
      return -1;
    }
    function baseIsNaN(value) {
      return value !== value;
    }
    function baseTimes(n, iteratee) {
      var index2 = -1, result = Array(n);
      while (++index2 < n) {
        result[index2] = iteratee(index2);
      }
      return result;
    }
    function baseValues(object2, props) {
      return arrayMap(props, function(key) {
        return object2[key];
      });
    }
    function overArg(func, transform2) {
      return function(arg) {
        return func(transform2(arg));
      };
    }
    var objectProto = Object.prototype;
    var hasOwnProperty = objectProto.hasOwnProperty;
    var objectToString = objectProto.toString;
    var propertyIsEnumerable = objectProto.propertyIsEnumerable;
    var nativeKeys = overArg(Object.keys, Object);
    var nativeMax = Math.max;
    function arrayLikeKeys(value, inherited) {
      var result = isArray(value) || isArguments(value) ? baseTimes(value.length, String) : [];
      var length = result.length, skipIndexes = !!length;
      for (var key in value) {
        if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && (key == "length" || isIndex(key, length)))) {
          result.push(key);
        }
      }
      return result;
    }
    function baseKeys(object2) {
      if (!isPrototype(object2)) {
        return nativeKeys(object2);
      }
      var result = [];
      for (var key in Object(object2)) {
        if (hasOwnProperty.call(object2, key) && key != "constructor") {
          result.push(key);
        }
      }
      return result;
    }
    function isIndex(value, length) {
      length = length == null ? MAX_SAFE_INTEGER : length;
      return !!length && (typeof value == "number" || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length);
    }
    function isPrototype(value) {
      var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto;
      return value === proto;
    }
    function includes(collection, value, fromIndex, guard) {
      collection = isArrayLike(collection) ? collection : values(collection);
      fromIndex = fromIndex && !guard ? toInteger(fromIndex) : 0;
      var length = collection.length;
      if (fromIndex < 0) {
        fromIndex = nativeMax(length + fromIndex, 0);
      }
      return isString(collection) ? fromIndex <= length && collection.indexOf(value, fromIndex) > -1 : !!length && baseIndexOf(collection, value, fromIndex) > -1;
    }
    function isArguments(value) {
      return isArrayLikeObject(value) && hasOwnProperty.call(value, "callee") && (!propertyIsEnumerable.call(value, "callee") || objectToString.call(value) == argsTag);
    }
    var isArray = Array.isArray;
    function isArrayLike(value) {
      return value != null && isLength(value.length) && !isFunction(value);
    }
    function isArrayLikeObject(value) {
      return isObjectLike(value) && isArrayLike(value);
    }
    function isFunction(value) {
      var tag = isObject3(value) ? objectToString.call(value) : "";
      return tag == funcTag || tag == genTag;
    }
    function isLength(value) {
      return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
    }
    function isObject3(value) {
      var type = typeof value;
      return !!value && (type == "object" || type == "function");
    }
    function isObjectLike(value) {
      return !!value && typeof value == "object";
    }
    function isString(value) {
      return typeof value == "string" || !isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag;
    }
    function isSymbol(value) {
      return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;
    }
    function toFinite(value) {
      if (!value) {
        return value === 0 ? value : 0;
      }
      value = toNumber(value);
      if (value === INFINITY || value === -INFINITY) {
        var sign = value < 0 ? -1 : 1;
        return sign * MAX_INTEGER;
      }
      return value === value ? value : 0;
    }
    function toInteger(value) {
      var result = toFinite(value), remainder = result % 1;
      return result === result ? remainder ? result - remainder : result : 0;
    }
    function toNumber(value) {
      if (typeof value == "number") {
        return value;
      }
      if (isSymbol(value)) {
        return NAN;
      }
      if (isObject3(value)) {
        var other = typeof value.valueOf == "function" ? value.valueOf() : value;
        value = isObject3(other) ? other + "" : other;
      }
      if (typeof value != "string") {
        return value === 0 ? value : +value;
      }
      value = value.replace(reTrim, "");
      var isBinary = reIsBinary.test(value);
      return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
    }
    function keys(object2) {
      return isArrayLike(object2) ? arrayLikeKeys(object2) : baseKeys(object2);
    }
    function values(object2) {
      return object2 ? baseValues(object2, keys(object2)) : [];
    }
    module.exports = includes;
  }
});

// ../../node_modules/.pnpm/lodash.isboolean@3.0.3/node_modules/lodash.isboolean/index.js
var require_lodash2 = __commonJS({
  "../../node_modules/.pnpm/lodash.isboolean@3.0.3/node_modules/lodash.isboolean/index.js"(exports, module) {
    var boolTag = "[object Boolean]";
    var objectProto = Object.prototype;
    var objectToString = objectProto.toString;
    function isBoolean(value) {
      return value === true || value === false || isObjectLike(value) && objectToString.call(value) == boolTag;
    }
    function isObjectLike(value) {
      return !!value && typeof value == "object";
    }
    module.exports = isBoolean;
  }
});

// ../../node_modules/.pnpm/lodash.isinteger@4.0.4/node_modules/lodash.isinteger/index.js
var require_lodash3 = __commonJS({
  "../../node_modules/.pnpm/lodash.isinteger@4.0.4/node_modules/lodash.isinteger/index.js"(exports, module) {
    var INFINITY = 1 / 0;
    var MAX_INTEGER = 17976931348623157e292;
    var NAN = 0 / 0;
    var symbolTag = "[object Symbol]";
    var reTrim = /^\s+|\s+$/g;
    var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
    var reIsBinary = /^0b[01]+$/i;
    var reIsOctal = /^0o[0-7]+$/i;
    var freeParseInt = parseInt;
    var objectProto = Object.prototype;
    var objectToString = objectProto.toString;
    function isInteger(value) {
      return typeof value == "number" && value == toInteger(value);
    }
    function isObject3(value) {
      var type = typeof value;
      return !!value && (type == "object" || type == "function");
    }
    function isObjectLike(value) {
      return !!value && typeof value == "object";
    }
    function isSymbol(value) {
      return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;
    }
    function toFinite(value) {
      if (!value) {
        return value === 0 ? value : 0;
      }
      value = toNumber(value);
      if (value === INFINITY || value === -INFINITY) {
        var sign = value < 0 ? -1 : 1;
        return sign * MAX_INTEGER;
      }
      return value === value ? value : 0;
    }
    function toInteger(value) {
      var result = toFinite(value), remainder = result % 1;
      return result === result ? remainder ? result - remainder : result : 0;
    }
    function toNumber(value) {
      if (typeof value == "number") {
        return value;
      }
      if (isSymbol(value)) {
        return NAN;
      }
      if (isObject3(value)) {
        var other = typeof value.valueOf == "function" ? value.valueOf() : value;
        value = isObject3(other) ? other + "" : other;
      }
      if (typeof value != "string") {
        return value === 0 ? value : +value;
      }
      value = value.replace(reTrim, "");
      var isBinary = reIsBinary.test(value);
      return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
    }
    module.exports = isInteger;
  }
});

// ../../node_modules/.pnpm/lodash.isnumber@3.0.3/node_modules/lodash.isnumber/index.js
var require_lodash4 = __commonJS({
  "../../node_modules/.pnpm/lodash.isnumber@3.0.3/node_modules/lodash.isnumber/index.js"(exports, module) {
    var numberTag = "[object Number]";
    var objectProto = Object.prototype;
    var objectToString = objectProto.toString;
    function isObjectLike(value) {
      return !!value && typeof value == "object";
    }
    function isNumber(value) {
      return typeof value == "number" || isObjectLike(value) && objectToString.call(value) == numberTag;
    }
    module.exports = isNumber;
  }
});

// ../../node_modules/.pnpm/lodash.isplainobject@4.0.6/node_modules/lodash.isplainobject/index.js
var require_lodash5 = __commonJS({
  "../../node_modules/.pnpm/lodash.isplainobject@4.0.6/node_modules/lodash.isplainobject/index.js"(exports, module) {
    var objectTag = "[object Object]";
    function isHostObject(value) {
      var result = false;
      if (value != null && typeof value.toString != "function") {
        try {
          result = !!(value + "");
        } catch (e) {
        }
      }
      return result;
    }
    function overArg(func, transform2) {
      return function(arg) {
        return func(transform2(arg));
      };
    }
    var funcProto = Function.prototype;
    var objectProto = Object.prototype;
    var funcToString = funcProto.toString;
    var hasOwnProperty = objectProto.hasOwnProperty;
    var objectCtorString = funcToString.call(Object);
    var objectToString = objectProto.toString;
    var getPrototype = overArg(Object.getPrototypeOf, Object);
    function isObjectLike(value) {
      return !!value && typeof value == "object";
    }
    function isPlainObject2(value) {
      if (!isObjectLike(value) || objectToString.call(value) != objectTag || isHostObject(value)) {
        return false;
      }
      var proto = getPrototype(value);
      if (proto === null) {
        return true;
      }
      var Ctor = hasOwnProperty.call(proto, "constructor") && proto.constructor;
      return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString;
    }
    module.exports = isPlainObject2;
  }
});

// ../../node_modules/.pnpm/lodash.isstring@4.0.1/node_modules/lodash.isstring/index.js
var require_lodash6 = __commonJS({
  "../../node_modules/.pnpm/lodash.isstring@4.0.1/node_modules/lodash.isstring/index.js"(exports, module) {
    var stringTag = "[object String]";
    var objectProto = Object.prototype;
    var objectToString = objectProto.toString;
    var isArray = Array.isArray;
    function isObjectLike(value) {
      return !!value && typeof value == "object";
    }
    function isString(value) {
      return typeof value == "string" || !isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag;
    }
    module.exports = isString;
  }
});

// ../../node_modules/.pnpm/lodash.once@4.1.1/node_modules/lodash.once/index.js
var require_lodash7 = __commonJS({
  "../../node_modules/.pnpm/lodash.once@4.1.1/node_modules/lodash.once/index.js"(exports, module) {
    var FUNC_ERROR_TEXT = "Expected a function";
    var INFINITY = 1 / 0;
    var MAX_INTEGER = 17976931348623157e292;
    var NAN = 0 / 0;
    var symbolTag = "[object Symbol]";
    var reTrim = /^\s+|\s+$/g;
    var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
    var reIsBinary = /^0b[01]+$/i;
    var reIsOctal = /^0o[0-7]+$/i;
    var freeParseInt = parseInt;
    var objectProto = Object.prototype;
    var objectToString = objectProto.toString;
    function before(n, func) {
      var result;
      if (typeof func != "function") {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
      n = toInteger(n);
      return function() {
        if (--n > 0) {
          result = func.apply(this, arguments);
        }
        if (n <= 1) {
          func = void 0;
        }
        return result;
      };
    }
    function once(func) {
      return before(2, func);
    }
    function isObject3(value) {
      var type = typeof value;
      return !!value && (type == "object" || type == "function");
    }
    function isObjectLike(value) {
      return !!value && typeof value == "object";
    }
    function isSymbol(value) {
      return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;
    }
    function toFinite(value) {
      if (!value) {
        return value === 0 ? value : 0;
      }
      value = toNumber(value);
      if (value === INFINITY || value === -INFINITY) {
        var sign = value < 0 ? -1 : 1;
        return sign * MAX_INTEGER;
      }
      return value === value ? value : 0;
    }
    function toInteger(value) {
      var result = toFinite(value), remainder = result % 1;
      return result === result ? remainder ? result - remainder : result : 0;
    }
    function toNumber(value) {
      if (typeof value == "number") {
        return value;
      }
      if (isSymbol(value)) {
        return NAN;
      }
      if (isObject3(value)) {
        var other = typeof value.valueOf == "function" ? value.valueOf() : value;
        value = isObject3(other) ? other + "" : other;
      }
      if (typeof value != "string") {
        return value === 0 ? value : +value;
      }
      value = value.replace(reTrim, "");
      var isBinary = reIsBinary.test(value);
      return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
    }
    module.exports = once;
  }
});

// ../../node_modules/.pnpm/jsonwebtoken@9.0.3/node_modules/jsonwebtoken/sign.js
var require_sign2 = __commonJS({
  "../../node_modules/.pnpm/jsonwebtoken@9.0.3/node_modules/jsonwebtoken/sign.js"(exports, module) {
    var timespan = require_timespan();
    var PS_SUPPORTED = require_psSupported();
    var validateAsymmetricKey = require_validateAsymmetricKey();
    var jws = require_jws();
    var includes = require_lodash();
    var isBoolean = require_lodash2();
    var isInteger = require_lodash3();
    var isNumber = require_lodash4();
    var isPlainObject2 = require_lodash5();
    var isString = require_lodash6();
    var once = require_lodash7();
    var { KeyObject, createSecretKey, createPrivateKey } = __require("crypto");
    var SUPPORTED_ALGS = ["RS256", "RS384", "RS512", "ES256", "ES384", "ES512", "HS256", "HS384", "HS512", "none"];
    if (PS_SUPPORTED) {
      SUPPORTED_ALGS.splice(3, 0, "PS256", "PS384", "PS512");
    }
    var sign_options_schema = {
      expiresIn: { isValid: function(value) {
        return isInteger(value) || isString(value) && value;
      }, message: '"expiresIn" should be a number of seconds or string representing a timespan' },
      notBefore: { isValid: function(value) {
        return isInteger(value) || isString(value) && value;
      }, message: '"notBefore" should be a number of seconds or string representing a timespan' },
      audience: { isValid: function(value) {
        return isString(value) || Array.isArray(value);
      }, message: '"audience" must be a string or array' },
      algorithm: { isValid: includes.bind(null, SUPPORTED_ALGS), message: '"algorithm" must be a valid string enum value' },
      header: { isValid: isPlainObject2, message: '"header" must be an object' },
      encoding: { isValid: isString, message: '"encoding" must be a string' },
      issuer: { isValid: isString, message: '"issuer" must be a string' },
      subject: { isValid: isString, message: '"subject" must be a string' },
      jwtid: { isValid: isString, message: '"jwtid" must be a string' },
      noTimestamp: { isValid: isBoolean, message: '"noTimestamp" must be a boolean' },
      keyid: { isValid: isString, message: '"keyid" must be a string' },
      mutatePayload: { isValid: isBoolean, message: '"mutatePayload" must be a boolean' },
      allowInsecureKeySizes: { isValid: isBoolean, message: '"allowInsecureKeySizes" must be a boolean' },
      allowInvalidAsymmetricKeyTypes: { isValid: isBoolean, message: '"allowInvalidAsymmetricKeyTypes" must be a boolean' }
    };
    var registered_claims_schema = {
      iat: { isValid: isNumber, message: '"iat" should be a number of seconds' },
      exp: { isValid: isNumber, message: '"exp" should be a number of seconds' },
      nbf: { isValid: isNumber, message: '"nbf" should be a number of seconds' }
    };
    function validate(schema, allowUnknown, object2, parameterName) {
      if (!isPlainObject2(object2)) {
        throw new Error('Expected "' + parameterName + '" to be a plain object.');
      }
      Object.keys(object2).forEach(function(key) {
        const validator = schema[key];
        if (!validator) {
          if (!allowUnknown) {
            throw new Error('"' + key + '" is not allowed in "' + parameterName + '"');
          }
          return;
        }
        if (!validator.isValid(object2[key])) {
          throw new Error(validator.message);
        }
      });
    }
    function validateOptions(options) {
      return validate(sign_options_schema, false, options, "options");
    }
    function validatePayload(payload) {
      return validate(registered_claims_schema, true, payload, "payload");
    }
    var options_to_payload = {
      "audience": "aud",
      "issuer": "iss",
      "subject": "sub",
      "jwtid": "jti"
    };
    var options_for_objects = [
      "expiresIn",
      "notBefore",
      "noTimestamp",
      "audience",
      "issuer",
      "subject",
      "jwtid"
    ];
    module.exports = function(payload, secretOrPrivateKey, options, callback) {
      if (typeof options === "function") {
        callback = options;
        options = {};
      } else {
        options = options || {};
      }
      const isObjectPayload = typeof payload === "object" && !Buffer.isBuffer(payload);
      const header = Object.assign({
        alg: options.algorithm || "HS256",
        typ: isObjectPayload ? "JWT" : void 0,
        kid: options.keyid
      }, options.header);
      function failure(err) {
        if (callback) {
          return callback(err);
        }
        throw err;
      }
      if (!secretOrPrivateKey && options.algorithm !== "none") {
        return failure(new Error("secretOrPrivateKey must have a value"));
      }
      if (secretOrPrivateKey != null && !(secretOrPrivateKey instanceof KeyObject)) {
        try {
          secretOrPrivateKey = createPrivateKey(secretOrPrivateKey);
        } catch (_) {
          try {
            secretOrPrivateKey = createSecretKey(typeof secretOrPrivateKey === "string" ? Buffer.from(secretOrPrivateKey) : secretOrPrivateKey);
          } catch (_2) {
            return failure(new Error("secretOrPrivateKey is not valid key material"));
          }
        }
      }
      if (header.alg.startsWith("HS") && secretOrPrivateKey.type !== "secret") {
        return failure(new Error(`secretOrPrivateKey must be a symmetric key when using ${header.alg}`));
      } else if (/^(?:RS|PS|ES)/.test(header.alg)) {
        if (secretOrPrivateKey.type !== "private") {
          return failure(new Error(`secretOrPrivateKey must be an asymmetric key when using ${header.alg}`));
        }
        if (!options.allowInsecureKeySizes && !header.alg.startsWith("ES") && secretOrPrivateKey.asymmetricKeyDetails !== void 0 && //KeyObject.asymmetricKeyDetails is supported in Node 15+
        secretOrPrivateKey.asymmetricKeyDetails.modulusLength < 2048) {
          return failure(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${header.alg}`));
        }
      }
      if (typeof payload === "undefined") {
        return failure(new Error("payload is required"));
      } else if (isObjectPayload) {
        try {
          validatePayload(payload);
        } catch (error40) {
          return failure(error40);
        }
        if (!options.mutatePayload) {
          payload = Object.assign({}, payload);
        }
      } else {
        const invalid_options = options_for_objects.filter(function(opt) {
          return typeof options[opt] !== "undefined";
        });
        if (invalid_options.length > 0) {
          return failure(new Error("invalid " + invalid_options.join(",") + " option for " + typeof payload + " payload"));
        }
      }
      if (typeof payload.exp !== "undefined" && typeof options.expiresIn !== "undefined") {
        return failure(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.'));
      }
      if (typeof payload.nbf !== "undefined" && typeof options.notBefore !== "undefined") {
        return failure(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.'));
      }
      try {
        validateOptions(options);
      } catch (error40) {
        return failure(error40);
      }
      if (!options.allowInvalidAsymmetricKeyTypes) {
        try {
          validateAsymmetricKey(header.alg, secretOrPrivateKey);
        } catch (error40) {
          return failure(error40);
        }
      }
      const timestamp2 = payload.iat || Math.floor(Date.now() / 1e3);
      if (options.noTimestamp) {
        delete payload.iat;
      } else if (isObjectPayload) {
        payload.iat = timestamp2;
      }
      if (typeof options.notBefore !== "undefined") {
        try {
          payload.nbf = timespan(options.notBefore, timestamp2);
        } catch (err) {
          return failure(err);
        }
        if (typeof payload.nbf === "undefined") {
          return failure(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));
        }
      }
      if (typeof options.expiresIn !== "undefined" && typeof payload === "object") {
        try {
          payload.exp = timespan(options.expiresIn, timestamp2);
        } catch (err) {
          return failure(err);
        }
        if (typeof payload.exp === "undefined") {
          return failure(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));
        }
      }
      Object.keys(options_to_payload).forEach(function(key) {
        const claim = options_to_payload[key];
        if (typeof options[key] !== "undefined") {
          if (typeof payload[claim] !== "undefined") {
            return failure(new Error('Bad "options.' + key + '" option. The payload already has an "' + claim + '" property.'));
          }
          payload[claim] = options[key];
        }
      });
      const encoding = options.encoding || "utf8";
      if (typeof callback === "function") {
        callback = callback && once(callback);
        jws.createSign({
          header,
          privateKey: secretOrPrivateKey,
          payload,
          encoding
        }).once("error", callback).once("done", function(signature) {
          if (!options.allowInsecureKeySizes && /^(?:RS|PS)/.test(header.alg) && signature.length < 256) {
            return callback(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${header.alg}`));
          }
          callback(null, signature);
        });
      } else {
        let signature = jws.sign({ header, payload, secret: secretOrPrivateKey, encoding });
        if (!options.allowInsecureKeySizes && /^(?:RS|PS)/.test(header.alg) && signature.length < 256) {
          throw new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${header.alg}`);
        }
        return signature;
      }
    };
  }
});

// ../../node_modules/.pnpm/jsonwebtoken@9.0.3/node_modules/jsonwebtoken/index.js
var require_jsonwebtoken = __commonJS({
  "../../node_modules/.pnpm/jsonwebtoken@9.0.3/node_modules/jsonwebtoken/index.js"(exports, module) {
    module.exports = {
      decode: require_decode(),
      verify: require_verify(),
      sign: require_sign2(),
      JsonWebTokenError: require_JsonWebTokenError(),
      NotBeforeError: require_NotBeforeError(),
      TokenExpiredError: require_TokenExpiredError()
    };
  }
});

// src/lib/auth-session.ts
function isAuthTokenPayload(value) {
  if (!value || typeof value !== "object") {
    return false;
  }
  const payload = value;
  return typeof payload.sub === "number" && Number.isInteger(payload.sub) && payload.sub > 0 && typeof payload.email === "string" && typeof payload.sv === "number" && Number.isInteger(payload.sv) && payload.sv >= 0;
}
function createAuthToken(user) {
  return import_jsonwebtoken.default.sign(
    { sub: user.id, email: user.email, sv: user.authTokenVersion },
    JWT_SECRET,
    { expiresIn: JWT_EXPIRES_IN }
  );
}
async function resolveAuthenticatedUser(token) {
  if (!token) {
    return null;
  }
  try {
    const payload = import_jsonwebtoken.default.verify(token, JWT_SECRET);
    if (!isAuthTokenPayload(payload)) {
      return null;
    }
    const key = `${payload.sub}:${payload.sv}:${token}`;
    const existing = inFlightAuthResolutions.get(key);
    if (existing) {
      return existing;
    }
    const work = db.select().from(usersTable).where(eq(usersTable.id, payload.sub)).limit(1).then((rows) => {
      const user = rows[0];
      if (!user || user.authTokenVersion !== payload.sv) {
        return null;
      }
      if (user.deletedAt != null) {
        return null;
      }
      return user;
    }).finally(() => {
      inFlightAuthResolutions.delete(key);
    });
    inFlightAuthResolutions.set(key, work);
    return work;
  } catch {
    return null;
  }
}
var import_jsonwebtoken, JWT_EXPIRES_IN, inFlightAuthResolutions;
var init_auth_session = __esm({
  "src/lib/auth-session.ts"() {
    "use strict";
    import_jsonwebtoken = __toESM(require_jsonwebtoken(), 1);
    init_src2();
    init_schema2();
    init_drizzle_orm();
    init_config();
    JWT_EXPIRES_IN = "7d";
    inFlightAuthResolutions = /* @__PURE__ */ new Map();
  }
});

// src/lib/membership-registration-id.ts
import { randomInt } from "crypto";
function normalizePrefix(value) {
  const trimmed = (value ?? "").trim();
  return trimmed.length > 0 ? trimmed.toUpperCase() : "WWN";
}
function normalizeDigits(value) {
  const rounded = Number.isFinite(value) ? Math.floor(value) : 7;
  if (rounded < 4) return 4;
  if (rounded > 12) return 12;
  return rounded;
}
function randomDigits(length) {
  let out = "";
  for (let i = 0; i < length; i += 1) {
    out += randomInt(0, 10).toString();
  }
  return out;
}
function buildMembershipRegistrationId(settings) {
  const prefix = normalizePrefix(settings.prefix);
  const digits = normalizeDigits(settings.digits);
  return `${prefix}-${randomDigits(digits)}`;
}
async function getPlatformMembershipIdSettings(db2) {
  const [existing] = await db2.select().from(membershipIdSettingsTable).where(eq(membershipIdSettingsTable.id, 1)).limit(1);
  if (existing) {
    return {
      id: existing.id,
      prefix: normalizePrefix(existing.prefix),
      digits: normalizeDigits(existing.digits)
    };
  }
  const [created] = await db2.insert(membershipIdSettingsTable).values({
    id: 1,
    prefix: "WWN",
    digits: 7
  }).returning();
  return {
    id: created.id,
    prefix: normalizePrefix(created.prefix),
    digits: normalizeDigits(created.digits)
  };
}
async function getOrganizationMembershipIdSettings(db2, organizationId) {
  const [existing] = await db2.select().from(organizationMembershipIdSettingsTable).where(eq(organizationMembershipIdSettingsTable.organizationId, organizationId)).limit(1);
  if (!existing) return null;
  return {
    id: existing.id,
    organizationId: existing.organizationId,
    prefix: normalizePrefix(existing.prefix),
    digits: normalizeDigits(existing.digits)
  };
}
async function assignMembershipRegistrationId(db2, input) {
  const [user] = await db2.select({
    id: usersTable.id,
    organizationId: usersTable.organizationId,
    membershipRegistrationId: usersTable.membershipRegistrationId
  }).from(usersTable).where(eq(usersTable.id, input.userId)).limit(1);
  if (!user) {
    throw new Error("User not found.");
  }
  if (user.membershipRegistrationId) {
    return user.membershipRegistrationId;
  }
  const organizationId = typeof input.organizationId === "number" ? input.organizationId : user.organizationId ?? null;
  const platform = await getPlatformMembershipIdSettings(db2);
  const orgSettings = typeof organizationId === "number" ? await getOrganizationMembershipIdSettings(db2, organizationId) : null;
  const settings = {
    prefix: orgSettings?.prefix ?? platform.prefix,
    digits: orgSettings?.digits ?? platform.digits
  };
  for (let attempt = 0; attempt < 25; attempt += 1) {
    const candidate = buildMembershipRegistrationId(settings);
    try {
      const [updated] = await db2.update(usersTable).set({
        membershipRegistrationId: candidate,
        updatedAt: /* @__PURE__ */ new Date()
      }).where(eq(usersTable.id, input.userId)).returning({ membershipRegistrationId: usersTable.membershipRegistrationId });
      if (updated?.membershipRegistrationId) {
        return updated.membershipRegistrationId;
      }
    } catch (err) {
      if (err?.code === "23505") {
        continue;
      }
      throw err;
    }
  }
  throw new Error("Could not generate a unique membership registration ID.");
}
var init_membership_registration_id = __esm({
  "src/lib/membership-registration-id.ts"() {
    "use strict";
    init_drizzle_orm();
    init_schema2();
  }
});

// src/lib/organization-invitations.ts
import { createHash as createHash2, randomBytes as randomBytes2 } from "crypto";
function createOrganizationInvitationToken() {
  const token = randomBytes2(24).toString("base64url");
  const tokenHash = hashOrganizationInvitationToken(token);
  const expiresAt = new Date(
    Date.now() + ORGANIZATION_INVITATION_TTL_DAYS * 24 * 60 * 60 * 1e3
  );
  return { token, tokenHash, expiresAt };
}
function hashOrganizationInvitationToken(token) {
  return createHash2("sha256").update(token).digest("hex");
}
function formatOrganizationRoleLabel(role) {
  if (role === "OWNER") {
    return "Organization";
  }
  return role.toLowerCase().split("_").map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(" ");
}
async function getActiveOrganizationInvitationByToken(token) {
  const tokenHash = hashOrganizationInvitationToken(token);
  const now = /* @__PURE__ */ new Date();
  const [invitation] = await db.select({
    id: organizationInvitationsTable.id,
    organizationId: organizationInvitationsTable.organizationId,
    email: organizationInvitationsTable.email,
    firstName: organizationInvitationsTable.firstName,
    lastName: organizationInvitationsTable.lastName,
    role: organizationInvitationsTable.role,
    invitedByUserId: organizationInvitationsTable.invitedByUserId,
    status: organizationInvitationsTable.status,
    expiresAt: organizationInvitationsTable.expiresAt,
    organizationName: organizationsTable.name,
    organizationType: organizationsTable.organizationType,
    operationalStatus: organizationsTable.operationalStatus
  }).from(organizationInvitationsTable).innerJoin(
    organizationsTable,
    eq(organizationInvitationsTable.organizationId, organizationsTable.id)
  ).where(
    and(
      eq(organizationInvitationsTable.tokenHash, tokenHash),
      eq(organizationInvitationsTable.status, "PENDING"),
      gt(organizationInvitationsTable.expiresAt, now)
    )
  );
  return invitation ?? null;
}
var ORGANIZATION_INVITATION_TTL_DAYS;
var init_organization_invitations = __esm({
  "src/lib/organization-invitations.ts"() {
    "use strict";
    init_src2();
    init_schema2();
    init_drizzle_orm();
    ORGANIZATION_INVITATION_TTL_DAYS = 7;
  }
});

// src/lib/profile.ts
function getAccountSetupState(input) {
  if (input.userRole === "ADMIN" || input.userRole === "SUPER_ADMIN") {
    return {
      currentStep: "COMPLETE",
      isComplete: true,
      nextPath: null
    };
  }
  if (!input.profileCompleted) {
    return {
      currentStep: "PROFILE",
      isComplete: false,
      nextPath: "/dashboard/membership"
    };
  }
  if (input.membershipStatus !== "ACTIVE") {
    return {
      currentStep: "MEMBERSHIP",
      isComplete: false,
      nextPath: "/dashboard/membership"
    };
  }
  if (input.onboardingRequired === true && input.onboardingCompleted === false) {
    return {
      currentStep: "ONBOARDING",
      isComplete: false,
      nextPath: "/dashboard/onboarding"
    };
  }
  return {
    currentStep: "COMPLETE",
    isComplete: true,
    nextPath: null
  };
}
function hasTextValue(value) {
  return typeof value === "string" ? value.trim().length > 0 : value != null;
}
function hasBooleanAnswer(value) {
  return value === true || value === false;
}
function isUserProfileComplete(user) {
  if (user.membershipType === "ORGANIZATION" && typeof user.organizationId === "number") {
    return ORGANIZATION_TEAM_MEMBER_REQUIRED_FIELDS.every(
      (field) => hasTextValue(user[field])
    );
  }
  let requiredTextFields = [
    ...INDIVIDUAL_REQUIRED_FIELDS
  ];
  if (user.membershipType === "INVESTOR") {
    requiredTextFields = [...INVESTOR_REQUIRED_FIELDS];
  } else if (user.membershipType === "ORGANIZATION") {
    requiredTextFields = [
      ...ORGANIZATION_ACCOUNT_REQUIRED_FIELDS.filter(
        (f) => f !== "businessName" && f !== "businessType" && f !== "yearsInBusiness" && f !== "annualRevenue"
      )
    ];
  }
  requiredTextFields = [
    ...requiredTextFields,
    "contactAddress",
    "contactStreet",
    "contactPostalCode",
    "contactCountryIso2",
    "nextOfKinFirstName",
    "nextOfKinLastName",
    "nextOfKinGender",
    "nextOfKinResidentialAddress",
    "nextOfKinStreet",
    "nextOfKinCity",
    "nextOfKinPostalCode",
    "nextOfKinEmail",
    "nextOfKinPhone",
    "nextOfKinRelationship",
    "nextOfKinOccupation"
  ];
  if (hasTextValue(user.referrerName)) {
    requiredTextFields.push("referrerName", "referrerPhone", "referrerWwnId");
  } else {
    requiredTextFields.push("howHeard");
  }
  if (user.employmentEmployed === true) {
    requiredTextFields.push(
      "occupation",
      "employmentStatus",
      "employerName",
      "employerAddress",
      "employmentPosition"
    );
  }
  if (user.membershipType === "INVESTOR") {
    requiredTextFields.push("investorCategory");
  }
  if (user.businessType !== "NOT_APPLICABLE" && hasTextValue(user.businessName)) {
    requiredTextFields.push(
      "businessName",
      "businessType",
      "yearsInBusiness",
      "annualRevenue"
    );
  }
  const consentAccepted = user.consentAccepted === true;
  const employmentAnswered = hasBooleanAnswer(user.employmentEmployed);
  const kycSubmittedOrApproved = user.kycStatus === "PENDING" || user.kycStatus === "APPROVED";
  return consentAccepted && employmentAnswered && kycSubmittedOrApproved && requiredTextFields.every((field) => hasTextValue(user[field]));
}
function formatUserProfile(user) {
  return {
    id: user.id,
    email: user.email,
    firstName: user.firstName,
    lastName: user.lastName ?? null,
    username: user.username ?? null,
    phone: user.phone ?? null,
    membershipRegistrationId: user.membershipRegistrationId ?? null,
    membershipType: user.membershipType ?? null,
    membershipStatus: user.membershipStatus ?? "PENDING",
    segment: user.segment ?? null,
    userRole: user.userRole ?? "MEMBER",
    bio: user.bio ?? null,
    contactAddress: user.contactAddress ?? null,
    contactStreet: user.contactStreet ?? null,
    contactPostalCode: user.contactPostalCode ?? null,
    contactCountryIso2: user.contactCountryIso2 ?? null,
    city: user.city ?? null,
    province: user.province ?? null,
    ageRange: user.ageRange ?? null,
    occupation: user.occupation ?? null,
    employmentEmployed: typeof user.employmentEmployed === "boolean" ? user.employmentEmployed : null,
    employmentStatus: user.employmentStatus ?? null,
    employerName: user.employerName ?? null,
    employerAddress: user.employerAddress ?? null,
    employmentPosition: user.employmentPosition ?? null,
    businessName: user.businessName ?? null,
    businessType: user.businessType ?? null,
    yearsInBusiness: user.yearsInBusiness ?? null,
    annualRevenue: user.annualRevenue ?? null,
    howHeard: user.howHeard ?? null,
    referrerName: user.referrerName ?? null,
    referrerPhone: user.referrerPhone ?? null,
    referrerWwnId: user.referrerWwnId ?? null,
    referrerAddress: user.referrerAddress ?? null,
    referrerStreet: user.referrerStreet ?? null,
    referrerCity: user.referrerCity ?? null,
    referrerPostalCode: user.referrerPostalCode ?? null,
    goals: user.goals ?? null,
    consentAccepted: Boolean(user.consentAccepted),
    consentAcceptedAt: user.consentAcceptedAt?.toISOString?.() ?? null,
    nextOfKinFirstName: user.nextOfKinFirstName ?? null,
    nextOfKinLastName: user.nextOfKinLastName ?? null,
    nextOfKinOtherNames: user.nextOfKinOtherNames ?? null,
    nextOfKinGender: user.nextOfKinGender ?? null,
    nextOfKinResidentialAddress: user.nextOfKinResidentialAddress ?? null,
    nextOfKinStreet: user.nextOfKinStreet ?? null,
    nextOfKinCity: user.nextOfKinCity ?? null,
    nextOfKinPostalCode: user.nextOfKinPostalCode ?? null,
    nextOfKinEmail: user.nextOfKinEmail ?? null,
    nextOfKinPhone: user.nextOfKinPhone ?? null,
    nextOfKinRelationship: user.nextOfKinRelationship ?? null,
    nextOfKinOccupation: user.nextOfKinOccupation ?? null,
    kycIdFrontUrl: user.kycIdFrontUrl ?? null,
    kycIdBackUrl: user.kycIdBackUrl ?? null,
    kycSelfieUrl: user.kycSelfieUrl ?? null,
    kycStatus: user.kycStatus ?? null,
    kycSubmittedAt: user.kycSubmittedAt?.toISOString?.() ?? null,
    kycReviewedAt: user.kycReviewedAt?.toISOString?.() ?? null,
    kycReviewedByUserId: user.kycReviewedByUserId ?? null,
    kycRejectionReason: user.kycRejectionReason ?? null,
    investorCategory: user.investorCategory ?? null,
    createdAt: user.createdAt.toISOString(),
    profileCompleted: isUserProfileComplete(user),
    onboardingCompleted: Boolean(user.onboardingCompletedAt)
  };
}
var INDIVIDUAL_REQUIRED_FIELDS, INVESTOR_REQUIRED_FIELDS, ORGANIZATION_ACCOUNT_REQUIRED_FIELDS, ORGANIZATION_TEAM_MEMBER_REQUIRED_FIELDS;
var init_profile = __esm({
  "src/lib/profile.ts"() {
    "use strict";
    INDIVIDUAL_REQUIRED_FIELDS = [
      "firstName",
      "phone",
      "city",
      "province",
      "ageRange",
      "goals"
    ];
    INVESTOR_REQUIRED_FIELDS = [
      "firstName",
      "phone",
      "city",
      "province",
      "goals"
    ];
    ORGANIZATION_ACCOUNT_REQUIRED_FIELDS = [
      "firstName",
      "phone",
      "city",
      "province",
      "occupation",
      "goals",
      "businessName",
      "businessType",
      "yearsInBusiness",
      "annualRevenue"
    ];
    ORGANIZATION_TEAM_MEMBER_REQUIRED_FIELDS = [
      "firstName",
      "phone"
    ];
  }
});

// src/lib/member-onboarding-program.ts
function normalizeOnboardingTargetMembershipType(membershipType) {
  if (membershipType === "INDIVIDUAL" || membershipType === "INVESTOR" || membershipType === "ORGANIZATION") {
    return membershipType;
  }
  return null;
}
async function getActiveOnboardingProgramForMembershipType(membershipType) {
  const normalizedMembershipType = normalizeOnboardingTargetMembershipType(membershipType);
  if (!normalizedMembershipType) return null;
  const now = /* @__PURE__ */ new Date();
  const [candidate] = await db.select({ id: onboardingProgramsTable.id }).from(onboardingProgramsTable).innerJoin(
    onboardingProgramWeeksTable,
    eq(onboardingProgramWeeksTable.programId, onboardingProgramsTable.id)
  ).innerJoin(
    onboardingWeekActivitiesTable,
    eq(onboardingWeekActivitiesTable.weekId, onboardingProgramWeeksTable.id)
  ).where(
    and(
      eq(onboardingProgramsTable.status, "PUBLISHED"),
      eq(
        onboardingProgramsTable.targetMembershipType,
        normalizedMembershipType
      ),
      or(
        sql`${onboardingProgramsTable.startDate} is null`,
        lte(onboardingProgramsTable.startDate, now)
      ),
      or(
        sql`${onboardingProgramsTable.endDate} is null`,
        gte(onboardingProgramsTable.endDate, now)
      )
    )
  ).groupBy(onboardingProgramsTable.id).orderBy(desc(onboardingProgramsTable.createdAt)).limit(1);
  if (!candidate?.id) return null;
  return db.select().from(onboardingProgramsTable).where(eq(onboardingProgramsTable.id, candidate.id)).then((rows) => rows[0] ?? null);
}
async function getOnboardingEnrollmentForProgram(userId, programId) {
  return db.select().from(onboardingEnrollmentsTable).where(
    and(
      eq(onboardingEnrollmentsTable.userId, userId),
      eq(onboardingEnrollmentsTable.programId, programId)
    )
  ).then((rows) => rows[0] ?? null);
}
function timestampsMatch(left, right) {
  if (!left && !right) return true;
  if (!left || !right) return false;
  return left.getTime() === right.getTime();
}
async function syncUserOnboardingCompletion(userId, enrollment, userCompletion) {
  const nextCompletedAt = enrollment?.completedAt ?? null;
  if (timestampsMatch(userCompletion, nextCompletedAt)) {
    return;
  }
  await db.update(usersTable).set({
    onboardingCompletedAt: nextCompletedAt,
    updatedAt: /* @__PURE__ */ new Date()
  }).where(eq(usersTable.id, userId));
}
async function getActiveOnboardingStateForUserRow(user) {
  const membershipType = normalizeOnboardingTargetMembershipType(user.membershipType);
  if (!membershipType) {
    return {
      required: false,
      completed: true,
      program: null,
      enrollment: null
    };
  }
  const program = await getActiveOnboardingProgramForMembershipType(membershipType);
  if (!program) {
    return {
      required: false,
      completed: true,
      program: null,
      enrollment: null
    };
  }
  const matchingEnrollment = await getOnboardingEnrollmentForProgram(user.id, program.id);
  return {
    required: true,
    completed: Boolean(matchingEnrollment?.completedAt),
    program,
    enrollment: matchingEnrollment
  };
}
async function getActiveOnboardingStateForUser(userId) {
  const [user] = await db.select().from(usersTable).where(eq(usersTable.id, userId));
  if (!user) {
    return {
      required: false,
      completed: true,
      program: null,
      enrollment: null
    };
  }
  return getActiveOnboardingStateForUserRow(user);
}
async function syncActiveOnboardingCompletionForUser(userId) {
  const [user] = await db.select().from(usersTable).where(eq(usersTable.id, userId));
  if (!user) return null;
  const onboardingState = await getActiveOnboardingStateForUserRow(user);
  await syncUserOnboardingCompletion(
    userId,
    onboardingState.required ? onboardingState.enrollment : null,
    user.onboardingCompletedAt
  );
  return onboardingState;
}
async function ensureActiveOnboardingEnrollmentForUser(userId) {
  const now = /* @__PURE__ */ new Date();
  const [user] = await db.select().from(usersTable).where(eq(usersTable.id, userId));
  if (!user) return null;
  const membershipType = normalizeOnboardingTargetMembershipType(user.membershipType);
  if (!membershipType) return null;
  if (user.membershipStatus !== "ACTIVE") return null;
  if (!isUserProfileComplete(user)) return null;
  const program = await getActiveOnboardingProgramForMembershipType(membershipType);
  if (!program) return null;
  const existing = await getOnboardingEnrollmentForProgram(userId, program.id);
  if (existing) {
    await syncUserOnboardingCompletion(userId, existing, user.onboardingCompletedAt);
    return existing;
  }
  const [enrollment] = await db.insert(onboardingEnrollmentsTable).values({
    userId,
    programId: program.id,
    enrolledAt: now,
    lastActivityAt: now,
    updatedAt: now
  }).returning();
  await syncUserOnboardingCompletion(userId, enrollment ?? null, user.onboardingCompletedAt);
  return enrollment;
}
var init_member_onboarding_program = __esm({
  "src/lib/member-onboarding-program.ts"() {
    "use strict";
    init_src2();
    init_schema2();
    init_drizzle_orm();
    init_profile();
  }
});

// src/lib/member-plan-entitlements.ts
async function getPlanEntitlementsForStatus(userId, status) {
  const [row] = await db.select({
    entitlements: membershipPlansTable.entitlements
  }).from(membershipSubscriptionsTable).leftJoin(
    membershipPlansTable,
    eq(membershipSubscriptionsTable.planId, membershipPlansTable.id)
  ).where(
    and(
      eq(membershipSubscriptionsTable.userId, userId),
      eq(membershipSubscriptionsTable.status, status)
    )
  ).orderBy(desc(membershipSubscriptionsTable.createdAt)).limit(1);
  if (row?.entitlements && typeof row.entitlements === "object") {
    return row.entitlements;
  }
  return null;
}
async function getPlanMetaForStatus(userId, status) {
  const [row] = await db.select({
    id: membershipPlansTable.id,
    membershipType: membershipPlansTable.membershipType,
    tier: membershipPlansTable.tier,
    name: membershipPlansTable.name
  }).from(membershipSubscriptionsTable).leftJoin(
    membershipPlansTable,
    eq(membershipSubscriptionsTable.planId, membershipPlansTable.id)
  ).where(
    and(
      eq(membershipSubscriptionsTable.userId, userId),
      eq(membershipSubscriptionsTable.status, status)
    )
  ).orderBy(desc(membershipSubscriptionsTable.createdAt)).limit(1);
  if (!row?.id) return null;
  return row;
}
async function getPreferredMemberPlanEntitlements(userId) {
  return await getPlanEntitlementsForStatus(userId, "ACTIVE") ?? await getPlanEntitlementsForStatus(userId, "PENDING") ?? {};
}
async function getPreferredMemberPlanMeta(userId) {
  return await getPlanMetaForStatus(userId, "ACTIVE") ?? await getPlanMetaForStatus(userId, "PENDING") ?? null;
}
var init_member_plan_entitlements = __esm({
  "src/lib/member-plan-entitlements.ts"() {
    "use strict";
    init_src2();
    init_schema2();
    init_drizzle_orm();
  }
});

// src/lib/organization-tenancy.ts
function isRecord(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
function readBoolean(value, fallback) {
  return typeof value === "boolean" ? value : fallback;
}
function readSeatLimit(value) {
  if (value === null) return null;
  if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
    return Math.trunc(value);
  }
  return null;
}
function normalizeOrganizationEntitlements(value) {
  if (!isRecord(value)) {
    return { ...DEFAULT_ORGANIZATION_ENTITLEMENTS };
  }
  return {
    tenant_access: readBoolean(
      value.tenant_access,
      DEFAULT_ORGANIZATION_ENTITLEMENTS.tenant_access
    ),
    member_management: readBoolean(
      value.member_management,
      DEFAULT_ORGANIZATION_ENTITLEMENTS.member_management
    ),
    seat_limit: readSeatLimit(value.seat_limit),
    org_billing_manage: readBoolean(
      value.org_billing_manage,
      DEFAULT_ORGANIZATION_ENTITLEMENTS.org_billing_manage
    ),
    org_wallet_operate: readBoolean(
      value.org_wallet_operate,
      DEFAULT_ORGANIZATION_ENTITLEMENTS.org_wallet_operate
    ),
    org_wallet_fund: readBoolean(
      value.org_wallet_fund,
      DEFAULT_ORGANIZATION_ENTITLEMENTS.org_wallet_fund
    ),
    org_member_contributions: readBoolean(
      value.org_member_contributions,
      DEFAULT_ORGANIZATION_ENTITLEMENTS.org_member_contributions
    ),
    org_financial_reporting: readBoolean(
      value.org_financial_reporting,
      DEFAULT_ORGANIZATION_ENTITLEMENTS.org_financial_reporting
    ),
    asca_access: readBoolean(
      value.asca_access,
      DEFAULT_ORGANIZATION_ENTITLEMENTS.asca_access
    ),
    programs_access: readBoolean(
      value.programs_access,
      DEFAULT_ORGANIZATION_ENTITLEMENTS.programs_access
    ),
    resources_access: readBoolean(
      value.resources_access,
      DEFAULT_ORGANIZATION_ENTITLEMENTS.resources_access
    ),
    workshops_access: readBoolean(
      value.workshops_access,
      DEFAULT_ORGANIZATION_ENTITLEMENTS.workshops_access
    ),
    white_label_resources_access: readBoolean(
      value.white_label_resources_access,
      DEFAULT_ORGANIZATION_ENTITLEMENTS.white_label_resources_access
    ),
    org_susu_operate: readBoolean(
      value.org_susu_operate,
      DEFAULT_ORGANIZATION_ENTITLEMENTS.org_susu_operate
    ),
    org_susu_education: readBoolean(
      value.org_susu_education,
      DEFAULT_ORGANIZATION_ENTITLEMENTS.org_susu_education
    ),
    investment_club_access: readBoolean(
      value.investment_club_access,
      DEFAULT_ORGANIZATION_ENTITLEMENTS.investment_club_access
    ),
    p2p_capital_access: readBoolean(
      value.p2p_capital_access,
      DEFAULT_ORGANIZATION_ENTITLEMENTS.p2p_capital_access
    ),
    asca_lending_pool_access: readBoolean(
      value.asca_lending_pool_access,
      DEFAULT_ORGANIZATION_ENTITLEMENTS.asca_lending_pool_access
    ),
    susu_matching_fund_access: readBoolean(
      value.susu_matching_fund_access,
      DEFAULT_ORGANIZATION_ENTITLEMENTS.susu_matching_fund_access
    ),
    quote_managed_only: readBoolean(
      value.quote_managed_only,
      DEFAULT_ORGANIZATION_ENTITLEMENTS.quote_managed_only
    )
  };
}
function isOrganizationOperational(status) {
  return status === "ACTIVE";
}
function canOrganizationRolePerform(role, action) {
  const permissions = getOrganizationRolePermissions(role);
  switch (action) {
    case "tenant_settings":
      return permissions.canManageSettings;
    case "members_manage":
      return permissions.canManageMembers;
    case "member_roles_manage":
      return permissions.canManageMemberRoles;
    case "billing_manage":
      return permissions.canManageBilling;
    case "wallet_operate":
      return permissions.canOperateWallet;
    case "wallet_fund":
      return permissions.canFundWallet;
    case "member_contributions_manage":
      return permissions.canManageMemberContributions;
    case "financial_reporting":
      return permissions.canViewFinancialReports;
    case "tenant_operate":
      return permissions.canAccessTenantProducts;
    default:
      return false;
  }
}
function getOrganizationRolePermissions(role) {
  if (!role) {
    return {
      isOwner: false,
      isAdmin: false,
      isMember: false,
      canAccessTenantProducts: false,
      canManageMembers: false,
      canManageMemberRoles: false,
      canManageBilling: false,
      canOperateWallet: false,
      canFundWallet: false,
      canManageMemberContributions: false,
      canViewFinancialReports: false,
      canManageSettings: false
    };
  }
  return ORGANIZATION_ROLE_MATRIX[role];
}
function resolveOrganizationTenantAccess(input) {
  const entitlements = normalizeOrganizationEntitlements(input.planEntitlements);
  const reasons = [];
  if (input.membershipType !== "ORGANIZATION") {
    reasons.push("Organization tenancy is available only to organization members.");
  }
  if (!input.organizationType) {
    reasons.push("Organization type must be classified before tenant access is enabled.");
  }
  if (input.planMembershipType && input.planMembershipType !== "ORGANIZATION") {
    reasons.push("Tenant access requires an organization-scoped plan.");
  }
  if (input.subscriptionStatus !== "ACTIVE") {
    reasons.push("An active organization subscription is required for tenant access.");
  }
  if (!isOrganizationOperational(input.organizationStatus)) {
    reasons.push("The organization is not in an operable status.");
  }
  if (!entitlements.tenant_access) {
    reasons.push("The active organization plan does not enable tenant access.");
  }
  return {
    allowed: reasons.length === 0,
    reasons,
    entitlements
  };
}
var ORGANIZATION_ROLE_MATRIX, DEFAULT_ORGANIZATION_ENTITLEMENTS;
var init_organization_tenancy = __esm({
  "src/lib/organization-tenancy.ts"() {
    "use strict";
    ORGANIZATION_ROLE_MATRIX = {
      OWNER: {
        isOwner: true,
        isAdmin: false,
        isMember: false,
        canAccessTenantProducts: true,
        canManageMembers: true,
        canManageMemberRoles: true,
        canManageBilling: true,
        canOperateWallet: true,
        canFundWallet: true,
        canManageMemberContributions: true,
        canViewFinancialReports: true,
        canManageSettings: true
      },
      ADMIN: {
        isOwner: false,
        isAdmin: true,
        isMember: false,
        canAccessTenantProducts: false,
        canManageMembers: true,
        canManageMemberRoles: true,
        canManageBilling: false,
        canOperateWallet: false,
        canFundWallet: false,
        canManageMemberContributions: false,
        canViewFinancialReports: false,
        canManageSettings: false
      },
      MEMBER: {
        isOwner: false,
        isAdmin: false,
        isMember: true,
        canAccessTenantProducts: true,
        canManageMembers: false,
        canManageMemberRoles: false,
        canManageBilling: false,
        canOperateWallet: false,
        canFundWallet: false,
        canManageMemberContributions: false,
        canViewFinancialReports: false,
        canManageSettings: false
      }
    };
    DEFAULT_ORGANIZATION_ENTITLEMENTS = {
      tenant_access: false,
      member_management: false,
      seat_limit: null,
      org_billing_manage: false,
      org_wallet_operate: false,
      org_wallet_fund: false,
      org_member_contributions: false,
      org_financial_reporting: false,
      asca_access: false,
      programs_access: false,
      resources_access: false,
      workshops_access: false,
      white_label_resources_access: false,
      org_susu_operate: false,
      org_susu_education: false,
      investment_club_access: false,
      p2p_capital_access: false,
      asca_lending_pool_access: true,
      susu_matching_fund_access: true,
      quote_managed_only: false
    };
  }
});

// src/lib/organization-product-access.ts
function enabled(reason = null) {
  return { allowed: true, state: "enabled", reason };
}
function quoteManaged(reason) {
  return { allowed: true, state: "quote_managed", reason };
}
function disabled(reason) {
  return { allowed: false, state: "disabled", reason };
}
function resolveOrganizationProductAccess(input) {
  const { tenantAccessAllowed, entitlements } = input;
  const tenantReason = "Your organization is not enabled for tenant product access.";
  if (!tenantAccessAllowed) {
    return {
      ASCA: disabled(tenantReason),
      PROGRAMS: disabled(tenantReason),
      RESOURCES: disabled(tenantReason),
      WORKSHOPS: disabled(tenantReason),
      WHITE_LABEL_RESOURCES: disabled(tenantReason),
      ORG_SUSU: disabled(tenantReason),
      ORG_SUSU_EDUCATION: disabled(tenantReason),
      INVESTMENT_CLUB: disabled(tenantReason),
      P2P_CAPITAL: disabled(tenantReason),
      ASCA_LENDING_POOL: disabled(tenantReason),
      SUSU_MATCHING_FUND: disabled(tenantReason)
    };
  }
  const ascaLendingPoolAccess = entitlements.asca_lending_pool_access;
  const ascaLendingPoolAllowed = ascaLendingPoolAccess === true || ascaLendingPoolAccess === void 0;
  return {
    ASCA: entitlements.asca_access ? enabled(null) : disabled("Your organization plan does not include ASCA access."),
    PROGRAMS: entitlements.programs_access || entitlements.workshops_access ? enabled(null) : entitlements.quote_managed_only ? quoteManaged(
      "Programs are available through a quote-managed organization workflow."
    ) : disabled("Your organization plan does not include program access."),
    RESOURCES: entitlements.resources_access || entitlements.white_label_resources_access || entitlements.org_susu_education ? enabled(null) : disabled("Your organization plan does not include resource access."),
    WORKSHOPS: entitlements.workshops_access ? enabled(null) : entitlements.quote_managed_only ? quoteManaged(
      "Workshops are available through quote-managed organization delivery."
    ) : disabled("Your organization plan does not include workshop access."),
    WHITE_LABEL_RESOURCES: entitlements.white_label_resources_access ? enabled(null) : disabled(
      "Your organization plan does not include white-label resource access."
    ),
    ORG_SUSU: entitlements.org_susu_operate ? enabled(null) : disabled("Your organization plan does not include org-operated SUSU."),
    ORG_SUSU_EDUCATION: entitlements.org_susu_education ? enabled(null) : disabled(
      "Your organization plan does not include SUSU education resources."
    ),
    INVESTMENT_CLUB: entitlements.investment_club_access ? enabled(null) : disabled(
      "Your organization plan does not include investment-club access."
    ),
    P2P_CAPITAL: entitlements.p2p_capital_access ? enabled(null) : disabled(
      "Your organization plan does not include partner-capital access."
    ),
    ASCA_LENDING_POOL: ascaLendingPoolAllowed ? enabled(null) : disabled(
      "Your organization plan does not include ASCA community lending pool access."
    ),
    SUSU_MATCHING_FUND: entitlements.susu_matching_fund_access === true || entitlements.susu_matching_fund_access === void 0 ? enabled(null) : disabled("Your organization plan does not include SUSU Matching Fund access.")
  };
}
var init_organization_product_access = __esm({
  "src/lib/organization-product-access.ts"() {
    "use strict";
  }
});

// src/lib/organization-context.ts
import { readFileSync as readFileSync2 } from "node:fs";
async function reportOrgGatingDebug(input) {
  if (process.env.ENABLE_ORG_GATING_DEBUG !== "true") {
    return;
  }
  let debugServerUrl = "http://127.0.0.1:7777/event";
  let sessionId = "org-entitlement-gating";
  try {
    const envText = readFileSync2(".dbg/org-entitlement-gating.env", "utf8");
    debugServerUrl = envText.match(/DEBUG_SERVER_URL=(.+)/)?.[1]?.trim() ?? debugServerUrl;
    sessionId = envText.match(/DEBUG_SESSION_ID=(.+)/)?.[1]?.trim() ?? sessionId;
  } catch {
  }
  await fetch(debugServerUrl, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      sessionId,
      runId: "pre-fix",
      hypothesisId: input.hypothesisId,
      location: input.location,
      msg: `[DEBUG] ${input.msg}`,
      data: input.data ?? {},
      traceId: input.traceId,
      ts: Date.now()
    })
  }).catch(() => {
  });
}
function isUniqueViolation(err) {
  if (!err || typeof err !== "object") return false;
  const code = "code" in err ? err.code : void 0;
  return code === "23505";
}
function toIsoStringOrNull(value) {
  return value ? value.toISOString() : null;
}
function buildPermissions(input) {
  const role = input.membershipRole;
  const tenantAllowed = input.tenantAccessAllowed;
  const rolePermissions = getOrganizationRolePermissions(role);
  const isOrganizationAuthority = rolePermissions.isOwner;
  const ownerOverride = isOrganizationAuthority;
  const canOperateTenant = ownerOverride || tenantAllowed && rolePermissions.canAccessTenantProducts && canOrganizationRolePerform(role, "tenant_operate");
  const canManageMembers = ownerOverride || tenantAllowed && rolePermissions.canManageMembers && canOrganizationRolePerform(role, "members_manage");
  const canManageRoles = ownerOverride || tenantAllowed && rolePermissions.canManageMemberRoles && canOrganizationRolePerform(role, "member_roles_manage");
  const canManageBilling = ownerOverride || tenantAllowed && rolePermissions.canManageBilling && canOrganizationRolePerform(role, "billing_manage");
  const canOperateWallet = ownerOverride || tenantAllowed && rolePermissions.canOperateWallet && canOrganizationRolePerform(role, "wallet_operate");
  const canFundWallet = ownerOverride || tenantAllowed && rolePermissions.canFundWallet && canOrganizationRolePerform(role, "wallet_fund");
  const canManageMemberContributions = ownerOverride || tenantAllowed && rolePermissions.canManageMemberContributions && canOrganizationRolePerform(role, "member_contributions_manage");
  const canParticipateMemberContributions = ownerOverride || tenantAllowed && rolePermissions.canAccessTenantProducts && canOrganizationRolePerform(role, "tenant_operate");
  const canViewFinancialReports = ownerOverride || tenantAllowed && rolePermissions.canViewFinancialReports && canOrganizationRolePerform(role, "financial_reporting");
  const canManageSettings = ownerOverride || tenantAllowed && rolePermissions.canManageSettings && canOrganizationRolePerform(role, "tenant_settings");
  return {
    isOwner: rolePermissions.isOwner,
    isAdmin: rolePermissions.isAdmin,
    isMember: rolePermissions.isMember,
    canOperateTenant,
    canManageMembers,
    canManageRoles,
    canManageBilling,
    canOperateWallet,
    canFundWallet,
    canManageMemberContributions,
    canParticipateMemberContributions,
    canViewFinancialReports,
    canManageSettings
  };
}
async function syncOrganizationSubscriptionStateWith(tx, input) {
  if (input.user.membershipType !== "ORGANIZATION" || input.plan.membershipType !== "ORGANIZATION" || typeof input.user.organizationId !== "number") {
    return null;
  }
  const [organization] = await tx.select({
    id: organizationsTable.id,
    organizationType: organizationsTable.organizationType,
    operationalStatus: organizationsTable.operationalStatus
  }).from(organizationsTable).where(eq(organizationsTable.id, input.user.organizationId)).limit(1);
  if (!organization) {
    throw new Error(
      "Organization account is missing a valid organization record."
    );
  }
  const [existing] = await tx.select().from(organizationSubscriptionsTable).where(
    and(
      eq(
        organizationSubscriptionsTable.organizationId,
        input.user.organizationId
      ),
      inArray(organizationSubscriptionsTable.status, ["PENDING", "ACTIVE"])
    )
  ).orderBy(desc(organizationSubscriptionsTable.createdAt)).limit(1);
  if (input.status === "CANCELLED") {
    if (existing && (existing.status === "PENDING" || existing.status === "ACTIVE" && Boolean(input.stripeSubscriptionId) && existing.stripeSubscriptionId === input.stripeSubscriptionId)) {
      await tx.update(organizationSubscriptionsTable).set({
        status: "CANCELLED",
        cancelledAt: input.now,
        updatedAt: input.now
      }).where(eq(organizationSubscriptionsTable.id, existing.id));
    }
    return null;
  }
  let organizationSubscription = existing ?? null;
  if (organizationSubscription?.status === "ACTIVE" && input.status === "PENDING") {
    if (!input.stripeSubscriptionId || organizationSubscription.stripeSubscriptionId !== input.stripeSubscriptionId) {
      return organizationSubscription;
    }
  }
  if (organizationSubscription && organizationSubscription.planId !== input.plan.id) {
    await tx.update(organizationSubscriptionsTable).set({
      status: "CANCELLED",
      cancelledAt: input.now,
      updatedAt: input.now
    }).where(
      eq(organizationSubscriptionsTable.id, organizationSubscription.id)
    );
    organizationSubscription = null;
  }
  const nextValues = {
    planId: input.plan.id,
    status: input.status,
    startDate: input.startDate ?? null,
    endDate: input.endDate ?? null,
    renewsAt: input.renewsAt ?? null,
    cancelledAt: null,
    stripeCustomerId: input.stripeCustomerId ?? null,
    stripeSubscriptionId: input.stripeSubscriptionId ?? null,
    updatedAt: input.now
  };
  if (!organizationSubscription) {
    try {
      [organizationSubscription] = await tx.insert(organizationSubscriptionsTable).values({
        organizationId: input.user.organizationId,
        ...nextValues
      }).returning();
    } catch (err) {
      if (!isUniqueViolation(err)) {
        throw err;
      }
      [organizationSubscription] = await tx.select().from(organizationSubscriptionsTable).where(
        and(
          eq(
            organizationSubscriptionsTable.organizationId,
            input.user.organizationId
          ),
          inArray(organizationSubscriptionsTable.status, [
            "PENDING",
            "ACTIVE"
          ])
        )
      ).orderBy(desc(organizationSubscriptionsTable.createdAt)).limit(1);
      if (!organizationSubscription) {
        throw err;
      }
      [organizationSubscription] = await tx.update(organizationSubscriptionsTable).set(nextValues).where(
        eq(organizationSubscriptionsTable.id, organizationSubscription.id)
      ).returning();
    }
  } else {
    [organizationSubscription] = await tx.update(organizationSubscriptionsTable).set(nextValues).where(eq(organizationSubscriptionsTable.id, organizationSubscription.id)).returning();
  }
  const organizationPatch = {};
  if (input.status === "ACTIVE" && organization.operationalStatus === "PENDING") {
    organizationPatch.operationalStatus = "ACTIVE";
  }
  if (Object.keys(organizationPatch).length > 0) {
    await tx.update(organizationsTable).set({
      ...organizationPatch,
      updatedAt: input.now
    }).where(eq(organizationsTable.id, organization.id));
  }
  return organizationSubscription;
}
async function resolveOrganizationSessionContext(userId) {
  const traceId = `orgctx-${userId}-${Date.now()}`;
  const [user] = await db.select({
    membershipType: usersTable.membershipType,
    organizationId: usersTable.organizationId
  }).from(usersTable).where(eq(usersTable.id, userId));
  if (!user || user.membershipType !== "ORGANIZATION" || typeof user.organizationId !== "number") {
    await reportOrgGatingDebug({
      hypothesisId: "A",
      location: "src/lib/organization-context.ts:resolveOrganizationSessionContext:user",
      msg: "Organization session context skipped before tenant resolution",
      data: {
        userId,
        membershipType: user?.membershipType ?? null,
        organizationId: user?.organizationId ?? null
      },
      traceId
    });
    return null;
  }
  const [organization, membership, subscriptionRow] = await Promise.all([
    db.select({
      id: organizationsTable.id,
      name: organizationsTable.name,
      type: organizationsTable.type,
      organizationType: organizationsTable.organizationType,
      operationalStatus: organizationsTable.operationalStatus
    }).from(organizationsTable).where(eq(organizationsTable.id, user.organizationId)).then((rows) => rows[0] ?? null),
    db.select({
      role: organizationMembersTable.role,
      status: organizationMembersTable.status,
      joinedAt: organizationMembersTable.joinedAt
    }).from(organizationMembersTable).where(
      and(
        eq(organizationMembersTable.organizationId, user.organizationId),
        eq(organizationMembersTable.userId, userId)
      )
    ).then((rows) => rows[0] ?? null),
    db.select({
      subscriptionId: organizationSubscriptionsTable.id,
      subscriptionStatus: organizationSubscriptionsTable.status,
      subscriptionStartDate: organizationSubscriptionsTable.startDate,
      subscriptionEndDate: organizationSubscriptionsTable.endDate,
      subscriptionRenewsAt: organizationSubscriptionsTable.renewsAt,
      planId: membershipPlansTable.id,
      planMembershipType: membershipPlansTable.membershipType,
      planOrganizationType: membershipPlansTable.organizationType,
      planTier: membershipPlansTable.tier,
      planName: membershipPlansTable.name,
      planDescription: membershipPlansTable.description,
      planEntitlements: membershipPlansTable.entitlements
    }).from(organizationSubscriptionsTable).innerJoin(
      membershipPlansTable,
      eq(organizationSubscriptionsTable.planId, membershipPlansTable.id)
    ).where(
      and(
        eq(
          organizationSubscriptionsTable.organizationId,
          user.organizationId
        ),
        inArray(organizationSubscriptionsTable.status, ["ACTIVE", "PENDING"])
      )
    ).orderBy(desc(organizationSubscriptionsTable.createdAt)).then((rows) => rows[0] ?? null)
  ]);
  if (!organization) {
    return null;
  }
  const baseTenantAccess = resolveOrganizationTenantAccess({
    membershipType: user.membershipType,
    organizationType: organization.organizationType,
    organizationStatus: organization.operationalStatus,
    subscriptionStatus: subscriptionRow?.subscriptionStatus ?? null,
    planMembershipType: subscriptionRow?.planMembershipType ?? null,
    planEntitlements: subscriptionRow?.planEntitlements ?? null
  });
  const tenantAccess = membership?.status === "PENDING" ? {
    allowed: false,
    reasons: [
      "Your organization access is pending activation by an organization owner."
    ],
    entitlements: baseTenantAccess.entitlements
  } : baseTenantAccess;
  await reportOrgGatingDebug({
    hypothesisId: "B",
    location: "src/lib/organization-context.ts:resolveOrganizationSessionContext:tenant",
    msg: "Resolved organization tenant access",
    data: {
      userId,
      organizationId: user.organizationId,
      organizationStatus: organization.operationalStatus,
      subscriptionId: subscriptionRow?.subscriptionId ?? null,
      subscriptionStatus: subscriptionRow?.subscriptionStatus ?? null,
      planId: subscriptionRow?.planId ?? null,
      planName: subscriptionRow?.planName ?? null,
      planMembershipType: subscriptionRow?.planMembershipType ?? null,
      planOrganizationType: subscriptionRow?.planOrganizationType ?? null,
      rawEntitlements: subscriptionRow?.planEntitlements && typeof subscriptionRow.planEntitlements === "object" ? subscriptionRow.planEntitlements : subscriptionRow?.planEntitlements ?? null,
      tenantAccessAllowed: tenantAccess.allowed,
      tenantAccessReasons: tenantAccess.reasons,
      resolvedEntitlements: tenantAccess.entitlements,
      resolvedProductAccess: resolveOrganizationProductAccess({
        tenantAccessAllowed: tenantAccess.allowed,
        entitlements: tenantAccess.entitlements
      })
    },
    traceId
  });
  return {
    organization: {
      id: organization.id,
      name: organization.name,
      type: organization.type,
      organizationType: organization.organizationType,
      operationalStatus: organization.operationalStatus
    },
    membership: membership ? {
      role: membership.role,
      status: membership.status,
      joinedAt: membership.joinedAt.toISOString()
    } : null,
    subscription: subscriptionRow && typeof subscriptionRow.subscriptionId === "number" ? {
      id: subscriptionRow.subscriptionId,
      status: subscriptionRow.subscriptionStatus,
      startDate: toIsoStringOrNull(subscriptionRow.subscriptionStartDate),
      endDate: toIsoStringOrNull(subscriptionRow.subscriptionEndDate),
      renewsAt: toIsoStringOrNull(subscriptionRow.subscriptionRenewsAt)
    } : null,
    plan: subscriptionRow && typeof subscriptionRow.planId === "number" ? {
      id: subscriptionRow.planId,
      membershipType: subscriptionRow.planMembershipType,
      organizationType: subscriptionRow.planOrganizationType,
      tier: subscriptionRow.planTier,
      name: subscriptionRow.planName,
      description: subscriptionRow.planDescription ?? null
    } : null,
    entitlements: tenantAccess.entitlements,
    tenantAccess: {
      allowed: tenantAccess.allowed,
      reasons: tenantAccess.reasons
    },
    productAccess: resolveOrganizationProductAccess({
      tenantAccessAllowed: tenantAccess.allowed,
      entitlements: tenantAccess.entitlements
    }),
    permissions: buildPermissions({
      membershipRole: membership?.role ?? null,
      entitlements: tenantAccess.entitlements,
      tenantAccessAllowed: tenantAccess.allowed
    })
  };
}
async function requireOrganizationTenantAccess(userId, options) {
  const context = await resolveOrganizationSessionContext(userId);
  if (!context) {
    throw new OrganizationTenantAccessError(
      "Organization tenant access is available only to organization members."
    );
  }
  if (!context.tenantAccess.allowed && !context.permissions.isOwner) {
    throw new OrganizationTenantAccessError(
      context.tenantAccess.reasons[0] ?? "Your organization is not enabled for tenant access."
    );
  }
  const membershipRole = context.membership?.role ?? null;
  const isWorkspaceMember = membershipRole === "MEMBER";
  if (!isWorkspaceMember && options?.capability && !context.entitlements[options.capability] && !context.permissions.isOwner) {
    throw new OrganizationTenantAccessError(
      `Your organization tenant access does not enable ${options.capability}.`
    );
  }
  if (!isWorkspaceMember && options?.productFeature && !context.productAccess[options.productFeature].allowed && !context.permissions.isOwner) {
    throw new OrganizationTenantAccessError(
      context.productAccess[options.productFeature].reason ?? `Your organization plan does not enable ${options.productFeature}.`
    );
  }
  if (options?.roleAction && !canOrganizationRolePerform(membershipRole, options.roleAction)) {
    throw new OrganizationTenantAccessError(
      "Your organization role does not allow this action."
    );
  }
  return context;
}
var OrganizationTenantAccessError;
var init_organization_context = __esm({
  "src/lib/organization-context.ts"() {
    "use strict";
    init_src2();
    init_schema2();
    init_drizzle_orm();
    init_organization_tenancy();
    init_organization_product_access();
    OrganizationTenantAccessError = class extends Error {
      statusCode;
      layer;
      constructor(message, statusCode = 403, layer) {
        super(message);
        this.name = "OrganizationTenantAccessError";
        this.statusCode = statusCode;
        this.layer = layer;
      }
    };
  }
});

// src/lib/session-profile.ts
async function buildSessionProfile(user, options) {
  const profile = formatUserProfile(user);
  const membershipType = profile.membershipType ?? "INDIVIDUAL";
  const organizationContext = membershipType === "ORGANIZATION" ? await resolveOrganizationSessionContext(user.id) : null;
  const membershipPlan = await getPreferredMemberPlanMeta(user.id);
  const planEntitlements = membershipType === "INDIVIDUAL" ? await getPreferredMemberPlanEntitlements(user.id) : null;
  const onboardingState = options.useUserRowForOnboarding ? await getActiveOnboardingStateForUserRow(user) : await getActiveOnboardingStateForUser(user.id);
  if (options.normalizeOrganizationTeamMemberOnboarding && membershipType === "ORGANIZATION" && organizationContext?.membership != null && organizationContext.permissions.isOwner !== true) {
    const accountSetup2 = getAccountSetupState({
      userRole: profile.userRole,
      profileCompleted: profile.profileCompleted,
      membershipStatus: profile.membershipStatus,
      onboardingRequired: false,
      onboardingCompleted: true
    });
    return {
      ...profile,
      onboardingRequired: false,
      onboardingCompleted: true,
      accountSetup: accountSetup2,
      organizationContext,
      membershipPlan,
      planEntitlements
    };
  }
  const accountSetup = getAccountSetupState({
    userRole: profile.userRole,
    profileCompleted: profile.profileCompleted,
    membershipStatus: profile.membershipStatus,
    onboardingRequired: onboardingState.required,
    onboardingCompleted: onboardingState.completed
  });
  return {
    ...profile,
    onboardingRequired: onboardingState.required,
    onboardingCompleted: onboardingState.completed,
    accountSetup,
    organizationContext,
    membershipPlan,
    planEntitlements
  };
}
async function formatSessionUserProfile(user, options = {}) {
  const key = [
    user.id,
    user.authTokenVersion,
    user.updatedAt?.getTime?.() ?? "na",
    options.normalizeOrganizationTeamMemberOnboarding ? "org-normalized" : "raw",
    options.useUserRowForOnboarding ? "row" : "id"
  ].join(":");
  const existing = inFlightSessionProfiles.get(key);
  if (existing) {
    return existing;
  }
  const work = buildSessionProfile(user, options).finally(() => {
    inFlightSessionProfiles.delete(key);
  });
  inFlightSessionProfiles.set(key, work);
  return work;
}
var inFlightSessionProfiles;
var init_session_profile = __esm({
  "src/lib/session-profile.ts"() {
    "use strict";
    init_member_onboarding_program();
    init_member_plan_entitlements();
    init_organization_context();
    init_profile();
    inFlightSessionProfiles = /* @__PURE__ */ new Map();
  }
});

// src/routes/auth.ts
var auth_exports = {};
__export(auth_exports, {
  default: () => auth_default
});
import { createHash as createHash3, randomBytes as randomBytes3, randomInt as randomInt2, timingSafeEqual } from "crypto";
async function formatUserProfileWithOnboarding(user) {
  return formatSessionUserProfile(user, {
    normalizeOrganizationTeamMemberOnboarding: true,
    useUserRowForOnboarding: true
  });
}
function hashesMatch(left, right) {
  const leftBuffer = Buffer.from(left, "utf8");
  const rightBuffer = Buffer.from(right, "utf8");
  if (leftBuffer.length !== rightBuffer.length) {
    return false;
  }
  return timingSafeEqual(leftBuffer, rightBuffer);
}
async function issueVerificationCode({
  userId,
  email: email3,
  firstName
}) {
  const now = Date.now();
  const oneMinuteAgo = new Date(now - VERIFICATION_RESEND_INTERVAL_MS);
  const recentTokens = await db.select().from(verificationTokensTable).where(
    and(
      eq(verificationTokensTable.userId, userId),
      gte(verificationTokensTable.createdAt, oneMinuteAgo)
    )
  );
  if (recentTokens.length > 0) {
    throw Object.assign(
      new Error(
        "Please wait at least 1 minute before requesting another code."
      ),
      { status: 429 }
    );
  }
  const since = new Date(now - 24 * 60 * 60 * 1e3);
  const dailyTokens = await db.select().from(verificationTokensTable).where(
    and(
      eq(verificationTokensTable.userId, userId),
      gte(verificationTokensTable.createdAt, since)
    )
  );
  if (dailyTokens.length >= VERIFICATION_MAX_DAILY) {
    throw Object.assign(
      new Error("Daily verification limit reached. Try again tomorrow."),
      { status: 429 }
    );
  }
  const code = generateVerificationCode();
  const codeHash = await bcryptjs_default.hash(code, 12);
  const expiresAt = new Date(
    now + VERIFICATION_CODE_EXPIRATION_MINUTES * 60 * 1e3
  );
  const [created] = await db.insert(verificationTokensTable).values({ userId, codeHash, expiresAt }).returning({ id: verificationTokensTable.id });
  try {
    await sendMail({
      to: email3,
      ...createVerificationCodeEmail({
        firstName,
        code,
        expiresInMinutes: VERIFICATION_CODE_EXPIRATION_MINUTES
      })
    });
  } catch (err) {
    logger.error({ err }, "Failed to send verification email");
    if (created?.id) {
      await db.delete(verificationTokensTable).where(eq(verificationTokensTable.id, created.id));
    }
    throw Object.assign(
      new Error("Unable to deliver verification code. Please try again."),
      { status: 503 }
    );
  }
}
async function issuePasswordResetCode({
  userId,
  email: email3,
  firstName
}) {
  const now = Date.now();
  const oneMinuteAgo = new Date(now - PASSWORD_RESET_RESEND_INTERVAL_MS);
  const recentTokens = await db.select().from(passwordResetTokensTable).where(
    and(
      eq(passwordResetTokensTable.userId, userId),
      gte(passwordResetTokensTable.createdAt, oneMinuteAgo)
    )
  );
  if (recentTokens.length > 0) {
    throw Object.assign(
      new Error(
        "Please wait at least 1 minute before requesting another password reset code."
      ),
      { status: 429 }
    );
  }
  const since = new Date(now - 24 * 60 * 60 * 1e3);
  const dailyTokens = await db.select().from(passwordResetTokensTable).where(
    and(
      eq(passwordResetTokensTable.userId, userId),
      gte(passwordResetTokensTable.createdAt, since)
    )
  );
  if (dailyTokens.length >= PASSWORD_RESET_MAX_DAILY) {
    throw Object.assign(
      new Error("Daily password reset limit reached. Try again tomorrow."),
      { status: 429 }
    );
  }
  await db.update(passwordResetTokensTable).set({ used: true }).where(
    and(
      eq(passwordResetTokensTable.userId, userId),
      eq(passwordResetTokensTable.used, false)
    )
  );
  const code = generateVerificationCode();
  const tokenHash = hashPasswordResetToken(`${userId}:${code}`);
  const expiresAt = new Date(
    now + PASSWORD_RESET_EXPIRATION_MINUTES * 60 * 1e3
  );
  const [created] = await db.insert(passwordResetTokensTable).values({
    userId,
    tokenHash,
    expiresAt,
    attempts: 0,
    isExchangeToken: false
  }).returning({ id: passwordResetTokensTable.id });
  try {
    await sendMail({
      to: email3,
      ...createPasswordResetEmail({
        firstName,
        code,
        expiresInMinutes: PASSWORD_RESET_EXPIRATION_MINUTES
      })
    });
  } catch (err) {
    logger.error({ err }, "Failed to send password reset email");
    if (created?.id) {
      await db.delete(passwordResetTokensTable).where(eq(passwordResetTokensTable.id, created.id));
    }
    throw Object.assign(
      new Error("Unable to deliver password reset code. Please try again."),
      { status: 503 }
    );
  }
}
function handleError(error40, res) {
  if (error40?.status) {
    return res.status(error40.status).json({ message: error40.message });
  }
  logger.error({ err: error40 }, "Unhandled auth error");
  return res.status(500).json({ message: "Internal server error." });
}
var import_express2, router2, COOKIE_MAX_AGE_MS, VERIFICATION_CODE_EXPIRATION_MINUTES, VERIFICATION_RESEND_INTERVAL_MS, VERIFICATION_MAX_DAILY, VERIFICATION_MAX_ATTEMPTS, PASSWORD_RESET_EXPIRATION_MINUTES, PASSWORD_RESET_RESEND_INTERVAL_MS, PASSWORD_RESET_MAX_DAILY, PASSWORD_RESET_MAX_ATTEMPTS, GENERIC_RESEND_CODE_MESSAGE, GENERIC_FORGOT_PASSWORD_MESSAGE, GENERIC_VERIFY_EMAIL_FAILURE_MESSAGE, AUTH_COOKIE_OPTIONS, SEGMENT_VALUES, MEMBERSHIP_TYPE_VALUES, INTERNATIONAL_PHONE_REGEX, optionalTrimmedString, optionalInternationalPhone, signupSchema, verifySchema, resendSchema, loginSchema, forgotPasswordSchema, verifyPasswordResetCodeSchema, resetPasswordSchema, generateVerificationCode, hashPasswordResetToken, auth_default;
var init_auth = __esm({
  "src/routes/auth.ts"() {
    "use strict";
    import_express2 = __toESM(require_express2(), 1);
    init_bcryptjs();
    init_zod();
    init_src2();
    init_schema2();
    init_drizzle_orm();
    init_mailer();
    init_auth_session();
    init_membership_registration_id();
    init_organization_invitations();
    init_logger();
    init_session_profile();
    init_config();
    router2 = (0, import_express2.Router)();
    COOKIE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
    VERIFICATION_CODE_EXPIRATION_MINUTES = 10;
    VERIFICATION_RESEND_INTERVAL_MS = 60 * 1e3;
    VERIFICATION_MAX_DAILY = 5;
    VERIFICATION_MAX_ATTEMPTS = 5;
    PASSWORD_RESET_EXPIRATION_MINUTES = 30;
    PASSWORD_RESET_RESEND_INTERVAL_MS = 60 * 1e3;
    PASSWORD_RESET_MAX_DAILY = 5;
    PASSWORD_RESET_MAX_ATTEMPTS = 5;
    GENERIC_RESEND_CODE_MESSAGE = "If the account can receive verification, a code has been sent.";
    GENERIC_FORGOT_PASSWORD_MESSAGE = "If an account exists for that email, a password reset code has been sent.";
    GENERIC_VERIFY_EMAIL_FAILURE_MESSAGE = "Verification failed. Request a new code or sign in.";
    AUTH_COOKIE_OPTIONS = {
      httpOnly: true,
      secure: COOKIE_SECURE,
      sameSite: COOKIE_SAME_SITE,
      path: "/",
      ...COOKIE_DOMAIN ? { domain: COOKIE_DOMAIN } : {}
    };
    SEGMENT_VALUES = [
      "PROFESSIONAL",
      "ENTREPRENEUR",
      "YOUTH",
      "SCHOOL",
      "INSTITUTION"
    ];
    MEMBERSHIP_TYPE_VALUES = [
      "INDIVIDUAL",
      "ORGANIZATION",
      "INVESTOR"
    ];
    INTERNATIONAL_PHONE_REGEX = /^\+[1-9]\d{7,14}$/;
    optionalTrimmedString = external_exports.string().trim().max(191).optional().or(external_exports.literal("")).transform((v) => v && v.length ? v : void 0);
    optionalInternationalPhone = external_exports.string().trim().optional().or(external_exports.literal("")).transform((value) => {
      if (!value) return void 0;
      return value.replace(/[\s().-]/g, "");
    }).refine(
      (value) => value === void 0 || INTERNATIONAL_PHONE_REGEX.test(value),
      { message: "Phone must be in international format like +14373247539." }
    );
    signupSchema = external_exports.object({
      email: external_exports.string().email(),
      phone: optionalInternationalPhone,
      password: external_exports.string().min(8),
      firstName: external_exports.string().min(1),
      lastName: optionalTrimmedString,
      segment: external_exports.enum(SEGMENT_VALUES).optional(),
      membershipType: external_exports.enum(MEMBERSHIP_TYPE_VALUES).optional(),
      invitationToken: optionalTrimmedString
    });
    verifySchema = external_exports.object({
      email: external_exports.string().email(),
      code: external_exports.string().regex(/^\d{6}$/)
    });
    resendSchema = external_exports.object({ email: external_exports.string().email() });
    loginSchema = external_exports.union([
      external_exports.object({
        email: external_exports.string().email(),
        password: external_exports.string().min(1)
      }),
      external_exports.object({
        identifier: external_exports.string().email(),
        password: external_exports.string().min(1)
      })
    ]).transform((value) => ({
      email: ("email" in value ? value.email : value.identifier).toLowerCase().trim(),
      password: value.password
    }));
    forgotPasswordSchema = external_exports.object({
      email: external_exports.string().email()
    });
    verifyPasswordResetCodeSchema = external_exports.object({
      email: external_exports.string().email(),
      code: external_exports.string().regex(/^\d{6}$/)
    });
    resetPasswordSchema = external_exports.object({
      token: external_exports.string().min(20),
      password: external_exports.string().min(8)
    });
    generateVerificationCode = () => randomInt2(0, 1e6).toString().padStart(6, "0");
    hashPasswordResetToken = (token) => createHash3("sha256").update(token).digest("hex");
    router2.post("/signup", async (req, res) => {
      try {
        const parseResult = signupSchema.safeParse(req.body);
        if (!parseResult.success) {
          return res.status(400).json({ errors: parseResult.error.flatten() });
        }
        const {
          email: email3,
          password,
          firstName,
          lastName,
          phone,
          segment,
          membershipType,
          invitationToken
        } = parseResult.data;
        const normalizedEmail = email3.toLowerCase().trim();
        const invitation = invitationToken ? await getActiveOrganizationInvitationByToken(invitationToken) : null;
        if (invitationToken && !invitation) {
          return res.status(400).json({
            message: "This organization invitation is invalid or has expired."
          });
        }
        if (invitation && invitation.email.toLowerCase().trim() !== normalizedEmail) {
          return res.status(400).json({
            message: "Use the same email address that received the organization invitation."
          });
        }
        if (invitation && invitation.operationalStatus !== "ACTIVE") {
          return res.status(403).json({
            message: "This organization invitation is no longer available because the organization is not currently active."
          });
        }
        const existing = await db.select().from(usersTable).where(eq(usersTable.email, normalizedEmail));
        if (existing.length > 0) {
          return res.status(409).json({ message: "Email already registered." });
        }
        const passwordHash = await bcryptjs_default.hash(password, 12);
        const [user] = await db.transaction(async (tx) => {
          const [createdUser] = await tx.insert(usersTable).values({
            email: normalizedEmail,
            passwordHash,
            firstName,
            lastName: lastName ?? null,
            phone: phone ?? null,
            username: null,
            // @ts-ignore — enum values from backup may not match generated types exactly
            segment: segment ?? null,
            // @ts-ignore
            membershipType: invitation ? "ORGANIZATION" : membershipType ?? null,
            // Invited workspace members skip the WWN membership plan flow
            membershipStatus: invitation ? "ACTIVE" : "PENDING",
            organizationId: invitation?.organizationId ?? null
          }).returning();
          await assignMembershipRegistrationId(tx, {
            userId: createdUser.id,
            organizationId: invitation?.organizationId ?? null
          });
          if (invitation) {
            await tx.insert(organizationMembersTable).values({
              organizationId: invitation.organizationId,
              userId: createdUser.id,
              role: invitation.role
            });
            await tx.update(organizationInvitationsTable).set({
              status: "ACCEPTED",
              acceptedAt: /* @__PURE__ */ new Date(),
              updatedAt: /* @__PURE__ */ new Date()
            }).where(eq(organizationInvitationsTable.id, invitation.id));
          }
          return [createdUser];
        });
        await issueVerificationCode({
          userId: user.id,
          email: user.email,
          firstName: user.firstName
        });
        return res.status(201).json({
          message: "Account created. Please verify your email.",
          userId: user.id
        });
      } catch (error40) {
        return handleError(error40, res);
      }
    });
    router2.post("/resend-code", async (req, res) => {
      try {
        const parseResult = resendSchema.safeParse(req.body);
        if (!parseResult.success) {
          return res.status(400).json({ errors: parseResult.error.flatten() });
        }
        const { email: email3 } = parseResult.data;
        const [user] = await db.select().from(usersTable).where(eq(usersTable.email, email3.toLowerCase().trim())).limit(1);
        if (user && !user.isEmailVerified) {
          try {
            await issueVerificationCode({
              userId: user.id,
              email: user.email,
              firstName: user.firstName
            });
          } catch (error40) {
            logger.warn(
              { err: error40, userId: user.id },
              "Suppressed resend-code delivery response to avoid account enumeration"
            );
          }
        }
        return res.status(200).json({ message: GENERIC_RESEND_CODE_MESSAGE });
      } catch (error40) {
        return handleError(error40, res);
      }
    });
    router2.post("/forgot-password", async (req, res) => {
      try {
        const parseResult = forgotPasswordSchema.safeParse(req.body);
        if (!parseResult.success) {
          return res.status(400).json({ errors: parseResult.error.flatten() });
        }
        const email3 = parseResult.data.email.toLowerCase().trim();
        const [user] = await db.select().from(usersTable).where(eq(usersTable.email, email3)).limit(1);
        if (user) {
          try {
            await issuePasswordResetCode({
              userId: user.id,
              email: user.email,
              firstName: user.firstName
            });
          } catch (error40) {
            logger.warn(
              { err: error40, userId: user.id },
              "Suppressed forgot-password delivery response to avoid account enumeration"
            );
          }
        }
        return res.status(200).json({
          message: GENERIC_FORGOT_PASSWORD_MESSAGE
        });
      } catch (error40) {
        logger.error({ err: error40 }, "Forgot password error");
        return handleError(error40, res);
      }
    });
    router2.post("/verify-password-reset", async (req, res) => {
      try {
        const parseResult = verifyPasswordResetCodeSchema.safeParse(req.body);
        if (!parseResult.success) {
          return res.status(400).json({ errors: parseResult.error.flatten() });
        }
        const email3 = parseResult.data.email.toLowerCase().trim();
        const code = parseResult.data.code;
        const [user] = await db.select().from(usersTable).where(eq(usersTable.email, email3));
        if (!user) {
          return res.status(400).json({ message: "Code is invalid or expired." });
        }
        const now = /* @__PURE__ */ new Date();
        const [tokenRow] = await db.select().from(passwordResetTokensTable).where(
          and(
            eq(passwordResetTokensTable.userId, user.id),
            eq(passwordResetTokensTable.used, false),
            eq(passwordResetTokensTable.isExchangeToken, false),
            gte(passwordResetTokensTable.expiresAt, now)
          )
        ).orderBy(desc(passwordResetTokensTable.createdAt)).limit(1);
        if (!tokenRow) {
          return res.status(400).json({ message: "Code is invalid or expired." });
        }
        if (tokenRow.attempts >= PASSWORD_RESET_MAX_ATTEMPTS) {
          return res.status(429).json({ message: "Too many attempts. Request a new code." });
        }
        const codeHash = hashPasswordResetToken(`${user.id}:${code}`);
        if (!hashesMatch(tokenRow.tokenHash, codeHash)) {
          const nextAttempts = tokenRow.attempts + 1;
          await db.update(passwordResetTokensTable).set({
            attempts: nextAttempts,
            used: nextAttempts >= PASSWORD_RESET_MAX_ATTEMPTS
          }).where(eq(passwordResetTokensTable.id, tokenRow.id));
          if (nextAttempts >= PASSWORD_RESET_MAX_ATTEMPTS) {
            return res.status(429).json({ message: "Too many attempts. Request a new code." });
          }
          return res.status(400).json({ message: "Code is invalid or expired." });
        }
        const resetToken = randomBytes3(32).toString("hex");
        const resetTokenHash = hashPasswordResetToken(resetToken);
        const expiresAt = new Date(
          Date.now() + PASSWORD_RESET_EXPIRATION_MINUTES * 60 * 1e3
        );
        await db.update(passwordResetTokensTable).set({
          tokenHash: resetTokenHash,
          expiresAt,
          attempts: 0,
          isExchangeToken: true
        }).where(eq(passwordResetTokensTable.id, tokenRow.id));
        return res.status(200).json({ message: "Code verified.", token: resetToken });
      } catch (error40) {
        return handleError(error40, res);
      }
    });
    router2.post("/reset-password", async (req, res) => {
      try {
        const parseResult = resetPasswordSchema.safeParse(req.body);
        if (!parseResult.success) {
          return res.status(400).json({ errors: parseResult.error.flatten() });
        }
        const tokenHash = hashPasswordResetToken(parseResult.data.token.trim());
        const now = /* @__PURE__ */ new Date();
        const [tokenRow] = await db.select().from(passwordResetTokensTable).where(
          and(
            eq(passwordResetTokensTable.tokenHash, tokenHash),
            eq(passwordResetTokensTable.used, false),
            eq(passwordResetTokensTable.isExchangeToken, true),
            gte(passwordResetTokensTable.expiresAt, now)
          )
        ).limit(1);
        if (!tokenRow) {
          return res.status(400).json({ message: "Reset session is invalid or expired." });
        }
        const passwordHash = await bcryptjs_default.hash(parseResult.data.password, 12);
        await db.transaction(async (tx) => {
          await tx.update(usersTable).set({
            passwordHash,
            authTokenVersion: sql`${usersTable.authTokenVersion} + 1`,
            updatedAt: /* @__PURE__ */ new Date()
          }).where(eq(usersTable.id, tokenRow.userId));
          await tx.update(passwordResetTokensTable).set({ used: true }).where(eq(passwordResetTokensTable.userId, tokenRow.userId));
        });
        res.clearCookie("wwn_token", AUTH_COOKIE_OPTIONS);
        return res.status(200).json({ message: "Password updated successfully." });
      } catch (error40) {
        return handleError(error40, res);
      }
    });
    router2.post("/verify-email", async (req, res) => {
      try {
        const parseResult = verifySchema.safeParse(req.body);
        if (!parseResult.success) {
          return res.status(400).json({ errors: parseResult.error.flatten() });
        }
        const { email: email3, code } = parseResult.data;
        const users = await db.select().from(usersTable).where(eq(usersTable.email, email3.toLowerCase().trim()));
        if (users.length === 0) {
          return res.status(400).json({ message: GENERIC_VERIFY_EMAIL_FAILURE_MESSAGE });
        }
        const user = users[0];
        if (user.isEmailVerified) {
          return res.status(400).json({ message: GENERIC_VERIFY_EMAIL_FAILURE_MESSAGE });
        }
        const tokens = await db.select().from(verificationTokensTable).where(eq(verificationTokensTable.userId, user.id)).orderBy(verificationTokensTable.createdAt);
        const token = tokens[tokens.length - 1];
        if (!token || token.expiresAt < /* @__PURE__ */ new Date()) {
          return res.status(400).json({ message: GENERIC_VERIFY_EMAIL_FAILURE_MESSAGE });
        }
        if (token.attempts >= VERIFICATION_MAX_ATTEMPTS) {
          return res.status(429).json({ message: "Too many attempts. Request a new code." });
        }
        const isMatch = await bcryptjs_default.compare(code, token.codeHash);
        if (!isMatch) {
          await db.update(verificationTokensTable).set({ attempts: token.attempts + 1 }).where(eq(verificationTokensTable.id, token.id));
          return res.status(400).json({ message: GENERIC_VERIFY_EMAIL_FAILURE_MESSAGE });
        }
        await db.update(usersTable).set({ isEmailVerified: true }).where(eq(usersTable.id, user.id));
        await db.delete(verificationTokensTable).where(eq(verificationTokensTable.userId, user.id));
        const [updatedUser] = await db.select().from(usersTable).where(eq(usersTable.id, user.id));
        const jwtToken = createAuthToken(updatedUser);
        res.cookie("wwn_token", jwtToken, {
          ...AUTH_COOKIE_OPTIONS,
          maxAge: COOKIE_MAX_AGE_MS
        });
        sendMail({
          to: updatedUser.email,
          ...createWelcomeEmail({
            firstName: updatedUser.firstName,
            membershipType: updatedUser.membershipType
          })
        }).catch(
          (err) => logger.error({ err }, "Failed to send welcome email")
        );
        return res.status(200).json({
          message: "Account verified and activated!",
          user: await formatUserProfileWithOnboarding(updatedUser)
        });
      } catch (error40) {
        return handleError(error40, res);
      }
    });
    router2.post("/login", async (req, res) => {
      try {
        const parseResult = loginSchema.safeParse(req.body);
        if (!parseResult.success) {
          return res.status(400).json({ errors: parseResult.error.flatten() });
        }
        const { email: email3, password } = parseResult.data;
        const users = await db.select().from(usersTable).where(eq(usersTable.email, email3));
        const user = users[0];
        if (!user) {
          return res.status(401).json({ message: "Invalid email or password." });
        }
        const isPasswordValid = await bcryptjs_default.compare(password, user.passwordHash);
        if (!isPasswordValid) {
          return res.status(401).json({ message: "Invalid email or password." });
        }
        if (user.deletedAt != null) {
          return res.status(403).json({ message: "Account is deleted." });
        }
        if (!user.isEmailVerified) {
          return res.status(403).json({
            message: "Please verify your email before logging in.",
            emailNotVerified: true,
            email: user.email
          });
        }
        const token = createAuthToken(user);
        res.cookie("wwn_token", token, {
          ...AUTH_COOKIE_OPTIONS,
          maxAge: COOKIE_MAX_AGE_MS
        });
        return res.status(200).json({
          message: "Login successful.",
          user: await formatUserProfileWithOnboarding(user)
        });
      } catch (error40) {
        return handleError(error40, res);
      }
    });
    router2.get("/me", async (req, res) => {
      const user = await resolveAuthenticatedUser(req.cookies?.wwn_token);
      if (!user) {
        return res.status(401).json({ message: "Invalid or expired token." });
      }
      try {
        return res.status(200).json({ user: await formatUserProfileWithOnboarding(user) });
      } catch {
        return res.status(401).json({ message: "Invalid or expired token." });
      }
    });
    router2.post("/logout", (_req, res) => {
      res.clearCookie("wwn_token", AUTH_COOKIE_OPTIONS);
      return res.status(200).json({ message: "Logged out successfully." });
    });
    auth_default = router2;
  }
});

// src/lib/investment-constants.ts
var INVESTMENT_WALLET_OWNER_ID;
var init_investment_constants = __esm({
  "src/lib/investment-constants.ts"() {
    "use strict";
    INVESTMENT_WALLET_OWNER_ID = 1;
  }
});

// src/lib/investment-funding.ts
function isUniqueViolation2(err) {
  if (typeof err !== "object" || err === null) return false;
  const record2 = err;
  const directCode = typeof record2.code === "string" ? record2.code : null;
  const cause = record2.cause;
  const causeCode = typeof cause === "object" && cause !== null && "code" in cause && typeof cause.code === "string" ? cause.code : null;
  return directCode === "23505" || causeCode === "23505";
}
async function ensureWalletWith(conn, ownerType, ownerId) {
  const existing = await conn.select().from(walletsTable).where(
    and(
      eq(walletsTable.ownerType, ownerType),
      eq(walletsTable.ownerId, ownerId)
    )
  );
  if (existing.length) return existing[0];
  const [created] = await conn.insert(walletsTable).values({ ownerType, ownerId }).returning();
  return created;
}
async function hasInvestmentWalletFundingWith(conn, interestId) {
  const [row] = await conn.select({
    hasFunding: sql`exists (
        select 1
        from wallet_transactions wt
        where (
          wt.type = 'INVESTMENT_PURCHASE'
          or (
            wt.type = 'ADJUSTMENT'
            and coalesce(wt.metadata ->> 'backfillKind', '') = 'LEGACY_CONFIRMED_INVESTMENT_FUNDING'
          )
        )
        and coalesce(wt.metadata ->> 'investmentInterestId', '') = ${String(interestId)}
      )`
  }).from(investmentInterestsTable).where(eq(investmentInterestsTable.id, interestId));
  return row?.hasFunding === true;
}
async function backfillConfirmedInvestmentFundingWith(conn, input) {
  const [interest] = await conn.select({
    id: investmentInterestsTable.id,
    userId: investmentInterestsTable.userId,
    opportunityId: investmentInterestsTable.opportunityId,
    amount: investmentInterestsTable.amount,
    status: investmentInterestsTable.status,
    confirmedAt: investmentInterestsTable.confirmedAt,
    opportunityTitle: investmentOpportunitiesTable.title
  }).from(investmentInterestsTable).leftJoin(
    investmentOpportunitiesTable,
    eq(
      investmentInterestsTable.opportunityId,
      investmentOpportunitiesTable.id
    )
  ).where(eq(investmentInterestsTable.id, input.interestId));
  if (!interest) {
    throw new Error("Investment interest not found.");
  }
  if (interest.status !== "CONFIRMED") {
    throw new Error("Only confirmed investments can be funding-backfilled.");
  }
  const hasFunding = await hasInvestmentWalletFundingWith(conn, interest.id);
  if (hasFunding) {
    throw new Error("This confirmed investment already has wallet funding.");
  }
  const investmentWallet = await ensureWalletWith(
    conn,
    "INVESTMENT",
    INVESTMENT_WALLET_OWNER_ID
  );
  const now = /* @__PURE__ */ new Date();
  const amountText = String(interest.amount);
  const idempotencyKey = `investment_funding_backfill:${interest.id}`;
  const [existingCreditTransaction] = await conn.select().from(walletTransactionsTable).where(eq(walletTransactionsTable.idempotencyKey, idempotencyKey));
  let creditTransaction = existingCreditTransaction ?? null;
  if (!creditTransaction) {
    try {
      const [created] = await conn.insert(walletTransactionsTable).values({
        type: "ADJUSTMENT",
        idempotencyKey,
        toWalletId: investmentWallet.id,
        amount: amountText,
        metadata: {
          investmentInterestId: interest.id,
          opportunityId: interest.opportunityId,
          investorId: interest.userId,
          approvedByAdminId: input.approvedByAdminId ?? null,
          source: "ADMIN_BACKFILL",
          backfillKind: "LEGACY_CONFIRMED_INVESTMENT_FUNDING",
          note: input.note?.trim() || "Historical confirmed investment funding backfilled into the Investment wallet."
        }
      }).returning();
      creditTransaction = created;
    } catch (err) {
      if (!isUniqueViolation2(err)) throw err;
      const [row] = await conn.select().from(walletTransactionsTable).where(eq(walletTransactionsTable.idempotencyKey, idempotencyKey));
      creditTransaction = row ?? null;
      if (!creditTransaction) throw err;
    }
  }
  const [existingPurchaseActivity] = await conn.select({ id: investmentTransactionsTable.id }).from(investmentTransactionsTable).where(
    and(
      eq(investmentTransactionsTable.userId, interest.userId),
      eq(investmentTransactionsTable.opportunityId, interest.opportunityId),
      eq(investmentTransactionsTable.type, "INVESTMENT_PURCHASE"),
      eq(investmentTransactionsTable.amount, amountText)
    )
  );
  let purchaseActivityId = existingPurchaseActivity?.id ?? null;
  if (!existingPurchaseActivity) {
    const [purchaseActivity] = await conn.insert(investmentTransactionsTable).values({
      userId: interest.userId,
      opportunityId: interest.opportunityId,
      amount: amountText,
      type: "INVESTMENT_PURCHASE",
      description: "Historical confirmed investment funding backfilled by admin into the Investment wallet.",
      processedAt: interest.confirmedAt ?? now,
      createdAt: now
    }).returning();
    purchaseActivityId = purchaseActivity.id;
  }
  return {
    interestId: interest.id,
    userId: interest.userId,
    opportunityId: interest.opportunityId,
    opportunityTitle: interest.opportunityTitle ?? null,
    amount: Number(interest.amount ?? 0),
    creditTransactionId: creditTransaction.id,
    purchaseActivityId
  };
}
async function recalculateInvestmentRaisedAmount(tx, opportunityId) {
  const [interestAgg] = await tx.select({ total: sum(investmentInterestsTable.amount) }).from(investmentInterestsTable).where(
    and(
      eq(investmentInterestsTable.opportunityId, opportunityId),
      eq(investmentInterestsTable.status, "CONFIRMED")
    )
  );
  const [ascaAgg] = await tx.select({ total: sum(ascasTable.currentAmount) }).from(ascasTable).where(
    and(
      eq(ascasTable.investmentId, opportunityId),
      eq(ascasTable.status, "INVESTED")
    )
  );
  const totalRaised = (Number(interestAgg?.total || 0) + Number(ascaAgg?.total || 0)).toString();
  await tx.update(investmentOpportunitiesTable).set({
    raisedAmount: totalRaised,
    updatedAt: /* @__PURE__ */ new Date()
  }).where(eq(investmentOpportunitiesTable.id, opportunityId));
  return totalRaised;
}
var init_investment_funding = __esm({
  "src/lib/investment-funding.ts"() {
    "use strict";
    init_schema2();
    init_drizzle_orm();
    init_investment_constants();
  }
});

// src/lib/membership-plan-tiers.ts
function getAllowedMembershipPlanTiers(membershipType) {
  return MEMBERSHIP_PLAN_TIERS_BY_TYPE[membershipType];
}
function isAllowedMembershipPlanTier(params) {
  return getAllowedMembershipPlanTiers(params.membershipType).includes(
    params.tier.toUpperCase()
  );
}
function isLegacyMembershipPlanTier(tier) {
  if (!tier) return false;
  return LEGACY_MEMBERSHIP_PLAN_TIERS.includes(
    tier.toUpperCase()
  );
}
var MEMBERSHIP_PLAN_TIERS_BY_TYPE, LEGACY_MEMBERSHIP_PLAN_TIERS;
var init_membership_plan_tiers = __esm({
  "src/lib/membership-plan-tiers.ts"() {
    "use strict";
    MEMBERSHIP_PLAN_TIERS_BY_TYPE = {
      INDIVIDUAL: ["PROFESSIONAL", "ENTREPRENEUR", "YOUTH", "ELITE"],
      ORGANIZATION: ["COMMUNITY", "EDUCATION", "GRASSROOT"],
      INVESTOR: ["WORKER", "IMPACT", "SPONSOR"]
    };
    LEGACY_MEMBERSHIP_PLAN_TIERS = [
      "STARTER",
      "PROFESSIONAL",
      "ELITE",
      "ENTREPRENEUR"
    ];
  }
});

// src/lib/investments.ts
function calculateAccruedInterest(params) {
  if (!Number.isFinite(params.principal) || params.principal <= 0) return 0;
  if (!Number.isFinite(params.annualRatePct) || params.annualRatePct <= 0)
    return 0;
  const msPerDay = 1e3 * 60 * 60 * 24;
  const start = params.startAt;
  const asOf = params.asOf ?? /* @__PURE__ */ new Date();
  let end = asOf;
  if (params.stopAt && params.stopAt.getTime() < end.getTime()) end = params.stopAt;
  if (params.termDays && params.termDays > 0) {
    const maturity = new Date(start.getTime() + params.termDays * msPerDay);
    if (maturity.getTime() < end.getTime()) end = maturity;
  }
  const days = Math.max(0, Math.floor((end.getTime() - start.getTime()) / msPerDay));
  if (days <= 0) return 0;
  const annualRate = params.annualRatePct / 100;
  return params.principal * annualRate * (days / 365);
}
function formatTermFromDeadline(params) {
  const msPerDay = 1e3 * 60 * 60 * 24;
  const days = Math.max(
    0,
    Math.ceil((params.deadline.getTime() - params.startAt.getTime()) / msPerDay)
  );
  if (days >= 365) return `${Math.round(days / 365)} years`;
  if (days >= 30) return `${Math.round(days / 30)} months`;
  return `${days} days`;
}
var init_investments = __esm({
  "src/lib/investments.ts"() {
    "use strict";
  }
});

// src/lib/live-events.ts
import { randomUUID } from "crypto";
function writeSse(res, value) {
  res.write(value);
}
function writeEvent(res, event) {
  writeSse(res, `id: ${event.id}
`);
  writeSse(res, `data: ${JSON.stringify(event)}

`);
}
function subscribeUserToLiveEvents(userId, res) {
  const set2 = subscribersByUserId.get(userId) ?? /* @__PURE__ */ new Set();
  set2.add(res);
  subscribersByUserId.set(userId, set2);
  return () => {
    const current = subscribersByUserId.get(userId);
    if (!current) return;
    current.delete(res);
    if (current.size === 0) subscribersByUserId.delete(userId);
  };
}
function publishLiveEventToUser(userId, input) {
  const event = {
    id: randomUUID(),
    ts: (/* @__PURE__ */ new Date()).toISOString(),
    kind: input.kind,
    scopes: input.scopes,
    payload: input.payload
  };
  const subscribers = subscribersByUserId.get(userId);
  if (!subscribers || subscribers.size === 0) return;
  for (const res of subscribers) {
    try {
      writeEvent(res, event);
    } catch {
      subscribers.delete(res);
    }
  }
  if (subscribers.size === 0) subscribersByUserId.delete(userId);
}
function writePing(res) {
  try {
    writeSse(res, `: ping ${Date.now()}

`);
  } catch {
  }
}
var subscribersByUserId;
var init_live_events = __esm({
  "src/lib/live-events.ts"() {
    "use strict";
    subscribersByUserId = /* @__PURE__ */ new Map();
  }
});

// src/lib/notifications.ts
async function createNotificationWith(session, input) {
  const [created] = await session.insert(notificationsTable).values({
    userId: input.userId,
    category: input.category,
    severity: input.severity,
    title: input.title,
    body: input.body,
    actionLabel: input.actionLabel ?? null,
    actionHref: input.actionHref ?? null
  }).returning();
  publishLiveEventToUser(input.userId, {
    kind: "DATA_CHANGED",
    scopes: ["notifications"],
    payload: { action: "notification_created", notificationId: created.id }
  });
  return created;
}
async function listNotificationsWith(session, input) {
  const where = input.includeRead ? eq(notificationsTable.userId, input.userId) : and(
    eq(notificationsTable.userId, input.userId),
    eq(notificationsTable.read, false)
  );
  return session.select().from(notificationsTable).where(where).orderBy(desc(notificationsTable.createdAt), desc(notificationsTable.id)).limit(input.limit).offset(input.offset);
}
async function getUnreadCountWith(session, userId) {
  const [row] = await session.select({ value: count() }).from(notificationsTable).where(
    and(eq(notificationsTable.userId, userId), eq(notificationsTable.read, false))
  );
  return Number(row?.value ?? 0);
}
async function getNotificationByIdWith(session, input) {
  const [row] = await session.select().from(notificationsTable).where(and(eq(notificationsTable.userId, input.userId), eq(notificationsTable.id, input.id)));
  return row ?? null;
}
async function markNotificationReadWith(session, input) {
  const existing = await getNotificationByIdWith(session, input);
  if (!existing) return null;
  if (existing.read) return existing;
  const now = /* @__PURE__ */ new Date();
  const [updated] = await session.update(notificationsTable).set({ read: true, readAt: now }).where(and(eq(notificationsTable.userId, input.userId), eq(notificationsTable.id, input.id))).returning();
  publishLiveEventToUser(input.userId, {
    kind: "DATA_CHANGED",
    scopes: ["notifications"],
    payload: { action: "notification_read", notificationId: input.id }
  });
  return updated ?? existing;
}
async function markAllNotificationsReadWith(session, userId) {
  const updated = await session.update(notificationsTable).set({ read: true, readAt: /* @__PURE__ */ new Date() }).where(and(eq(notificationsTable.userId, userId), eq(notificationsTable.read, false))).returning({ id: notificationsTable.id });
  if (updated.length) {
    publishLiveEventToUser(userId, {
      kind: "DATA_CHANGED",
      scopes: ["notifications"],
      payload: { action: "notifications_read_all", count: updated.length }
    });
  }
  return updated.length;
}
var init_notifications = __esm({
  "src/lib/notifications.ts"() {
    "use strict";
    init_schema2();
    init_drizzle_orm();
    init_live_events();
  }
});

// src/lib/push.ts
async function upsertExpoPushTokenWith(session, input) {
  const now = /* @__PURE__ */ new Date();
  const existing = await session.select().from(userPushTokensTable).where(eq(userPushTokensTable.token, input.token)).limit(1);
  if (existing[0]) {
    const [updated] = await session.update(userPushTokensTable).set({
      userId: input.userId,
      platform: "EXPO",
      deviceName: input.deviceName ?? null,
      deviceId: input.deviceId ?? null,
      isEnabled: true,
      lastSeenAt: now,
      updatedAt: now
    }).where(eq(userPushTokensTable.id, existing[0].id)).returning();
    return updated;
  }
  const [created] = await session.insert(userPushTokensTable).values({
    userId: input.userId,
    platform: "EXPO",
    token: input.token,
    deviceName: input.deviceName ?? null,
    deviceId: input.deviceId ?? null,
    isEnabled: true,
    lastSeenAt: now,
    updatedAt: now
  }).returning();
  return created;
}
async function disableExpoPushTokenWith(session, input) {
  const now = /* @__PURE__ */ new Date();
  const [updated] = await session.update(userPushTokensTable).set({ isEnabled: false, updatedAt: now }).where(
    and(
      eq(userPushTokensTable.userId, input.userId),
      eq(userPushTokensTable.token, input.token)
    )
  ).returning();
  return updated ?? null;
}
async function listActiveExpoPushTokensWith(session, userId) {
  const rows = await session.select({ token: userPushTokensTable.token }).from(userPushTokensTable).where(
    and(
      eq(userPushTokensTable.userId, userId),
      eq(userPushTokensTable.isEnabled, true),
      eq(userPushTokensTable.platform, "EXPO")
    )
  );
  return rows.map((r) => r.token);
}
function chunk(input, size) {
  if (size <= 0) return [input];
  const output = [];
  for (let i = 0; i < input.length; i += size) {
    output.push(input.slice(i, i + size));
  }
  return output;
}
async function sendExpoPushToTokens(input) {
  const tokens = [...new Set(input.tokens)].filter((t) => t.trim().length > 0);
  if (tokens.length === 0) {
    return { successCount: 0, errorCount: 0, tokensToDisable: [] };
  }
  const messages = tokens.map((to) => ({
    to,
    sound: "default",
    title: input.title,
    body: input.body,
    data: input.data ?? {}
  }));
  const tokensToDisable = /* @__PURE__ */ new Set();
  let successCount = 0;
  let errorCount = 0;
  for (const batch of chunk(messages, 100)) {
    const res = await fetch("https://exp.host/--/api/v2/push/send", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json"
      },
      body: JSON.stringify(batch)
    });
    if (!res.ok) {
      const payload = await res.text().catch(() => "");
      throw new Error(`Expo push send failed: HTTP ${res.status} ${payload}`);
    }
    const json3 = await res.json().catch(() => null);
    const tickets = Array.isArray(json3) ? json3 : json3?.data;
    if (!Array.isArray(tickets)) {
      throw new Error("Expo push send failed: unexpected response payload");
    }
    for (let i = 0; i < tickets.length && i < batch.length; i += 1) {
      const ticket = tickets[i];
      const to = batch[i]?.to;
      if (!to) continue;
      if (ticket && ticket.status === "ok") {
        successCount += 1;
        continue;
      }
      errorCount += 1;
      const message = typeof ticket?.message === "string" ? ticket.message : "";
      const details = ticket && typeof ticket.details === "object" && ticket.details ? ticket.details : null;
      const detailError = typeof details?.error === "string" ? details.error : null;
      const shouldDisable = detailError === "DeviceNotRegistered" || detailError === "InvalidPushToken" || /not a valid expo push token/i.test(message);
      if (shouldDisable) {
        tokensToDisable.add(to);
      }
    }
  }
  return {
    successCount,
    errorCount,
    tokensToDisable: [...tokensToDisable]
  };
}
var init_push = __esm({
  "src/lib/push.ts"() {
    "use strict";
    init_schema2();
    init_drizzle_orm();
  }
});

// src/lib/notification-preferences.ts
function defaultEnabled(channel) {
  if (channel === "PUSH") return true;
  return true;
}
async function isChannelEnabledForCategoryWith(session, input) {
  if (input.channel === "EMAIL") return true;
  const [row] = await session.select({ enabled: userNotificationPreferencesTable.enabled }).from(userNotificationPreferencesTable).where(
    and(
      eq(userNotificationPreferencesTable.userId, input.userId),
      eq(userNotificationPreferencesTable.channel, input.channel),
      eq(userNotificationPreferencesTable.category, input.category)
    )
  ).limit(1);
  return row ? row.enabled : defaultEnabled(input.channel);
}
async function upsertNotificationPreferenceWith(session, input) {
  const enabled2 = input.channel === "EMAIL" ? true : input.enabled;
  const now = /* @__PURE__ */ new Date();
  const existing = await session.select({ id: userNotificationPreferencesTable.id }).from(userNotificationPreferencesTable).where(
    and(
      eq(userNotificationPreferencesTable.userId, input.userId),
      eq(userNotificationPreferencesTable.channel, input.channel),
      eq(userNotificationPreferencesTable.category, input.category)
    )
  ).limit(1);
  if (existing[0]) {
    const [updated] = await session.update(userNotificationPreferencesTable).set({ enabled: enabled2, updatedAt: now }).where(eq(userNotificationPreferencesTable.id, existing[0].id)).returning();
    return updated;
  }
  const [created] = await session.insert(userNotificationPreferencesTable).values({
    userId: input.userId,
    channel: input.channel,
    category: input.category,
    enabled: enabled2,
    updatedAt: now
  }).returning();
  return created;
}
async function listNotificationPreferencesWith(session, userId) {
  const rows = await session.select({
    channel: userNotificationPreferencesTable.channel,
    category: userNotificationPreferencesTable.category,
    enabled: userNotificationPreferencesTable.enabled
  }).from(userNotificationPreferencesTable).where(eq(userNotificationPreferencesTable.userId, userId));
  const categories = notificationCategoryEnum.enumValues;
  const channels = notificationChannelEnum.enumValues;
  const defaults2 = /* @__PURE__ */ new Map();
  for (const channel of channels) {
    for (const category of categories) {
      defaults2.set(`${channel}:${category}`, defaultEnabled(channel));
    }
  }
  for (const row of rows) {
    defaults2.set(`${row.channel}:${row.category}`, row.enabled);
  }
  return {
    categories,
    channels,
    preferences: channels.map((channel) => ({
      channel,
      categories: categories.map((category) => ({
        category,
        enabled: channel === "EMAIL" ? true : defaults2.get(`${channel}:${category}`) ?? defaultEnabled(channel)
      }))
    }))
  };
}
var init_notification_preferences = __esm({
  "src/lib/notification-preferences.ts"() {
    "use strict";
    init_schema2();
    init_drizzle_orm();
  }
});

// src/lib/notification-dispatcher.ts
function readBooleanEnv(key) {
  const raw = process.env[key];
  if (!raw) return false;
  const normalized = raw.trim().toLowerCase();
  return normalized === "1" || normalized === "true" || normalized === "yes";
}
function shouldSendEmailForCategory(category) {
  if (!readBooleanEnv("NOTIFICATIONS_EMAIL_ENABLED")) return false;
  if (category === "MEMBERSHIP") {
    const flag = process.env.NOTIFICATIONS_EMAIL_MEMBERSHIP_ENABLED;
    if (flag == null) return true;
    return readBooleanEnv("NOTIFICATIONS_EMAIL_MEMBERSHIP_ENABLED");
  }
  if (category === "PAYMENT") {
    const flag = process.env.NOTIFICATIONS_EMAIL_PAYMENT_ENABLED;
    if (flag == null) return true;
    return readBooleanEnv("NOTIFICATIONS_EMAIL_PAYMENT_ENABLED");
  }
  if (category === "SAVINGS") {
    const flag = process.env.NOTIFICATIONS_EMAIL_SAVINGS_ENABLED;
    if (flag == null) return true;
    return readBooleanEnv("NOTIFICATIONS_EMAIL_SAVINGS_ENABLED");
  }
  if (category === "LENDING") {
    const flag = process.env.NOTIFICATIONS_EMAIL_LENDING_ENABLED;
    if (flag == null) return true;
    return readBooleanEnv("NOTIFICATIONS_EMAIL_LENDING_ENABLED");
  }
  return true;
}
function shouldSendPushForCategory(category) {
  if (!readBooleanEnv("NOTIFICATIONS_PUSH_ENABLED")) return false;
  if (category === "MEMBERSHIP") {
    const flag = process.env.NOTIFICATIONS_PUSH_MEMBERSHIP_ENABLED;
    if (flag == null) return true;
    return readBooleanEnv("NOTIFICATIONS_PUSH_MEMBERSHIP_ENABLED");
  }
  if (category === "PAYMENT") {
    const flag = process.env.NOTIFICATIONS_PUSH_PAYMENT_ENABLED;
    if (flag == null) return true;
    return readBooleanEnv("NOTIFICATIONS_PUSH_PAYMENT_ENABLED");
  }
  if (category === "SAVINGS") {
    const flag = process.env.NOTIFICATIONS_PUSH_SAVINGS_ENABLED;
    if (flag == null) return true;
    return readBooleanEnv("NOTIFICATIONS_PUSH_SAVINGS_ENABLED");
  }
  if (category === "LENDING") {
    const flag = process.env.NOTIFICATIONS_PUSH_LENDING_ENABLED;
    if (flag == null) return true;
    return readBooleanEnv("NOTIFICATIONS_PUSH_LENDING_ENABLED");
  }
  return true;
}
async function notifyInAppWith(session, input) {
  return createNotificationWith(session, input);
}
async function deliverPushIfEnabled(input) {
  if (!shouldSendPushForCategory(input.category)) {
    return { status: "SKIPPED", reason: "push_disabled_by_env" };
  }
  const enabled2 = await isChannelEnabledForCategoryWith(db, {
    userId: input.userId,
    channel: "PUSH",
    category: input.category
  });
  if (!enabled2) {
    return { status: "SKIPPED", reason: "push_disabled_by_user" };
  }
  const tokens = await listActiveExpoPushTokensWith(db, input.userId);
  if (tokens.length === 0) {
    return { status: "SKIPPED", reason: "no_push_tokens" };
  }
  const pushResult = await sendExpoPushToTokens({
    tokens,
    title: input.title,
    body: input.body,
    data: input.data ?? {}
  });
  if (pushResult.tokensToDisable.length > 0) {
    await Promise.all(
      pushResult.tokensToDisable.map(
        (token) => disableExpoPushTokenWith(db, { userId: input.userId, token }).catch(
          () => null
        )
      )
    );
  }
  if (pushResult.successCount > 0) {
    return { status: "SENT" };
  }
  const allInvalid = pushResult.tokensToDisable.length > 0 && pushResult.tokensToDisable.length === tokens.length;
  return { status: "SKIPPED", reason: allInvalid ? "push_tokens_invalid" : "push_failed" };
}
async function deliverPushIgnoringPreferences(input) {
  if (!shouldSendPushForCategory(input.category)) {
    return { status: "SKIPPED", reason: "push_disabled_by_env" };
  }
  const tokens = await listActiveExpoPushTokensWith(db, input.userId);
  if (tokens.length === 0) {
    return { status: "SKIPPED", reason: "no_push_tokens" };
  }
  const pushResult = await sendExpoPushToTokens({
    tokens,
    title: input.title,
    body: input.body,
    data: input.data ?? {}
  });
  if (pushResult.tokensToDisable.length > 0) {
    await Promise.all(
      pushResult.tokensToDisable.map(
        (token) => disableExpoPushTokenWith(db, { userId: input.userId, token }).catch(
          () => null
        )
      )
    );
  }
  if (pushResult.successCount > 0) {
    return { status: "SENT" };
  }
  const allInvalid = pushResult.tokensToDisable.length > 0 && pushResult.tokensToDisable.length === tokens.length;
  return { status: "SKIPPED", reason: allInvalid ? "push_tokens_invalid" : "push_failed" };
}
async function deliverMembershipActivatedEmailIfEnabled(input) {
  if (!shouldSendEmailForCategory("MEMBERSHIP")) {
    return { status: "SKIPPED", reason: "email_disabled_by_env" };
  }
  const enabled2 = await isChannelEnabledForCategoryWith(db, {
    userId: input.userId,
    channel: "EMAIL",
    category: "MEMBERSHIP"
  });
  if (!enabled2) {
    return { status: "SKIPPED", reason: "email_disabled_by_user" };
  }
  const { subject, text: text2, html } = createMembershipActivatedEmail({
    firstName: input.firstName,
    planName: input.planName,
    renewalDate: input.renewalDate,
    amount: input.amount,
    currency: input.currency
  });
  await sendMail({ to: input.to, subject, text: text2, html });
  return { status: "SENT" };
}
async function deliverReminderEmailIfEnabled(input) {
  if (!shouldSendEmailForCategory(input.category)) {
    return { status: "SKIPPED", reason: "email_disabled_by_env" };
  }
  const enabled2 = await isChannelEnabledForCategoryWith(db, {
    userId: input.userId,
    channel: "EMAIL",
    category: input.category
  });
  if (!enabled2) {
    return { status: "SKIPPED", reason: "email_disabled_by_user" };
  }
  const { subject, text: text2, html } = createReminderEmail({
    firstName: input.firstName,
    eyebrow: "Reminder",
    title: input.title,
    intro: input.intro,
    lines: input.lines,
    actionLabel: input.actionLabel ?? null,
    actionHref: input.actionHref ?? null
  });
  await sendMail({ to: input.to, subject, text: text2, html });
  return { status: "SENT" };
}
async function deliverReminderEmailIgnoringPreferences(input) {
  if (!shouldSendEmailForCategory(input.category)) {
    return { status: "SKIPPED", reason: "email_disabled_by_env" };
  }
  const { subject, text: text2, html } = createReminderEmail({
    firstName: input.firstName,
    eyebrow: "Reminder",
    title: input.title,
    intro: input.intro,
    lines: input.lines,
    actionLabel: input.actionLabel ?? null,
    actionHref: input.actionHref ?? null
  });
  await sendMail({ to: input.to, subject, text: text2, html });
  return { status: "SENT" };
}
var init_notification_dispatcher = __esm({
  "src/lib/notification-dispatcher.ts"() {
    "use strict";
    init_mailer();
    init_notifications();
    init_src2();
    init_push();
    init_notification_preferences();
  }
});

// src/lib/investment-returns.ts
function roundMoney(value) {
  return Number(value.toFixed(2));
}
function isUniqueViolation3(err) {
  if (typeof err !== "object" || err === null) return false;
  const record2 = err;
  const directCode = typeof record2.code === "string" ? record2.code : null;
  const cause = record2.cause;
  const causeCode = typeof cause === "object" && cause !== null && "code" in cause && typeof cause.code === "string" ? cause.code : null;
  return directCode === "23505" || causeCode === "23505";
}
async function ensureWalletWith2(conn, ownerType, ownerId) {
  const existing = await conn.select().from(walletsTable).where(
    and(
      eq(walletsTable.ownerType, ownerType),
      eq(walletsTable.ownerId, ownerId)
    )
  );
  if (existing.length) return existing[0];
  const [created] = await conn.insert(walletsTable).values({ ownerType, ownerId }).returning();
  return created;
}
async function getWalletBalanceWith(conn, walletId) {
  const [row] = await conn.select({
    total: sum(
      sql`case
          when ${walletTransactionsTable.toWalletId} = ${walletId} then ${walletTransactionsTable.amount}
          when ${walletTransactionsTable.fromWalletId} = ${walletId} then -${walletTransactionsTable.amount}
          else 0
        end`
    )
  }).from(walletTransactionsTable).where(
    or(
      eq(walletTransactionsTable.toWalletId, walletId),
      eq(walletTransactionsTable.fromWalletId, walletId)
    )
  );
  return Number(row?.total ?? 0);
}
async function getInvestmentReturnPayoutSnapshotWith(conn, interestId, asOf = /* @__PURE__ */ new Date()) {
  const [row] = await conn.select({
    interestId: investmentInterestsTable.id,
    userId: investmentInterestsTable.userId,
    opportunityId: investmentInterestsTable.opportunityId,
    principalAmount: investmentInterestsTable.amount,
    status: investmentInterestsTable.status,
    confirmedAt: investmentInterestsTable.confirmedAt,
    deadline: investmentOpportunitiesTable.deadline,
    expectedReturnPct: investmentOpportunitiesTable.expectedReturnPct
  }).from(investmentInterestsTable).innerJoin(
    investmentOpportunitiesTable,
    eq(investmentInterestsTable.opportunityId, investmentOpportunitiesTable.id)
  ).where(eq(investmentInterestsTable.id, interestId));
  if (!row) {
    throw new Error("Investment interest not found.");
  }
  if (row.status !== "CONFIRMED") {
    throw new Error("Only confirmed investments can receive return payouts.");
  }
  if (!row.confirmedAt) {
    throw new Error("Confirmed investment is missing its confirmation date.");
  }
  const [paidRow] = await conn.select({
    total: sum(investmentTransactionsTable.amount)
  }).from(investmentTransactionsTable).where(
    and(
      eq(investmentTransactionsTable.userId, row.userId),
      eq(investmentTransactionsTable.opportunityId, row.opportunityId),
      eq(investmentTransactionsTable.type, "INVESTMENT_RETURN_PAYOUT")
    )
  );
  const [paidPrincipalRow] = await conn.select({
    total: sum(investmentTransactionsTable.amount)
  }).from(investmentTransactionsTable).where(
    and(
      eq(investmentTransactionsTable.userId, row.userId),
      eq(investmentTransactionsTable.opportunityId, row.opportunityId),
      eq(investmentTransactionsTable.type, "INVESTMENT_PRINCIPAL_PAYOUT")
    )
  );
  const principalAmount = Number(row.principalAmount ?? 0);
  const accruedReturnAmount = roundMoney(
    calculateAccruedInterest({
      principal: principalAmount,
      annualRatePct: Number(row.expectedReturnPct ?? 0),
      startAt: row.confirmedAt,
      asOf,
      stopAt: row.deadline
    })
  );
  const paidPrincipalAmount = roundMoney(Number(paidPrincipalRow?.total ?? 0));
  const paidReturnAmount = roundMoney(Number(paidRow?.total ?? 0));
  const payablePrincipalAmount = row.deadline.getTime() <= asOf.getTime() ? roundMoney(Math.max(0, principalAmount - paidPrincipalAmount)) : 0;
  const payableReturnAmount = roundMoney(
    Math.max(0, accruedReturnAmount - paidReturnAmount)
  );
  return {
    interestId: row.interestId,
    userId: row.userId,
    opportunityId: row.opportunityId,
    principalAmount,
    expectedReturnPct: Number(row.expectedReturnPct ?? 0),
    confirmedAt: row.confirmedAt,
    deadline: row.deadline,
    isMatured: row.deadline.getTime() <= asOf.getTime(),
    accruedReturnAmount,
    paidPrincipalAmount,
    payablePrincipalAmount,
    paidReturnAmount,
    payableReturnAmount
  };
}
async function listDueInvestmentReturnInterestIdsWith(conn, asOf = /* @__PURE__ */ new Date()) {
  const rows = await conn.select({ interestId: investmentInterestsTable.id }).from(investmentInterestsTable).innerJoin(
    investmentOpportunitiesTable,
    eq(investmentInterestsTable.opportunityId, investmentOpportunitiesTable.id)
  ).where(
    and(
      eq(investmentInterestsTable.status, "CONFIRMED"),
      lte(investmentOpportunitiesTable.deadline, asOf)
    )
  );
  return rows.map((row) => row.interestId);
}
async function payoutInvestmentReturnWith(conn, input) {
  await conn.execute(
    sql`select pg_advisory_xact_lock(${INVESTMENT_RETURN_PAYOUT_LOCK_KEY_A}, ${input.interestId})`
  );
  const asOf = input.asOf ?? /* @__PURE__ */ new Date();
  const snapshot = await getInvestmentReturnPayoutSnapshotWith(
    conn,
    input.interestId,
    asOf
  );
  const principalPayoutAmount = snapshot.isMatured ? snapshot.payablePrincipalAmount : 0;
  if (snapshot.payableReturnAmount <= 0 && principalPayoutAmount <= 0) {
    throw new Error("No unpaid investment payout is available yet.");
  }
  const requestedAmount = input.amount === void 0 ? snapshot.payableReturnAmount : roundMoney(input.amount);
  if (!Number.isFinite(requestedAmount) || requestedAmount < 0) {
    throw new Error("Return payout amount must be greater than zero.");
  }
  if (requestedAmount <= 0 && principalPayoutAmount <= 0) {
    throw new Error("Return payout amount must be greater than zero.");
  }
  if (requestedAmount > snapshot.payableReturnAmount) {
    throw new Error("Return payout amount exceeds the unpaid accrued return.");
  }
  const userWallet = await ensureWalletWith2(conn, "USER", snapshot.userId);
  const investmentWallet = await ensureWalletWith2(
    conn,
    "INVESTMENT",
    INVESTMENT_WALLET_OWNER_ID
  );
  const investmentWalletBalance = await getWalletBalanceWith(conn, investmentWallet.id);
  const totalPayoutAmount = roundMoney(requestedAmount + principalPayoutAmount);
  if (investmentWalletBalance < totalPayoutAmount) {
    throw new Error("Investment wallet does not have enough balance for this payout.");
  }
  const normalizedAmount = requestedAmount.toFixed(2);
  const normalizedPrincipalAmount = principalPayoutAmount.toFixed(2);
  const [sequenceRow] = await conn.select({
    value: sql`count(*)`
  }).from(walletTransactionsTable).where(
    and(
      eq(walletTransactionsTable.type, "INVESTMENT_RETURN_PAYOUT"),
      sql`coalesce(${walletTransactionsTable.metadata} ->> 'investmentInterestId', '') = ${String(snapshot.interestId)}`
    )
  );
  const payoutSequence = Number(sequenceRow?.value ?? 0) + 1;
  const idempotencyKey = `investment_return_payout:${snapshot.interestId}:${payoutSequence}`;
  const principalIdempotencyKey = `investment_principal_payout:${snapshot.interestId}`;
  const [existingWalletTx] = await conn.select().from(walletTransactionsTable).where(eq(walletTransactionsTable.idempotencyKey, idempotencyKey));
  const [existingPrincipalWalletTx] = await conn.select().from(walletTransactionsTable).where(eq(walletTransactionsTable.idempotencyKey, principalIdempotencyKey));
  let walletTransaction = existingWalletTx ?? null;
  let principalWalletTransaction = existingPrincipalWalletTx ?? null;
  let didCreateWalletTx = false;
  let didCreatePrincipalWalletTx = false;
  if (principalPayoutAmount > 0 && !principalWalletTransaction) {
    try {
      const [created] = await conn.insert(walletTransactionsTable).values({
        type: "INVESTMENT_PRINCIPAL_PAYOUT",
        idempotencyKey: principalIdempotencyKey,
        fromWalletId: investmentWallet.id,
        toWalletId: userWallet.id,
        amount: normalizedPrincipalAmount,
        metadata: {
          investmentInterestId: snapshot.interestId,
          opportunityId: snapshot.opportunityId,
          investorId: snapshot.userId,
          source: input.source,
          paidByAdminId: input.paidByAdminId ?? null,
          principalAmount: snapshot.principalAmount,
          paidPrincipalAmountBefore: snapshot.paidPrincipalAmount
        }
      }).returning();
      principalWalletTransaction = created;
      didCreatePrincipalWalletTx = true;
    } catch (err) {
      if (!isUniqueViolation3(err)) throw err;
      const [row] = await conn.select().from(walletTransactionsTable).where(eq(walletTransactionsTable.idempotencyKey, principalIdempotencyKey));
      principalWalletTransaction = row ?? null;
      if (!principalWalletTransaction) throw err;
    }
  }
  if (requestedAmount > 0 && !walletTransaction) {
    try {
      const [created] = await conn.insert(walletTransactionsTable).values({
        type: "INVESTMENT_RETURN_PAYOUT",
        idempotencyKey,
        fromWalletId: investmentWallet.id,
        toWalletId: userWallet.id,
        amount: normalizedAmount,
        metadata: {
          investmentInterestId: snapshot.interestId,
          opportunityId: snapshot.opportunityId,
          investorId: snapshot.userId,
          source: input.source,
          paidByAdminId: input.paidByAdminId ?? null,
          accruedReturnAmount: snapshot.accruedReturnAmount,
          paidReturnAmountBefore: snapshot.paidReturnAmount
        }
      }).returning();
      walletTransaction = created;
      didCreateWalletTx = true;
    } catch (err) {
      if (!isUniqueViolation3(err)) throw err;
      const [row] = await conn.select().from(walletTransactionsTable).where(eq(walletTransactionsTable.idempotencyKey, idempotencyKey));
      walletTransaction = row ?? null;
      if (!walletTransaction) throw err;
    }
  }
  if (didCreateWalletTx || didCreatePrincipalWalletTx) {
    const notificationTitle = principalPayoutAmount > 0 && requestedAmount > 0 ? "Investment principal and return paid" : principalPayoutAmount > 0 ? "Investment principal paid" : "Investment return paid";
    const notificationBody = principalPayoutAmount > 0 && requestedAmount > 0 ? `Your investment principal and return totaling ${Number(totalPayoutAmount.toFixed(2)).toLocaleString("en-CA", { style: "currency", currency: "CAD" })} have been credited to your wallet.` : principalPayoutAmount > 0 ? `Your investment principal of ${Number(normalizedPrincipalAmount).toLocaleString("en-CA", { style: "currency", currency: "CAD" })} has been credited to your wallet.` : `Your investment return of ${Number(normalizedAmount).toLocaleString("en-CA", { style: "currency", currency: "CAD" })} has been credited to your wallet.`;
    await notifyInAppWith(conn, {
      userId: snapshot.userId,
      category: "INVESTMENT",
      severity: "SUCCESS",
      title: notificationTitle,
      body: notificationBody,
      actionLabel: "View Susunomics",
      actionHref: "/dashboard/investments"
    });
  }
  let principalInvestmentTransactionId = null;
  if (principalPayoutAmount > 0) {
    const [existingPrincipalInvestmentTransaction] = await conn.select({ id: investmentTransactionsTable.id }).from(investmentTransactionsTable).where(
      and(
        eq(investmentTransactionsTable.userId, snapshot.userId),
        eq(investmentTransactionsTable.opportunityId, snapshot.opportunityId),
        eq(investmentTransactionsTable.type, "INVESTMENT_PRINCIPAL_PAYOUT")
      )
    );
    if (existingPrincipalInvestmentTransaction) {
      principalInvestmentTransactionId = existingPrincipalInvestmentTransaction.id;
    } else {
      const [principalInvestmentTransaction] = await conn.insert(investmentTransactionsTable).values({
        userId: snapshot.userId,
        opportunityId: snapshot.opportunityId,
        amount: normalizedPrincipalAmount,
        type: "INVESTMENT_PRINCIPAL_PAYOUT",
        description: input.source === "AUTO_MATURITY" ? "Investment principal paid automatically at maturity from the Investment wallet." : "Investment principal paid by admin from the Investment wallet.",
        processedAt: asOf,
        createdAt: asOf
      }).returning();
      principalInvestmentTransactionId = principalInvestmentTransaction.id;
    }
  }
  const [existingInvestmentTransaction] = await conn.select({ id: investmentTransactionsTable.id }).from(investmentTransactionsTable).where(
    and(
      eq(investmentTransactionsTable.userId, snapshot.userId),
      eq(investmentTransactionsTable.opportunityId, snapshot.opportunityId),
      eq(investmentTransactionsTable.type, "INVESTMENT_RETURN_PAYOUT"),
      eq(investmentTransactionsTable.amount, normalizedAmount),
      eq(investmentTransactionsTable.processedAt, asOf)
    )
  );
  let investmentTransactionId = null;
  if (requestedAmount <= 0) {
    investmentTransactionId = null;
  } else if (existingInvestmentTransaction) {
    investmentTransactionId = existingInvestmentTransaction.id;
  } else {
    const [investmentTransaction] = await conn.insert(investmentTransactionsTable).values({
      userId: snapshot.userId,
      opportunityId: snapshot.opportunityId,
      amount: normalizedAmount,
      type: "INVESTMENT_RETURN_PAYOUT",
      description: input.source === "AUTO_MATURITY" ? "Investment return paid automatically at maturity from the Investment wallet." : "Investment return paid by admin from the Investment wallet.",
      processedAt: asOf,
      createdAt: asOf
    }).returning();
    investmentTransactionId = investmentTransaction.id;
  }
  return {
    amountPaid: totalPayoutAmount,
    returnAmountPaid: requestedAmount,
    principalAmountPaid: principalPayoutAmount,
    walletTransactionId: walletTransaction?.id ?? principalWalletTransaction?.id ?? null,
    principalWalletTransactionId: principalWalletTransaction?.id ?? null,
    investmentTransactionId: investmentTransactionId ?? principalInvestmentTransactionId,
    principalInvestmentTransactionId,
    snapshot
  };
}
var INVESTMENT_RETURN_PAYOUT_LOCK_KEY_A;
var init_investment_returns = __esm({
  "src/lib/investment-returns.ts"() {
    "use strict";
    init_schema2();
    init_drizzle_orm();
    init_investment_constants();
    init_investments();
    init_notification_dispatcher();
    INVESTMENT_RETURN_PAYOUT_LOCK_KEY_A = 92117;
  }
});

// src/lib/notification-deliveries.ts
function isUniqueViolation4(err) {
  if (typeof err !== "object" || err === null) return false;
  const record2 = err;
  const directCode = typeof record2.code === "string" ? record2.code : null;
  const cause = record2.cause;
  const causeCode = typeof cause === "object" && cause !== null && "code" in cause && typeof cause.code === "string" ? cause.code : null;
  return directCode === "23505" || causeCode === "23505";
}
async function reserveNotificationDeliveryWith(session, input) {
  try {
    const [created] = await session.insert(notificationDeliveriesTable).values({
      userId: input.userId,
      channel: input.channel,
      category: input.category,
      status: input.status,
      idempotencyKey: input.idempotencyKey,
      provider: input.provider ?? null,
      errorMessage: input.errorMessage ?? null,
      metadata: input.metadata ?? {},
      occurredAt: input.occurredAt ?? /* @__PURE__ */ new Date()
    }).onConflictDoNothing().returning();
    if (!created) return { reserved: false };
    return { reserved: true, row: created };
  } catch (err) {
    if (isUniqueViolation4(err)) return { reserved: false };
    throw err;
  }
}
async function finalizeNotificationDeliveryWith(session, input) {
  const [updated] = await session.update(notificationDeliveriesTable).set({
    status: input.status,
    provider: input.provider ?? null,
    errorMessage: input.errorMessage ?? null,
    notificationId: input.notificationId ?? null,
    metadata: input.metadata ?? {}
  }).where(eq(notificationDeliveriesTable.idempotencyKey, input.idempotencyKey)).returning();
  return updated ?? null;
}
var init_notification_deliveries = __esm({
  "src/lib/notification-deliveries.ts"() {
    "use strict";
    init_schema2();
    init_drizzle_orm();
  }
});

// src/lib/credit-score.ts
async function calculateCreditScore(userId) {
  const [user, consistencyScore, missedContributionsScore, participationScore] = await Promise.all([
    db.select({
      createdAt: usersTable.createdAt,
      onboardingCompletedAt: usersTable.onboardingCompletedAt,
      membershipType: usersTable.membershipType
    }).from(usersTable).where(eq(usersTable.id, userId)).then((rows) => rows[0] ?? null),
    calculatePaymentConsistency(userId),
    calculateMissedContributions(userId),
    calculateParticipation(userId)
  ]);
  const onboardingState = await getActiveOnboardingStateForUser(userId);
  if (!user) {
    throw new Error("User not found");
  }
  const userCreatedAt = user.createdAt;
  const now = /* @__PURE__ */ new Date();
  const membershipMonths = Math.max(
    1,
    Math.floor(
      (now.getTime() - userCreatedAt.getTime()) / (1e3 * 60 * 60 * 24 * 30)
    )
  );
  let durationScore = 50;
  if (membershipMonths >= 3) durationScore = 70;
  if (membershipMonths >= 6) durationScore = 85;
  if (membershipMonths >= 12) durationScore = 95;
  if (membershipMonths >= 24) durationScore = 100;
  const factors = [
    { name: "Payment Consistency", score: consistencyScore, weight: "High" },
    {
      name: "Missed Contributions",
      score: missedContributionsScore,
      weight: "High"
    },
    { name: "Membership Duration", score: durationScore, weight: "Medium" },
    {
      name: "Participation History",
      score: participationScore,
      weight: "Medium"
    }
  ];
  const totalWeight = factors.reduce((acc, f) => acc + WEIGHTS[f.weight], 0);
  const weightedScore = Math.round(
    factors.reduce((acc, f) => acc + f.score * WEIGHTS[f.weight], 0) / totalWeight
  );
  const onboardingBoost = user.membershipType === "INDIVIDUAL" && onboardingState.completed ? 65 : 0;
  if (onboardingBoost > 0) {
    factors.push({ name: "WWN Onboarding", score: 65, weight: "Low" });
  }
  const score = Math.min(100, weightedScore + onboardingBoost);
  return { score, factors };
}
async function calculatePaymentConsistency(userId) {
  const [[contributionStats], [helpingHandStats], [loanStats]] = await Promise.all([
    db.select({
      paid: sql`count(*) filter (where ${savingsContributionsTable.status} = 'PAID')`,
      lateOrMissed: sql`count(*) filter (where ${savingsContributionsTable.status} in ('MISSED'))`
    }).from(savingsContributionsTable).where(eq(savingsContributionsTable.userId, userId)),
    db.select({
      paid: sql`count(*) filter (where ${helpingHandRepaymentsTable.status} = 'PAID')`,
      lateOrMissed: sql`count(*) filter (where ${helpingHandRepaymentsTable.status} = 'LATE')`
    }).from(helpingHandRepaymentsTable).innerJoin(
      helpingHandApplicationsTable,
      eq(
        helpingHandRepaymentsTable.helpingHandApplicationId,
        helpingHandApplicationsTable.id
      )
    ).where(eq(helpingHandApplicationsTable.userId, userId)),
    db.select({
      paid: sql`count(*) filter (where ${loanRepaymentsTable.status} = 'PAID')`,
      lateOrMissed: sql`count(*) filter (where ${loanRepaymentsTable.status} = 'LATE')`
    }).from(loanRepaymentsTable).innerJoin(
      loanApplicationsTable,
      eq(loanRepaymentsTable.loanApplicationId, loanApplicationsTable.id)
    ).where(eq(loanApplicationsTable.borrowerId, userId))
  ]);
  const onTime = Number(contributionStats?.paid ?? 0) + Number(helpingHandStats?.paid ?? 0) + Number(loanStats?.paid ?? 0);
  const late2 = Number(contributionStats?.lateOrMissed ?? 0) + Number(helpingHandStats?.lateOrMissed ?? 0) + Number(loanStats?.lateOrMissed ?? 0);
  const totalProcessed = onTime + late2;
  if (totalProcessed === 0) return 50;
  const onTimePercent = onTime / totalProcessed * 100;
  let consistencyScore = 50;
  if (onTimePercent >= 100) consistencyScore = 100;
  else if (onTimePercent >= 95) consistencyScore = 90;
  else if (onTimePercent >= 90) consistencyScore = 80;
  else if (onTimePercent >= 85) consistencyScore = 70;
  else if (onTimePercent >= 80) consistencyScore = 60;
  else consistencyScore = 50;
  return consistencyScore;
}
async function calculateMissedContributions(userId) {
  const [contributionStats] = await db.select({
    total: sql`count(*)`,
    missed: sql`count(*) filter (where ${savingsContributionsTable.status} = 'MISSED')`
  }).from(savingsContributionsTable).where(eq(savingsContributionsTable.userId, userId));
  const totalContributions = Number(contributionStats?.total ?? 0);
  if (totalContributions === 0) return 100;
  const missedContributions = Number(contributionStats?.missed ?? 0);
  const missRate = missedContributions / totalContributions * 100;
  let score = 100;
  if (missRate > 0) score = 85;
  if (missRate > 5) score = 70;
  if (missRate > 10) score = 55;
  if (missRate > 20) score = 40;
  if (missRate > 30) score = 25;
  return score;
}
async function calculateParticipation(userId) {
  const [membershipStats] = await db.select({ total: sql`count(*)` }).from(circleMembershipsTable).where(eq(circleMembershipsTable.userId, userId));
  const circleCount = Number(membershipStats?.total ?? 0);
  let participationScore = 50;
  if (circleCount >= 1) participationScore = 65;
  if (circleCount >= 2) participationScore = 80;
  if (circleCount >= 3) participationScore = 95;
  return participationScore;
}
async function updateCreditScore(userId) {
  const { score, factors } = await calculateCreditScore(userId);
  await db.transaction(async (tx) => {
    const existingScores = await tx.select({ id: wwnCreditScoresTable.id }).from(wwnCreditScoresTable).where(eq(wwnCreditScoresTable.userId, userId));
    let scoreId;
    if (existingScores.length > 0) {
      scoreId = existingScores[0].id;
      await tx.update(wwnCreditScoresTable).set({
        score,
        computedAt: /* @__PURE__ */ new Date()
      }).where(eq(wwnCreditScoresTable.id, scoreId));
      await tx.delete(creditScoreFactorsTable).where(eq(creditScoreFactorsTable.creditScoreId, scoreId));
    } else {
      const [newScore] = await tx.insert(wwnCreditScoresTable).values({
        userId,
        score
      }).returning({ id: wwnCreditScoresTable.id });
      scoreId = newScore.id;
    }
    await tx.insert(creditScoreFactorsTable).values(
      factors.map((factor) => ({
        creditScoreId: scoreId,
        factorName: factor.name,
        score: factor.score,
        weight: factor.weight
      }))
    );
  });
  return { score, factors };
}
var WEIGHTS;
var init_credit_score = __esm({
  "src/lib/credit-score.ts"() {
    "use strict";
    init_src2();
    init_schema2();
    init_drizzle_orm();
    init_member_onboarding_program();
    WEIGHTS = {
      High: 0.5,
      Medium: 0.3,
      Low: 0.2
    };
  }
});

// src/lib/lending.ts
function hasMoreThanTwoDecimalPlaces(value) {
  return Math.round(value * 100) !== value * 100;
}
function formatMoneyAmount(value) {
  return (Math.round(value * 100) / 100).toFixed(2);
}
function parseMoneyAmount(value) {
  const amount = Number(value ?? 0);
  return Number.isFinite(amount) ? amount : 0;
}
function calculateRemainingPoolCapacity(targetAmount, confirmedCommittedAmount) {
  return Math.max(
    0,
    parseMoneyAmount(targetAmount) - parseMoneyAmount(confirmedCommittedAmount)
  );
}
function calculateAvailableToLend(walletBalance, reservedAmount) {
  return Math.max(
    0,
    parseMoneyAmount(walletBalance) - parseMoneyAmount(reservedAmount)
  );
}
function calculateOutstandingPrincipal(disbursedAmount, repaidAmount) {
  return Math.max(
    0,
    parseMoneyAmount(disbursedAmount) - parseMoneyAmount(repaidAmount)
  );
}
function formatExpectedReturnLabel(expectedReturnPct) {
  return `${formatMoneyAmount(expectedReturnPct)}% p.a.`;
}
function formatTermMonthsLabel(termMonths) {
  return `${termMonths} month${termMonths === 1 ? "" : "s"}`;
}
function formatRepaymentFrequencyLabel(frequency) {
  switch (frequency) {
    case "WEEKLY":
      return "Weekly";
    case "BIWEEKLY":
      return "Biweekly";
    case "MONTHLY":
    default:
      return "Monthly";
  }
}
function normalizeLendingLoanType(value) {
  return value === "COMMUNITY_LENDING" ? "COMMUNITY_LENDING" : "P2P_LENDING";
}
function isCommunityLendingLoanType(value) {
  return normalizeLendingLoanType(value) === "COMMUNITY_LENDING";
}
function isP2PLendingLoanType(value) {
  return normalizeLendingLoanType(value) === "P2P_LENDING";
}
function calculateProcessingFeeAmount(principalAmount, processingFeePct) {
  const principal = parseMoneyAmount(principalAmount);
  const feePct = parseMoneyAmount(processingFeePct);
  if (principal <= 0 || feePct <= 0) return 0;
  return principal * (feePct / 100);
}
function calculateSimpleAnnualRateAmount(principalAmount, annualRatePct, termMonths) {
  const principal = parseMoneyAmount(principalAmount);
  const ratePct = parseMoneyAmount(annualRatePct);
  const months = Number(termMonths ?? 0);
  if (principal <= 0 || ratePct <= 0 || months <= 0) return 0;
  return principal * (ratePct / 100) * (months / 12);
}
function clampPct(value, max = 100) {
  const pct = parseMoneyAmount(value);
  if (!Number.isFinite(pct)) return 0;
  return Math.max(0, Math.min(max, pct));
}
function calculatePlatformAppreciationShareAmount(appreciationAmount, platformSharePct) {
  const appreciation = Math.max(0, parseMoneyAmount(appreciationAmount));
  if (appreciation <= 0) return 0;
  const sharePct = clampPct(platformSharePct, 50);
  if (sharePct <= 0) return 0;
  return appreciation * (sharePct / 100);
}
function calculateLenderNetAppreciationAmount(appreciationAmount, platformSharePct) {
  const appreciation = Math.max(0, parseMoneyAmount(appreciationAmount));
  const platformShare = calculatePlatformAppreciationShareAmount(
    appreciation,
    platformSharePct
  );
  return Math.max(0, appreciation - platformShare);
}
function calculateNetExpectedReturnPct(params) {
  const principal = parseMoneyAmount(params.principalAmount);
  const months = Number(params.termMonths ?? 0);
  if (principal <= 0 || months <= 0) return 0;
  const netAppreciation = calculateLenderNetAppreciationAmount(
    params.appreciationAmount,
    params.platformAppreciationSharePct
  );
  return Math.max(0, netAppreciation / principal * (12 / months) * 100);
}
function calculateMinAppreciationAmount(params) {
  const principal = parseMoneyAmount(params.principalAmount);
  const months = Number(params.termMonths ?? 0);
  if (principal <= 0) return 0;
  const type = (params.minAppreciationType ?? "NONE").toUpperCase();
  switch (type) {
    case "FIXED": {
      return Math.max(0, parseMoneyAmount(params.minAppreciationValue));
    }
    case "PCT_OF_PRINCIPAL": {
      const pct = clampPct(params.minAppreciationValue, 100);
      if (pct <= 0) return 0;
      return principal * (pct / 100);
    }
    case "TERM_TIERED": {
      const raw = params.minAppreciationTiers;
      const tiers = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : null;
      if (!tiers) return 0;
      const keys = Object.keys(tiers).map((k) => Number(k)).filter((k) => Number.isFinite(k) && k > 0).sort((a, b) => a - b);
      if (!keys.length) return 0;
      const selectedKey = Number.isFinite(months) && months > 0 ? keys.reduce((best, current) => {
        if (current <= months) return current;
        return best;
      }, keys[0]) : keys[0];
      const pctRaw = tiers[String(selectedKey)];
      const pct = clampPct(
        typeof pctRaw === "number" || typeof pctRaw === "string" ? pctRaw : 0,
        100
      );
      if (pct <= 0) return 0;
      return principal * (pct / 100);
    }
    case "NONE":
    default:
      return 0;
  }
}
function calculateRepaymentInstallmentCount(termMonths, repaymentFrequency) {
  const months = Number(termMonths ?? 0);
  if (months <= 0) return 0;
  switch (repaymentFrequency) {
    case "WEEKLY":
      return Math.max(1, Math.round(months * 52 / 12));
    case "BIWEEKLY":
      return Math.max(1, Math.round(months * 26 / 12));
    case "MONTHLY":
    default:
      return Math.max(1, months);
  }
}
function addDays(date6, days) {
  const d = new Date(date6);
  d.setDate(d.getDate() + days);
  return d;
}
function addMonths(date6, months) {
  const d = new Date(date6);
  d.setMonth(d.getMonth() + months);
  return d;
}
function addRepaymentPeriod(start, frequency, index2) {
  if (frequency === "WEEKLY") return addDays(start, 7 * index2);
  if (frequency === "BIWEEKLY") return addDays(start, 14 * index2);
  return addMonths(start, index2);
}
function buildLendingRepaymentSchedule(params) {
  const installmentCount = calculateRepaymentInstallmentCount(
    params.termMonths,
    params.repaymentFrequency
  );
  const frequency = params.repaymentFrequency ?? "MONTHLY";
  const totalCents = Math.round(params.totalAmount * 100);
  const baseCents = installmentCount > 0 ? Math.floor(totalCents / installmentCount) : 0;
  const remainderCents = installmentCount > 0 ? totalCents - baseCents * installmentCount : 0;
  return Array.from({ length: installmentCount }, (_, index2) => {
    const cents = baseCents + (index2 < remainderCents ? 1 : 0);
    return {
      dueDate: index2 === 0 ? params.firstDueDate : addRepaymentPeriod(params.firstDueDate, frequency, index2),
      amount: formatMoneyAmount(cents / 100)
    };
  });
}
function toRepaymentTimestamp(value) {
  const date6 = value instanceof Date ? value : new Date(value ?? "");
  return Number.isFinite(date6.getTime()) ? date6.getTime() : null;
}
function hasLoanRepaymentActivity(repayment) {
  return parseMoneyAmount(repayment.paidAmount) > 0 || parseMoneyAmount(repayment.principalPaidAmount) > 0 || parseMoneyAmount(repayment.returnPaidAmount) > 0 || parseMoneyAmount(repayment.feePaidAmount) > 0 || parseMoneyAmount(repayment.creditedToPoolAmount) > 0 || repayment.status === "PAID";
}
function canReplaceLoanRepaymentSchedule(repayments) {
  return repayments.every((repayment) => !hasLoanRepaymentActivity(repayment));
}
function doesLoanRepaymentScheduleMatch(existingRepayments, nextSchedule) {
  if (existingRepayments.length !== nextSchedule.length) return false;
  return existingRepayments.every((repayment, index2) => {
    const nextEntry = nextSchedule[index2];
    if (!nextEntry) return false;
    return toRepaymentTimestamp(repayment.dueDate) === toRepaymentTimestamp(nextEntry.dueDate) && formatMoneyAmount(parseMoneyAmount(repayment.amount)) === formatMoneyAmount(parseMoneyAmount(nextEntry.amount));
  });
}
function calculateBorrowerTotalRepayableAmount(params) {
  const principal = parseMoneyAmount(params.principalAmount);
  if (principal <= 0) return 0;
  return principal + parseMoneyAmount(params.appreciationAmount) + calculateProcessingFeeAmount(principal, params.processingFeePct);
}
function calculateEstimatedInstallmentAmount(params) {
  const total = calculateBorrowerTotalRepayableAmount(params);
  const count3 = calculateRepaymentInstallmentCount(
    params.termMonths,
    params.repaymentFrequency
  );
  if (total <= 0 || count3 <= 0) return 0;
  return total / count3;
}
function buildLoanPricingSnapshot(params) {
  const termMonths = Number(params.termMonths ?? 0);
  const repaymentFrequency = params.repaymentFrequency ?? "MONTHLY";
  const totalRepayableAmount = calculateBorrowerTotalRepayableAmount(params);
  const estimatedInstallmentAmount = calculateEstimatedInstallmentAmount(params);
  return {
    termMonths,
    repaymentFrequency,
    termLabel: formatTermMonthsLabel(termMonths),
    repaymentScheduleLabel: formatRepaymentFrequencyLabel(repaymentFrequency),
    totalRepayableAmount,
    estimatedInstallmentAmount
  };
}
function calculateProjectedReturnAmount(principalAmount, expectedReturnPct, termMonths) {
  return calculateSimpleAnnualRateAmount(
    principalAmount,
    expectedReturnPct,
    termMonths
  );
}
function calculateP2PBorrowerRatePct(params) {
  return Math.max(
    0,
    parseMoneyAmount(params.investorRatePct) + parseMoneyAmount(params.wwnMarginPct) + parseMoneyAmount(params.reserveContributionPct)
  );
}
function buildP2PRatePricingSnapshot(params) {
  const investorReturnAmount = calculateSimpleAnnualRateAmount(
    params.principalAmount,
    params.investorRatePct,
    params.termMonths
  );
  const wwnMarginAmount = calculateSimpleAnnualRateAmount(
    params.principalAmount,
    params.wwnMarginPct,
    params.termMonths
  );
  const reserveContributionAmount = calculateSimpleAnnualRateAmount(
    params.principalAmount,
    params.reserveContributionPct,
    params.termMonths
  );
  const platformRateAmount = wwnMarginAmount + reserveContributionAmount;
  const borrowerRateAmount = investorReturnAmount + platformRateAmount;
  const borrowerRatePct = calculateP2PBorrowerRatePct(params);
  const platformSharePctOfBorrowerRate = borrowerRateAmount > 0 ? Math.max(0, Math.min(100, platformRateAmount / borrowerRateAmount * 100)) : 0;
  return {
    investorReturnAmount,
    wwnMarginAmount,
    reserveContributionAmount,
    platformRateAmount,
    borrowerRateAmount,
    borrowerRatePct,
    platformSharePctOfBorrowerRate
  };
}
function allocateProRataReturnAmount(totalReturnAmount, commitments) {
  const totalAmount = parseMoneyAmount(totalReturnAmount);
  if (totalAmount <= 0 || commitments.length === 0) {
    return commitments.map((commitment) => ({
      ...commitment,
      allocatedReturnAmount: 0,
      ownershipPct: 0
    }));
  }
  const normalized = commitments.map((commitment) => ({
    commitment,
    amount: parseMoneyAmount(commitment.amount)
  }));
  const totalCommitted = normalized.reduce((sum3, item) => sum3 + item.amount, 0);
  if (totalCommitted <= 0) {
    return commitments.map((commitment) => ({
      ...commitment,
      allocatedReturnAmount: 0,
      ownershipPct: 0
    }));
  }
  const totalCents = Math.round(totalAmount * 100);
  const allocated = normalized.map((item, index2) => {
    const rawCents = totalCents * item.amount / totalCommitted;
    const cents = Math.floor(rawCents);
    return {
      index: index2,
      ...item,
      cents,
      remainder: rawCents - cents,
      ownershipPct: item.amount / totalCommitted
    };
  });
  let remainingCents = totalCents - allocated.reduce((sum3, item) => sum3 + item.cents, 0);
  allocated.slice().sort((a, b) => b.remainder - a.remainder).forEach((item) => {
    if (remainingCents <= 0) return;
    allocated[item.index].cents += 1;
    remainingCents -= 1;
  });
  return allocated.map((item) => ({
    ...item.commitment,
    allocatedReturnAmount: item.cents / 100,
    ownershipPct: item.ownershipPct
  }));
}
function canMembersBrowseLendingPool(status) {
  return MEMBER_VISIBLE_LENDING_POOL_STATUSES.includes(
    status
  );
}
function isCommitmentStatusTransitionAllowed(currentStatus, nextStatus) {
  return currentStatus === nextStatus ? true : (COMMITMENT_STATUS_TRANSITIONS[currentStatus] ?? []).includes(nextStatus);
}
function isLendingApplicationTransitionAllowed(currentStatus, nextStatus) {
  return currentStatus === nextStatus ? true : (LENDING_APPLICATION_TRANSITIONS[currentStatus] ?? []).includes(
    nextStatus
  );
}
function validateLendingBorrowerApplicationInput(input, maxRequestAmount = LENDING_POOL_MAX_REQUEST_AMOUNT) {
  const parsed = lendingBorrowerApplicationSchema.safeParse(input ?? {});
  if (!parsed.success) {
    return { ok: false, errors: parsed.error.flatten() };
  }
  if (hasMoreThanTwoDecimalPlaces(parsed.data.amount)) {
    return {
      ok: false,
      message: "Requested amount cannot have more than 2 decimal places."
    };
  }
  if (hasMoreThanTwoDecimalPlaces(parsed.data.appreciationAmount)) {
    return {
      ok: false,
      message: "Community support / appreciation amount cannot have more than 2 decimal places."
    };
  }
  if (parsed.data.amount > maxRequestAmount) {
    return {
      ok: false,
      message: `Requested amount exceeds the Lending Pool limit of $${maxRequestAmount.toFixed(2)}.`
    };
  }
  return { ok: true, data: parsed.data };
}
var LENDING_POOL_MAX_REQUEST_AMOUNT, ACTIVE_COMMITMENT_STATUSES, COMMITMENT_STATUS_TRANSITIONS, LENDING_APPLICATION_TRANSITIONS, ACTIVE_LENDING_APPLICATION_STATUSES, RESERVED_LENDING_APPLICATION_STATUSES, MEMBER_VISIBLE_LENDING_POOL_STATUSES, lendingBorrowerApplicationSchema;
var init_lending = __esm({
  "src/lib/lending.ts"() {
    "use strict";
    init_zod();
    LENDING_POOL_MAX_REQUEST_AMOUNT = 25e3;
    ACTIVE_COMMITMENT_STATUSES = ["PENDING", "CONFIRMED"];
    COMMITMENT_STATUS_TRANSITIONS = {
      PENDING: ["CONFIRMED", "CANCELLED"],
      CONFIRMED: ["CANCELLED"],
      CANCELLED: []
    };
    LENDING_APPLICATION_TRANSITIONS = {
      DRAFT: ["SUBMITTED"],
      SUBMITTED: ["WAITLISTED", "UNDER_REVIEW", "REJECTED", "CANCELLED"],
      WAITLISTED: ["UNDER_REVIEW", "REJECTED", "CANCELLED"],
      UNDER_REVIEW: ["APPROVED", "WAITLISTED", "REJECTED", "CANCELLED"],
      APPROVED: ["FUNDED", "REJECTED", "CANCELLED"],
      APPROVED_RESERVED: ["FUNDED", "WAITLISTED", "REJECTED", "CANCELLED"],
      FUNDED: ["REPAYING"],
      REPAYING: ["CLOSED"],
      CLOSED: [],
      REJECTED: [],
      CANCELLED: []
    };
    ACTIVE_LENDING_APPLICATION_STATUSES = [
      "DRAFT",
      "SUBMITTED",
      "WAITLISTED",
      "UNDER_REVIEW",
      "APPROVED",
      "APPROVED_RESERVED",
      "FUNDED",
      "REPAYING"
    ];
    RESERVED_LENDING_APPLICATION_STATUSES = [
      "APPROVED_RESERVED"
    ];
    MEMBER_VISIBLE_LENDING_POOL_STATUSES = ["OPEN"];
    lendingBorrowerApplicationSchema = external_exports.object({
      templateId: external_exports.coerce.number().int().positive().optional(),
      amount: external_exports.coerce.number().positive(),
      termMonths: external_exports.coerce.number().int().positive().max(24).optional(),
      appreciationAmount: external_exports.coerce.number().nonnegative().default(0),
      purpose: external_exports.string().trim().min(3).max(200),
      notes: external_exports.string().trim().max(2e3).optional().or(external_exports.literal("")),
      acceptedTerms: external_exports.boolean().optional()
    });
  }
});

// src/lib/admin-metrics.ts
function buildPlatformRevenueSummary(input) {
  const payments = formatMoneyAmount(parseMoneyAmount(input.completedPaymentTotal));
  const lendingFees = formatMoneyAmount(0);
  return {
    total: payments,
    payments,
    lendingFees
  };
}
var init_admin_metrics = __esm({
  "src/lib/admin-metrics.ts"() {
    "use strict";
    init_lending();
  }
});

// src/lib/helping-hand.ts
function getLendingPoolTier(score) {
  if (score === null) return "Unscored";
  if (score >= 80) return "Excellent";
  if (score >= 65) return "Good";
  if (score >= 50) return "Fair";
  return "Needs Improvement";
}
function validateHelpingHandApplicationInput(input, maxRequestAmount) {
  const parsed = helpingHandApplicationSchema.safeParse(input ?? {});
  if (!parsed.success) {
    return { ok: false, errors: parsed.error.flatten() };
  }
  if (hasMoreThanTwoDecimalPlaces(parsed.data.requestedAmount)) {
    return {
      ok: false,
      message: "Requested amount cannot have more than 2 decimal places."
    };
  }
  if (typeof maxRequestAmount === "number" && parsed.data.requestedAmount > maxRequestAmount) {
    return {
      ok: false,
      message: `Requested amount exceeds your SUSU Matching Fund limit of $${maxRequestAmount.toFixed(2)}.`
    };
  }
  return { ok: true, data: parsed.data };
}
function parseRepaymentFrequency(schedule) {
  const normalized = (schedule ?? "").trim().toLowerCase();
  if (normalized.includes("biweekly") || normalized.includes("bi-weekly") || normalized.includes("fortnight")) {
    return "BIWEEKLY";
  }
  if (normalized.includes("weekly")) return "WEEKLY";
  return "MONTHLY";
}
function addDays2(date6, days) {
  const d = new Date(date6);
  d.setDate(d.getDate() + days);
  return d;
}
function addMonths2(date6, months) {
  const d = new Date(date6);
  d.setMonth(d.getMonth() + months);
  return d;
}
function addPeriod(start, frequency, index2) {
  if (frequency === "WEEKLY") return addDays2(start, 7 * index2);
  if (frequency === "BIWEEKLY") return addDays2(start, 14 * index2);
  return addMonths2(start, index2);
}
function parseTermDescriptor(term) {
  const normalized = (term ?? "").trim().toLowerCase();
  const match = normalized.match(
    /(\d+(?:\.\d+)?)\s*-?\s*(years?|yrs?|yr|months?|mos?|mo|weeks?|wks?|wk|days?|d)\b/
  );
  if (!match) return null;
  const quantity = Number(match[1]);
  const unit = match[2];
  if (!Number.isFinite(quantity) || quantity <= 0) return null;
  if (unit.startsWith("y")) return { quantity, unit: "YEAR" };
  if (unit.startsWith("mo")) return { quantity, unit: "MONTH" };
  if (unit.startsWith("w")) return { quantity, unit: "WEEK" };
  return { quantity, unit: "DAY" };
}
function getHelpingHandInstallmentCount(term, repaymentSchedule) {
  const frequency = parseRepaymentFrequency(repaymentSchedule);
  const descriptor = parseTermDescriptor(term);
  const fallbackDays = Math.max(
    1,
    Number.parseInt((term ?? "").match(/\d+/)?.[0] ?? "30", 10)
  );
  if (descriptor) {
    const { quantity, unit } = descriptor;
    if (frequency === "MONTHLY") {
      if (unit === "YEAR") return Math.max(1, Math.ceil(quantity * 12));
      if (unit === "MONTH") return Math.max(1, Math.ceil(quantity));
      if (unit === "WEEK") return Math.max(1, Math.ceil(quantity / 4));
      return Math.max(1, Math.ceil(quantity / 30));
    }
    if (frequency === "BIWEEKLY") {
      if (unit === "YEAR") return Math.max(1, Math.ceil(quantity * 365 / 14));
      if (unit === "MONTH") return Math.max(1, Math.ceil(quantity * 30 / 14));
      if (unit === "WEEK") return Math.max(1, Math.ceil(quantity / 2));
      return Math.max(1, Math.ceil(quantity / 14));
    }
    if (unit === "YEAR") return Math.max(1, Math.ceil(quantity * 52));
    if (unit === "MONTH") return Math.max(1, Math.ceil(quantity * 30 / 7));
    if (unit === "WEEK") return Math.max(1, Math.ceil(quantity));
    return Math.max(1, Math.ceil(quantity / 7));
  }
  if (frequency === "MONTHLY") return Math.max(1, Math.ceil(fallbackDays / 30));
  if (frequency === "BIWEEKLY")
    return Math.max(1, Math.ceil(fallbackDays / 14));
  return Math.max(1, Math.ceil(fallbackDays / 7));
}
function buildHelpingHandRepaymentSchedule(params) {
  const installmentCount = getHelpingHandInstallmentCount(
    params.term,
    params.repaymentSchedule
  );
  const frequency = parseRepaymentFrequency(params.repaymentSchedule);
  const totalCents = Math.round(params.totalAmount * 100);
  const baseCents = Math.floor(totalCents / installmentCount);
  const remainderCents = totalCents - baseCents * installmentCount;
  return Array.from({ length: installmentCount }, (_, index2) => {
    const cents = baseCents + (index2 < remainderCents ? 1 : 0);
    return {
      dueDate: index2 === 0 ? params.firstDueDate : addPeriod(params.firstDueDate, frequency, index2),
      amount: formatMoneyAmount(cents / 100)
    };
  });
}
function deriveHelpingHandRepaymentUpdate(existing, patch, now = /* @__PURE__ */ new Date()) {
  const effectiveAmount = parseMoneyAmount(patch.amount ?? existing.amount);
  if (!Number.isFinite(effectiveAmount) || effectiveAmount <= 0) {
    throw new Error("Repayment amount must be positive.");
  }
  const hasIncomingPaidAmount = patch.paidAmount !== void 0;
  const paidAmountValue = hasIncomingPaidAmount ? parseMoneyAmount(patch.paidAmount) : existing.paidAmount !== null ? parseMoneyAmount(existing.paidAmount) : 0;
  if (!Number.isFinite(paidAmountValue) || paidAmountValue < 0) {
    throw new Error("Paid amount must be valid.");
  }
  if (paidAmountValue > effectiveAmount) {
    throw new Error(
      "Paid amount cannot exceed the scheduled installment amount."
    );
  }
  const effectiveStatus = patch.status ?? existing.status;
  const updates = {
    amount: formatMoneyAmount(effectiveAmount),
    status: effectiveStatus,
    method: patch.method ?? existing.method,
    paidAmount: null,
    paidAt: null
  };
  if (effectiveStatus === "WAIVED") {
    updates.method = null;
    return updates;
  }
  if (effectiveStatus === "PAID") {
    updates.paidAt = now;
    updates.paidAmount = hasIncomingPaidAmount ? formatMoneyAmount(paidAmountValue) : formatMoneyAmount(effectiveAmount);
    return updates;
  }
  if (paidAmountValue > 0) {
    updates.paidAmount = formatMoneyAmount(paidAmountValue);
    if (paidAmountValue >= effectiveAmount) {
      updates.status = "PAID";
      updates.paidAt = now;
      updates.paidAmount = formatMoneyAmount(effectiveAmount);
      return updates;
    }
    if (!patch.status) {
      updates.status = existing.status === "LATE" ? "LATE" : "PENDING";
    }
    return updates;
  }
  if (!patch.status && existing.dueDate.getTime() < now.getTime()) {
    updates.status = existing.status === "LATE" ? "LATE" : "PENDING";
  }
  if (updates.status !== "PAID" && updates.status !== "WAIVED") {
    updates.paidAt = null;
    updates.paidAmount = null;
    if (!patch.method) {
      updates.method = null;
    }
  }
  return updates;
}
var HELPING_HAND_APPLICATION_TRANSITIONS, helpingHandApplicationSchema;
var init_helping_hand = __esm({
  "src/lib/helping-hand.ts"() {
    "use strict";
    init_zod();
    init_lending();
    HELPING_HAND_APPLICATION_TRANSITIONS = {
      DRAFT: ["SUBMITTED"],
      SUBMITTED: ["UNDER_REVIEW", "REJECTED"],
      UNDER_REVIEW: ["APPROVED", "REJECTED"],
      APPROVED: ["FUNDED", "REJECTED"],
      FUNDED: ["REPAYING"],
      REPAYING: ["CLOSED"],
      CLOSED: [],
      REJECTED: []
    };
    helpingHandApplicationSchema = external_exports.object({
      requestedAmount: external_exports.coerce.number().positive(),
      purpose: external_exports.string().trim().min(3).max(200),
      term: external_exports.string().trim().min(2).max(100),
      repaymentSchedule: external_exports.string().trim().min(2).max(100),
      notes: external_exports.string().trim().max(2e3).optional().or(external_exports.literal(""))
    });
  }
});

// src/lib/susu.ts
function formatSusuCircleSuffix(circleName) {
  const normalized = circleName?.trim();
  return normalized ? ` for ${normalized}` : "";
}
function addDays3(date6, days) {
  const next = new Date(date6);
  next.setDate(next.getDate() + days);
  return next;
}
function addMonths3(date6, months) {
  const next = new Date(date6);
  next.setMonth(next.getMonth() + months);
  return next;
}
function getCircleRuntimeStatus(input) {
  if (input.status === "FORMING") {
    return "FORMING";
  }
  if (input.status === "COMPLETED" || input.status === "CANCELLED") {
    return input.status;
  }
  const now = input.now ?? /* @__PURE__ */ new Date();
  const startDate = input.startDate ? new Date(input.startDate) : null;
  if (input.status === "UPCOMING") {
    if (startDate && !Number.isNaN(startDate.getTime()) && startDate > now) {
      return "UPCOMING";
    }
    return "ACTIVE";
  }
  return "ACTIVE";
}
function addCirclePeriod(start, frequency, index2) {
  if (frequency === "WEEKLY") return addDays3(start, 7 * index2);
  if (frequency === "BIWEEKLY") return addDays3(start, 14 * index2);
  return addMonths3(start, index2);
}
function getNextCircleDueDate(input) {
  const now = input.now ?? /* @__PURE__ */ new Date();
  const anchorDate = input.anchorDate && !Number.isNaN(input.anchorDate.getTime()) ? input.anchorDate : now;
  let next = new Date(anchorDate);
  let index2 = 0;
  while (next <= now) {
    index2 += 1;
    next = addCirclePeriod(anchorDate, input.frequency, index2);
  }
  return next;
}
function calculateCirclePayoutAmount(contributionAmount, maxMembers) {
  return formatMoneyAmount(Number(contributionAmount) * maxMembers);
}
function isManualCircleLifecycleStatusAllowed(status) {
  return status !== "COMPLETED" && status !== "CANCELLED";
}
function isPayoutDue(input) {
  return input.scheduledDate.getTime() <= (input.now ?? /* @__PURE__ */ new Date()).getTime();
}
async function hasBlockingPayoutContributionIssuesWith(conn, circleId, userId, now = /* @__PURE__ */ new Date()) {
  const [row] = await conn.select({ count: count() }).from(savingsContributionsTable).where(
    and(
      eq(savingsContributionsTable.circleId, circleId),
      eq(savingsContributionsTable.userId, userId),
      or(
        eq(savingsContributionsTable.status, "MISSED"),
        and(
          eq(savingsContributionsTable.status, "PENDING"),
          lte(savingsContributionsTable.dueDate, now)
        )
      )
    )
  );
  return Number(row?.count ?? 0) > 0;
}
function planCirclePayoutScheduleRepair(input) {
  const existingByMemberKey = new Map(
    input.existingRows.map(
      (row) => [`${row.userId}:${row.position}`, row]
    )
  );
  const updates = [];
  const inserts = [];
  for (const expected of input.expectedRows) {
    const existing = existingByMemberKey.get(
      `${expected.userId}:${expected.position}`
    );
    if (!existing) {
      inserts.push(expected);
      continue;
    }
    if (existing.status === "PENDING" && (existing.scheduledDate.getTime() !== expected.scheduledDate.getTime() || Number(existing.amount) !== Number(expected.amount))) {
      updates.push({
        id: existing.id,
        scheduledDate: expected.scheduledDate,
        amount: expected.amount
      });
    }
  }
  return { updates, inserts };
}
function buildCircleScheduleEntries(input) {
  const sortedMembers = [...input.members].sort(
    (a, b) => a.position - b.position
  );
  const dueDates = Array.from(
    { length: input.maxMembers },
    (_, index2) => addCirclePeriod(input.startDate, input.frequency, index2)
  );
  const contributionAmount = formatMoneyAmount(
    Number(input.contributionAmount)
  );
  const payoutAmount = calculateCirclePayoutAmount(
    input.contributionAmount,
    input.maxMembers
  );
  return {
    dueDates,
    contributionRows: sortedMembers.flatMap(
      (member) => dueDates.map((dueDate) => ({
        circleId: input.circleId,
        userId: member.userId,
        dueDate,
        amount: contributionAmount,
        status: "PENDING"
      }))
    ),
    payoutRows: sortedMembers.map((member) => ({
      circleId: input.circleId,
      userId: member.userId,
      position: member.position,
      scheduledDate: addCirclePeriod(
        input.startDate,
        input.frequency,
        Math.max(member.position - 1, 0)
      ),
      amount: payoutAmount,
      status: "PENDING"
    }))
  };
}
async function ensureWalletWith3(conn, ownerType, ownerId) {
  const existing = await conn.select().from(walletsTable).where(
    and(
      eq(walletsTable.ownerType, ownerType),
      eq(walletsTable.ownerId, ownerId)
    )
  );
  if (existing.length) return existing[0];
  const [created] = await conn.insert(walletsTable).values({ ownerType, ownerId }).returning();
  return created;
}
function getCircleTreasuryOwner(input) {
  if (typeof input.organizationId === "number") {
    return {
      ownerType: "CIRCLE",
      ownerId: input.circleId,
      isDedicatedWallet: true,
      dashboardHref: "/dashboard/org-susu"
    };
  }
  return {
    ownerType: "SUSU",
    ownerId: SUSU_WALLET_OWNER_ID,
    isDedicatedWallet: false,
    dashboardHref: "/dashboard/savings"
  };
}
async function getCircleRecordWith(conn, circleId) {
  const [circle] = await conn.select({
    id: savingsCirclesTable.id,
    organizationId: savingsCirclesTable.organizationId
  }).from(savingsCirclesTable).where(eq(savingsCirclesTable.id, circleId));
  return circle ?? null;
}
async function ensureCircleTreasuryWalletWith(conn, circleInput) {
  const circle = typeof circleInput === "number" ? await getCircleRecordWith(conn, circleInput) : circleInput;
  if (!circle) {
    return null;
  }
  const owner = getCircleTreasuryOwner({
    circleId: circle.id,
    organizationId: circle.organizationId
  });
  return ensureWalletWith3(conn, owner.ownerType, owner.ownerId);
}
function getCircleDashboardHref(input) {
  return getCircleTreasuryOwner({
    circleId: 0,
    organizationId: input.organizationId
  }).dashboardHref;
}
function getCircleCreatorUserId(circle) {
  return circle.organizationId !== null && circle.organizationId !== void 0 ? circle.createdByOrganizationMemberUserId ?? null : circle.createdByAdminId ?? null;
}
function getCircleCreatorSeatIssue(input) {
  const expectedUserId = getCircleCreatorUserId(input.circle);
  if (!expectedUserId) {
    return input.circle.organizationId !== null && input.circle.organizationId !== void 0 ? "This organization circle is missing its founding member for spot 1." : "This circle is missing its admin creator for spot 1.";
  }
  const positionOneMember = input.members.find((member) => member.position === 1) ?? null;
  if (!positionOneMember || positionOneMember.userId !== expectedUserId) {
    return "Spot 1 must remain reserved for the creator/admin before anyone else can join.";
  }
  return null;
}
function isCircleCreatorSeatIntact(input) {
  return getCircleCreatorSeatIssue(input) === null;
}
async function getCircleCreatorSeatIssueWith(conn, circleId) {
  const [circle] = await conn.select({
    organizationId: savingsCirclesTable.organizationId,
    createdByAdminId: savingsCirclesTable.createdByAdminId,
    createdByOrganizationMemberUserId: savingsCirclesTable.createdByOrganizationMemberUserId
  }).from(savingsCirclesTable).where(eq(savingsCirclesTable.id, circleId));
  if (!circle) {
    return "Circle not found.";
  }
  const positionOneMembers = await conn.select({
    userId: circleMembershipsTable.userId,
    position: circleMembershipsTable.position
  }).from(circleMembershipsTable).where(
    and(
      eq(circleMembershipsTable.circleId, circleId),
      eq(circleMembershipsTable.position, 1)
    )
  );
  return getCircleCreatorSeatIssue({
    circle,
    members: positionOneMembers
  });
}
async function getWalletBalanceWith2(conn, walletId) {
  const [[credits], [debits]] = await Promise.all([
    conn.select({ total: sum(walletTransactionsTable.amount) }).from(walletTransactionsTable).where(eq(walletTransactionsTable.toWalletId, walletId)),
    conn.select({ total: sum(walletTransactionsTable.amount) }).from(walletTransactionsTable).where(eq(walletTransactionsTable.fromWalletId, walletId))
  ]);
  return Number(credits.total ?? 0) - Number(debits.total ?? 0);
}
async function getWalletReservedBalanceWith(conn, walletId) {
  const [[investmentReserved], [cashoutReserved]] = await Promise.all([
    conn.select({ total: sum(investmentIntentReservationsTable.amount) }).from(investmentIntentReservationsTable).innerJoin(
      investmentInterestsTable,
      eq(
        investmentIntentReservationsTable.interestId,
        investmentInterestsTable.id
      )
    ).where(
      and(
        eq(investmentIntentReservationsTable.walletId, walletId),
        eq(investmentIntentReservationsTable.status, "RESERVED"),
        eq(investmentInterestsTable.status, "PENDING")
      )
    ),
    conn.select({ total: sum(walletPaymentIntentsTable.amount) }).from(walletPaymentIntentsTable).where(
      and(
        eq(walletPaymentIntentsTable.walletId, walletId),
        eq(walletPaymentIntentsTable.type, "CASH_OUT"),
        inArray(walletPaymentIntentsTable.status, [
          "CREATED",
          "PENDING"
        ])
      )
    )
  ]);
  return Number(investmentReserved?.total ?? 0) + Number(cashoutReserved?.total ?? 0);
}
async function getWalletAvailableBalanceWith(conn, walletId) {
  const [balance, reservedBalance] = await Promise.all([
    getWalletBalanceWith2(conn, walletId),
    getWalletReservedBalanceWith(conn, walletId)
  ]);
  return Math.max(0, balance - reservedBalance);
}
async function getCircleMemberCountWith(conn, circleId) {
  const [row] = await conn.select({ count: count() }).from(circleMembershipsTable).where(eq(circleMembershipsTable.circleId, circleId));
  return Number(row?.count ?? 0);
}
async function getCircleAllocationBalanceWith(conn, circleId) {
  const summary = await getCircleAllocationSummaryWith(conn, circleId);
  return summary?.allocationBalance ?? 0;
}
async function getCircleAllocationSummaryWith(conn, circleId) {
  const circle = await getCircleRecordWith(conn, circleId);
  if (!circle) return null;
  const treasuryWallet = await ensureCircleTreasuryWalletWith(conn, circle);
  if (!treasuryWallet) return null;
  const owner = getCircleTreasuryOwner({
    circleId: circle.id,
    organizationId: circle.organizationId
  });
  const treasuryBalance = await getWalletBalanceWith2(conn, treasuryWallet.id);
  if (owner.isDedicatedWallet) {
    const [totalInRow, totalOutRow] = await Promise.all([
      conn.select({ total: sum(walletTransactionsTable.amount) }).from(walletTransactionsTable).where(eq(walletTransactionsTable.toWalletId, treasuryWallet.id)),
      conn.select({ total: sum(walletTransactionsTable.amount) }).from(walletTransactionsTable).where(eq(walletTransactionsTable.fromWalletId, treasuryWallet.id))
    ]);
    const totalIn2 = Number(totalInRow[0]?.total ?? 0);
    const totalOut2 = Number(totalOutRow[0]?.total ?? 0);
    return {
      wallet: treasuryWallet,
      owner,
      treasuryBalance,
      totalIn: totalIn2,
      totalOut: totalOut2,
      allocationBalance: treasuryBalance
    };
  }
  const [circleInRow, circleOutRow] = await Promise.all([
    conn.select({ total: sum(walletTransactionsTable.amount) }).from(walletTransactionsTable).where(
      and(
        eq(walletTransactionsTable.toWalletId, treasuryWallet.id),
        sql`coalesce(${walletTransactionsTable.metadata} ->> 'circleId', '') = ${String(circleId)}`
      )
    ),
    conn.select({ total: sum(walletTransactionsTable.amount) }).from(walletTransactionsTable).where(
      and(
        eq(walletTransactionsTable.fromWalletId, treasuryWallet.id),
        sql`coalesce(${walletTransactionsTable.metadata} ->> 'circleId', '') = ${String(circleId)}`
      )
    )
  ]);
  const totalIn = Number(circleInRow[0]?.total ?? 0);
  const totalOut = Number(circleOutRow[0]?.total ?? 0);
  return {
    wallet: treasuryWallet,
    owner,
    treasuryBalance,
    totalIn,
    totalOut,
    allocationBalance: totalIn - totalOut
  };
}
async function getCircleAllocationTransactionsWith(conn, circleId) {
  const summary = await getCircleAllocationSummaryWith(conn, circleId);
  if (!summary) return [];
  const rows = summary.owner.isDedicatedWallet ? await conn.select({
    id: walletTransactionsTable.id,
    type: walletTransactionsTable.type,
    amount: walletTransactionsTable.amount,
    fromWalletId: walletTransactionsTable.fromWalletId,
    toWalletId: walletTransactionsTable.toWalletId,
    metadata: walletTransactionsTable.metadata,
    createdAt: walletTransactionsTable.createdAt
  }).from(walletTransactionsTable).where(
    or(
      eq(walletTransactionsTable.fromWalletId, summary.wallet.id),
      eq(walletTransactionsTable.toWalletId, summary.wallet.id)
    )
  ).orderBy(asc(walletTransactionsTable.createdAt)) : await conn.select({
    id: walletTransactionsTable.id,
    type: walletTransactionsTable.type,
    amount: walletTransactionsTable.amount,
    fromWalletId: walletTransactionsTable.fromWalletId,
    toWalletId: walletTransactionsTable.toWalletId,
    metadata: walletTransactionsTable.metadata,
    createdAt: walletTransactionsTable.createdAt
  }).from(walletTransactionsTable).where(
    and(
      or(
        eq(walletTransactionsTable.fromWalletId, summary.wallet.id),
        eq(walletTransactionsTable.toWalletId, summary.wallet.id)
      ),
      sql`coalesce(${walletTransactionsTable.metadata} ->> 'circleId', '') = ${String(circleId)}`
    )
  ).orderBy(asc(walletTransactionsTable.createdAt));
  return rows.map((row) => ({
    id: row.id,
    type: row.type,
    amount: Number(row.amount),
    direction: row.toWalletId === summary.wallet.id ? "IN" : "OUT",
    createdAt: row.createdAt.toISOString(),
    metadata: row.metadata && typeof row.metadata === "object" ? row.metadata : {}
  }));
}
async function insertMany(conn, table, rows) {
  if (!rows.length) return;
  const chunkSize = 500;
  for (let index2 = 0; index2 < rows.length; index2 += chunkSize) {
    await conn.insert(table).values(rows.slice(index2, index2 + chunkSize)).onConflictDoNothing();
  }
}
async function repairCircleContributionScheduleWith(conn, circleId) {
  const [circle] = await conn.select({
    id: savingsCirclesTable.id,
    maxMembers: savingsCirclesTable.maxMembers,
    startDate: savingsCirclesTable.startDate,
    frequency: savingsCirclesTable.frequency,
    contributionAmount: savingsCirclesTable.contributionAmount
  }).from(savingsCirclesTable).where(eq(savingsCirclesTable.id, circleId));
  if (!circle)
    return { deletedContributionRows: 0, insertedContributionRows: 0 };
  if (!circle.startDate)
    return { deletedContributionRows: 0, insertedContributionRows: 0 };
  const toDueDateKey = (dueDate) => dueDate.toISOString().split("T")[0] ?? "";
  const scheduleDueDates = Array.from(
    { length: circle.maxMembers },
    (_, index2) => addCirclePeriod(
      circle.startDate,
      circle.frequency,
      index2
    )
  );
  const scheduleKeyToDueDate = new Map(
    scheduleDueDates.map(
      (dueDate) => [toDueDateKey(dueDate), dueDate]
    )
  );
  const scheduleKeys = Array.from(scheduleKeyToDueDate.keys());
  const scheduleKeySet = new Set(scheduleKeys);
  const members = await conn.select({
    userId: circleMembershipsTable.userId
  }).from(circleMembershipsTable).where(eq(circleMembershipsTable.circleId, circleId));
  const memberUserIds = members.map((m) => m.userId);
  const contributionRows = await conn.select({
    id: savingsContributionsTable.id,
    userId: savingsContributionsTable.userId,
    dueDate: savingsContributionsTable.dueDate,
    status: savingsContributionsTable.status,
    createdAt: savingsContributionsTable.createdAt
  }).from(savingsContributionsTable).where(eq(savingsContributionsTable.circleId, circleId)).orderBy(
    asc(savingsContributionsTable.userId),
    asc(savingsContributionsTable.dueDate),
    asc(savingsContributionsTable.createdAt)
  );
  const rowsByUser = /* @__PURE__ */ new Map();
  for (const row of contributionRows) {
    const rows = rowsByUser.get(row.userId) ?? [];
    rows.push(row);
    rowsByUser.set(row.userId, rows);
  }
  const contributionAmount = formatMoneyAmount(
    Number(circle.contributionAmount)
  );
  const pendingDeleteIds = [];
  const dueDateUpdates = [];
  for (const userId of memberUserIds) {
    const userRows = rowsByUser.get(userId) ?? [];
    const finalizedRows = userRows.filter((row) => row.status !== "PENDING");
    const pendingRows = userRows.filter((row) => row.status === "PENDING");
    const finalizedScheduleKeys = new Set(
      finalizedRows.map((row) => toDueDateKey(row.dueDate)).filter((key) => scheduleKeySet.has(key))
    );
    const presentScheduleKeys = new Set(
      userRows.map((row) => toDueDateKey(row.dueDate)).filter((key) => scheduleKeySet.has(key))
    );
    const missingScheduleKeys = scheduleKeys.filter(
      (key) => !presentScheduleKeys.has(key)
    );
    const scheduleKeysWithOnlyPending = scheduleKeys.filter(
      (key) => presentScheduleKeys.has(key) && !finalizedScheduleKeys.has(key)
    );
    const candidateFinalizedOutsideSchedule = finalizedRows.filter((row) => !scheduleKeySet.has(toDueDateKey(row.dueDate))).slice().sort(
      (left, right) => left.dueDate.getTime() - right.dueDate.getTime() || left.createdAt.getTime() - right.createdAt.getTime()
    );
    const targetKeys = [...missingScheduleKeys, ...scheduleKeysWithOnlyPending];
    const updateCount = Math.min(
      targetKeys.length,
      candidateFinalizedOutsideSchedule.length
    );
    for (let i = 0; i < updateCount; i += 1) {
      const targetKey = targetKeys[i];
      const dueDate = scheduleKeyToDueDate.get(targetKey);
      const row = candidateFinalizedOutsideSchedule[i];
      if (!dueDate) continue;
      for (const pending of pendingRows) {
        if (toDueDateKey(pending.dueDate) === targetKey) {
          pendingDeleteIds.push(pending.id);
        }
      }
      dueDateUpdates.push({ id: row.id, dueDate });
      presentScheduleKeys.add(targetKey);
      finalizedScheduleKeys.add(targetKey);
    }
    for (const pending of pendingRows) {
      const key = toDueDateKey(pending.dueDate);
      if (!scheduleKeySet.has(key)) {
        pendingDeleteIds.push(pending.id);
        continue;
      }
      if (finalizedScheduleKeys.has(key)) {
        pendingDeleteIds.push(pending.id);
      }
    }
    const pendingScheduleRows = pendingRows.filter((row) => !pendingDeleteIds.includes(row.id)).filter((row) => scheduleKeySet.has(toDueDateKey(row.dueDate))).slice().sort(
      (left, right) => left.dueDate.getTime() - right.dueDate.getTime() || left.createdAt.getTime() - right.createdAt.getTime()
    );
    const pendingByKey = /* @__PURE__ */ new Map();
    for (const row of pendingScheduleRows) {
      const key = toDueDateKey(row.dueDate);
      const rows = pendingByKey.get(key) ?? [];
      rows.push(row);
      pendingByKey.set(key, rows);
    }
    for (const rows of pendingByKey.values()) {
      if (rows.length <= 1) continue;
      const sorted = rows.slice().sort(
        (left, right) => left.createdAt.getTime() - right.createdAt.getTime() || left.id - right.id
      );
      for (const extra of sorted.slice(1)) {
        pendingDeleteIds.push(extra.id);
      }
    }
    const pendingUnique = pendingScheduleRows.filter(
      (row) => !pendingDeleteIds.includes(row.id)
    );
    const allowedPendingCount = Math.max(
      0,
      circle.maxMembers - finalizedScheduleKeys.size
    );
    for (const extra of pendingUnique.slice(allowedPendingCount)) {
      pendingDeleteIds.push(extra.id);
    }
  }
  const uniquePendingDeleteIds = Array.from(new Set(pendingDeleteIds));
  if (uniquePendingDeleteIds.length) {
    await conn.delete(savingsContributionsTable).where(inArray(savingsContributionsTable.id, uniquePendingDeleteIds));
  }
  if (dueDateUpdates.length) {
    const now = /* @__PURE__ */ new Date();
    for (const update of dueDateUpdates) {
      await conn.update(savingsContributionsTable).set({ dueDate: update.dueDate, updatedAt: now }).where(eq(savingsContributionsTable.id, update.id));
    }
  }
  const deletedIdSet = new Set(uniquePendingDeleteIds);
  const updatedIdToDueDate = new Map(
    dueDateUpdates.map((u) => [u.id, u.dueDate])
  );
  const remainingRows = contributionRows.filter((row) => !deletedIdSet.has(row.id)).map((row) => {
    const updatedDueDate = updatedIdToDueDate.get(row.id);
    return updatedDueDate ? { ...row, dueDate: updatedDueDate } : row;
  });
  const existingScheduleKeysByUser = /* @__PURE__ */ new Map();
  for (const row of remainingRows) {
    const key = toDueDateKey(row.dueDate);
    if (!scheduleKeySet.has(key)) continue;
    const userKeys = existingScheduleKeysByUser.get(row.userId) ?? /* @__PURE__ */ new Set();
    userKeys.add(key);
    existingScheduleKeysByUser.set(row.userId, userKeys);
  }
  const missingRows = [];
  for (const userId of memberUserIds) {
    const existingKeys = existingScheduleKeysByUser.get(userId) ?? /* @__PURE__ */ new Set();
    for (const key of scheduleKeys) {
      if (existingKeys.has(key)) continue;
      const dueDate = scheduleKeyToDueDate.get(key);
      if (!dueDate) continue;
      missingRows.push({
        circleId,
        userId,
        dueDate,
        amount: contributionAmount,
        status: "PENDING"
      });
    }
  }
  if (missingRows.length) {
    await insertMany(conn, savingsContributionsTable, missingRows);
  }
  return {
    deletedContributionRows: uniquePendingDeleteIds.length,
    insertedContributionRows: missingRows.length
  };
}
async function repairCirclePayoutScheduleWith(conn, circleId) {
  const [circle] = await conn.select({
    id: savingsCirclesTable.id,
    maxMembers: savingsCirclesTable.maxMembers,
    startDate: savingsCirclesTable.startDate,
    frequency: savingsCirclesTable.frequency,
    contributionAmount: savingsCirclesTable.contributionAmount
  }).from(savingsCirclesTable).where(eq(savingsCirclesTable.id, circleId));
  if (!circle || !circle.startDate) {
    return { updatedPayoutRows: 0, insertedPayoutRows: 0 };
  }
  const members = await conn.select({
    userId: circleMembershipsTable.userId,
    position: circleMembershipsTable.position
  }).from(circleMembershipsTable).where(eq(circleMembershipsTable.circleId, circleId)).orderBy(asc(circleMembershipsTable.position));
  if (!members.length) {
    return { updatedPayoutRows: 0, insertedPayoutRows: 0 };
  }
  const expectedPayoutRows = buildCircleScheduleEntries({
    circleId,
    startDate: circle.startDate,
    frequency: circle.frequency,
    maxMembers: circle.maxMembers,
    contributionAmount: circle.contributionAmount,
    members
  }).payoutRows;
  const existingPayoutRows = await conn.select({
    id: circlePayoutsTable.id,
    userId: circlePayoutsTable.userId,
    position: circlePayoutsTable.position,
    scheduledDate: circlePayoutsTable.scheduledDate,
    amount: circlePayoutsTable.amount,
    status: circlePayoutsTable.status
  }).from(circlePayoutsTable).where(eq(circlePayoutsTable.circleId, circleId));
  const { updates: payoutUpdates, inserts: missingPayoutRows } = planCirclePayoutScheduleRepair({
    expectedRows: expectedPayoutRows,
    existingRows: existingPayoutRows
  });
  for (const update of payoutUpdates) {
    await conn.update(circlePayoutsTable).set({
      scheduledDate: update.scheduledDate,
      amount: update.amount
    }).where(eq(circlePayoutsTable.id, update.id));
  }
  if (missingPayoutRows.length) {
    await insertMany(conn, circlePayoutsTable, missingPayoutRows);
  }
  return {
    updatedPayoutRows: payoutUpdates.length,
    insertedPayoutRows: missingPayoutRows.length
  };
}
async function generateCircleScheduleWith(conn, circleId) {
  const [circle] = await conn.select().from(savingsCirclesTable).where(eq(savingsCirclesTable.id, circleId));
  if (!circle) return null;
  const startDate = circle.startDate ?? /* @__PURE__ */ new Date();
  const updates = {};
  if (!circle.startDate) {
    updates.startDate = startDate;
  }
  if (circle.endDate !== null) {
    updates.endDate = null;
  }
  if (Object.keys(updates).length) {
    await conn.update(savingsCirclesTable).set({ ...updates, updatedAt: /* @__PURE__ */ new Date() }).where(eq(savingsCirclesTable.id, circleId));
  }
  const members = await conn.select({
    userId: circleMembershipsTable.userId,
    position: circleMembershipsTable.position
  }).from(circleMembershipsTable).where(eq(circleMembershipsTable.circleId, circleId)).orderBy(asc(circleMembershipsTable.position));
  if (!members.length) return null;
  await ensureCircleTreasuryWalletWith(conn, circle);
  const entries = buildCircleScheduleEntries({
    circleId,
    startDate,
    frequency: circle.frequency,
    maxMembers: circle.maxMembers,
    contributionAmount: circle.contributionAmount,
    members
  });
  await insertMany(conn, savingsContributionsTable, entries.contributionRows);
  await insertMany(conn, circlePayoutsTable, entries.payoutRows);
  await repairCircleContributionScheduleWith(conn, circleId);
  await repairCirclePayoutScheduleWith(conn, circleId);
  return {
    circleId,
    payoutAmount: entries.payoutRows[0]?.amount ?? calculateCirclePayoutAmount(circle.contributionAmount, circle.maxMembers),
    memberCount: members.length
  };
}
async function activateCircleIfReadyWith(conn, circleId) {
  const [circle] = await conn.select().from(savingsCirclesTable).where(eq(savingsCirclesTable.id, circleId));
  if (!circle) return { activated: false, circle: null };
  const currentMembers = await getCircleMemberCountWith(conn, circleId);
  const runtimeStatus = getCircleRuntimeStatus({
    status: circle.status,
    startDate: circle.startDate
  });
  if (["COMPLETED", "CANCELLED"].includes(runtimeStatus)) {
    return { activated: false, circle, currentMembers };
  }
  if (circle.status !== "FORMING") {
    return { activated: false, circle, currentMembers };
  }
  if (currentMembers < circle.maxMembers) {
    return { activated: false, circle, currentMembers };
  }
  const creatorSeatIssue = await getCircleCreatorSeatIssueWith(conn, circleId);
  if (creatorSeatIssue) {
    return {
      activated: false,
      circle,
      currentMembers,
      blockedReason: creatorSeatIssue
    };
  }
  const nextDueDate = getNextCircleDueDate({
    anchorDate: circle.startDate,
    frequency: circle.frequency
  });
  const [updatedCircle] = await conn.update(savingsCirclesTable).set({
    status: "ACTIVE",
    startDate: nextDueDate,
    endDate: null,
    updatedAt: /* @__PURE__ */ new Date()
  }).where(eq(savingsCirclesTable.id, circleId)).returning();
  await generateCircleScheduleWith(conn, circleId);
  return {
    activated: true,
    circle: updatedCircle ?? circle,
    currentMembers
  };
}
async function processCircleAutomationWith(conn, circleId) {
  let [circle] = await conn.select().from(savingsCirclesTable).where(eq(savingsCirclesTable.id, circleId));
  if (!circle || ["COMPLETED", "CANCELLED"].includes(
    getCircleRuntimeStatus({
      status: circle.status,
      startDate: circle.startDate
    })
  )) {
    return { autoPaidContributions: 0, autoPaidPayouts: 0, completed: false };
  }
  if (circle.status === "FORMING") {
    const now2 = /* @__PURE__ */ new Date();
    const nextDueDate = getNextCircleDueDate({
      anchorDate: circle.startDate,
      frequency: circle.frequency,
      now: now2
    });
    if (circle.startDate && !Number.isNaN(circle.startDate.getTime()) && circle.startDate.getTime() !== nextDueDate.getTime()) {
      const previousStartDate = circle.startDate;
      const [rolledCircle] = await conn.update(savingsCirclesTable).set({ startDate: nextDueDate, updatedAt: now2 }).where(eq(savingsCirclesTable.id, circleId)).returning();
      circle = rolledCircle ?? circle;
      await conn.update(savingsContributionsTable).set({ dueDate: nextDueDate, updatedAt: now2 }).where(
        and(
          eq(savingsContributionsTable.circleId, circleId),
          eq(savingsContributionsTable.status, "PAID"),
          eq(savingsContributionsTable.dueDate, previousStartDate)
        )
      );
    }
    const currentMembers = await getCircleMemberCountWith(conn, circleId);
    const timeoutDays = circle.formingTimeoutDays ?? 14;
    const timeoutAt = addDays3(circle.createdAt, timeoutDays);
    if (currentMembers < circle.maxMembers && timeoutAt < now2) {
      const circleTreasuryWallet2 = await ensureCircleTreasuryWalletWith(
        conn,
        circle
      );
      if (!circleTreasuryWallet2) {
        return {
          autoPaidContributions: 0,
          autoPaidPayouts: 0,
          completed: false
        };
      }
      const members = await conn.select({ userId: circleMembershipsTable.userId }).from(circleMembershipsTable).where(eq(circleMembershipsTable.circleId, circleId));
      for (const member of members) {
        const userWallet = await ensureWalletWith3(conn, "USER", member.userId);
        const [paidRow] = await conn.select({ total: sum(savingsContributionsTable.amount) }).from(savingsContributionsTable).where(
          and(
            eq(savingsContributionsTable.circleId, circleId),
            eq(savingsContributionsTable.userId, member.userId),
            eq(savingsContributionsTable.status, "PAID")
          )
        );
        const refundAmount = Number(paidRow?.total ?? 0);
        if (refundAmount <= 0) continue;
        await conn.insert(walletTransactionsTable).values({
          type: "REFUND",
          idempotencyKey: `susu:forming-timeout-refund:${circleId}:${member.userId}`,
          fromWalletId: circleTreasuryWallet2.id,
          toWalletId: userWallet.id,
          amount: String(refundAmount.toFixed(2)),
          metadata: {
            source: "susu_forming_timeout_refund",
            circleId,
            userId: member.userId
          }
        }).onConflictDoNothing();
        await conn.update(savingsContributionsTable).set({
          status: "WAIVED",
          updatedAt: now2
        }).where(
          and(
            eq(savingsContributionsTable.circleId, circleId),
            eq(savingsContributionsTable.userId, member.userId),
            eq(savingsContributionsTable.status, "PAID")
          )
        );
      }
      const [cancelledCircle] = await conn.update(savingsCirclesTable).set({ status: "CANCELLED", updatedAt: now2, endDate: null }).where(eq(savingsCirclesTable.id, circleId)).returning();
      circle = cancelledCircle ?? circle;
      return { autoPaidContributions: 0, autoPaidPayouts: 0, completed: false };
    }
  }
  if (getCircleRuntimeStatus({
    status: circle.status,
    startDate: circle.startDate
  }) !== "ACTIVE") {
    const activation = await activateCircleIfReadyWith(conn, circleId);
    if (!activation.circle) {
      return {
        autoPaidContributions: 0,
        autoPaidPayouts: 0,
        completed: false
      };
    }
    circle = activation.circle;
  }
  if (!circle || circle.status !== "ACTIVE") {
    return { autoPaidContributions: 0, autoPaidPayouts: 0, completed: false };
  }
  const now = /* @__PURE__ */ new Date();
  const circleTreasuryWallet = await ensureCircleTreasuryWalletWith(
    conn,
    circle
  );
  if (!circleTreasuryWallet) {
    return { autoPaidContributions: 0, autoPaidPayouts: 0, completed: false };
  }
  const dashboardHref = getCircleDashboardHref({
    organizationId: circle.organizationId
  });
  let autoPaidContributions = 0;
  let autoPaidPayouts = 0;
  const canAutoDeductContributions = circle.organizationId ? circle.orgAutoDeductEnabled : true;
  let dueContributions = canAutoDeductContributions ? await conn.select().from(savingsContributionsTable).where(
    and(
      eq(savingsContributionsTable.circleId, circleId),
      eq(savingsContributionsTable.status, "PENDING"),
      lte(savingsContributionsTable.dueDate, now)
    )
  ).orderBy(
    asc(savingsContributionsTable.dueDate),
    asc(savingsContributionsTable.userId)
  ) : [];
  if (circle.organizationId === null && dueContributions.length > 0) {
    const eligibleUserIds = Array.from(
      new Set(dueContributions.map((row) => row.userId))
    );
    const autoDeductMemberUserIds = eligibleUserIds.length > 0 ? new Set(
      (await conn.select({ userId: circleMembershipsTable.userId }).from(circleMembershipsTable).where(
        and(
          eq(circleMembershipsTable.circleId, circleId),
          eq(circleMembershipsTable.memberAutoDeductEnabled, true),
          inArray(circleMembershipsTable.userId, eligibleUserIds)
        )
      )).map((row) => row.userId)
    ) : /* @__PURE__ */ new Set();
    dueContributions = dueContributions.filter(
      (row) => autoDeductMemberUserIds.has(row.userId)
    );
  }
  const orgSeatUserIds = circle.organizationId !== null && dueContributions.length > 0 ? new Set(
    (await conn.select({
      userId: organizationMembersTable.userId,
      role: organizationMembersTable.role
    }).from(organizationMembersTable).where(
      and(
        eq(
          organizationMembersTable.organizationId,
          circle.organizationId
        ),
        inArray(
          organizationMembersTable.userId,
          Array.from(
            new Set(dueContributions.map((row) => row.userId))
          )
        )
      )
    )).filter((row) => row.role === "OWNER" || row.role === "ADMIN").map((row) => row.userId)
  ) : /* @__PURE__ */ new Set();
  for (const contribution of dueContributions) {
    const shouldUseOrganizationWallet = circle.organizationId !== null && orgSeatUserIds.has(contribution.userId);
    const userWallet = shouldUseOrganizationWallet ? await ensureWalletWith3(conn, "ORGANIZATION", circle.organizationId) : await ensureWalletWith3(conn, "USER", contribution.userId);
    const availableBalance = await getWalletAvailableBalanceWith(
      conn,
      userWallet.id
    );
    const amount = Number(contribution.amount);
    if (availableBalance < amount) {
      const pushKey = `susu_auto_debit_failed:${contribution.id}:push`;
      const emailKey = `susu_auto_debit_failed:${contribution.id}:email`;
      const reserved = await reserveNotificationDeliveryWith(conn, {
        userId: contribution.userId,
        channel: "PUSH",
        category: "SAVINGS",
        idempotencyKey: pushKey,
        status: "SKIPPED",
        provider: null,
        metadata: {
          kind: "susu_auto_debit_failed",
          circleId,
          contributionId: contribution.id,
          dueDate: contribution.dueDate.toISOString(),
          requiredAmount: amount,
          availableBalance
        }
      });
      if (reserved.reserved) {
        const amountLabel = `$${amount.toFixed(2)}`;
        const availableLabel = `$${availableBalance.toFixed(2)}`;
        const walletLabel = shouldUseOrganizationWallet ? "organization wallet" : "wallet";
        const circleSuffix = formatSusuCircleSuffix(circle.name);
        const inApp = await notifyInAppWith(conn, {
          userId: contribution.userId,
          category: "SAVINGS",
          severity: "ERROR",
          title: "Contribution payment missed",
          body: `We could not auto-pay your SUSU contribution${circleSuffix} of ${amountLabel} due on ${contribution.dueDate.toLocaleDateString("en-CA")} because your ${walletLabel} balance is ${availableLabel}.`,
          actionLabel: circle.organizationId !== null ? "Open Organization SUSU" : "Open Savings",
          actionHref: dashboardHref
        });
        try {
          const pushResult = await deliverPushIfEnabled({
            userId: contribution.userId,
            category: "SAVINGS",
            title: "Contribution payment missed",
            body: `We could not auto-pay your SUSU contribution${circleSuffix} due on ${contribution.dueDate.toLocaleDateString("en-CA")}.`,
            data: { actionHref: dashboardHref }
          });
          await finalizeNotificationDeliveryWith(conn, {
            idempotencyKey: pushKey,
            status: pushResult.status,
            provider: pushResult.status === "SENT" ? "EXPO" : null,
            errorMessage: pushResult.reason ?? null,
            notificationId: inApp.id,
            metadata: {
              kind: "susu_auto_debit_failed",
              reason: pushResult.reason ?? null
            }
          });
        } catch (err) {
          await finalizeNotificationDeliveryWith(conn, {
            idempotencyKey: pushKey,
            status: "FAILED",
            provider: "EXPO",
            errorMessage: err instanceof Error ? err.message : String(err),
            notificationId: inApp.id,
            metadata: { kind: "susu_auto_debit_failed" }
          });
        }
        const emailReserved = await reserveNotificationDeliveryWith(conn, {
          userId: contribution.userId,
          channel: "EMAIL",
          category: "SAVINGS",
          idempotencyKey: emailKey,
          status: "SKIPPED",
          provider: null,
          metadata: {
            kind: "susu_auto_debit_failed",
            circleId,
            contributionId: contribution.id,
            dueDate: contribution.dueDate.toISOString()
          }
        });
        if (emailReserved.reserved) {
          const [u] = await conn.select({
            email: usersTable.email,
            firstName: usersTable.firstName
          }).from(usersTable).where(eq(usersTable.id, contribution.userId));
          if (u) {
            try {
              const emailResult = await deliverReminderEmailIfEnabled({
                userId: contribution.userId,
                to: u.email,
                firstName: u.firstName,
                category: "SAVINGS",
                title: "Contribution payment missed",
                intro: `We could not auto-pay your SUSU contribution${circleSuffix} due on ${contribution.dueDate.toLocaleDateString("en-CA")}.`,
                lines: [
                  `Required amount: ${amountLabel}`,
                  `Wallet balance available: ${availableLabel}`,
                  "Please top up your wallet and pay your contribution to stay in good standing."
                ],
                actionLabel: circle.organizationId !== null ? "Open Organization SUSU" : "Open Savings",
                actionHref: dashboardHref
              });
              await finalizeNotificationDeliveryWith(conn, {
                idempotencyKey: emailKey,
                status: emailResult.status,
                provider: emailResult.status === "SENT" ? "SMTP" : null,
                errorMessage: emailResult.reason ?? null,
                notificationId: inApp.id,
                metadata: {
                  kind: "susu_auto_debit_failed",
                  reason: emailResult.reason ?? null
                }
              });
            } catch (err) {
              await finalizeNotificationDeliveryWith(conn, {
                idempotencyKey: emailKey,
                status: "FAILED",
                provider: "SMTP",
                errorMessage: err instanceof Error ? err.message : String(err),
                notificationId: inApp.id,
                metadata: { kind: "susu_auto_debit_failed" }
              });
            }
          }
        }
      }
      continue;
    }
    const idempotencyKey = `susu:auto-contribution:${contribution.id}`;
    const [createdTx] = await conn.insert(walletTransactionsTable).values({
      type: "CONTRIBUTION",
      idempotencyKey,
      fromWalletId: userWallet.id,
      toWalletId: circleTreasuryWallet.id,
      amount: formatMoneyAmount(amount),
      metadata: {
        source: circle.organizationId !== null ? shouldUseOrganizationWallet ? "org_susu_auto_contribution_org_wallet" : "org_susu_auto_contribution_member_wallet" : "susu_auto_contribution",
        circleId,
        contributionId: contribution.id,
        userId: contribution.userId,
        dueDate: contribution.dueDate.toISOString()
      }
    }).onConflictDoNothing().returning({
      id: walletTransactionsTable.id,
      createdAt: walletTransactionsTable.createdAt
    });
    const [existingTx] = createdTx ? [createdTx] : await conn.select({
      id: walletTransactionsTable.id,
      createdAt: walletTransactionsTable.createdAt
    }).from(walletTransactionsTable).where(eq(walletTransactionsTable.idempotencyKey, idempotencyKey)).limit(1);
    if (!existingTx) continue;
    const paidAt = existingTx.createdAt ?? now;
    const [updatedContribution] = await conn.update(savingsContributionsTable).set({
      paidAt,
      status: "PAID",
      method: "WALLET",
      receiptRef: `wallet_tx:${existingTx.id}`,
      updatedAt: now
    }).where(
      and(
        eq(savingsContributionsTable.id, contribution.id),
        eq(savingsContributionsTable.status, "PENDING")
      )
    ).returning();
    if (updatedContribution) {
      autoPaidContributions += 1;
    }
  }
  const duePayouts = await conn.select().from(circlePayoutsTable).where(
    and(
      eq(circlePayoutsTable.circleId, circleId),
      eq(circlePayoutsTable.status, "PENDING"),
      lte(circlePayoutsTable.scheduledDate, now)
    )
  ).orderBy(
    asc(circlePayoutsTable.scheduledDate),
    asc(circlePayoutsTable.position)
  );
  for (const payout of duePayouts) {
    const hasBlockingContributionIssues = await hasBlockingPayoutContributionIssuesWith(
      conn,
      circleId,
      payout.userId,
      now
    );
    if (hasBlockingContributionIssues) continue;
    const allocationBalance = await getCircleAllocationBalanceWith(
      conn,
      circleId
    );
    const amount = Number(payout.amount);
    if (allocationBalance < amount) continue;
    const userWallet = await ensureWalletWith3(conn, "USER", payout.userId);
    const idempotencyKey = `susu:auto-payout:${payout.id}`;
    const [createdTx] = await conn.insert(walletTransactionsTable).values({
      type: "PAYOUT",
      idempotencyKey,
      fromWalletId: circleTreasuryWallet.id,
      toWalletId: userWallet.id,
      amount: formatMoneyAmount(amount),
      metadata: {
        source: "susu_auto_payout",
        circleId,
        payoutId: payout.id,
        payoutUserId: payout.userId,
        position: payout.position
      }
    }).onConflictDoNothing().returning({
      id: walletTransactionsTable.id,
      createdAt: walletTransactionsTable.createdAt
    });
    const [existingTx] = createdTx ? [createdTx] : await conn.select({
      id: walletTransactionsTable.id,
      createdAt: walletTransactionsTable.createdAt
    }).from(walletTransactionsTable).where(eq(walletTransactionsTable.idempotencyKey, idempotencyKey)).limit(1);
    if (!existingTx) continue;
    const paidDate = existingTx.createdAt ?? now;
    const [updatedPayout] = await conn.update(circlePayoutsTable).set({
      paidDate,
      status: "PAID"
    }).where(
      and(
        eq(circlePayoutsTable.id, payout.id),
        eq(circlePayoutsTable.status, "PENDING")
      )
    ).returning();
    if (updatedPayout) {
      autoPaidPayouts += 1;
      const amountLabel = amount.toLocaleString("en-CA", {
        style: "currency",
        currency: "CAD"
      });
      const circleSuffix = formatSusuCircleSuffix(circle.name);
      const inApp = await notifyInAppWith(conn, {
        userId: payout.userId,
        category: "SAVINGS",
        severity: "SUCCESS",
        title: "SUSU payout received",
        body: `Your SUSU payout${circleSuffix} of ${amountLabel} has been added to your wallet.`,
        actionLabel: circle.organizationId !== null ? "Open Organization SUSU" : "Open Savings",
        actionHref: dashboardHref
      });
      const pushKey = `susu_payout_paid:${payout.id}:push`;
      const pushReserved = await reserveNotificationDeliveryWith(conn, {
        userId: payout.userId,
        channel: "PUSH",
        category: "SAVINGS",
        idempotencyKey: pushKey,
        status: "SKIPPED",
        provider: null,
        metadata: {
          kind: "susu_payout_paid",
          circleId,
          payoutId: payout.id,
          amount
        }
      });
      if (pushReserved.reserved) {
        try {
          const pushResult = await deliverPushIfEnabled({
            userId: payout.userId,
            category: "SAVINGS",
            title: "SUSU payout received",
            body: `Your SUSU payout${circleSuffix} of ${amountLabel} has been added to your wallet.`,
            data: { actionHref: dashboardHref }
          });
          await finalizeNotificationDeliveryWith(conn, {
            idempotencyKey: pushKey,
            status: pushResult.status,
            provider: pushResult.status === "SENT" ? "EXPO" : null,
            errorMessage: pushResult.reason ?? null,
            notificationId: inApp.id,
            metadata: {
              kind: "susu_payout_paid",
              reason: pushResult.reason ?? null
            }
          });
        } catch (err) {
          await finalizeNotificationDeliveryWith(conn, {
            idempotencyKey: pushKey,
            status: "FAILED",
            provider: "EXPO",
            errorMessage: err instanceof Error ? err.message : String(err),
            notificationId: inApp.id,
            metadata: { kind: "susu_payout_paid" }
          });
        }
      }
      const emailKey = `susu_payout_paid:${payout.id}:email`;
      const emailReserved = await reserveNotificationDeliveryWith(conn, {
        userId: payout.userId,
        channel: "EMAIL",
        category: "SAVINGS",
        idempotencyKey: emailKey,
        status: "SKIPPED",
        provider: null,
        metadata: {
          kind: "susu_payout_paid",
          circleId,
          payoutId: payout.id,
          amount
        }
      });
      if (emailReserved.reserved) {
        const [u] = await conn.select({
          email: usersTable.email,
          firstName: usersTable.firstName
        }).from(usersTable).where(eq(usersTable.id, payout.userId));
        if (u) {
          try {
            const emailResult = await deliverReminderEmailIfEnabled({
              userId: payout.userId,
              to: u.email,
              firstName: u.firstName,
              category: "SAVINGS",
              title: "SUSU payout received",
              intro: `Your SUSU payout${circleSuffix} of ${amountLabel} has been added to your wallet.`,
              lines: [
                "Open Savings to review the payout and your updated wallet balance."
              ],
              actionLabel: circle.organizationId !== null ? "Open Organization SUSU" : "Open Savings",
              actionHref: dashboardHref
            });
            await finalizeNotificationDeliveryWith(conn, {
              idempotencyKey: emailKey,
              status: emailResult.status,
              provider: emailResult.status === "SENT" ? "SMTP" : null,
              errorMessage: emailResult.reason ?? null,
              notificationId: inApp.id,
              metadata: {
                kind: "susu_payout_paid",
                reason: emailResult.reason ?? null
              }
            });
          } catch (err) {
            await finalizeNotificationDeliveryWith(conn, {
              idempotencyKey: emailKey,
              status: "FAILED",
              provider: "SMTP",
              errorMessage: err instanceof Error ? err.message : String(err),
              notificationId: inApp.id,
              metadata: { kind: "susu_payout_paid" }
            });
          }
        }
      }
    }
  }
  const [remainingPayouts] = await conn.select({ count: count() }).from(circlePayoutsTable).where(
    and(
      eq(circlePayoutsTable.circleId, circleId),
      ne(circlePayoutsTable.status, "PAID")
    )
  );
  const [remainingContributions] = await conn.select({ count: count() }).from(savingsContributionsTable).where(
    and(
      eq(savingsContributionsTable.circleId, circleId),
      ne(savingsContributionsTable.status, "PAID"),
      ne(savingsContributionsTable.status, "WAIVED")
    )
  );
  const completed = Number(remainingPayouts?.count ?? 0) === 0 && Number(remainingContributions?.count ?? 0) === 0;
  if (completed) {
    await conn.update(savingsCirclesTable).set({
      status: "COMPLETED",
      updatedAt: now
    }).where(
      and(
        eq(savingsCirclesTable.id, circleId),
        eq(savingsCirclesTable.status, "ACTIVE")
      )
    );
  }
  return { autoPaidContributions, autoPaidPayouts, completed };
}
async function processAllActiveCirclesWith(conn) {
  const activeCircles = await conn.select({ id: savingsCirclesTable.id }).from(savingsCirclesTable).where(
    inArray(savingsCirclesTable.status, ["UPCOMING", "ACTIVE", "FORMING"])
  );
  const summary = {
    processedCircles: activeCircles.length,
    autoPaidContributions: 0,
    autoPaidPayouts: 0,
    completedCircles: 0
  };
  for (const circle of activeCircles) {
    try {
      const result = await processCircleAutomationWith(conn, circle.id);
      summary.autoPaidContributions += result.autoPaidContributions;
      summary.autoPaidPayouts += result.autoPaidPayouts;
      if (result.completed) {
        summary.completedCircles += 1;
      }
    } catch {
      continue;
    }
  }
  return summary;
}
var SUSU_WALLET_OWNER_ID;
var init_susu = __esm({
  "src/lib/susu.ts"() {
    "use strict";
    init_schema2();
    init_drizzle_orm();
    init_lending();
    init_notification_dispatcher();
    init_notification_deliveries();
    SUSU_WALLET_OWNER_ID = 1;
  }
});

// src/lib/individual-plan-entitlements.ts
function isRecord2(value) {
  return typeof value === "object" && value !== null;
}
function normalizeIndividualPlanEntitlements(value) {
  const source = isRecord2(value) ? value : {};
  return {
    member_susu_access: typeof source.member_susu_access === "boolean" ? source.member_susu_access : DEFAULT_INDIVIDUAL_PLAN_ENTITLEMENTS.member_susu_access,
    susunomics_access: typeof source.susunomics_access === "boolean" ? source.susunomics_access : DEFAULT_INDIVIDUAL_PLAN_ENTITLEMENTS.susunomics_access,
    community_lending_access: typeof source.community_lending_access === "boolean" ? source.community_lending_access : DEFAULT_INDIVIDUAL_PLAN_ENTITLEMENTS.community_lending_access,
    p2p_lending_access: typeof source.p2p_lending_access === "boolean" ? source.p2p_lending_access : DEFAULT_INDIVIDUAL_PLAN_ENTITLEMENTS.p2p_lending_access
  };
}
var DEFAULT_INDIVIDUAL_PLAN_ENTITLEMENTS;
var init_individual_plan_entitlements = __esm({
  "src/lib/individual-plan-entitlements.ts"() {
    "use strict";
    DEFAULT_INDIVIDUAL_PLAN_ENTITLEMENTS = {
      // Preserve current behavior for existing individual plans unless explicitly changed.
      member_susu_access: true,
      susunomics_access: true,
      community_lending_access: true,
      p2p_lending_access: false
    };
  }
});

// src/lib/asca.ts
function getContributionModel(constitution) {
  if (typeof constitution?.equalContribution === "boolean") {
    return constitution.equalContribution ? "EQUAL" : "VARIABLE";
  }
  if (constitution?.contributionModel === "EQUAL") return "EQUAL";
  if (constitution?.contributionModel === "VARIABLE") return "VARIABLE";
  return "EQUAL";
}
function getAscaBorrowingPolicy(constitution) {
  const raw = constitution && typeof constitution === "object" && !Array.isArray(constitution) ? constitution.borrowingPolicy : null;
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
  const parsed = AscaBorrowingPolicySchema.safeParse(raw);
  if (!parsed.success) return null;
  if (parsed.data.enabled !== true) return null;
  return {
    enabled: true,
    approvalMode: "OWNER_ADMIN",
    maxBorrowPctOfPool: Number(parsed.data.maxBorrowPctOfPool ?? 60),
    maxBorrowPctOfOwnContribution: Number(
      parsed.data.maxBorrowPctOfOwnContribution ?? 100
    ),
    liquidityReservePct: Number(parsed.data.liquidityReservePct ?? 20),
    termMonths: Number(parsed.data.termMonths ?? 6),
    repaymentFrequency: parsed.data.repaymentFrequency ?? "MONTHLY",
    borrowerAppreciationPct: Number(parsed.data.borrowerAppreciationPct ?? 12),
    processingFeePct: Number(parsed.data.processingFeePct ?? 0),
    minContributionAgeDays: Number(parsed.data.minContributionAgeDays ?? 0)
  };
}
function getAscaLendingPoolConstitution(constitution) {
  const raw = constitution && typeof constitution === "object" && !Array.isArray(constitution) ? constitution.lendingPool : null;
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
  const parsed = AscaLendingPoolSchema.safeParse(raw);
  if (!parsed.success) return null;
  if (parsed.data.enabled !== true) return null;
  return {
    enabled: true,
    eligibilityMode: parsed.data.eligibilityMode ?? "CONTRIBUTORS_ONLY",
    maxPctOfPoolAfterReserve: Number(parsed.data.maxPctOfPoolAfterReserve ?? 60),
    defaultTermMonths: Number(parsed.data.defaultTermMonths ?? 12),
    defaultRepaymentFrequency: parsed.data.defaultRepaymentFrequency ?? "MONTHLY",
    defaultBorrowerAppreciationPct: Number(
      parsed.data.defaultBorrowerAppreciationPct ?? 8
    ),
    defaultProcessingFeePct: Number(parsed.data.defaultProcessingFeePct ?? 0)
  };
}
function normalizeMoneyString(input, field) {
  const parsed = Number(String(input).trim());
  if (!Number.isFinite(parsed)) {
    throw new Error(`${field} must be a valid number.`);
  }
  if (parsed < 0) {
    throw new Error(`${field} must be 0 or more.`);
  }
  return parsed.toFixed(2);
}
function normalizeDateInput(input, field) {
  const trimmed = String(input ?? "").trim();
  const parsed = new Date(trimmed);
  if (!trimmed || Number.isNaN(parsed.getTime())) {
    throw new Error(`${field} must be a valid date.`);
  }
  return parsed;
}
function getContributionFrequency(constitution) {
  if (constitution?.installmentPolicy === "FULL") return "ONCE";
  const raw = String(
    constitution?.contributionFrequency ?? "MONTHLY"
  ).toUpperCase();
  if (raw === "WEEKLY") return "WEEKLY";
  if (raw === "ONCE") return "ONCE";
  return "MONTHLY";
}
function clampCents(value) {
  if (!Number.isFinite(value)) return 0;
  return Math.max(0, Math.round(value));
}
function allocateProRataSettlementShares(members, totalSettlementCents, principalCentsTotal) {
  if (totalSettlementCents <= 0 || principalCentsTotal <= 0) {
    return members.map((member) => ({ ...member, payoutCents: 0 }));
  }
  const seeded = members.map((member, index2) => {
    const rawShare = totalSettlementCents * member.contributedCents / principalCentsTotal;
    const baseShare = Math.floor(rawShare);
    return {
      ...member,
      payoutCents: baseShare,
      remainderWeight: rawShare - baseShare,
      originalIndex: index2
    };
  });
  let remainingCents = totalSettlementCents - seeded.reduce((sum3, member) => sum3 + member.payoutCents, 0);
  seeded.slice().sort((a, b) => {
    if (b.remainderWeight !== a.remainderWeight) {
      return b.remainderWeight - a.remainderWeight;
    }
    return a.originalIndex - b.originalIndex;
  }).slice(0, Math.max(0, remainingCents)).forEach((member) => {
    const target = seeded[member.originalIndex];
    target.payoutCents += 1;
    remainingCents -= 1;
  });
  return seeded.map(({ remainderWeight, originalIndex, ...member }) => member);
}
function computeTotalInstallments(startAt, endAt, frequency) {
  if (frequency === "ONCE") return 1;
  const start = new Date(startAt);
  const end = new Date(endAt);
  if (end.getTime() <= start.getTime()) return 1;
  if (frequency === "WEEKLY") {
    const diffDays = Math.floor(
      (end.getTime() - start.getTime()) / (1e3 * 60 * 60 * 24)
    );
    return Math.max(1, Math.floor(diffDays / 7) + 1);
  }
  const startYear = start.getFullYear();
  const startMonth = start.getMonth();
  const endYear = end.getFullYear();
  const endMonth = end.getMonth();
  const months = (endYear - startYear) * 12 + (endMonth - startMonth);
  const extra = end.getDate() >= start.getDate() ? 1 : 0;
  return Math.max(1, months + extra);
}
function computeElapsedInstallments(startAt, now, frequency) {
  if (frequency === "ONCE") return now.getTime() >= startAt.getTime() ? 1 : 0;
  if (now.getTime() < startAt.getTime()) return 0;
  if (frequency === "WEEKLY") {
    const diffDays = Math.floor(
      (now.getTime() - startAt.getTime()) / (1e3 * 60 * 60 * 24)
    );
    return Math.max(1, Math.floor(diffDays / 7) + 1);
  }
  const startYear = startAt.getFullYear();
  const startMonth = startAt.getMonth();
  const nowYear = now.getFullYear();
  const nowMonth = now.getMonth();
  const months = (nowYear - startYear) * 12 + (nowMonth - startMonth);
  const extra = now.getDate() >= startAt.getDate() ? 1 : 0;
  return Math.max(1, months + extra);
}
function computeCatchUpRequiredCents(params) {
  const targetCents = clampCents(Number(params.targetContribution) * 100);
  const contributedCents = clampCents(Number(params.contributedAmount) * 100);
  if (targetCents <= 0) return 0;
  const totalInstallments = computeTotalInstallments(
    params.fundingStartAt,
    params.fundingEndAt,
    params.frequency
  );
  const elapsedInstallments = Math.min(
    totalInstallments,
    computeElapsedInstallments(
      params.fundingStartAt,
      params.now,
      params.frequency
    )
  );
  const installmentCents = Math.max(
    1,
    Math.round(targetCents / totalInstallments)
  );
  const expectedByNowCents = Math.min(
    targetCents,
    installmentCents * elapsedInstallments
  );
  const required2 = expectedByNowCents - contributedCents;
  return required2 > 0 ? required2 : 0;
}
function computeEqualTargetContribution(params) {
  const target = Number(params.targetAmount);
  const maxMembers = params.maxMembers;
  if (!Number.isFinite(target) || target <= 0) {
    throw new Error("Target pool amount is required for equal contribution.");
  }
  if (!Number.isFinite(maxMembers) || maxMembers < 2) {
    throw new Error("maxMembers must be at least 2 for equal contribution.");
  }
  return (target / maxMembers).toFixed(2);
}
async function ensureWalletWith4(conn, ownerType, ownerId) {
  const existing = await conn.select().from(walletsTable).where(
    and(
      eq(walletsTable.ownerType, ownerType),
      eq(walletsTable.ownerId, ownerId)
    )
  );
  if (existing.length) return existing[0];
  const [created] = await conn.insert(walletsTable).values({ ownerType, ownerId }).returning();
  return created;
}
async function createAsca(input, creatorUserId, options) {
  return await db.transaction(async (tx) => {
    const constitution = input.constitution;
    const contributionModel = getContributionModel(constitution);
    const {
      equalContribution: _equalContribution,
      contributionModel: _contributionModel,
      ...constitutionRest
    } = constitution ?? {};
    const normalizedTargetAmount = normalizeMoneyString(
      input.targetAmount,
      "targetAmount"
    );
    const normalizedFundingEndAt = normalizeDateInput(
      input.fundingEndAt,
      "fundingEndAt"
    );
    const normalizedTermsHtml = typeof input.termsHtml === "string" && input.termsHtml.trim().length > 0 ? input.termsHtml.trim() : void 0;
    const borrowingPolicy = getAscaBorrowingPolicy(constitution);
    const lendingPoolConstitution = getAscaLendingPoolConstitution(constitution);
    if (!Number.isFinite(Number(normalizedTargetAmount)) || Number(normalizedTargetAmount) <= 0) {
      throw new Error("Target pool amount must be greater than 0.");
    }
    if (!Number.isFinite(Number(constitution?.maxMembers)) || Number(constitution.maxMembers) < 2) {
      throw new Error("maxMembers must be at least 2.");
    }
    if (input.type !== "GENERAL" && borrowingPolicy) {
      throw new Error("Borrowing can only be enabled for GENERAL ASCA groups.");
    }
    if (input.type !== "GENERAL" && lendingPoolConstitution) {
      throw new Error(
        "Community lending pool can only be enabled for GENERAL ASCA groups."
      );
    }
    if (input.type === "INVESTMENT" && input.investmentId) {
      const [opp] = await tx.select({ organizationId: investmentOpportunitiesTable.organizationId }).from(investmentOpportunitiesTable).where(eq(investmentOpportunitiesTable.id, input.investmentId));
      if (!opp) {
        throw new Error("Investment opportunity not found.");
      }
      if (options?.organizationId) {
        if (opp.organizationId !== options.organizationId) {
          throw new Error(
            "Investment opportunity belongs to a different organization."
          );
        }
      } else {
        if (opp.organizationId !== null) {
          throw new Error(
            "Cannot select an organization-specific investment for a global ASCA."
          );
        }
      }
    }
    const [asca] = await tx.insert(ascasTable).values({
      name: input.name,
      description: input.description,
      termsHtml: normalizedTermsHtml,
      organizationId: options?.organizationId ?? null,
      type: input.type,
      status: "DRAFT",
      investmentId: input.investmentId,
      targetAmount: normalizedTargetAmount,
      fundingEndAt: normalizedFundingEndAt,
      constitution: {
        ...constitutionRest,
        equalContribution: contributionModel === "EQUAL"
      }
    }).returning();
    const escrowWallet = await ensureWalletWith4(tx, "ASCA", asca.id);
    await tx.update(ascasTable).set({ escrowWalletId: escrowWallet.id }).where(eq(ascasTable.id, asca.id));
    if (input.joinCreator === true) {
      const targetContribution = contributionModel === "EQUAL" ? computeEqualTargetContribution({
        targetAmount: normalizedTargetAmount,
        maxMembers: Number(constitution.maxMembers)
      }) : "0.00";
      const [existingMember] = await tx.select({ id: ascaMembersTable.id }).from(ascaMembersTable).where(
        and(
          eq(ascaMembersTable.ascaId, asca.id),
          eq(ascaMembersTable.userId, creatorUserId)
        )
      );
      if (!existingMember) {
        await tx.insert(ascaMembersTable).values({
          ascaId: asca.id,
          userId: creatorUserId,
          targetContribution,
          status: "ACTIVE"
        });
      }
    } else {
      await tx.delete(ascaMembersTable).where(
        and(
          eq(ascaMembersTable.ascaId, asca.id),
          eq(ascaMembersTable.userId, creatorUserId)
        )
      );
    }
    return { ...asca, escrowWalletId: escrowWallet.id };
  });
}
async function deleteAscaGroup(params) {
  return await db.transaction(async (tx) => {
    const [asca] = await tx.select().from(ascasTable).where(eq(ascasTable.id, params.ascaId));
    if (!asca) throw new Error("ASCA not found");
    const expectedOrg = params.organizationId ?? null;
    if ((asca.organizationId ?? null) !== expectedOrg) {
      throw new Error("ASCA not found");
    }
    if (asca.status === "CLOSED") {
      throw new Error("This ASCA cannot be deleted.");
    }
    const currentAmountCents = clampCents(
      Number(String(asca.currentAmount ?? "0")) * 100
    );
    if (currentAmountCents > 0) {
      throw new Error("ASCA cannot be deleted while it has funds.");
    }
    const [contributionCount] = await tx.select({ count: sql`count(*)` }).from(ascaContributionsTable).where(eq(ascaContributionsTable.ascaId, params.ascaId));
    if (Number(contributionCount?.count ?? 0) > 0) {
      throw new Error("ASCA cannot be deleted after contributions exist.");
    }
    const members = await tx.select({
      userId: ascaMembersTable.userId,
      contributedAmount: ascaMembersTable.contributedAmount
    }).from(ascaMembersTable).where(eq(ascaMembersTable.ascaId, params.ascaId));
    const allowedMembers = members.filter(
      (m) => m.userId === params.triggerUserId
    );
    if (members.length !== allowedMembers.length) {
      throw new Error("ASCA cannot be deleted after members have joined.");
    }
    const hasContribution = allowedMembers.some(
      (m) => clampCents(Number(String(m.contributedAmount ?? "0")) * 100) > 0
    );
    if (hasContribution) {
      throw new Error("ASCA cannot be deleted after contributions exist.");
    }
    const escrowWalletId = asca.escrowWalletId;
    if (escrowWalletId) {
      const [walletTxCount] = await tx.select({ count: sql`count(*)` }).from(walletTransactionsTable).where(
        sql`${walletTransactionsTable.fromWalletId} = ${escrowWalletId} OR ${walletTransactionsTable.toWalletId} = ${escrowWalletId}`
      );
      if (Number(walletTxCount?.count ?? 0) > 0) {
        throw new Error(
          "ASCA cannot be deleted after wallet transactions exist."
        );
      }
    }
    await tx.delete(ascasTable).where(eq(ascasTable.id, params.ascaId));
    if (escrowWalletId) {
      await tx.delete(walletsTable).where(eq(walletsTable.id, escrowWalletId));
    }
    return true;
  });
}
async function publishAsca(ascaId, options) {
  return await db.transaction(async (tx) => {
    const [asca] = await tx.select().from(ascasTable).where(eq(ascasTable.id, ascaId));
    if (!asca) throw new Error("ASCA not found");
    const expectedOrg = options?.organizationId === void 0 ? void 0 : options.organizationId ?? null;
    if (expectedOrg !== void 0) {
      if ((asca.organizationId ?? null) !== expectedOrg) {
        throw new Error("ASCA not found");
      }
    }
    if (asca.status !== "DRAFT") {
      throw new Error("Only draft ASCAs can be published.");
    }
    if (asca.fundingEndAt && /* @__PURE__ */ new Date() > new Date(asca.fundingEndAt)) {
      throw new Error("Funding end date has already passed.");
    }
    const [updated] = await tx.update(ascasTable).set({
      status: "FUNDING",
      fundingStartAt: asca.fundingStartAt ?? /* @__PURE__ */ new Date(),
      updatedAt: /* @__PURE__ */ new Date()
    }).where(eq(ascasTable.id, ascaId)).returning();
    return updated;
  });
}
async function unpublishAsca(ascaId, options) {
  return await db.transaction(async (tx) => {
    const [asca] = await tx.select().from(ascasTable).where(eq(ascasTable.id, ascaId));
    if (!asca) throw new Error("ASCA not found");
    const expectedOrg = options?.organizationId === void 0 ? void 0 : options.organizationId ?? null;
    if (expectedOrg !== void 0) {
      if ((asca.organizationId ?? null) !== expectedOrg) {
        throw new Error("ASCA not found");
      }
    }
    if (asca.status !== "FUNDING") {
      throw new Error("Only funding ASCAs can be unpublished.");
    }
    const currentAmount = parseFloat(asca.currentAmount || "0");
    if (currentAmount > 0) {
      throw new Error(
        "You cannot unpublish an ASCA that already has contributions."
      );
    }
    const [updated] = await tx.update(ascasTable).set({ status: "DRAFT", updatedAt: /* @__PURE__ */ new Date() }).where(eq(ascasTable.id, ascaId)).returning();
    return updated;
  });
}
async function joinAsca(ascaId, userId, params) {
  return await db.transaction(async (tx) => {
    const [asca] = await tx.select().from(ascasTable).where(eq(ascasTable.id, ascaId));
    if (!asca) throw new Error("ASCA not found");
    if (asca.status !== "FUNDING" && asca.status !== "DRAFT") {
      throw new Error("ASCA is not accepting new members at this stage.");
    }
    const now = /* @__PURE__ */ new Date();
    if (asca.fundingStartAt && now < new Date(asca.fundingStartAt)) {
      throw new Error("Funding has not started yet.");
    }
    if (asca.fundingEndAt && now > new Date(asca.fundingEndAt)) {
      throw new Error("Funding period has ended.");
    }
    const constitution = asca.constitution;
    const contributionModel = getContributionModel(constitution);
    if (constitution?.allowLateJoin === false && asca.status === "FUNDING") {
      throw new Error(
        "This ASCA constitution does not allow late joiners after funding has started."
      );
    }
    if (constitution?.maxMembers) {
      const [memberCount] = await tx.select({ count: sql`count(*)` }).from(ascaMembersTable).where(eq(ascaMembersTable.ascaId, ascaId));
      if (Number(memberCount.count) >= constitution.maxMembers) {
        throw new Error("This ASCA has reached its maximum member capacity.");
      }
    }
    const [existingMember] = await tx.select().from(ascaMembersTable).where(
      and(
        eq(ascaMembersTable.ascaId, ascaId),
        eq(ascaMembersTable.userId, userId)
      )
    );
    if (existingMember) {
      throw new Error("User is already a member of this ASCA.");
    }
    const targetContribution = contributionModel === "EQUAL" ? computeEqualTargetContribution({
      targetAmount: asca.targetAmount ? normalizeMoneyString(String(asca.targetAmount), "targetAmount") : (() => {
        throw new Error(
          "Target pool amount is required for equal contribution."
        );
      })(),
      maxMembers: Number(constitution?.maxMembers)
    }) : params?.targetContribution ? normalizeMoneyString(
      params.targetContribution,
      "targetContribution"
    ) : "0.00";
    const shouldCatchUp = asca.status === "FUNDING" && Boolean(asca.fundingStartAt) && asca.fundingStartAt !== null && (() => {
      const startAt = new Date(asca.fundingStartAt);
      const graceMs = ASCA_CATCH_UP_GRACE_DAYS * 24 * 60 * 60 * 1e3;
      return now.getTime() - startAt.getTime() >= graceMs;
    })();
    if (shouldCatchUp && contributionModel === "EQUAL") {
      const constitutionFrequency = getContributionFrequency(constitution);
      const requiredCatchUpCents = computeCatchUpRequiredCents({
        targetContribution,
        contributedAmount: "0.00",
        fundingStartAt: new Date(asca.fundingStartAt),
        fundingEndAt: new Date(asca.fundingEndAt),
        frequency: constitutionFrequency,
        now
      });
      if (requiredCatchUpCents > 0) {
        const providedCatchUpCents = clampCents(
          Number(params?.catchUpAmount ?? 0) * 100
        );
        if (providedCatchUpCents < requiredCatchUpCents) {
          throw new AscaCatchUpRequiredError(
            (requiredCatchUpCents / 100).toFixed(2)
          );
        }
      }
    }
    const [member] = await tx.insert(ascaMembersTable).values({
      ascaId,
      userId,
      targetContribution,
      status: "ACTIVE"
    }).returning();
    if (shouldCatchUp && contributionModel === "EQUAL") {
      const constitutionFrequency = getContributionFrequency(constitution);
      const requiredCatchUpCents = computeCatchUpRequiredCents({
        targetContribution,
        contributedAmount: "0.00",
        fundingStartAt: new Date(asca.fundingStartAt),
        fundingEndAt: new Date(asca.fundingEndAt),
        frequency: constitutionFrequency,
        now
      });
      if (requiredCatchUpCents > 0) {
        const amount = requiredCatchUpCents / 100;
        await contributeToAscaInternal(tx, asca, member, userId, amount);
      }
    }
    return member;
  });
}
async function contributeToAscaInternal(tx, asca, member, userId, amount) {
  if (amount <= 0) throw new Error("Contribution must be greater than 0");
  const now = /* @__PURE__ */ new Date();
  if (asca.fundingStartAt && now < new Date(asca.fundingStartAt)) {
    throw new Error("Funding has not started yet.");
  }
  if (asca.fundingEndAt && now > new Date(asca.fundingEndAt)) {
    throw new Error("Funding period has ended.");
  }
  if (!asca.escrowWalletId)
    throw new Error("ASCA escrow wallet not initialized");
  const amountCents = Math.round(amount * 100);
  if (!Number.isFinite(amountCents) || amountCents <= 0) {
    throw new Error("Contribution amount must be valid.");
  }
  const currentPoolCents = Math.round(
    Number(String(asca.currentAmount ?? "0")) * 100
  );
  const targetPoolCents = Math.round(
    Number(String(asca.targetAmount ?? "0")) * 100
  );
  if (Number.isFinite(targetPoolCents) && targetPoolCents > 0) {
    const remainingPoolCents = targetPoolCents - currentPoolCents;
    if (remainingPoolCents <= 0) {
      throw new Error("This ASCA has already reached its target pool.");
    }
    if (amountCents > remainingPoolCents) {
      throw new Error(
        `Contribution exceeds the remaining pool target (${(remainingPoolCents / 100).toFixed(2)}).`
      );
    }
  }
  const constitution = asca.constitution;
  const contributionModel = getContributionModel(constitution);
  if (contributionModel === "EQUAL") {
    const memberTargetCents = Math.round(
      Number(String(member.targetContribution ?? "0")) * 100
    );
    const memberContributedCents = Math.round(
      Number(String(member.contributedAmount ?? "0")) * 100
    );
    if (Number.isFinite(memberTargetCents) && memberTargetCents > 0) {
      const remainingMemberCents = memberTargetCents - memberContributedCents;
      if (remainingMemberCents <= 0) {
        throw new Error(
          "You have already completed your required contribution for this ASCA."
        );
      }
      if (amountCents > remainingMemberCents) {
        throw new Error(
          `Contribution exceeds your remaining required amount (${(remainingMemberCents / 100).toFixed(2)}).`
        );
      }
    }
  }
  const userWallet = await ensureWalletWith4(tx, "USER", userId);
  const availableBalance = await getWalletAvailableBalanceWith(
    tx,
    userWallet.id
  );
  if (availableBalance < amount) {
    throw new Error("Insufficient funds in personal wallet");
  }
  const [transaction] = await tx.insert(walletTransactionsTable).values({
    fromWalletId: userWallet.id,
    toWalletId: asca.escrowWalletId,
    type: "ASCA_CONTRIBUTION",
    amount: amount.toString(),
    metadata: { description: `Contribution to ASCA: ${asca.name}` }
  }).returning();
  const [contribution] = await tx.insert(ascaContributionsTable).values({
    ascaId: asca.id,
    memberId: member.id,
    amount: amount.toString(),
    status: "PAID",
    paidAt: /* @__PURE__ */ new Date(),
    transactionId: transaction.id
  }).returning();
  await tx.update(ascaMembersTable).set({
    contributedAmount: sql`${ascaMembersTable.contributedAmount} + ${amount}`
  }).where(eq(ascaMembersTable.id, member.id));
  const [updatedAsca] = await tx.update(ascasTable).set({
    currentAmount: sql`${ascasTable.currentAmount} + ${amount}`
  }).where(eq(ascasTable.id, asca.id)).returning();
  if (updatedAsca.status === "FUNDING" && updatedAsca.targetAmount) {
    const current = parseFloat(updatedAsca.currentAmount || "0");
    const target = parseFloat(updatedAsca.targetAmount);
    if (current >= target) {
      if (updatedAsca.type === "INVESTMENT" && updatedAsca.investmentId) {
        await tx.update(ascasTable).set({
          status: "READY",
          organizationId: updatedAsca.organizationId ?? null,
          updatedAt: /* @__PURE__ */ new Date()
        }).where(eq(ascasTable.id, updatedAsca.id));
        try {
          await convertAscaToInvestment(
            updatedAsca.id,
            updatedAsca.investmentId,
            userId
          );
        } catch (e) {
          console.error("Auto-conversion failed for Investment ASCA", e);
        }
      } else {
        await tx.update(ascasTable).set({
          status: "PENDING_INVESTMENT",
          organizationId: updatedAsca.organizationId ?? null,
          updatedAt: /* @__PURE__ */ new Date()
        }).where(eq(ascasTable.id, updatedAsca.id));
      }
    }
  }
  return contribution;
}
async function contributeToAsca(ascaId, userId, amount) {
  return await db.transaction(async (tx) => {
    const [asca] = await tx.select().from(ascasTable).where(eq(ascasTable.id, ascaId));
    if (!asca) throw new Error("ASCA not found");
    const [member] = await tx.select().from(ascaMembersTable).where(
      and(
        eq(ascaMembersTable.ascaId, ascaId),
        eq(ascaMembersTable.userId, userId)
      )
    );
    if (!member) throw new Error("User is not a member of this ASCA");
    return await contributeToAscaInternal(tx, asca, member, userId, amount);
  });
}
async function cancelAsca(ascaId, adminUserId) {
  return await db.transaction(async (tx) => {
    const [asca] = await tx.select().from(ascasTable).where(eq(ascasTable.id, ascaId));
    if (!asca) throw new Error("ASCA not found");
    if (asca.status === "CANCELLED" || asca.status === "CLOSED") {
      throw new Error("ASCA is already terminated");
    }
    const members = await tx.select().from(ascaMembersTable).where(eq(ascaMembersTable.ascaId, ascaId));
    if (asca.escrowWalletId) {
      for (const member of members) {
        const contributed = parseFloat(member.contributedAmount || "0");
        if (contributed > 0) {
          const userWallet = await ensureWalletWith4(tx, "USER", member.userId);
          await tx.insert(walletTransactionsTable).values({
            fromWalletId: asca.escrowWalletId,
            toWalletId: userWallet.id,
            type: "ASCA_REFUND",
            amount: contributed.toString(),
            metadata: { description: `ASCA Refund: ${asca.name}` }
          });
          await tx.update(ascaContributionsTable).set({ status: "REFUNDED" }).where(
            and(
              eq(ascaContributionsTable.memberId, member.id),
              eq(ascaContributionsTable.status, "PAID")
            )
          );
        }
      }
    }
    await tx.update(ascasTable).set({ status: "CANCELLED", currentAmount: "0" }).where(eq(ascasTable.id, ascaId));
    return true;
  });
}
async function withdrawAsca(ascaId, triggerUserId) {
  return await db.transaction(async (tx) => {
    const [asca] = await tx.select().from(ascasTable).where(eq(ascasTable.id, ascaId));
    if (!asca) throw new Error("ASCA not found");
    if (asca.status === "CANCELLED" || asca.status === "CLOSED") {
      throw new Error("ASCA is already terminated");
    }
    if (asca.status !== "READY" && asca.status !== "PENDING_INVESTMENT" && asca.status !== "INVESTED" && asca.status !== "MATURED") {
      throw new Error(
        "This ASCA is not eligible for withdrawal at this stage."
      );
    }
    const members = await tx.select().from(ascaMembersTable).where(eq(ascaMembersTable.ascaId, ascaId));
    const principalCentsTotal = members.reduce((sum3, member) => {
      return sum3 + clampCents(Number(String(member.contributedAmount ?? "0")) * 100);
    }, 0);
    if (principalCentsTotal <= 0) {
      throw new Error("No contributed funds are available for withdrawal.");
    }
    let sourceWalletId = null;
    let distributeMaturedSettlementProRata = false;
    if (asca.status === "READY" || asca.status === "PENDING_INVESTMENT") {
      sourceWalletId = asca.escrowWalletId ?? null;
    } else {
      if (!asca.investmentId) {
        throw new Error("Investment ASCA is missing investmentId.");
      }
      const [opportunity] = await tx.select({ deadline: investmentOpportunitiesTable.deadline }).from(investmentOpportunitiesTable).where(eq(investmentOpportunitiesTable.id, asca.investmentId));
      if (!opportunity) {
        throw new Error("Investment opportunity not found for this ASCA.");
      }
      distributeMaturedSettlementProRata = new Date(opportunity.deadline).getTime() <= Date.now();
      const investmentWallet = await ensureWalletWith4(
        tx,
        "INVESTMENT",
        asca.investmentId
      );
      sourceWalletId = investmentWallet.id;
    }
    if (!sourceWalletId) throw new Error("Source wallet not initialized.");
    const availableBalance = await getWalletAvailableBalanceWith(
      tx,
      sourceWalletId
    );
    const availableCents = clampCents(availableBalance * 100);
    if (!distributeMaturedSettlementProRata && availableCents < principalCentsTotal) {
      throw new Error("Insufficient funds available for withdrawal.");
    }
    if (distributeMaturedSettlementProRata && availableCents <= 0) {
      throw new Error("No matured proceeds are available for settlement yet.");
    }
    const settlementMembers = members.map((member) => ({
      member,
      contributedCents: clampCents(
        Number(String(member.contributedAmount ?? "0")) * 100
      )
    })).filter((entry) => entry.contributedCents > 0);
    const payoutPlan = distributeMaturedSettlementProRata ? allocateProRataSettlementShares(
      settlementMembers,
      availableCents,
      principalCentsTotal
    ) : settlementMembers.map((entry) => ({
      ...entry,
      payoutCents: entry.contributedCents
    }));
    for (const entry of payoutPlan) {
      if (entry.payoutCents <= 0) continue;
      const userWallet = await ensureWalletWith4(
        tx,
        "USER",
        entry.member.userId
      );
      const gainLossCents = entry.payoutCents - entry.contributedCents;
      await tx.insert(walletTransactionsTable).values({
        fromWalletId: sourceWalletId,
        toWalletId: userWallet.id,
        type: "ASCA_REFUND",
        amount: (entry.payoutCents / 100).toFixed(2),
        metadata: {
          description: distributeMaturedSettlementProRata ? `ASCA Maturity Settlement: ${asca.name}` : `ASCA Withdrawal: ${asca.name}`,
          settlementMode: distributeMaturedSettlementProRata ? "PRO_RATA_MATURED" : "PRINCIPAL_ONLY",
          contributedAmount: (entry.contributedCents / 100).toFixed(2),
          settlementAmount: (entry.payoutCents / 100).toFixed(2),
          gainLossAmount: (gainLossCents / 100).toFixed(2),
          ascaId,
          triggerUserId
        }
      });
      await tx.update(ascaContributionsTable).set({ status: "REFUNDED" }).where(
        and(
          eq(ascaContributionsTable.memberId, entry.member.id),
          eq(ascaContributionsTable.status, "PAID")
        )
      );
    }
    await tx.update(ascasTable).set({ status: "CLOSED", currentAmount: "0", updatedAt: /* @__PURE__ */ new Date() }).where(eq(ascasTable.id, ascaId));
    return true;
  });
}
async function withdrawAscaOffline(ascaId, triggerUserId) {
  return await db.transaction(async (tx) => {
    const [asca] = await tx.select().from(ascasTable).where(eq(ascasTable.id, ascaId));
    if (!asca) throw new Error("ASCA not found");
    if (asca.status === "CANCELLED" || asca.status === "CLOSED") {
      throw new Error("ASCA is already terminated");
    }
    if (asca.type !== "GENERAL" || asca.investmentId) {
      throw new Error("Offline withdrawal is only allowed for General ASCAs.");
    }
    if (!asca.fundingEndAt) {
      throw new Error("Funding end date is not configured for this ASCA.");
    }
    const now = /* @__PURE__ */ new Date();
    if (now <= new Date(asca.fundingEndAt)) {
      throw new Error("Offline withdrawal is only allowed after funding ends.");
    }
    if (asca.status !== "PENDING_INVESTMENT" && asca.status !== "READY") {
      throw new Error(
        "ASCA is not eligible for offline withdrawal at this stage."
      );
    }
    if (!asca.escrowWalletId)
      throw new Error("ASCA escrow wallet not initialized.");
    const amount = Number(String(asca.currentAmount ?? "0"));
    const amountCents = clampCents(amount * 100);
    if (!Number.isFinite(amountCents) || amountCents <= 0) {
      throw new Error("No funds are available for offline withdrawal.");
    }
    const availableBalance = await getWalletAvailableBalanceWith(
      tx,
      asca.escrowWalletId
    );
    const availableCents = clampCents(availableBalance * 100);
    if (availableCents < amountCents) {
      throw new Error(
        "Insufficient funds available in the ASCA escrow wallet."
      );
    }
    const adminWallet = await ensureWalletWith4(tx, "USER", triggerUserId);
    await tx.insert(walletTransactionsTable).values({
      fromWalletId: asca.escrowWalletId,
      toWalletId: adminWallet.id,
      type: "ASCA_OFFLINE_WITHDRAWAL",
      amount: (amountCents / 100).toFixed(2),
      metadata: {
        description: `ASCA Offline Withdrawal: ${asca.name}`,
        ascaId
      }
    });
    await tx.update(ascasTable).set({ status: "CLOSED", currentAmount: "0", updatedAt: /* @__PURE__ */ new Date() }).where(eq(ascasTable.id, ascaId));
    return true;
  });
}
async function convertAscaToInvestment(ascaId, investmentId, triggerUserId) {
  return await db.transaction(async (tx) => {
    const [asca] = await tx.select().from(ascasTable).where(eq(ascasTable.id, ascaId));
    if (!asca) throw new Error("ASCA not found");
    if (asca.type === "INVESTMENT" && !asca.investmentId) {
      throw new Error("Investment ASCA must have an investmentId configured.");
    }
    if (asca.type === "GENERAL" && asca.investmentId && asca.investmentId !== investmentId) {
    }
    if (asca.status !== "READY" && asca.status !== "PENDING_INVESTMENT") {
      throw new Error(
        `ASCA must be READY or PENDING_INVESTMENT. Current status: ${asca.status}`
      );
    }
    if (!asca.escrowWalletId) throw new Error("ASCA has no escrow wallet.");
    const currentAmount = parseFloat(asca.currentAmount || "0");
    if (currentAmount <= 0) throw new Error("ASCA has no funds to invest.");
    const [opportunity] = await tx.select().from(investmentOpportunitiesTable).where(eq(investmentOpportunitiesTable.id, investmentId));
    if (!opportunity) throw new Error("Investment opportunity not found.");
    if (opportunity.status !== "OPEN")
      throw new Error("Investment opportunity is not OPEN.");
    const opportunityWallet = await ensureWalletWith4(
      tx,
      "INVESTMENT",
      opportunity.id
    );
    await tx.insert(walletTransactionsTable).values({
      fromWalletId: asca.escrowWalletId,
      toWalletId: opportunityWallet.id,
      type: "ASCA_INVESTMENT",
      amount: currentAmount.toString(),
      metadata: {
        description: `ASCA ${asca.name} investment in ${opportunity.title}`
      }
    });
    await tx.update(ascasTable).set({
      status: "INVESTED",
      investmentId: opportunity.id,
      organizationId: asca.organizationId ?? null,
      updatedAt: /* @__PURE__ */ new Date()
    }).where(eq(ascasTable.id, ascaId));
    await recalculateInvestmentRaisedAmount(tx, opportunity.id);
    return true;
  });
}
async function closeAsca(ascaId) {
  return await db.transaction(async (tx) => {
    const [asca] = await tx.select().from(ascasTable).where(eq(ascasTable.id, ascaId));
    if (!asca) throw new Error("ASCA not found");
    if (asca.status === "CANCELLED" || asca.status === "CLOSED") {
      throw new Error("ASCA is already terminated");
    }
    if (asca.status !== "INVESTED" && asca.status !== "MATURED") {
      throw new Error("Only invested or matured ASCAs can be archived.");
    }
    const [updated] = await tx.update(ascasTable).set({ status: "CLOSED", updatedAt: /* @__PURE__ */ new Date() }).where(eq(ascasTable.id, ascaId)).returning();
    return updated;
  });
}
var AscaBorrowingPolicySchema, AscaLendingPoolSchema, CreateAscaSchema, AscaCatchUpRequiredError, ASCA_CATCH_UP_GRACE_DAYS;
var init_asca = __esm({
  "src/lib/asca.ts"() {
    "use strict";
    init_src2();
    init_schema2();
    init_drizzle_orm();
    init_investment_funding();
    init_zod();
    init_susu();
    AscaBorrowingPolicySchema = external_exports.object({
      enabled: external_exports.boolean().optional(),
      approvalMode: external_exports.enum(["OWNER_ADMIN"]).optional(),
      maxBorrowPctOfPool: external_exports.number().min(1).max(100).optional(),
      maxBorrowPctOfOwnContribution: external_exports.number().min(1).max(100).optional(),
      liquidityReservePct: external_exports.number().min(0).max(95).optional(),
      termMonths: external_exports.number().int().min(1).max(36).optional(),
      repaymentFrequency: external_exports.enum(["WEEKLY", "BIWEEKLY", "MONTHLY"]).optional(),
      borrowerAppreciationPct: external_exports.number().min(0).max(100).optional(),
      processingFeePct: external_exports.number().min(0).max(25).optional(),
      minContributionAgeDays: external_exports.number().int().min(0).max(365).optional()
    }).partial();
    AscaLendingPoolSchema = external_exports.object({
      enabled: external_exports.boolean().optional(),
      eligibilityMode: external_exports.enum(["CONTRIBUTORS_ONLY", "ALL_ORG_MEMBERS"]).optional(),
      maxPctOfPoolAfterReserve: external_exports.number().min(0).max(100).optional(),
      defaultTermMonths: external_exports.number().int().min(1).max(36).optional(),
      defaultRepaymentFrequency: external_exports.enum(["WEEKLY", "BIWEEKLY", "MONTHLY"]).optional(),
      defaultBorrowerAppreciationPct: external_exports.number().min(0).max(100).optional(),
      defaultProcessingFeePct: external_exports.number().min(0).max(25).optional()
    }).partial();
    CreateAscaSchema = external_exports.object({
      name: external_exports.string().min(3),
      description: external_exports.string().optional(),
      termsHtml: external_exports.string().optional(),
      type: external_exports.enum(["GENERAL", "INVESTMENT"]),
      investmentId: external_exports.number().optional(),
      targetAmount: external_exports.string().trim().min(1),
      fundingEndAt: external_exports.string().trim().min(1),
      joinCreator: external_exports.boolean().optional().default(false),
      constitution: external_exports.object({
        allowLateJoin: external_exports.boolean().optional(),
        maxMembers: external_exports.number().int().min(2),
        installmentPolicy: external_exports.enum(["INSTALLMENTS", "FULL"]).optional(),
        contributionFrequency: external_exports.enum(["WEEKLY", "MONTHLY"]).optional(),
        equalContribution: external_exports.boolean().optional().default(true),
        contributionModel: external_exports.enum(["EQUAL", "VARIABLE"]).optional(),
        borrowingPolicy: AscaBorrowingPolicySchema.optional(),
        lendingPool: AscaLendingPoolSchema.optional()
      }).passthrough()
    });
    AscaCatchUpRequiredError = class extends Error {
      requiredCatchUpAmount;
      constructor(requiredCatchUpAmount) {
        super(
          `Late join requires a catch-up contribution of ${requiredCatchUpAmount}.`
        );
        this.requiredCatchUpAmount = requiredCatchUpAmount;
      }
    };
    ASCA_CATCH_UP_GRACE_DAYS = 7;
  }
});

// src/lib/member-access.ts
function normalizeInvestorSegment(segment, investorCategory) {
  const raw = segment && segment.trim() || investorCategory && investorCategory.trim() || "";
  if (raw === "WORKER_OWNER") return "WORKER_OWNER";
  if (raw === "COMMUNITY_SPONSOR") return "COMMUNITY_SPONSOR";
  if (raw === "IMPACT_INVESTOR") return "IMPACT_INVESTOR";
  return "NONE";
}
function getInvestorPackageLens(input) {
  const isInvestor = input.membershipType === "INVESTOR";
  const isActive = input.membershipStatus === "ACTIVE";
  const isAdmin = input.userRole === "ADMIN" || input.userRole === "SUPER_ADMIN";
  const segment = isInvestor ? normalizeInvestorSegment(input.segment, input.investorCategory) : "NONE";
  const segmentGated = {
    canRosca: isAdmin || isInvestor && segment === "WORKER_OWNER",
    canAsca: isAdmin || isInvestor && segment === "WORKER_OWNER",
    canDonate: true,
    canDonatePrimary: isInvestor && segment === "COMMUNITY_SPONSOR",
    canInvest: isAdmin || isInvestor && (segment === "WORKER_OWNER" || segment === "IMPACT_INVESTOR"),
    canInvestOneTime: isAdmin || isInvestor && (segment === "WORKER_OWNER" || segment === "IMPACT_INVESTOR"),
    canInvestCrowd: isAdmin || isInvestor && segment === "WORKER_OWNER",
    canLendingBorrow: isAdmin || isInvestor && segment === "WORKER_OWNER",
    canLendingDirectLend: false,
    canSeeBoardMetrics: isAdmin || isInvestor && segment === "WORKER_OWNER",
    canDoTreasuryTransfer: isAdmin || isInvestor && segment === "WORKER_OWNER",
    canEditImpactStories: isAdmin || isInvestor && segment === "WORKER_OWNER",
    canSeeAllDashboardAreas: isAdmin || isInvestor && segment === "WORKER_OWNER"
  };
  return {
    segment: isAdmin ? "WORKER_OWNER" : segment,
    ...segmentGated,
    canRosca: isActive ? segmentGated.canRosca : false,
    canAsca: isActive ? segmentGated.canAsca : false,
    canDonate: segmentGated.canDonate,
    canDonatePrimary: isActive ? segmentGated.canDonatePrimary : false,
    canInvest: isActive ? segmentGated.canInvest : false,
    canInvestOneTime: isActive ? segmentGated.canInvestOneTime : false,
    canInvestCrowd: isActive ? segmentGated.canInvestCrowd : false,
    canLendingBorrow: isActive ? segmentGated.canLendingBorrow : false,
    canLendingDirectLend: false,
    canSeeBoardMetrics: isActive ? segmentGated.canSeeBoardMetrics : false,
    canDoTreasuryTransfer: isActive ? segmentGated.canDoTreasuryTransfer : false,
    canEditImpactStories: segmentGated.canEditImpactStories,
    canSeeAllDashboardAreas: isActive ? segmentGated.canSeeAllDashboardAreas : false
  };
}
function hasActiveMembership(membershipStatus) {
  return membershipStatus === "ACTIVE";
}
function getMemberProductAccess(input) {
  const config2 = FEATURE_CONFIG[input.feature];
  if (!config2.allowedMembershipTypes.includes(input.membershipType ?? "")) {
    return {
      allowed: false,
      reason: `Your membership type does not include ${config2.label} access.`
    };
  }
  if (!hasActiveMembership(input.membershipStatus)) {
    return {
      allowed: false,
      reason: `Activate your WWN membership plan to access ${config2.label}.`
    };
  }
  if (input.onboardingRequired === true && input.onboardingCompleted === false) {
    return {
      allowed: false,
      reason: `Complete onboarding to access ${config2.label}.`
    };
  }
  if (input.membershipType === "INDIVIDUAL") {
    const entitlementKey = INDIVIDUAL_FEATURE_ENTITLEMENTS[input.feature];
    if (entitlementKey) {
      const entitlements = normalizeIndividualPlanEntitlements(
        input.planEntitlements
      );
      if (entitlements[entitlementKey] !== true) {
        return {
          allowed: false,
          reason: `Your membership plan does not include ${config2.label}.`
        };
      }
    }
  }
  return { allowed: true, reason: null };
}
var FEATURE_CONFIG, INDIVIDUAL_FEATURE_ENTITLEMENTS;
var init_member_access = __esm({
  "src/lib/member-access.ts"() {
    "use strict";
    init_individual_plan_entitlements();
    FEATURE_CONFIG = {
      SUSU: {
        label: "ROSCA circles (Susu)",
        allowedMembershipTypes: ["INDIVIDUAL"]
      },
      ASCA: {
        label: "ASCA circles",
        allowedMembershipTypes: ["INDIVIDUAL", "INVESTOR"]
      },
      INVESTMENTS: {
        label: "investments",
        allowedMembershipTypes: ["INDIVIDUAL", "INVESTOR"]
      },
      INVESTMENTS_CROWD: {
        label: "crowd (ROSCA-linked) investments",
        allowedMembershipTypes: ["INDIVIDUAL", "INVESTOR"]
      },
      INVESTMENTS_ONE_TIME: {
        label: "one-time fixed-return investments",
        allowedMembershipTypes: ["INDIVIDUAL", "INVESTOR"]
      },
      COMMUNITY: {
        label: "community",
        allowedMembershipTypes: ["INDIVIDUAL", "ORGANIZATION", "INVESTOR"]
      },
      LENDING_BORROWER: {
        label: "member lending",
        allowedMembershipTypes: ["INDIVIDUAL"]
      },
      LENDING_LENDER: {
        label: "P2P Lending",
        allowedMembershipTypes: ["INDIVIDUAL"]
      },
      LENDING_DIRECT_LEND: {
        label: "direct P2P lending fund",
        allowedMembershipTypes: []
      },
      BOARD_METRICS: {
        label: "board-level ecosystem metrics",
        allowedMembershipTypes: ["INVESTOR"]
      },
      TREASURY_TRANSFER: {
        label: "treasury transfers (Investment \u2192 Lending)",
        allowedMembershipTypes: ["INVESTOR"]
      },
      DONATIONS: {
        label: "donation programs",
        allowedMembershipTypes: ["INDIVIDUAL", "ORGANIZATION", "INVESTOR"]
      }
    };
    INDIVIDUAL_FEATURE_ENTITLEMENTS = {
      SUSU: "member_susu_access",
      INVESTMENTS: "susunomics_access",
      LENDING_BORROWER: "community_lending_access",
      LENDING_LENDER: "p2p_lending_access"
    };
  }
});

// src/routes/admin.ts
var admin_exports = {};
__export(admin_exports, {
  default: () => admin_default
});
async function requireAdmin(req, res, next) {
  const user = await resolveAuthenticatedUser(req.cookies?.wwn_token);
  if (!user) {
    return res.status(401).json({ message: "Invalid or expired token." });
  }
  if (user.userRole !== "ADMIN" && user.userRole !== "SUPER_ADMIN") {
    return res.status(403).json({ message: "Admin access required." });
  }
  req.admin = user;
  next();
}
async function requireAdminOrWorkerOwner(req, res, next) {
  const user = await resolveAuthenticatedUser(req.cookies?.wwn_token);
  if (!user) {
    return res.status(401).json({ message: "Invalid or expired token." });
  }
  const isAdmin = user.userRole === "ADMIN" || user.userRole === "SUPER_ADMIN";
  const segment = normalizeInvestorSegment(
    user.segment,
    user.investorCategory
  );
  const isWorkerOwner = (user.membershipType === "INVESTOR" || isAdmin) && (segment === "WORKER_OWNER" || isAdmin);
  const lens = getInvestorPackageLens({
    membershipType: user.membershipType ?? null,
    membershipStatus: user.membershipStatus ?? null,
    userRole: user.userRole ?? null,
    segment: user.segment ?? null,
    investorCategory: user.investorCategory ?? null
  });
  if (!isAdmin && !(isWorkerOwner && lens.canEditImpactStories)) {
    return res.status(403).json({ message: "Admin or Worker Owner access required." });
  }
  req.admin = user;
  req.workerOwner = isWorkerOwner;
  next();
}
async function formatAdminProfile(user) {
  return formatSessionUserProfile(user, {
    normalizeOrganizationTeamMemberOnboarding: true,
    useUserRowForOnboarding: true
  });
}
function handleError2(err, res) {
  if (err?.status && err?.message) {
    return res.status(err.status).json({ message: err.message });
  }
  logger.error({ err }, "Admin route error");
  return res.status(500).json({ message: "Internal server error." });
}
function getLendingDashboardHref(loanType, audience) {
  if (audience === "FUNDER") {
    return loanType === "COMMUNITY_LENDING" ? "/dashboard/member-lending" : "/dashboard/p2p-lending";
  }
  return "/dashboard/member-lending";
}
function getLendingAudienceLabel(loanType) {
  return loanType === "COMMUNITY_LENDING" ? "member" : "investor";
}
function getLendingProductLabel(loanType) {
  return loanType === "COMMUNITY_LENDING" ? "Community Lending" : "P2P Lending";
}
function deriveCommunityTemplateReturnTerms(input) {
  const floorAppreciationAmount = calculateMinAppreciationAmount({
    principalAmount: input.minRequestAmount,
    termMonths: input.borrowerTermMonths,
    minAppreciationType: input.minAppreciationType,
    minAppreciationValue: input.minAppreciationValue,
    minAppreciationTiers: input.minAppreciationTiers
  });
  const expectedReturnPct = calculateNetExpectedReturnPct({
    principalAmount: input.minRequestAmount,
    appreciationAmount: floorAppreciationAmount,
    termMonths: input.borrowerTermMonths,
    platformAppreciationSharePct: input.platformAppreciationSharePct
  });
  return {
    expectedReturnPct,
    termMonths: input.borrowerTermMonths,
    expectedReturn: formatExpectedReturnLabel(expectedReturnPct),
    term: formatTermMonthsLabel(input.borrowerTermMonths)
  };
}
function buildBorrowerLendingStatusNotification(input) {
  const productLabel = getLendingProductLabel(input.loanType);
  const fundingAudience = getLendingAudienceLabel(input.loanType);
  const approvedAmount = input.approvedAmount != null ? formatMoneyAmount(parseMoneyAmount(input.approvedAmount)) : null;
  const disbursedAmount = input.disbursedAmount != null ? formatMoneyAmount(parseMoneyAmount(input.disbursedAmount)) : null;
  switch (input.status) {
    case "WAITLISTED":
      return {
        severity: "INFO",
        title: `${productLabel} request waitlisted`,
        body: `Your ${productLabel} request is waitlisted for the next ${fundingAudience} funding slot.`
      };
    case "UNDER_REVIEW":
      return {
        severity: "INFO",
        title: `${productLabel} request under review`,
        body: `WWN is reviewing your ${productLabel} request now.`
      };
    case "APPROVED":
      return {
        severity: "SUCCESS",
        title: `${productLabel} request approved`,
        body: approvedAmount ? `Your ${productLabel} request for $${approvedAmount} is approved and now open for ${fundingAudience} funding.` : `Your ${productLabel} request is approved and now open for ${fundingAudience} funding.`
      };
    case "APPROVED_RESERVED":
      return {
        severity: "SUCCESS",
        title: `${productLabel} capital reserved`,
        body: approvedAmount ? `WWN reserved $${approvedAmount} for your ${productLabel} request and is preparing disbursement.` : `WWN reserved capital for your ${productLabel} request and is preparing disbursement.`
      };
    case "FUNDED":
      return {
        severity: "SUCCESS",
        title: `${productLabel} loan disbursed`,
        body: disbursedAmount ? `Your ${productLabel} loan has been disbursed and $${disbursedAmount} was released.` : `Your ${productLabel} loan has been disbursed.`
      };
    case "REPAYING":
      return {
        severity: "INFO",
        title: `${productLabel} repayment started`,
        body: disbursedAmount ? `Your ${productLabel} loan has been disbursed and is now in repayment. $${disbursedAmount} was released.` : `Your ${productLabel} loan has been disbursed and is now in repayment.`
      };
    case "CLOSED":
      return {
        severity: "SUCCESS",
        title: `${productLabel} loan closed`,
        body: `Your ${productLabel} loan has been closed.`
      };
    case "REJECTED":
      return {
        severity: "WARNING",
        title: `${productLabel} request declined`,
        body: `Your ${productLabel} request was not approved.`
      };
    case "CANCELLED":
      return {
        severity: "INFO",
        title: `${productLabel} request cancelled`,
        body: `Your ${productLabel} request has been cancelled.`
      };
    default:
      return null;
  }
}
function queueLendingPushNotification(input) {
  void (async () => {
    const reserved = await reserveNotificationDeliveryWith(db, {
      userId: input.userId,
      channel: "PUSH",
      category: "LENDING",
      idempotencyKey: input.idempotencyKey,
      status: "SKIPPED",
      provider: null,
      metadata: input.metadata
    });
    if (!reserved.reserved) return;
    try {
      const pushResult = await deliverPushIfEnabled({
        userId: input.userId,
        category: "LENDING",
        title: input.title,
        body: input.body,
        data: { actionHref: input.actionHref }
      });
      await finalizeNotificationDeliveryWith(db, {
        idempotencyKey: input.idempotencyKey,
        status: pushResult.status,
        provider: pushResult.status === "SENT" ? "EXPO" : null,
        errorMessage: pushResult.reason ?? null,
        notificationId: input.notificationId,
        metadata: {
          ...input.metadata,
          reason: pushResult.reason ?? null
        }
      });
    } catch (err) {
      await finalizeNotificationDeliveryWith(db, {
        idempotencyKey: input.idempotencyKey,
        status: "FAILED",
        provider: "EXPO",
        errorMessage: err instanceof Error ? err.message : String(err),
        notificationId: input.notificationId,
        metadata: input.metadata
      });
    }
  })();
}
async function ensureWallet(ownerType, ownerId) {
  const existing = await db.select().from(walletsTable).where(
    and(
      eq(walletsTable.ownerType, ownerType),
      eq(walletsTable.ownerId, ownerId)
    )
  );
  if (existing.length) return existing[0];
  const [created] = await db.insert(walletsTable).values({ ownerType, ownerId }).returning();
  return created;
}
function isUniqueViolation5(err) {
  if (typeof err !== "object" || err === null) return false;
  const record2 = err;
  const directCode = typeof record2.code === "string" ? record2.code : null;
  const cause = record2.cause;
  const causeCode = typeof cause === "object" && cause !== null && "code" in cause && typeof cause.code === "string" ? cause.code : null;
  return directCode === "23505" || causeCode === "23505";
}
async function ensureWalletWith5(conn, ownerType, ownerId) {
  const existing = await conn.select().from(walletsTable).where(
    and(
      eq(walletsTable.ownerType, ownerType),
      eq(walletsTable.ownerId, ownerId)
    )
  );
  if (existing.length) return existing[0];
  const [created] = await conn.insert(walletsTable).values({ ownerType, ownerId }).returning();
  return created;
}
async function getWalletBalanceWith3(conn, walletId) {
  const [row] = await conn.select({
    total: sql`
        coalesce(sum(case when ${walletTransactionsTable.toWalletId} = ${walletId} then ${walletTransactionsTable.amount} else 0 end), 0)
        - coalesce(sum(case when ${walletTransactionsTable.fromWalletId} = ${walletId} then ${walletTransactionsTable.amount} else 0 end), 0)
      `
  }).from(walletTransactionsTable).where(
    or(
      eq(walletTransactionsTable.toWalletId, walletId),
      eq(walletTransactionsTable.fromWalletId, walletId)
    )
  );
  return Number(row?.total ?? 0);
}
async function reconcileInvestmentOpportunityRaisedAmountWith(conn, opportunityId) {
  await recalculateInvestmentRaisedAmount(conn, opportunityId);
}
async function getWalletBalance(walletId) {
  const [row] = await db.select({
    total: sql`
        coalesce(sum(case when ${walletTransactionsTable.toWalletId} = ${walletId} then ${walletTransactionsTable.amount} else 0 end), 0)
        - coalesce(sum(case when ${walletTransactionsTable.fromWalletId} = ${walletId} then ${walletTransactionsTable.amount} else 0 end), 0)
      `
  }).from(walletTransactionsTable).where(
    or(
      eq(walletTransactionsTable.toWalletId, walletId),
      eq(walletTransactionsTable.fromWalletId, walletId)
    )
  );
  return Number(row?.total ?? 0);
}
function getMetadataNumberValue(metadata, key) {
  if (!metadata || typeof metadata !== "object") return null;
  const value = metadata[key];
  if (typeof value === "number" && Number.isFinite(value)) return value;
  if (typeof value === "string" && value.trim() !== "" && !Number.isNaN(Number(value))) {
    return Number(value);
  }
  return null;
}
function formatWalletMetadataLabel(value) {
  if (!value) return null;
  return value.toLowerCase().replaceAll("_", " ").replace(/\b\w/g, (char2) => char2.toUpperCase());
}
async function getWalletTransactions(walletId) {
  const txs = await db.select().from(walletTransactionsTable).where(
    or(
      eq(walletTransactionsTable.fromWalletId, walletId),
      eq(walletTransactionsTable.toWalletId, walletId)
    )
  ).orderBy(desc(walletTransactionsTable.createdAt)).limit(50);
  const opportunityIds = Array.from(
    new Set(
      txs.flatMap((transaction) => {
        const metadata = transaction.metadata ?? {};
        return [
          getMetadataNumberValue(metadata, "opportunityId"),
          getMetadataNumberValue(metadata, "poolId")
        ].filter((value) => value != null);
      })
    )
  );
  const applicationIds = Array.from(
    new Set(
      txs.flatMap((transaction) => {
        const metadata = transaction.metadata ?? {};
        return [
          getMetadataNumberValue(metadata, "applicationId"),
          getMetadataNumberValue(metadata, "loanApplicationId")
        ].filter((value) => value != null);
      })
    )
  );
  const repaymentIds = Array.from(
    new Set(
      txs.flatMap((transaction) => {
        const metadata = transaction.metadata ?? {};
        return [getMetadataNumberValue(metadata, "repaymentId")].filter(
          (value) => value != null
        );
      })
    )
  );
  const commitmentIds = Array.from(
    new Set(
      txs.flatMap((transaction) => {
        const metadata = transaction.metadata ?? {};
        return [getMetadataNumberValue(metadata, "commitmentId")].filter(
          (value) => value != null
        );
      })
    )
  );
  const circleIds = Array.from(
    new Set(
      txs.flatMap((transaction) => {
        const metadata = transaction.metadata ?? {};
        return [getMetadataNumberValue(metadata, "circleId")].filter(
          (value) => value != null
        );
      })
    )
  );
  const [opportunities, applications, repayments, commitments, circles] = await Promise.all([
    opportunityIds.length > 0 ? db.select({
      id: lendingOpportunitiesTable.id,
      title: lendingOpportunitiesTable.title
    }).from(lendingOpportunitiesTable).where(inArray(lendingOpportunitiesTable.id, opportunityIds)) : Promise.resolve([]),
    applicationIds.length > 0 ? db.select({
      id: loanApplicationsTable.id,
      purpose: loanApplicationsTable.purpose,
      loanType: loanApplicationsTable.loanType,
      opportunityId: loanApplicationsTable.opportunityId,
      borrowerId: loanApplicationsTable.borrowerId
    }).from(loanApplicationsTable).where(inArray(loanApplicationsTable.id, applicationIds)) : Promise.resolve([]),
    repaymentIds.length > 0 ? db.select({
      id: loanRepaymentsTable.id,
      loanApplicationId: loanRepaymentsTable.loanApplicationId,
      dueDate: loanRepaymentsTable.dueDate,
      status: loanRepaymentsTable.status,
      amount: loanRepaymentsTable.amount,
      paidAmount: loanRepaymentsTable.paidAmount,
      principalPaidAmount: loanRepaymentsTable.principalPaidAmount,
      returnPaidAmount: loanRepaymentsTable.returnPaidAmount,
      feePaidAmount: loanRepaymentsTable.feePaidAmount
    }).from(loanRepaymentsTable).where(inArray(loanRepaymentsTable.id, repaymentIds)) : Promise.resolve([]),
    commitmentIds.length > 0 ? db.select({
      id: lendingCommitmentsTable.id,
      opportunityId: lendingCommitmentsTable.opportunityId,
      userId: lendingCommitmentsTable.userId,
      amount: lendingCommitmentsTable.amount,
      status: lendingCommitmentsTable.status
    }).from(lendingCommitmentsTable).where(inArray(lendingCommitmentsTable.id, commitmentIds)) : Promise.resolve([]),
    circleIds.length > 0 ? db.select({
      id: savingsCirclesTable.id,
      name: savingsCirclesTable.name
    }).from(savingsCirclesTable).where(inArray(savingsCirclesTable.id, circleIds)) : Promise.resolve([])
  ]);
  const userIds = Array.from(
    new Set(
      [
        ...txs.flatMap((transaction) => {
          const metadata = transaction.metadata ?? {};
          return [
            getMetadataNumberValue(metadata, "userId"),
            getMetadataNumberValue(metadata, "investorId"),
            getMetadataNumberValue(metadata, "borrowerId"),
            getMetadataNumberValue(metadata, "memberId"),
            getMetadataNumberValue(metadata, "payoutUserId")
          ].filter((value) => value != null);
        }),
        ...applications.map((application) => application.borrowerId),
        ...commitments.map((commitment) => commitment.userId)
      ].filter((value) => value != null)
    )
  );
  const opportunitiesById = /* @__PURE__ */ new Map();
  for (const opportunity of opportunities) {
    opportunitiesById.set(opportunity.id, opportunity.title);
  }
  const applicationsById = /* @__PURE__ */ new Map();
  for (const application of applications) {
    applicationsById.set(application.id, {
      purpose: application.purpose,
      loanType: application.loanType,
      opportunityId: application.opportunityId ?? null,
      borrowerId: application.borrowerId
    });
  }
  const repaymentsById = /* @__PURE__ */ new Map();
  for (const repayment of repayments) {
    repaymentsById.set(repayment.id, {
      loanApplicationId: repayment.loanApplicationId,
      dueDate: repayment.dueDate,
      status: repayment.status,
      amount: String(repayment.amount),
      paidAmount: repayment.paidAmount == null ? null : String(repayment.paidAmount),
      principalPaidAmount: String(repayment.principalPaidAmount),
      returnPaidAmount: String(repayment.returnPaidAmount),
      feePaidAmount: String(repayment.feePaidAmount)
    });
  }
  const commitmentsById = /* @__PURE__ */ new Map();
  for (const commitment of commitments) {
    commitmentsById.set(commitment.id, {
      opportunityId: commitment.opportunityId,
      userId: commitment.userId,
      amount: String(commitment.amount),
      status: commitment.status
    });
  }
  const circlesById = /* @__PURE__ */ new Map();
  for (const circle of circles) {
    circlesById.set(circle.id, circle.name);
  }
  const usersById = /* @__PURE__ */ new Map();
  if (userIds.length > 0) {
    const users = await db.select({
      id: usersTable.id,
      firstName: usersTable.firstName,
      lastName: usersTable.lastName,
      email: usersTable.email
    }).from(usersTable).where(inArray(usersTable.id, userIds));
    for (const user of users) {
      const fullName = [user.firstName, user.lastName].filter((value) => Boolean(value && value.trim())).join(" ").trim();
      usersById.set(user.id, fullName || user.email || "");
    }
  }
  return txs.map((t) => {
    const metadata = { ...t.metadata ?? {} };
    const userId = getMetadataNumberValue(metadata, "userId");
    const investorId = getMetadataNumberValue(metadata, "investorId");
    const borrowerId = getMetadataNumberValue(metadata, "borrowerId");
    const memberId = getMetadataNumberValue(metadata, "memberId");
    const payoutUserId = getMetadataNumberValue(metadata, "payoutUserId");
    const opportunityId = getMetadataNumberValue(metadata, "opportunityId") ?? getMetadataNumberValue(metadata, "poolId");
    const applicationId = getMetadataNumberValue(metadata, "applicationId") ?? getMetadataNumberValue(metadata, "loanApplicationId");
    const repaymentId = getMetadataNumberValue(metadata, "repaymentId");
    const commitmentId = getMetadataNumberValue(metadata, "commitmentId");
    const circleId = getMetadataNumberValue(metadata, "circleId");
    if (userId != null) {
      metadata.userName = usersById.get(userId) ?? "";
    }
    if (investorId != null) {
      metadata.investorName = usersById.get(investorId) ?? "";
    }
    if (borrowerId != null) {
      metadata.borrowerName = usersById.get(borrowerId) ?? "";
    }
    if (memberId != null) {
      metadata.memberName = usersById.get(memberId) ?? "";
    }
    if (payoutUserId != null) {
      metadata.payoutUserName = usersById.get(payoutUserId) ?? "";
    }
    if (opportunityId != null) {
      metadata.opportunityName = opportunitiesById.get(opportunityId) ?? "";
    }
    if (circleId != null) {
      metadata.circleName = circlesById.get(circleId) ?? "";
    }
    if (applicationId != null) {
      const application = applicationsById.get(applicationId);
      if (application) {
        const loanTypeLabel = formatWalletMetadataLabel(application.loanType);
        metadata.applicationName = application.purpose?.trim() || `${loanTypeLabel ?? "Loan"} application`;
        metadata.applicationTypeLabel = loanTypeLabel ?? "";
        if (typeof metadata.opportunityName !== "string" || metadata.opportunityName.trim() === "") {
          metadata.opportunityName = application.opportunityId != null ? opportunitiesById.get(application.opportunityId) ?? "" : "";
        }
        if (typeof metadata.borrowerName !== "string" || metadata.borrowerName.trim() === "") {
          metadata.borrowerName = usersById.get(application.borrowerId) ?? "";
        }
      }
    }
    if (repaymentId != null) {
      const repayment = repaymentsById.get(repaymentId);
      if (repayment) {
        metadata.repaymentDueDate = repayment.dueDate.toISOString();
        metadata.repaymentName = `Repayment due ${repayment.dueDate.toISOString().slice(0, 10)}`;
        metadata.repaymentStatus = repayment.status;
        metadata.repaymentAmount = formatMoneyAmount(
          parseMoneyAmount(repayment.amount)
        );
        metadata.repaymentPaidAmount = repayment.paidAmount == null ? "" : formatMoneyAmount(parseMoneyAmount(repayment.paidAmount));
        metadata.repaymentPrincipalAmount = formatMoneyAmount(
          parseMoneyAmount(repayment.principalPaidAmount)
        );
        metadata.repaymentReturnAmount = formatMoneyAmount(
          parseMoneyAmount(repayment.returnPaidAmount)
        );
        metadata.repaymentFeeAmount = formatMoneyAmount(
          parseMoneyAmount(repayment.feePaidAmount)
        );
        if (typeof metadata.applicationName !== "string" || metadata.applicationName.trim() === "") {
          const repaymentApplication = applicationsById.get(
            repayment.loanApplicationId
          );
          if (repaymentApplication) {
            metadata.applicationName = repaymentApplication.purpose?.trim() || "Loan application";
            metadata.applicationTypeLabel = formatWalletMetadataLabel(repaymentApplication.loanType) ?? "";
            if (typeof metadata.opportunityName !== "string" || metadata.opportunityName.trim() === "") {
              metadata.opportunityName = repaymentApplication.opportunityId != null ? opportunitiesById.get(
                repaymentApplication.opportunityId
              ) ?? "" : "";
            }
            if (typeof metadata.borrowerName !== "string" || metadata.borrowerName.trim() === "") {
              metadata.borrowerName = usersById.get(repaymentApplication.borrowerId) ?? "";
            }
          }
        }
      }
    }
    if (commitmentId != null) {
      const commitment = commitmentsById.get(commitmentId);
      if (commitment) {
        const commitmentInvestorName = usersById.get(commitment.userId) ?? "";
        metadata.commitmentAmount = formatMoneyAmount(
          parseMoneyAmount(commitment.amount)
        );
        metadata.commitmentStatus = commitment.status;
        metadata.commitmentName = commitmentInvestorName ? `${commitmentInvestorName} commitment` : "Commitment";
        if (typeof metadata.investorName !== "string" || metadata.investorName.trim() === "") {
          metadata.investorName = commitmentInvestorName;
        }
        if (typeof metadata.opportunityName !== "string" || metadata.opportunityName.trim() === "") {
          metadata.opportunityName = opportunitiesById.get(commitment.opportunityId) ?? "";
        }
      }
    }
    const actorName = (typeof metadata.investorName === "string" && metadata.investorName.trim() !== "" ? metadata.investorName : null) ?? (typeof metadata.memberName === "string" && metadata.memberName.trim() !== "" ? metadata.memberName : null) ?? (typeof metadata.borrowerName === "string" && metadata.borrowerName.trim() !== "" ? metadata.borrowerName : null) ?? (typeof metadata.payoutUserName === "string" && metadata.payoutUserName.trim() !== "" ? metadata.payoutUserName : null) ?? (typeof metadata.userName === "string" && metadata.userName.trim() !== "" ? metadata.userName : null);
    if (actorName) {
      metadata.actorName = actorName;
    }
    return {
      id: t.id,
      type: t.type,
      amount: Number(t.amount),
      direction: t.toWalletId === walletId ? "IN" : "OUT",
      createdAt: t.createdAt.toISOString(),
      metadata
    };
  });
}
async function ensureSusuWallet() {
  return ensureWallet("SUSU", SUSU_WALLET_OWNER_ID2);
}
async function ensureSusuWalletWith(conn) {
  return ensureWalletWith5(conn, "SUSU", SUSU_WALLET_OWNER_ID2);
}
async function ensureInvestmentWallet() {
  return ensureWallet("INVESTMENT", INVESTMENT_WALLET_OWNER_ID);
}
async function ensureInvestmentWalletWith(conn) {
  return ensureWalletWith5(conn, "INVESTMENT", INVESTMENT_WALLET_OWNER_ID);
}
async function ensureLendingMasterWallet() {
  return ensureWallet("LENDING_MASTER", LENDING_MASTER_WALLET_OWNER_ID);
}
async function ensureLendingMasterWalletWith(conn) {
  return ensureWalletWith5(
    conn,
    "LENDING_MASTER",
    LENDING_MASTER_WALLET_OWNER_ID
  );
}
async function getCircleAllocationTransactions(circleId) {
  return getCircleAllocationTransactionsWith(db, circleId);
}
async function getCircleAllocationSummary(circleId) {
  const summary = await getCircleAllocationSummaryWith(db, circleId);
  if (!summary) {
    return null;
  }
  return {
    susuWallet: summary.wallet,
    treasuryBalance: summary.treasuryBalance,
    totalIn: summary.totalIn,
    totalOut: summary.totalOut,
    allocationBalance: summary.allocationBalance,
    ownerType: summary.owner.ownerType,
    ownerId: summary.owner.ownerId,
    isDedicatedWallet: summary.owner.isDedicatedWallet
  };
}
async function buildSusuWalletCatalog() {
  const susuWallet = await ensureSusuWallet();
  const [balance, circleStats] = await Promise.all([
    getWalletBalance(susuWallet.id),
    db.select({ count: count() }).from(savingsCirclesTable)
  ]);
  return [
    {
      walletId: susuWallet.id,
      ownerType: "SUSU",
      ownerId: SUSU_WALLET_OWNER_ID2,
      label: "SUSU Wallet",
      subtitle: `${Number(circleStats[0]?.count ?? 0)} circles share this treasury`,
      currency: susuWallet.currency,
      balance
    }
  ];
}
async function buildInvestmentWalletCatalog() {
  const investmentWallet = await ensureInvestmentWallet();
  const [balance, opportunityStats, confirmedTotal] = await Promise.all([
    getWalletBalance(investmentWallet.id),
    db.select({ count: count() }).from(investmentOpportunitiesTable),
    db.select({ total: sum(investmentInterestsTable.amount) }).from(investmentInterestsTable).where(eq(investmentInterestsTable.status, "CONFIRMED"))
  ]);
  return [
    {
      walletId: investmentWallet.id,
      ownerType: "INVESTMENT",
      ownerId: INVESTMENT_WALLET_OWNER_ID,
      label: "Investment Wallet",
      subtitle: `${Number(opportunityStats[0]?.count ?? 0)} opportunities \xB7 $${Number(confirmedTotal[0]?.total ?? 0).toLocaleString("en-CA", { minimumFractionDigits: 2, maximumFractionDigits: 2 })} approved`,
      currency: investmentWallet.currency,
      balance
    }
  ];
}
async function buildLendingMasterWalletCatalog() {
  const lendingWallet = await ensureLendingMasterWallet();
  const [balance, opportunityStats, confirmedTotal] = await Promise.all([
    getWalletBalance(lendingWallet.id),
    db.select({ count: count() }).from(lendingOpportunitiesTable),
    db.select({ total: sum(lendingCommitmentsTable.amount) }).from(lendingCommitmentsTable).where(eq(lendingCommitmentsTable.status, "CONFIRMED"))
  ]);
  return [
    {
      walletId: lendingWallet.id,
      ownerType: "LENDING_MASTER",
      ownerId: 1,
      label: "Lending Master Wallet",
      subtitle: `${Number(opportunityStats[0]?.count ?? 0)} opportunities \xB7 $${Number(confirmedTotal[0]?.total ?? 0).toLocaleString("en-CA", { minimumFractionDigits: 2, maximumFractionDigits: 2 })} approved`,
      currency: lendingWallet.currency,
      balance
    }
  ];
}
async function getWalletOwnerDescriptor(ownerType, ownerId) {
  if (ownerType === "USER") {
    const [user] = await db.select({
      id: usersTable.id,
      email: usersTable.email,
      firstName: usersTable.firstName,
      lastName: usersTable.lastName,
      membershipType: usersTable.membershipType,
      membershipStatus: usersTable.membershipStatus
    }).from(usersTable).where(eq(usersTable.id, ownerId));
    if (!user) return null;
    const fullName = [user.firstName, user.lastName].filter(Boolean).join(" ");
    return {
      label: fullName || user.email,
      subtitle: `${user.membershipType ?? "MEMBER"} \xB7 ${user.membershipStatus ?? "PENDING"} \xB7 ${user.email}`
    };
  }
  if (ownerType === "SUSU") {
    return {
      label: "SUSU Wallet",
      subtitle: "Unified treasury across all ROSCA circles (Susu)"
    };
  }
  if (ownerType === "INVESTMENT") {
    return {
      label: "Investment Wallet",
      subtitle: "Dedicated treasury for confirmed investments and investment returns"
    };
  }
  if (ownerType === "LENDING_MASTER") {
    return {
      label: "Lending Master Wallet",
      subtitle: "Unified treasury shared by all lending opportunities"
    };
  }
  if (ownerType === "PLATFORM") {
    return {
      label: "Platform Wallet",
      subtitle: "WWN platform revenue wallet"
    };
  }
  return null;
}
function addDays4(date6, days) {
  const d = new Date(date6);
  d.setDate(d.getDate() + days);
  return d;
}
function addMonths4(date6, months) {
  const d = new Date(date6);
  d.setMonth(d.getMonth() + months);
  return d;
}
function addPeriod2(start, frequency, index2) {
  if (frequency === "WEEKLY") return addDays4(start, 7 * index2);
  if (frequency === "BIWEEKLY") return addDays4(start, 14 * index2);
  return addMonths4(start, index2);
}
async function getConfirmedCommitmentTotalWith(conn, opportunityId) {
  const [row] = await conn.select({ total: sum(lendingCommitmentsTable.amount) }).from(lendingCommitmentsTable).where(
    and(
      eq(lendingCommitmentsTable.opportunityId, opportunityId),
      eq(lendingCommitmentsTable.status, "CONFIRMED")
    )
  );
  return row?.total ?? "0";
}
async function reconcilePoolCommittedAmountWith(conn, opportunityId) {
  const committedAmount = await getConfirmedCommitmentTotalWith(
    conn,
    opportunityId
  );
  const [opportunity] = await conn.update(lendingOpportunitiesTable).set({
    committedAmount,
    updatedAt: /* @__PURE__ */ new Date()
  }).where(eq(lendingOpportunitiesTable.id, opportunityId)).returning();
  return opportunity;
}
async function getLendingMasterWalletBalanceWith(conn) {
  const wallet = await ensureLendingMasterWalletWith(conn);
  return getWalletBalanceWith3(conn, wallet.id);
}
async function getReservedMasterAmountWith(conn, excludeReservedApplicationId) {
  const applications = await conn.select({
    id: loanApplicationsTable.id,
    approvedAmount: loanApplicationsTable.approvedAmount,
    requestedAmount: loanApplicationsTable.requestedAmount
  }).from(loanApplicationsTable).where(
    inArray(loanApplicationsTable.status, [
      ...RESERVED_LENDING_APPLICATION_STATUSES
    ])
  );
  return applications.reduce((sum3, application) => {
    if (excludeReservedApplicationId && application.id === excludeReservedApplicationId) {
      return sum3;
    }
    return sum3 + parseMoneyAmount(
      application.approvedAmount ?? application.requestedAmount ?? "0"
    );
  }, 0);
}
async function getPoolAvailableToLendWith(conn, _opportunityId, excludeReservedApplicationId) {
  const [walletBalance, reservedAmount] = await Promise.all([
    getLendingMasterWalletBalanceWith(conn),
    getReservedMasterAmountWith(conn, excludeReservedApplicationId)
  ]);
  return calculateAvailableToLend(walletBalance, reservedAmount);
}
async function getConfirmedPoolCommitmentsWith(conn, opportunityId) {
  return conn.select({
    id: lendingCommitmentsTable.id,
    userId: lendingCommitmentsTable.userId,
    amount: lendingCommitmentsTable.amount,
    confirmedAt: lendingCommitmentsTable.confirmedAt
  }).from(lendingCommitmentsTable).where(
    and(
      eq(lendingCommitmentsTable.opportunityId, opportunityId),
      eq(lendingCommitmentsTable.status, "CONFIRMED")
    )
  ).orderBy(
    asc(lendingCommitmentsTable.confirmedAt),
    asc(lendingCommitmentsTable.id)
  );
}
async function getPoolOperationalMetricsMapWith(conn, pools) {
  const opportunityIds = pools.map((pool2) => pool2.id);
  const metricsMap = /* @__PURE__ */ new Map();
  if (!opportunityIds.length) {
    return metricsMap;
  }
  const [
    walletBalance,
    reservedMasterAmount,
    reservedByOpportunity,
    applicationCounts,
    outstandingApplications,
    repaymentsByApplication,
    repaymentsByOpportunity,
    realizedReturns,
    allocatedReturns
  ] = await Promise.all([
    getLendingMasterWalletBalanceWith(conn),
    getReservedMasterAmountWith(conn),
    conn.select({
      opportunityId: loanApplicationsTable.opportunityId,
      total: sql`sum(coalesce(${loanApplicationsTable.approvedAmount}, ${loanApplicationsTable.requestedAmount}, '0'))`
    }).from(loanApplicationsTable).where(
      and(
        inArray(loanApplicationsTable.opportunityId, opportunityIds),
        inArray(loanApplicationsTable.status, [
          ...RESERVED_LENDING_APPLICATION_STATUSES
        ])
      )
    ).groupBy(loanApplicationsTable.opportunityId),
    conn.select({
      opportunityId: loanApplicationsTable.opportunityId,
      activeLoanCount: sql`count(*) filter (where ${loanApplicationsTable.status} in ('FUNDED', 'REPAYING'))`,
      waitlistedApplicationCount: sql`count(*) filter (where ${loanApplicationsTable.status} = 'WAITLISTED')`
    }).from(loanApplicationsTable).where(inArray(loanApplicationsTable.opportunityId, opportunityIds)).groupBy(loanApplicationsTable.opportunityId),
    conn.select({
      opportunityId: loanApplicationsTable.opportunityId,
      id: loanApplicationsTable.id,
      disbursedAmount: loanApplicationsTable.disbursedAmount
    }).from(loanApplicationsTable).where(
      and(
        inArray(loanApplicationsTable.opportunityId, opportunityIds),
        inArray(loanApplicationsTable.status, ["FUNDED", "REPAYING"])
      )
    ),
    conn.select({
      loanApplicationId: loanRepaymentsTable.loanApplicationId,
      total: sum(loanRepaymentsTable.creditedToPoolAmount)
    }).from(loanRepaymentsTable).innerJoin(
      loanApplicationsTable,
      eq(loanRepaymentsTable.loanApplicationId, loanApplicationsTable.id)
    ).where(inArray(loanApplicationsTable.opportunityId, opportunityIds)).groupBy(loanRepaymentsTable.loanApplicationId),
    conn.select({
      opportunityId: loanApplicationsTable.opportunityId,
      total: sum(loanRepaymentsTable.creditedToPoolAmount)
    }).from(loanRepaymentsTable).innerJoin(
      loanApplicationsTable,
      eq(loanRepaymentsTable.loanApplicationId, loanApplicationsTable.id)
    ).where(inArray(loanApplicationsTable.opportunityId, opportunityIds)).groupBy(loanApplicationsTable.opportunityId),
    conn.select({
      opportunityId: lendingOpportunityReturnEventsTable.opportunityId,
      total: sum(lendingOpportunityReturnEventsTable.returnAmount)
    }).from(lendingOpportunityReturnEventsTable).where(
      inArray(
        lendingOpportunityReturnEventsTable.opportunityId,
        opportunityIds
      )
    ).groupBy(lendingOpportunityReturnEventsTable.opportunityId),
    conn.select({
      opportunityId: lendingOpportunityReturnAllocationsTable.opportunityId,
      total: sum(
        lendingOpportunityReturnAllocationsTable.allocatedReturnAmount
      )
    }).from(lendingOpportunityReturnAllocationsTable).where(
      inArray(
        lendingOpportunityReturnAllocationsTable.opportunityId,
        opportunityIds
      )
    ).groupBy(lendingOpportunityReturnAllocationsTable.opportunityId)
  ]);
  const availableToLend = calculateAvailableToLend(
    walletBalance,
    reservedMasterAmount
  );
  const reservedAmountByOpportunityId = /* @__PURE__ */ new Map();
  for (const reservation of reservedByOpportunity) {
    if (reservation.opportunityId == null) continue;
    reservedAmountByOpportunityId.set(
      reservation.opportunityId,
      parseMoneyAmount(reservation.total)
    );
  }
  const activeLoanCountByOpportunityId = /* @__PURE__ */ new Map();
  const waitlistedCountByOpportunityId = /* @__PURE__ */ new Map();
  for (const counts of applicationCounts) {
    if (counts.opportunityId == null) continue;
    activeLoanCountByOpportunityId.set(
      counts.opportunityId,
      Number(counts.activeLoanCount ?? 0)
    );
    waitlistedCountByOpportunityId.set(
      counts.opportunityId,
      Number(counts.waitlistedApplicationCount ?? 0)
    );
  }
  const outstandingAppsByOpportunityId = /* @__PURE__ */ new Map();
  for (const application of outstandingApplications) {
    if (application.opportunityId == null) continue;
    const list = outstandingAppsByOpportunityId.get(application.opportunityId) ?? [];
    list.push({
      id: application.id,
      disbursedAmount: application.disbursedAmount
    });
    outstandingAppsByOpportunityId.set(application.opportunityId, list);
  }
  const repaidByApplicationId = /* @__PURE__ */ new Map();
  for (const repayment of repaymentsByApplication) {
    repaidByApplicationId.set(
      repayment.loanApplicationId,
      parseMoneyAmount(repayment.total)
    );
  }
  const repaymentsReceivedByOpportunityId = /* @__PURE__ */ new Map();
  for (const repayment of repaymentsByOpportunity) {
    if (repayment.opportunityId == null) continue;
    repaymentsReceivedByOpportunityId.set(
      repayment.opportunityId,
      parseMoneyAmount(repayment.total)
    );
  }
  const realizedReturnByOpportunityId = /* @__PURE__ */ new Map();
  for (const event of realizedReturns) {
    realizedReturnByOpportunityId.set(
      event.opportunityId,
      parseMoneyAmount(event.total)
    );
  }
  const allocatedReturnByOpportunityId = /* @__PURE__ */ new Map();
  for (const allocation of allocatedReturns) {
    allocatedReturnByOpportunityId.set(
      allocation.opportunityId,
      parseMoneyAmount(allocation.total)
    );
  }
  for (const pool2 of pools) {
    const reservedAmount = reservedAmountByOpportunityId.get(pool2.id) ?? 0;
    const poolApplications = outstandingAppsByOpportunityId.get(pool2.id) ?? [];
    const outstandingPrincipal = poolApplications.reduce((sum3, application) => {
      return sum3 + calculateOutstandingPrincipal(
        application.disbursedAmount,
        repaidByApplicationId.get(application.id) ?? 0
      );
    }, 0);
    const repaymentsReceived = repaymentsReceivedByOpportunityId.get(pool2.id) ?? 0;
    const realizedReturn = realizedReturnByOpportunityId.get(pool2.id) ?? 0;
    const allocatedReturn = allocatedReturnByOpportunityId.get(pool2.id) ?? 0;
    const projectedReturn = calculateProjectedReturnAmount(
      pool2.committedAmount,
      pool2.expectedReturnPct,
      pool2.termMonths
    );
    metricsMap.set(pool2.id, {
      walletBalance,
      reservedAmount,
      availableToLend,
      outstandingPrincipal,
      repaymentsReceived,
      projectedReturn,
      realizedReturn,
      allocatedReturn,
      unrealizedReturn: Math.max(0, projectedReturn - realizedReturn),
      realizedYieldPct: parseMoneyAmount(pool2.committedAmount) > 0 ? realizedReturn / parseMoneyAmount(pool2.committedAmount) * 100 : 0,
      activeLoanCount: activeLoanCountByOpportunityId.get(pool2.id) ?? 0,
      waitlistedApplicationCount: waitlistedCountByOpportunityId.get(pool2.id) ?? 0
    });
  }
  return metricsMap;
}
async function createLendingReturnAllocationEvent(params) {
  const {
    conn,
    opportunityId,
    applicationId,
    repaymentId,
    walletTransactionId
  } = params;
  const returnAmount = Math.max(0, params.returnAmount);
  const grossAmount = Math.max(0, params.grossAmount);
  const principalAmount = Math.max(0, params.principalAmount);
  if (walletTransactionId != null) {
    const [existingEvent] = await conn.select().from(lendingOpportunityReturnEventsTable).where(
      and(
        eq(lendingOpportunityReturnEventsTable.repaymentId, repaymentId),
        eq(
          lendingOpportunityReturnEventsTable.walletTransactionId,
          walletTransactionId
        )
      )
    );
    if (existingEvent) return existingEvent;
  }
  const [event] = await conn.insert(lendingOpportunityReturnEventsTable).values({
    opportunityId,
    repaymentId,
    loanApplicationId: applicationId,
    walletTransactionId,
    grossAmount: formatMoneyAmount(grossAmount),
    principalAmount: formatMoneyAmount(principalAmount),
    returnAmount: formatMoneyAmount(returnAmount),
    allocatedReturnAmount: formatMoneyAmount(0),
    occurredAt: params.occurredAt ?? /* @__PURE__ */ new Date()
  }).returning();
  const commitments = await getConfirmedPoolCommitmentsWith(
    conn,
    opportunityId
  );
  if (!commitments.length) {
    return event;
  }
  const principalAllocations = allocateProRataReturnAmount(
    principalAmount,
    commitments
  );
  const returnAllocations = allocateProRataReturnAmount(
    returnAmount,
    commitments
  );
  if (returnAmount > 0) {
    const returnAllocationRows = returnAllocations.filter(
      (allocation) => allocation.allocatedReturnAmount > 0
    );
    if (returnAllocationRows.length > 0) {
      await conn.insert(lendingOpportunityReturnAllocationsTable).values(
        returnAllocationRows.map((allocation) => ({
          returnEventId: event.id,
          commitmentId: allocation.id,
          opportunityId,
          userId: allocation.userId,
          commitmentAmountSnapshot: formatMoneyAmount(
            parseMoneyAmount(allocation.amount)
          ),
          ownershipPctSnapshot: String(allocation.ownershipPct.toFixed(6)),
          allocatedReturnAmount: formatMoneyAmount(
            allocation.allocatedReturnAmount
          ),
          occurredAt: params.occurredAt ?? /* @__PURE__ */ new Date()
        }))
      );
    }
  }
  const allocatedPrincipalAmount = principalAllocations.reduce(
    (sum3, allocation) => sum3 + allocation.allocatedReturnAmount,
    0
  );
  const allocatedReturnAmount = returnAllocations.reduce(
    (sum3, allocation) => sum3 + allocation.allocatedReturnAmount,
    0
  );
  const totalInvestorPayoutAmount = allocatedPrincipalAmount + allocatedReturnAmount;
  if (totalInvestorPayoutAmount <= 0) {
    return event;
  }
  const masterWallet = await ensureLendingMasterWalletWith(conn);
  const masterWalletBalance = await getWalletBalanceWith3(conn, masterWallet.id);
  if (masterWalletBalance < totalInvestorPayoutAmount) {
    throw new Error(
      "Lending Master Wallet does not have enough balance to pay out investor principal and returns."
    );
  }
  for (const allocation of commitments) {
    const investorWallet = await ensureWalletWith5(
      conn,
      "USER",
      allocation.userId
    );
    const principalAllocation = principalAllocations.find((item) => item.id === allocation.id)?.allocatedReturnAmount ?? 0;
    const returnAllocation = returnAllocations.find((item) => item.id === allocation.id)?.allocatedReturnAmount ?? 0;
    if (principalAllocation > 0) {
      const principalPayoutIdempotencyKey = `lending_principal_payout:${event.id}:${allocation.id}`;
      const [existingPrincipalPayoutTx] = await conn.select({ id: walletTransactionsTable.id }).from(walletTransactionsTable).where(
        eq(
          walletTransactionsTable.idempotencyKey,
          principalPayoutIdempotencyKey
        )
      );
      if (!existingPrincipalPayoutTx) {
        await conn.insert(walletTransactionsTable).values({
          type: "LENDING_PRINCIPAL_PAYOUT",
          idempotencyKey: principalPayoutIdempotencyKey,
          fromWalletId: masterWallet.id,
          toWalletId: investorWallet.id,
          amount: formatMoneyAmount(principalAllocation),
          metadata: {
            source: "lending_principal_payout",
            opportunityId,
            repaymentId,
            applicationId,
            returnEventId: event.id,
            commitmentId: allocation.id,
            investorId: allocation.userId
          }
        });
      }
    }
    if (returnAllocation > 0) {
      const payoutIdempotencyKey = `lending_return_payout:${event.id}:${allocation.id}`;
      const [existingPayoutTx] = await conn.select({ id: walletTransactionsTable.id }).from(walletTransactionsTable).where(
        eq(walletTransactionsTable.idempotencyKey, payoutIdempotencyKey)
      );
      if (!existingPayoutTx) {
        await conn.insert(walletTransactionsTable).values({
          type: "LENDING_RETURN_PAYOUT",
          idempotencyKey: payoutIdempotencyKey,
          fromWalletId: masterWallet.id,
          toWalletId: investorWallet.id,
          amount: formatMoneyAmount(returnAllocation),
          metadata: {
            source: "lending_return_payout",
            opportunityId,
            repaymentId,
            applicationId,
            returnEventId: event.id,
            commitmentId: allocation.id,
            investorId: allocation.userId
          }
        });
      }
    }
  }
  const [updatedEvent] = await conn.update(lendingOpportunityReturnEventsTable).set({
    allocatedReturnAmount: formatMoneyAmount(allocatedReturnAmount)
  }).where(eq(lendingOpportunityReturnEventsTable.id, event.id)).returning();
  return updatedEvent ?? event;
}
async function getRemainingPoolCapacityWith(conn, opportunityId) {
  const [opportunity] = await conn.select({
    targetAmount: lendingOpportunitiesTable.targetAmount
  }).from(lendingOpportunitiesTable).where(eq(lendingOpportunitiesTable.id, opportunityId));
  if (!opportunity) return 0;
  const confirmedTotal = parseMoneyAmount(
    await getConfirmedCommitmentTotalWith(conn, opportunityId)
  );
  return Math.max(
    0,
    parseMoneyAmount(opportunity.targetAmount) - confirmedTotal
  );
}
async function generateCircleSchedule(circleId) {
  await generateCircleScheduleWith(db, circleId);
  await processCircleAutomationWith(db, circleId);
}
function normalizePlanEntitlementsForMembershipType(membershipType, entitlements) {
  const source = entitlements ?? {};
  if (membershipType === "INDIVIDUAL") {
    return normalizeIndividualPlanEntitlements(source);
  }
  if (membershipType !== "ORGANIZATION") {
    return {};
  }
  return {
    tenant_access: typeof source.tenant_access === "boolean" ? source.tenant_access : void 0,
    member_management: typeof source.member_management === "boolean" ? source.member_management : void 0,
    seat_limit: typeof source.seat_limit === "number" || source.seat_limit === null ? source.seat_limit : void 0,
    org_billing_manage: typeof source.org_billing_manage === "boolean" ? source.org_billing_manage : void 0,
    org_wallet_operate: typeof source.org_wallet_operate === "boolean" ? source.org_wallet_operate : void 0,
    org_wallet_fund: typeof source.org_wallet_fund === "boolean" ? source.org_wallet_fund : void 0,
    org_member_contributions: typeof source.org_member_contributions === "boolean" ? source.org_member_contributions : void 0,
    org_financial_reporting: typeof source.org_financial_reporting === "boolean" ? source.org_financial_reporting : void 0,
    programs_access: typeof source.programs_access === "boolean" ? source.programs_access : void 0,
    resources_access: typeof source.resources_access === "boolean" ? source.resources_access : void 0,
    workshops_access: typeof source.workshops_access === "boolean" ? source.workshops_access : void 0,
    white_label_resources_access: typeof source.white_label_resources_access === "boolean" ? source.white_label_resources_access : void 0,
    org_susu_operate: typeof source.org_susu_operate === "boolean" ? source.org_susu_operate : void 0,
    org_susu_education: typeof source.org_susu_education === "boolean" ? source.org_susu_education : void 0,
    investment_club_access: typeof source.investment_club_access === "boolean" ? source.investment_club_access : void 0,
    p2p_capital_access: typeof source.p2p_capital_access === "boolean" ? source.p2p_capital_access : void 0,
    asca_access: typeof source.asca_access === "boolean" ? source.asca_access : void 0,
    quote_managed_only: typeof source.quote_managed_only === "boolean" ? source.quote_managed_only : void 0
  };
}
function onboardingProgramWindowsOverlap(startA, endA, startB, endB) {
  const startsBeforeOtherEnds = !startA || !endB || startA.getTime() <= endB.getTime();
  const otherStartsBeforeEnds = !startB || !endA || startB.getTime() <= endA.getTime();
  return startsBeforeOtherEnds && otherStartsBeforeEnds;
}
async function assertNoPublishedOnboardingProgramConflict(input, client = db) {
  if (input.status !== "PUBLISHED") {
    return;
  }
  const existingPrograms = await client.select({
    id: onboardingProgramsTable.id,
    startDate: onboardingProgramsTable.startDate,
    endDate: onboardingProgramsTable.endDate
  }).from(onboardingProgramsTable).where(
    and(
      eq(onboardingProgramsTable.status, "PUBLISHED"),
      eq(
        onboardingProgramsTable.targetMembershipType,
        input.targetMembershipType
      ),
      input.id != null ? ne(onboardingProgramsTable.id, input.id) : sql`true`
    )
  );
  const conflictingProgram = existingPrograms.find(
    (program) => onboardingProgramWindowsOverlap(
      input.startDate,
      input.endDate,
      program.startDate,
      program.endDate
    )
  );
  if (conflictingProgram) {
    throw Object.assign(
      new Error(
        `Another published onboarding program already targets ${input.targetMembershipType.toLowerCase()} members during this schedule.`
      ),
      { status: 409 }
    );
  }
}
async function getOnboardingProgramStructureCounts(programId, client = db) {
  const [weeksRow] = await client.select({ count: count() }).from(onboardingProgramWeeksTable).where(eq(onboardingProgramWeeksTable.programId, programId));
  const [activitiesRow] = await client.select({ count: count() }).from(onboardingProgramWeeksTable).innerJoin(
    onboardingWeekActivitiesTable,
    eq(onboardingWeekActivitiesTable.weekId, onboardingProgramWeeksTable.id)
  ).where(eq(onboardingProgramWeeksTable.programId, programId));
  return {
    weekCount: Number(weeksRow?.count ?? 0),
    activityCount: Number(activitiesRow?.count ?? 0)
  };
}
async function assertPublishedOnboardingProgramHasContent(input, client = db) {
  if (input.status !== "PUBLISHED" || input.id == null) {
    return;
  }
  const { weekCount, activityCount } = await getOnboardingProgramStructureCounts(input.id, client);
  if (weekCount === 0 || activityCount === 0) {
    throw Object.assign(
      new Error(
        "A published onboarding program must include at least one week and one activity."
      ),
      { status: 409 }
    );
  }
}
var import_express3, router3, PLATFORM_WALLET_OWNER_ID, optionalAdminProfileString, adminProfileUpdateSchema, adminCredentialsUpdateSchema, SUSU_WALLET_OWNER_ID2, LENDING_MASTER_WALLET_OWNER_ID, communityNullableSafeUrl, optionalOrganizationQuoteAmount, RESOURCE_SLUG_REGEX, resourceSafeUrl, optionalResourceUrl, optionalResourceText, createResourceSchema, updateResourceSchema, ACADEMY_SLUG_REGEX, academyHttpUrl, academyNullableHttpUrl, HELPING_HAND_REPAYMENT_CREATEABLE_APPLICATION_STATUSES, HELPING_HAND_REPAYMENT_SERVICEABLE_APPLICATION_STATUSES, REPAYMENT_CREATEABLE_APPLICATION_STATUSES, REPAYMENT_SERVICEABLE_APPLICATION_STATUSES, allowedInvestorPlanTiers, investmentOpportunityEligibleInvestorTiersSchema, investmentOpportunityFundingModelSchema, planEntitlementsSchema, onboardingSlideSchema, onboardingProgramSchema, onboardingWeekSchema, onboardingActivitySchema, communityStorySchema, admin_default;
var init_admin = __esm({
  "src/routes/admin.ts"() {
    "use strict";
    import_express3 = __toESM(require_express2(), 1);
    init_bcryptjs();
    init_zod();
    init_src2();
    init_investment_funding();
    init_schema2();
    init_schema2();
    init_drizzle_orm();
    init_logger();
    init_membership_plan_tiers();
    init_investments();
    init_investment_constants();
    init_investment_funding();
    init_investment_returns();
    init_notification_dispatcher();
    init_notifications();
    init_notification_deliveries();
    init_credit_score();
    init_member_onboarding_program();
    init_lending();
    init_admin_metrics();
    init_helping_hand();
    init_susu();
    init_organization_context();
    init_auth_session();
    init_live_events();
    init_individual_plan_entitlements();
    init_asca();
    init_session_profile();
    init_member_access();
    router3 = (0, import_express3.Router)();
    router3.get("/stories", async (_req, res) => {
      try {
        const stories = await db.select().from(communityPostsTable).where(eq(communityPostsTable.postType, "ADMIN_STORY")).orderBy(desc(communityPostsTable.createdAt));
        return res.json({ stories });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/stories", requireAdminOrWorkerOwner, async (req, res) => {
      try {
        const data = communityStorySchema.parse(req.body);
        const admin = req.admin;
        const [story] = await db.insert(communityPostsTable).values({
          ...data,
          postType: "ADMIN_STORY",
          authorId: admin.id,
          publishedAt: data.isPublished ? /* @__PURE__ */ new Date() : null
        }).returning();
        return res.status(201).json({ story });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.patch(
      "/stories/:id",
      requireAdminOrWorkerOwner,
      async (req, res) => {
        try {
          const id = Number(req.params.id);
          const data = communityStorySchema.partial().parse(req.body);
          const updates = {
            ...data,
            updatedAt: /* @__PURE__ */ new Date()
          };
          if (data.isPublished !== void 0) {
            updates.publishedAt = data.isPublished ? /* @__PURE__ */ new Date() : null;
          }
          const [story] = await db.update(communityPostsTable).set(updates).where(
            and(
              eq(communityPostsTable.id, id),
              eq(communityPostsTable.postType, "ADMIN_STORY")
            )
          ).returning();
          if (!story) return res.status(404).json({ message: "Story not found" });
          return res.json({ story });
        } catch (err) {
          return handleError2(err, res);
        }
      }
    );
    router3.delete(
      "/stories/:id",
      requireAdminOrWorkerOwner,
      async (req, res) => {
        try {
          const id = Number(req.params.id);
          const [deleted] = await db.delete(communityPostsTable).where(
            and(
              eq(communityPostsTable.id, id),
              eq(communityPostsTable.postType, "ADMIN_STORY")
            )
          ).returning();
          if (!deleted) return res.status(404).json({ message: "Story not found" });
          return res.json({ ok: true });
        } catch (err) {
          return handleError2(err, res);
        }
      }
    );
    router3.use(requireAdmin);
    PLATFORM_WALLET_OWNER_ID = 1;
    optionalAdminProfileString = external_exports.string().trim().max(191).optional().or(external_exports.literal("")).transform((value) => value && value.length ? value : null);
    adminProfileUpdateSchema = external_exports.object({
      firstName: external_exports.string().trim().min(1).max(191).optional(),
      lastName: optionalAdminProfileString,
      phone: optionalAdminProfileString,
      username: external_exports.string().trim().min(3).max(30).regex(/^[a-zA-Z0-9_]+$/).optional().or(external_exports.literal("")).transform((value) => value && value.length ? value : null),
      bio: optionalAdminProfileString,
      city: optionalAdminProfileString,
      province: optionalAdminProfileString,
      occupation: optionalAdminProfileString
    });
    adminCredentialsUpdateSchema = external_exports.object({
      email: external_exports.string().trim().email().optional().transform((value) => value?.toLowerCase() ?? void 0),
      currentPassword: external_exports.string().min(1),
      newPassword: external_exports.string().min(8).optional()
    });
    router3.get("/profile", async (req, res) => {
      try {
        const adminId = req.admin.id;
        const [user] = await db.select().from(usersTable).where(eq(usersTable.id, adminId));
        if (!user) {
          return res.status(404).json({ message: "Admin user not found." });
        }
        return res.json({
          profile: await formatAdminProfile(user)
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.patch("/profile", async (req, res) => {
      try {
        const adminId = req.admin.id;
        const parsed = adminProfileUpdateSchema.safeParse(req.body ?? {});
        if (!parsed.success) {
          return res.status(400).json({ errors: parsed.error.flatten() });
        }
        const updates = Object.fromEntries(
          Object.entries(parsed.data).filter(([, value]) => value !== void 0)
        );
        const [existingUser] = await db.select().from(usersTable).where(eq(usersTable.id, adminId));
        if (!existingUser) {
          return res.status(404).json({ message: "Admin user not found." });
        }
        if (Object.keys(updates).length === 0) {
          return res.json({
            profile: await formatAdminProfile(existingUser)
          });
        }
        if (typeof updates.username === "string" && updates.username.length > 0) {
          const existingUsername = await db.select({ id: usersTable.id }).from(usersTable).where(eq(usersTable.username, updates.username));
          if (existingUsername.some((row) => row.id !== adminId)) {
            return res.status(409).json({ message: "Username already taken." });
          }
        }
        const [updatedUser] = await db.update(usersTable).set({
          ...updates,
          updatedAt: /* @__PURE__ */ new Date()
        }).where(eq(usersTable.id, adminId)).returning();
        publishLiveEventToUser(adminId, {
          kind: "DATA_CHANGED",
          scopes: ["profile"],
          payload: { action: "admin_profile_updated" }
        });
        return res.json({
          profile: await formatAdminProfile(updatedUser),
          message: "Admin profile updated."
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.patch("/profile/credentials", async (req, res) => {
      try {
        const adminId = req.admin.id;
        const parsed = adminCredentialsUpdateSchema.safeParse(req.body ?? {});
        if (!parsed.success) {
          return res.status(400).json({ errors: parsed.error.flatten() });
        }
        const [existingUser] = await db.select().from(usersTable).where(eq(usersTable.id, adminId));
        if (!existingUser) {
          return res.status(404).json({ message: "Admin user not found." });
        }
        const nextEmail = parsed.data.email;
        const nextPassword = parsed.data.newPassword;
        if (!nextEmail && !nextPassword) {
          return res.status(400).json({
            message: "Provide a new email address or a new password."
          });
        }
        const currentPasswordValid = await bcryptjs_default.compare(
          parsed.data.currentPassword,
          existingUser.passwordHash
        );
        if (!currentPasswordValid) {
          return res.status(401).json({ message: "Current password is incorrect." });
        }
        if (nextEmail && nextEmail !== existingUser.email) {
          const existingEmail = await db.select({ id: usersTable.id }).from(usersTable).where(eq(usersTable.email, nextEmail));
          if (existingEmail.some((row) => row.id !== adminId)) {
            return res.status(409).json({ message: "Email address already in use." });
          }
        }
        const [updatedUser] = await db.update(usersTable).set({
          email: nextEmail ?? existingUser.email,
          passwordHash: nextPassword ? await bcryptjs_default.hash(nextPassword, 12) : existingUser.passwordHash,
          updatedAt: /* @__PURE__ */ new Date()
        }).where(eq(usersTable.id, adminId)).returning();
        publishLiveEventToUser(adminId, {
          kind: "DATA_CHANGED",
          scopes: ["profile"],
          payload: { action: "admin_credentials_updated" }
        });
        return res.json({
          profile: await formatAdminProfile(updatedUser),
          message: "Sign-in details updated."
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/bank-setup", async (_req, res) => {
      try {
        const [setup] = await db.select().from(bankSetupTable).limit(1);
        if (!setup) {
          return res.status(500).json({ message: "Bank setup is not configured." });
        }
        return res.json({
          bankSetup: {
            eft: {
              accountName: setup.eftAccountName,
              institutionNumber: setup.eftInstitutionNumber,
              transitNumber: setup.eftTransitNumber,
              accountNumber: setup.eftAccountNumber
            },
            interac: {
              recipientName: setup.interacRecipientName,
              email: setup.interacEmail
            },
            charges: {
              cashoutMinAmount: Number(setup.cashoutMinAmount),
              cashoutFeePct: Number(setup.cashoutFeePct),
              cashoutFeeFixed: Number(setup.cashoutFeeFixed)
            },
            updatedAt: setup.updatedAt.toISOString()
          }
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.put("/bank-setup", async (req, res) => {
      try {
        const parsed = external_exports.object({
          eft: external_exports.object({
            accountName: external_exports.string().min(1).max(200),
            institutionNumber: external_exports.string().min(1).max(20),
            transitNumber: external_exports.string().min(1).max(20),
            accountNumber: external_exports.string().min(1).max(50)
          }),
          interac: external_exports.object({
            recipientName: external_exports.string().min(1).max(200),
            email: external_exports.string().email().max(200)
          }),
          charges: external_exports.object({
            cashoutMinAmount: external_exports.coerce.number().min(0),
            cashoutFeePct: external_exports.coerce.number().min(0),
            cashoutFeeFixed: external_exports.coerce.number().min(0)
          })
        }).safeParse(req.body ?? {});
        if (!parsed.success) {
          return res.status(400).json({ errors: parsed.error.flatten() });
        }
        const cashoutMinAmount = Number(parsed.data.charges.cashoutMinAmount);
        const cashoutFeePct = Number(parsed.data.charges.cashoutFeePct);
        const cashoutFeeFixed = Number(parsed.data.charges.cashoutFeeFixed);
        if (!Number.isFinite(cashoutMinAmount) || !Number.isFinite(cashoutFeePct) || !Number.isFinite(cashoutFeeFixed)) {
          return res.status(400).json({ message: "Invalid bank charges configuration." });
        }
        const updated = await db.transaction(async (tx) => {
          const now = /* @__PURE__ */ new Date();
          const [existing] = await tx.select().from(bankSetupTable).where(eq(bankSetupTable.id, 1)).limit(1);
          const values = {
            eftAccountName: parsed.data.eft.accountName.trim(),
            eftInstitutionNumber: parsed.data.eft.institutionNumber.trim(),
            eftTransitNumber: parsed.data.eft.transitNumber.trim(),
            eftAccountNumber: parsed.data.eft.accountNumber.trim(),
            interacRecipientName: parsed.data.interac.recipientName.trim(),
            interacEmail: parsed.data.interac.email.trim(),
            cashoutMinAmount: cashoutMinAmount.toFixed(2),
            cashoutFeePct: cashoutFeePct.toFixed(3),
            cashoutFeeFixed: cashoutFeeFixed.toFixed(2),
            updatedAt: now
          };
          if (!existing) {
            const [created] = await tx.insert(bankSetupTable).values({ id: 1, ...values }).returning();
            return created;
          }
          const [saved] = await tx.update(bankSetupTable).set(values).where(eq(bankSetupTable.id, 1)).returning();
          return saved;
        });
        return res.json({
          bankSetup: {
            eft: {
              accountName: updated.eftAccountName,
              institutionNumber: updated.eftInstitutionNumber,
              transitNumber: updated.eftTransitNumber,
              accountNumber: updated.eftAccountNumber
            },
            interac: {
              recipientName: updated.interacRecipientName,
              email: updated.interacEmail
            },
            charges: {
              cashoutMinAmount: Number(updated.cashoutMinAmount),
              cashoutFeePct: Number(updated.cashoutFeePct),
              cashoutFeeFixed: Number(updated.cashoutFeeFixed)
            },
            updatedAt: updated.updatedAt.toISOString()
          }
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/membership-id-settings", async (_req, res) => {
      try {
        const [settings] = await db.select().from(membershipIdSettingsTable).where(eq(membershipIdSettingsTable.id, 1)).limit(1);
        if (!settings) {
          return res.status(200).json({
            settings: { prefix: "WWN", digits: 7 }
          });
        }
        return res.json({
          settings: {
            prefix: settings.prefix.toUpperCase(),
            digits: Number(settings.digits)
          }
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.put("/membership-id-settings", async (req, res) => {
      try {
        const parsed = external_exports.object({
          prefix: external_exports.string().trim().min(1).max(12).regex(/^[a-zA-Z0-9]+$/).transform((value) => value.toUpperCase()),
          digits: external_exports.coerce.number().int().min(4).max(12)
        }).safeParse(req.body ?? {});
        if (!parsed.success) {
          return res.status(400).json({ errors: parsed.error.flatten() });
        }
        const saved = await db.transaction(async (tx) => {
          const now = /* @__PURE__ */ new Date();
          const [existing] = await tx.select().from(membershipIdSettingsTable).where(eq(membershipIdSettingsTable.id, 1)).limit(1);
          const values = {
            prefix: parsed.data.prefix,
            digits: parsed.data.digits,
            updatedAt: now
          };
          if (!existing) {
            const [created] = await tx.insert(membershipIdSettingsTable).values({ id: 1, ...values }).returning();
            return created;
          }
          const [updated] = await tx.update(membershipIdSettingsTable).set(values).where(eq(membershipIdSettingsTable.id, 1)).returning();
          return updated;
        });
        return res.json({
          settings: {
            prefix: saved.prefix,
            digits: Number(saved.digits)
          }
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    SUSU_WALLET_OWNER_ID2 = 1;
    LENDING_MASTER_WALLET_OWNER_ID = 1;
    router3.get("/stats", async (_req, res) => {
      try {
        const [
          [memberStats],
          [circleStats],
          [helpingHandStats],
          [investmentStats],
          [paymentStats],
          [intakeStats]
        ] = await Promise.all([
          db.select({
            total: sql`count(*) filter (where not exists (select 1 from organization_members om where om.user_id = ${usersTable.id} and om.role != 'OWNER'))`,
            active: sql`count(*) filter (where ${usersTable.membershipStatus} = 'ACTIVE' and not exists (select 1 from organization_members om where om.user_id = ${usersTable.id} and om.role != 'OWNER'))`,
            pending: sql`count(*) filter (where ${usersTable.membershipStatus} = 'PENDING' and not exists (select 1 from organization_members om where om.user_id = ${usersTable.id} and om.role != 'OWNER'))`,
            suspended: sql`count(*) filter (where ${usersTable.membershipStatus} = 'SUSPENDED' and not exists (select 1 from organization_members om where om.user_id = ${usersTable.id} and om.role != 'OWNER'))`,
            individual: sql`count(*) filter (where ${usersTable.membershipType} = 'INDIVIDUAL' and not exists (select 1 from organization_members om where om.user_id = ${usersTable.id} and om.role != 'OWNER'))`,
            organization: sql`count(*) filter (where ${usersTable.membershipType} = 'ORGANIZATION' and not exists (select 1 from organization_members om where om.user_id = ${usersTable.id} and om.role != 'OWNER'))`,
            investor: sql`count(*) filter (where ${usersTable.membershipType} = 'INVESTOR' and not exists (select 1 from organization_members om where om.user_id = ${usersTable.id} and om.role != 'OWNER'))`
          }).from(usersTable),
          db.select({
            total: count(),
            active: sql`count(*) filter (where ${savingsCirclesTable.status} = 'ACTIVE')`
          }).from(savingsCirclesTable),
          db.select({
            submitted: sql`count(*) filter (where ${helpingHandApplicationsTable.status} = 'SUBMITTED')`,
            underReview: sql`count(*) filter (where ${helpingHandApplicationsTable.status} = 'UNDER_REVIEW')`
          }).from(helpingHandApplicationsTable),
          db.select({
            openOpportunities: sql`count(*) filter (where ${investmentOpportunitiesTable.status} = 'OPEN')`,
            totalRaised: sum(investmentOpportunitiesTable.raisedAmount)
          }).from(investmentOpportunitiesTable),
          db.select({
            total: sql`sum(${paymentsTable.amount}) filter (where ${paymentsTable.status} = 'COMPLETED')`
          }).from(paymentsTable),
          db.select({
            pending: sql`count(*) filter (where ${organizationIntakesTable.status} in ('PENDING', 'IN_REVIEW'))`
          }).from(organizationIntakesTable)
        ]);
        return res.json({
          members: {
            total: Number(memberStats.total),
            active: Number(memberStats.active),
            pending: Number(memberStats.pending),
            suspended: Number(memberStats.suspended),
            byType: {
              INDIVIDUAL: Number(memberStats.individual),
              ORGANIZATION: Number(memberStats.organization),
              INVESTOR: Number(memberStats.investor)
            }
          },
          circles: {
            total: Number(circleStats.total),
            active: Number(circleStats.active)
          },
          helpingHand: {
            submitted: Number(helpingHandStats.submitted),
            underReview: Number(helpingHandStats.underReview)
          },
          investments: {
            openOpportunities: Number(investmentStats.openOpportunities),
            totalRaised: investmentStats.totalRaised ?? "0"
          },
          revenue: buildPlatformRevenueSummary({
            completedPaymentTotal: paymentStats.total
          }),
          intakes: {
            pending: Number(intakeStats.pending)
          }
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/notification-deliveries", async (req, res) => {
      try {
        const page = Math.max(1, Number(req.query.page) || 1);
        const limit = Math.min(200, Number(req.query.limit) || 50);
        const offset = (page - 1) * limit;
        const [rows] = await Promise.all([
          db.select({
            id: notificationDeliveriesTable.id,
            occurredAt: notificationDeliveriesTable.occurredAt,
            userId: notificationDeliveriesTable.userId,
            userEmail: usersTable.email,
            channel: notificationDeliveriesTable.channel,
            category: notificationDeliveriesTable.category,
            status: notificationDeliveriesTable.status,
            provider: notificationDeliveriesTable.provider,
            errorMessage: notificationDeliveriesTable.errorMessage,
            idempotencyKey: notificationDeliveriesTable.idempotencyKey,
            notificationId: notificationDeliveriesTable.notificationId
          }).from(notificationDeliveriesTable).leftJoin(
            usersTable,
            eq(notificationDeliveriesTable.userId, usersTable.id)
          ).orderBy(desc(notificationDeliveriesTable.occurredAt)).limit(limit).offset(offset)
        ]);
        return res.json({
          page,
          limit,
          deliveries: rows.map((row) => ({
            id: row.id,
            occurredAt: row.occurredAt.toISOString(),
            userId: row.userId,
            userEmail: row.userEmail,
            channel: row.channel,
            category: row.category,
            status: row.status,
            provider: row.provider,
            errorMessage: row.errorMessage,
            idempotencyKey: row.idempotencyKey,
            notificationId: row.notificationId
          }))
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/notifications/inbox", async (req, res) => {
      try {
        const adminId = req.admin?.id ?? null;
        if (!adminId)
          return res.status(401).json({ message: "Not authenticated." });
        const limit = Math.min(200, Number(req.query.limit) || 50);
        const offset = Math.max(0, Number(req.query.offset) || 0);
        const includeRead = String(req.query.includeRead ?? "true") !== "false";
        const rows = await listNotificationsWith(db, {
          userId: adminId,
          limit,
          offset,
          includeRead
        });
        return res.json({
          notifications: rows.map((row) => ({
            id: String(row.id),
            category: row.category,
            severity: row.severity,
            title: row.title,
            body: row.body,
            read: row.read,
            readAt: row.readAt ? row.readAt.toISOString() : null,
            createdAt: row.createdAt.toISOString(),
            actionLabel: row.actionLabel ?? null,
            actionHref: row.actionHref ?? null
          }))
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/notifications/inbox/unread-count", async (req, res) => {
      try {
        const adminId = req.admin?.id ?? null;
        if (!adminId)
          return res.status(401).json({ message: "Not authenticated." });
        const unreadCount = await getUnreadCountWith(db, adminId);
        return res.json({ unreadCount });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/notifications/inbox/read-all", async (req, res) => {
      try {
        const adminId = req.admin?.id ?? null;
        if (!adminId)
          return res.status(401).json({ message: "Not authenticated." });
        const updatedCount = await markAllNotificationsReadWith(db, adminId);
        return res.json({ updatedCount });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/notifications/inbox/:id/read", async (req, res) => {
      try {
        const adminId = req.admin?.id ?? null;
        if (!adminId)
          return res.status(401).json({ message: "Not authenticated." });
        const notificationId = Number(req.params.id);
        if (!Number.isFinite(notificationId) || notificationId <= 0) {
          return res.status(400).json({ message: "Invalid notification id." });
        }
        const notification = await markNotificationReadWith(db, {
          userId: adminId,
          id: notificationId
        });
        if (!notification) return res.status(404).json({ message: "Not found." });
        return res.json({
          notification: {
            id: String(notification.id),
            category: notification.category,
            severity: notification.severity,
            title: notification.title,
            body: notification.body,
            read: notification.read,
            readAt: notification.readAt ? notification.readAt.toISOString() : null,
            createdAt: notification.createdAt.toISOString(),
            actionLabel: notification.actionLabel ?? null,
            actionHref: notification.actionHref ?? null
          }
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/notifications/send", async (req, res) => {
      try {
        const adminId = req.admin?.id ?? null;
        if (!adminId)
          return res.status(401).json({ message: "Not authenticated." });
        const parsed = external_exports.object({
          target: external_exports.object({
            mode: external_exports.enum([
              "USER_IDS",
              "ALL_ACTIVE",
              "ACTIVE_INDIVIDUAL",
              "ACTIVE_INVESTOR",
              "ACTIVE_ORGANIZATION"
            ]),
            userIds: external_exports.array(external_exports.number().int().positive()).optional()
          }),
          message: external_exports.object({
            category: external_exports.enum([
              "SYSTEM",
              "MEMBERSHIP",
              "SAVINGS",
              "LENDING",
              "INVESTMENT",
              "ACADEMY",
              "PAYMENT",
              "COMMUNITY"
            ]),
            severity: external_exports.enum(["INFO", "SUCCESS", "WARNING", "ERROR"]),
            title: external_exports.string().trim().min(1).max(120),
            body: external_exports.string().trim().min(1).max(1200),
            actionLabel: external_exports.string().trim().max(60).optional().or(external_exports.literal("")),
            actionHref: external_exports.string().trim().max(191).optional().or(external_exports.literal(""))
          }),
          channels: external_exports.object({
            push: external_exports.boolean().optional(),
            email: external_exports.boolean().optional()
          }).optional()
        }).safeParse(req.body);
        if (!parsed.success) {
          return res.status(400).json({ errors: parsed.error.flatten() });
        }
        const target = parsed.data.target;
        const message = parsed.data.message;
        const channels = {
          push: Boolean(parsed.data.channels?.push),
          email: Boolean(parsed.data.channels?.email)
        };
        const conditions = [];
        if (target.mode === "USER_IDS") {
          const ids = target.userIds ?? [];
          if (!ids.length) {
            return res.status(400).json({ message: "Provide userIds." });
          }
          conditions.push(inArray(usersTable.id, ids));
        } else {
          conditions.push(eq(usersTable.userRole, "MEMBER"));
          conditions.push(eq(usersTable.membershipStatus, "ACTIVE"));
          if (target.mode === "ACTIVE_INDIVIDUAL") {
            conditions.push(eq(usersTable.membershipType, "INDIVIDUAL"));
          }
          if (target.mode === "ACTIVE_INVESTOR") {
            conditions.push(eq(usersTable.membershipType, "INVESTOR"));
          }
          if (target.mode === "ACTIVE_ORGANIZATION") {
            conditions.push(eq(usersTable.membershipType, "ORGANIZATION"));
          }
        }
        const recipients = await db.select({
          id: usersTable.id,
          email: usersTable.email,
          firstName: usersTable.firstName
        }).from(usersTable).where(conditions.length ? and(...conditions) : void 0).limit(501);
        if (recipients.length === 0) {
          return res.status(200).json({ sent: 0 });
        }
        if (recipients.length > 500) {
          return res.status(400).json({ message: "Too many recipients. Narrow the target." });
        }
        const cleanedActionLabel = message.actionLabel?.trim() || null;
        const cleanedActionHref = message.actionHref?.trim() || null;
        let pushSent = 0;
        let pushSkipped = 0;
        let pushFailed = 0;
        let emailSent = 0;
        let emailSkipped = 0;
        let emailFailed = 0;
        const results = await Promise.all(
          recipients.map(async (recipient) => {
            const inApp = await notifyInAppWith(db, {
              userId: recipient.id,
              category: message.category,
              severity: message.severity,
              title: message.title,
              body: message.body,
              actionLabel: cleanedActionLabel,
              actionHref: cleanedActionHref,
              metadata: {
                kind: "admin_custom",
                adminId
              }
            });
            const tasks = [];
            if (channels.push) {
              const key = `admin_custom:${adminId}:${inApp.id}:push`;
              tasks.push(
                (async () => {
                  const reserved = await reserveNotificationDeliveryWith(db, {
                    userId: recipient.id,
                    channel: "PUSH",
                    category: message.category,
                    idempotencyKey: key,
                    status: "SKIPPED",
                    provider: null,
                    metadata: {
                      kind: "admin_custom",
                      adminId,
                      notificationId: inApp.id
                    }
                  });
                  if (!reserved.reserved) return;
                  try {
                    const push = await deliverPushIgnoringPreferences({
                      userId: recipient.id,
                      category: message.category,
                      title: message.title,
                      body: message.body,
                      data: { notificationId: inApp.id, kind: "admin_custom" }
                    });
                    const baseMeta = reserved.row.metadata ?? {};
                    await finalizeNotificationDeliveryWith(db, {
                      idempotencyKey: key,
                      status: push.status,
                      provider: push.status === "SENT" ? "EXPO" : null,
                      metadata: {
                        ...baseMeta,
                        reason: push.reason ?? null
                      },
                      notificationId: inApp.id
                    });
                    if (push.status === "SENT") pushSent += 1;
                    else pushSkipped += 1;
                  } catch (err) {
                    await finalizeNotificationDeliveryWith(db, {
                      idempotencyKey: key,
                      status: "FAILED",
                      provider: null,
                      errorMessage: err instanceof Error ? err.message : String(err),
                      notificationId: inApp.id
                    });
                    pushFailed += 1;
                  }
                })()
              );
            }
            if (channels.email) {
              const key = `admin_custom:${adminId}:${inApp.id}:email`;
              tasks.push(
                (async () => {
                  const reserved = await reserveNotificationDeliveryWith(db, {
                    userId: recipient.id,
                    channel: "EMAIL",
                    category: message.category,
                    idempotencyKey: key,
                    status: "SKIPPED",
                    provider: null,
                    metadata: {
                      kind: "admin_custom",
                      adminId,
                      notificationId: inApp.id
                    }
                  });
                  if (!reserved.reserved) return;
                  try {
                    const to = String(recipient.email ?? "").trim();
                    if (!to) {
                      const baseMeta2 = reserved.row.metadata ?? {};
                      await finalizeNotificationDeliveryWith(db, {
                        idempotencyKey: key,
                        status: "SKIPPED",
                        provider: null,
                        metadata: { ...baseMeta2, reason: "no_email" },
                        notificationId: inApp.id
                      });
                      emailSkipped += 1;
                      return;
                    }
                    const email3 = await deliverReminderEmailIgnoringPreferences({
                      userId: recipient.id,
                      to,
                      firstName: recipient.firstName,
                      category: message.category,
                      title: message.title,
                      intro: message.body,
                      lines: [],
                      actionLabel: cleanedActionLabel,
                      actionHref: cleanedActionHref
                    });
                    const baseMeta = reserved.row.metadata ?? {};
                    await finalizeNotificationDeliveryWith(db, {
                      idempotencyKey: key,
                      status: email3.status,
                      provider: email3.status === "SENT" ? "SMTP" : null,
                      metadata: {
                        ...baseMeta,
                        reason: email3.reason ?? null
                      },
                      notificationId: inApp.id
                    });
                    if (email3.status === "SENT") emailSent += 1;
                    else emailSkipped += 1;
                  } catch (err) {
                    await finalizeNotificationDeliveryWith(db, {
                      idempotencyKey: key,
                      status: "FAILED",
                      provider: "SMTP",
                      errorMessage: err instanceof Error ? err.message : String(err),
                      notificationId: inApp.id
                    });
                    emailFailed += 1;
                  }
                })()
              );
            }
            await Promise.all(tasks);
            return inApp.id;
          })
        );
        return res.status(201).json({
          sent: results.length,
          deliveries: {
            push: channels.push ? { sent: pushSent, skipped: pushSkipped, failed: pushFailed } : null,
            email: channels.email ? { sent: emailSent, skipped: emailSkipped, failed: emailFailed } : null
          }
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/members", async (req, res) => {
      try {
        const page = Math.max(1, Number(req.query.page) || 1);
        const limit = Math.min(100, Number(req.query.limit) || 25);
        const offset = (page - 1) * limit;
        const search = req.query.search || "";
        const status = req.query.status || "";
        const type = req.query.type || "";
        const conditions = [
          sql`not exists (select 1 from organization_members om where om.user_id = ${usersTable.id} and om.role != 'OWNER')`
        ];
        if (search) {
          conditions.push(
            or(
              ilike(usersTable.email, `%${search}%`),
              ilike(usersTable.firstName, `%${search}%`),
              ilike(usersTable.lastName, `%${search}%`),
              ilike(usersTable.username, `%${search}%`)
            )
          );
        }
        if (status)
          conditions.push(eq(usersTable.membershipStatus, status));
        if (type)
          conditions.push(eq(usersTable.membershipType, type));
        const whereClause = conditions.length > 0 ? and(...conditions) : void 0;
        const [members, [totalRow]] = await Promise.all([
          db.select({
            id: usersTable.id,
            email: usersTable.email,
            firstName: usersTable.firstName,
            lastName: usersTable.lastName,
            username: usersTable.username,
            membershipType: usersTable.membershipType,
            membershipStatus: usersTable.membershipStatus,
            userRole: usersTable.userRole,
            isEmailVerified: usersTable.isEmailVerified,
            city: usersTable.city,
            province: usersTable.province,
            investorCategory: usersTable.investorCategory,
            kycStatus: usersTable.kycStatus,
            kycSubmittedAt: usersTable.kycSubmittedAt,
            createdAt: usersTable.createdAt
          }).from(usersTable).where(whereClause).orderBy(desc(usersTable.createdAt)).limit(limit).offset(offset),
          db.select({ count: count() }).from(usersTable).where(whereClause)
        ]);
        return res.json({ members, total: Number(totalRow.count), page, limit });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.patch("/members/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        const schema = external_exports.object({
          membershipStatus: external_exports.enum(["PENDING", "ACTIVE", "SUSPENDED", "EXPIRED", "CANCELLED"]).optional(),
          userRole: external_exports.enum(["MEMBER", "ADMIN", "SUPER_ADMIN"]).optional()
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success)
          return res.status(400).json({ errors: parsed.error.flatten() });
        const updates = {};
        if (parsed.data.membershipStatus)
          updates.membershipStatus = parsed.data.membershipStatus;
        if (parsed.data.userRole) updates.userRole = parsed.data.userRole;
        const [updated] = await db.update(usersTable).set(updates).where(eq(usersTable.id, id)).returning();
        if (!updated) return res.status(404).json({ message: "Member not found." });
        if (parsed.data.membershipStatus === "ACTIVE") {
          ensureActiveOnboardingEnrollmentForUser(id).catch(() => {
          });
        }
        return res.json({ member: updated });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.patch("/members/:id/kyc", async (req, res) => {
      try {
        const id = Number(req.params.id);
        const adminUser = req.admin;
        const schema = external_exports.object({
          status: external_exports.enum(["APPROVED", "REJECTED"]),
          rejectionReason: external_exports.string().trim().max(500).optional().nullable()
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success) {
          return res.status(400).json({ errors: parsed.error.flatten() });
        }
        const now = /* @__PURE__ */ new Date();
        const updates = {
          kycStatus: parsed.data.status,
          kycReviewedAt: now,
          kycReviewedByUserId: adminUser?.id ?? null,
          kycRejectionReason: parsed.data.status === "REJECTED" ? parsed.data.rejectionReason ?? "Rejected" : null,
          updatedAt: now
        };
        const [updated] = await db.update(usersTable).set(updates).where(eq(usersTable.id, id)).returning();
        if (!updated) {
          return res.status(404).json({ message: "Member not found." });
        }
        publishLiveEventToUser(id, {
          kind: "DATA_CHANGED",
          scopes: ["profile"],
          payload: { action: "kyc_reviewed" }
        });
        return res.json({ member: updated });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/organizations", async (_req, res) => {
      try {
        const orgs = await db.select({
          id: organizationsTable.id,
          name: organizationsTable.name,
          type: organizationsTable.type,
          city: organizationsTable.city,
          province: organizationsTable.province,
          contactName: organizationsTable.contactName,
          website: organizationsTable.website,
          createdAt: organizationsTable.createdAt
        }).from(organizationsTable).orderBy(desc(organizationsTable.createdAt));
        const intakes = await db.select().from(organizationIntakesTable).orderBy(
          desc(organizationIntakesTable.updatedAt),
          desc(organizationIntakesTable.createdAt),
          desc(organizationIntakesTable.id)
        );
        const intakeMap = {};
        for (const intake of intakes) {
          if (!(intake.organizationId in intakeMap)) {
            intakeMap[intake.organizationId] = intake;
          }
        }
        const result = orgs.map((org) => ({
          ...org,
          intake: intakeMap[org.id] ?? null,
          intakes: intakes.filter((intake) => intake.organizationId === org.id),
          quoteCount: intakes.filter((intake) => intake.organizationId === org.id).length
        }));
        return res.json({ organizations: result, total: result.length });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.patch("/organizations/:orgId/intake", async (req, res) => {
      try {
        const orgId = Number(req.params.orgId);
        const schema = external_exports.object({
          intakeId: external_exports.number().int().positive().optional(),
          status: external_exports.enum([
            "PENDING",
            "IN_REVIEW",
            "QUOTED",
            "ACCEPTED",
            "COMPLETED",
            "CANCELLED"
          ]).optional(),
          quoteAmount: optionalOrganizationQuoteAmount,
          quoteNote: external_exports.string().optional(),
          quoteLink: external_exports.preprocess((value) => {
            if (value == null) return void 0;
            if (typeof value !== "string") return value;
            const trimmed = value.trim();
            return trimmed.length ? trimmed : void 0;
          }, external_exports.string().optional())
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success)
          return res.status(400).json({ errors: parsed.error.flatten() });
        const { intakeId: _intakeId, ...updateData } = parsed.data;
        const intakeTargetId = parsed.data.intakeId;
        const [targetIntake] = typeof intakeTargetId === "number" ? await db.select({ id: organizationIntakesTable.id }).from(organizationIntakesTable).where(
          and(
            eq(organizationIntakesTable.id, intakeTargetId),
            eq(organizationIntakesTable.organizationId, orgId)
          )
        ).limit(1) : await db.select({ id: organizationIntakesTable.id }).from(organizationIntakesTable).where(eq(organizationIntakesTable.organizationId, orgId)).orderBy(
          desc(organizationIntakesTable.updatedAt),
          desc(organizationIntakesTable.createdAt),
          desc(organizationIntakesTable.id)
        ).limit(1);
        if (!targetIntake)
          return res.status(404).json({ message: "Intake not found." });
        const [updated] = await db.update(organizationIntakesTable).set({
          ...updateData,
          reviewedByAdminId: req.admin.id,
          reviewedAt: /* @__PURE__ */ new Date()
        }).where(eq(organizationIntakesTable.id, targetIntake.id)).returning();
        if (!updated) return res.status(404).json({ message: "Intake not found." });
        return res.json({ intake: updated });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/investors", async (_req, res) => {
      try {
        const investors = await db.select({
          id: usersTable.id,
          email: usersTable.email,
          firstName: usersTable.firstName,
          lastName: usersTable.lastName,
          membershipStatus: usersTable.membershipStatus,
          investorCategory: usersTable.investorCategory,
          city: usersTable.city,
          province: usersTable.province,
          createdAt: usersTable.createdAt
        }).from(usersTable).where(eq(usersTable.membershipType, "INVESTOR")).orderBy(desc(usersTable.createdAt));
        return res.json({ investors, total: investors.length });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    communityNullableSafeUrl = external_exports.preprocess(
      (value) => {
        if (value == null) return null;
        if (typeof value !== "string") return value;
        const trimmed = value.trim();
        return trimmed.length === 0 ? null : trimmed;
      },
      external_exports.union([
        external_exports.string().trim().min(1).refine((value) => {
          if (value.startsWith("/")) return true;
          try {
            const url2 = new URL(value);
            return url2.protocol === "http:" || url2.protocol === "https:";
          } catch {
            return false;
          }
        }),
        external_exports.null()
      ])
    );
    optionalOrganizationQuoteAmount = external_exports.preprocess(
      (value) => {
        if (value == null) return void 0;
        if (typeof value !== "string") return value;
        const trimmed = value.trim();
        if (!trimmed) return void 0;
        const normalized = trimmed.replace(/[$,\s]/g, "");
        return normalized.length ? normalized : void 0;
      },
      external_exports.string().regex(/^\d+(\.\d{1,2})?$/).optional()
    );
    router3.get("/community/announcements", async (_req, res) => {
      try {
        const announcements = await db.select().from(announcementsTable).orderBy(desc(announcementsTable.publishedAt));
        return res.json({ announcements, total: announcements.length });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/community/announcements", async (req, res) => {
      try {
        const schema = external_exports.object({
          title: external_exports.string().min(1),
          body: external_exports.string().min(1),
          category: external_exports.string().min(1),
          pinned: external_exports.boolean().default(false)
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success) {
          return res.status(400).json({ errors: parsed.error.flatten() });
        }
        const now = /* @__PURE__ */ new Date();
        const [announcement] = await db.insert(announcementsTable).values({
          ...parsed.data,
          publishedBy: req.admin.id,
          publishedAt: now,
          updatedAt: now
        }).returning();
        return res.status(201).json({ announcement });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.patch("/community/announcements/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        if (!Number.isFinite(id) || id <= 0) {
          return res.status(400).json({ message: "Invalid announcement id." });
        }
        const schema = external_exports.object({
          title: external_exports.string().min(1).optional(),
          body: external_exports.string().min(1).optional(),
          category: external_exports.string().min(1).optional(),
          pinned: external_exports.boolean().optional()
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success) {
          return res.status(400).json({ errors: parsed.error.flatten() });
        }
        const [announcement] = await db.update(announcementsTable).set({ ...parsed.data, updatedAt: /* @__PURE__ */ new Date() }).where(eq(announcementsTable.id, id)).returning();
        if (!announcement) {
          return res.status(404).json({ message: "Announcement not found." });
        }
        return res.json({ announcement });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.delete("/community/announcements/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        if (!Number.isFinite(id) || id <= 0) {
          return res.status(400).json({ message: "Invalid announcement id." });
        }
        await db.delete(announcementsTable).where(eq(announcementsTable.id, id));
        return res.json({ message: "Announcement deleted." });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/community/events", async (_req, res) => {
      try {
        const [events, rsvpCounts] = await Promise.all([
          db.select().from(communityEventsTable).orderBy(asc(communityEventsTable.date)),
          db.select({
            eventId: eventRsvpsTable.eventId,
            goingCount: count(eventRsvpsTable.id)
          }).from(eventRsvpsTable).where(eq(eventRsvpsTable.status, "GOING")).groupBy(eventRsvpsTable.eventId)
        ]);
        const goingCountByEventId = new Map(
          rsvpCounts.map((row) => [row.eventId, Number(row.goingCount ?? 0)])
        );
        return res.json({
          events: events.map((event) => ({
            ...event,
            goingCount: goingCountByEventId.get(event.id) ?? 0
          })),
          total: events.length
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/community/events/:id/rsvps", async (req, res) => {
      try {
        const eventId = Number(req.params.id);
        if (!Number.isFinite(eventId) || eventId <= 0) {
          return res.status(400).json({ message: "Invalid event id." });
        }
        const [event] = await db.select({
          id: communityEventsTable.id,
          title: communityEventsTable.title
        }).from(communityEventsTable).where(eq(communityEventsTable.id, eventId));
        if (!event) {
          return res.status(404).json({ message: "Event not found." });
        }
        const rsvps = await db.select({
          id: eventRsvpsTable.id,
          status: eventRsvpsTable.status,
          createdAt: eventRsvpsTable.createdAt,
          userId: usersTable.id,
          email: usersTable.email,
          firstName: usersTable.firstName,
          lastName: usersTable.lastName
        }).from(eventRsvpsTable).innerJoin(usersTable, eq(eventRsvpsTable.userId, usersTable.id)).where(eq(eventRsvpsTable.eventId, eventId)).orderBy(desc(eventRsvpsTable.createdAt));
        return res.json({
          event,
          rsvps: rsvps.map((row) => ({
            id: row.id,
            status: String(row.status),
            createdAt: row.createdAt,
            user: {
              id: row.userId,
              email: row.email,
              firstName: row.firstName,
              lastName: row.lastName
            }
          })),
          total: rsvps.length
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/community/events", async (req, res) => {
      try {
        const schema = external_exports.object({
          title: external_exports.string().min(1),
          description: external_exports.string().min(1),
          date: external_exports.string().min(1),
          startTime: external_exports.string().min(1),
          endTime: external_exports.string().min(1).nullable().optional(),
          location: external_exports.string().min(1),
          type: external_exports.enum(["VIRTUAL", "IN_PERSON", "HYBRID"]).default("VIRTUAL"),
          maxAttendees: external_exports.number().int().positive().nullable().optional(),
          coverImageUrl: communityNullableSafeUrl.optional()
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success) {
          return res.status(400).json({ errors: parsed.error.flatten() });
        }
        const parsedDate = new Date(parsed.data.date);
        if (Number.isNaN(parsedDate.getTime())) {
          return res.status(400).json({ message: "Invalid event date." });
        }
        const now = /* @__PURE__ */ new Date();
        const [event] = await db.insert(communityEventsTable).values({
          title: parsed.data.title,
          description: parsed.data.description,
          date: parsedDate,
          startTime: parsed.data.startTime,
          endTime: parsed.data.endTime ?? null,
          location: parsed.data.location,
          type: parsed.data.type,
          maxAttendees: parsed.data.maxAttendees ?? null,
          organizerId: req.admin.id,
          coverImageUrl: parsed.data.coverImageUrl ?? null,
          updatedAt: now
        }).returning();
        return res.status(201).json({ event });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.patch("/community/events/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        if (!Number.isFinite(id) || id <= 0) {
          return res.status(400).json({ message: "Invalid event id." });
        }
        const schema = external_exports.object({
          title: external_exports.string().min(1).optional(),
          description: external_exports.string().min(1).optional(),
          date: external_exports.string().min(1).optional(),
          startTime: external_exports.string().min(1).optional(),
          endTime: external_exports.string().min(1).nullable().optional(),
          location: external_exports.string().min(1).optional(),
          type: external_exports.enum(["VIRTUAL", "IN_PERSON", "HYBRID"]).optional(),
          maxAttendees: external_exports.number().int().positive().nullable().optional(),
          coverImageUrl: communityNullableSafeUrl.optional()
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success) {
          return res.status(400).json({ errors: parsed.error.flatten() });
        }
        const updates = {
          ...parsed.data,
          updatedAt: /* @__PURE__ */ new Date()
        };
        if (typeof parsed.data.date === "string") {
          const parsedDate = new Date(parsed.data.date);
          if (Number.isNaN(parsedDate.getTime())) {
            return res.status(400).json({ message: "Invalid event date." });
          }
          updates.date = parsedDate;
        }
        const [event] = await db.update(communityEventsTable).set(updates).where(eq(communityEventsTable.id, id)).returning();
        if (!event) {
          return res.status(404).json({ message: "Event not found." });
        }
        return res.json({ event });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.delete("/community/events/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        if (!Number.isFinite(id) || id <= 0) {
          return res.status(400).json({ message: "Invalid event id." });
        }
        await db.delete(communityEventsTable).where(eq(communityEventsTable.id, id));
        return res.json({ message: "Event deleted." });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    RESOURCE_SLUG_REGEX = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
    resourceSafeUrl = external_exports.string().trim().min(1).refine((value) => {
      if (value.startsWith("/")) return true;
      try {
        const url2 = new URL(value);
        return url2.protocol === "http:" || url2.protocol === "https:";
      } catch {
        return false;
      }
    });
    optionalResourceUrl = external_exports.preprocess((value) => {
      if (value == null) return void 0;
      if (typeof value !== "string") return value;
      const trimmed = value.trim();
      return trimmed === "" ? void 0 : trimmed;
    }, resourceSafeUrl.optional());
    optionalResourceText = external_exports.preprocess((value) => {
      if (value == null) return void 0;
      if (typeof value !== "string") return value;
      const trimmed = value.trim();
      return trimmed === "" ? void 0 : trimmed;
    }, external_exports.string().optional());
    createResourceSchema = external_exports.object({
      title: external_exports.string().trim().min(1),
      slug: external_exports.string().trim().regex(RESOURCE_SLUG_REGEX),
      description: optionalResourceText,
      resourceKind: external_exports.enum(["FILE", "ARTICLE"]).default("FILE"),
      categoryId: external_exports.number().int().positive(),
      fileUrl: optionalResourceUrl,
      fileType: external_exports.enum([
        "PDF",
        "VIDEO",
        "DOCUMENT",
        "SPREADSHEET",
        "IMAGE",
        "LINK",
        "OTHER"
      ]).default("PDF"),
      fileSize: external_exports.number().optional(),
      coverImageUrl: optionalResourceUrl,
      authorName: optionalResourceText,
      contentHtml: optionalResourceText,
      showToIndividuals: external_exports.boolean().default(false),
      showToInvestors: external_exports.boolean().default(true),
      showToOrganizations: external_exports.boolean().default(true),
      isPublished: external_exports.boolean().default(false)
    }).superRefine((data, ctx) => {
      if (!data.showToIndividuals && !data.showToInvestors && !data.showToOrganizations) {
        ctx.addIssue({
          code: external_exports.ZodIssueCode.custom,
          message: "Select at least one audience.",
          path: ["showToIndividuals"]
        });
      }
      if (data.resourceKind === "ARTICLE") {
        if (!data.contentHtml) {
          ctx.addIssue({
            code: external_exports.ZodIssueCode.custom,
            message: "Article content is required.",
            path: ["contentHtml"]
          });
        }
        return;
      }
      if (!data.fileUrl) {
        ctx.addIssue({
          code: external_exports.ZodIssueCode.custom,
          message: "File URL is required for file resources.",
          path: ["fileUrl"]
        });
      }
    });
    updateResourceSchema = external_exports.object({
      title: external_exports.string().trim().min(1).optional(),
      slug: external_exports.string().trim().regex(RESOURCE_SLUG_REGEX).optional(),
      description: optionalResourceText,
      resourceKind: external_exports.enum(["FILE", "ARTICLE"]).optional(),
      categoryId: external_exports.number().int().positive().optional(),
      fileUrl: optionalResourceUrl,
      fileType: external_exports.enum(["PDF", "VIDEO", "DOCUMENT", "SPREADSHEET", "IMAGE", "LINK", "OTHER"]).optional(),
      fileSize: external_exports.number().optional(),
      coverImageUrl: optionalResourceUrl,
      authorName: optionalResourceText,
      contentHtml: optionalResourceText,
      showToIndividuals: external_exports.boolean().optional(),
      showToInvestors: external_exports.boolean().optional(),
      showToOrganizations: external_exports.boolean().optional(),
      isPublished: external_exports.boolean().optional()
    });
    router3.get("/resources", async (_req, res) => {
      try {
        const resources = await db.select().from(resourcesTable).orderBy(desc(resourcesTable.createdAt));
        const categories = await db.select().from(resourceCategoriesTable).orderBy(resourceCategoriesTable.sortOrder);
        return res.json({ resources, categories });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/resources/categories", async (_req, res) => {
      try {
        const categories = await db.select().from(resourceCategoriesTable).orderBy(resourceCategoriesTable.sortOrder);
        return res.json({ categories });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/resources/categories", async (req, res) => {
      try {
        const schema = external_exports.object({
          name: external_exports.string().min(1),
          slug: external_exports.string().regex(RESOURCE_SLUG_REGEX),
          sortOrder: external_exports.number().int().min(0).default(0)
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success)
          return res.status(400).json({ errors: parsed.error.flatten() });
        try {
          const [category] = await db.insert(resourceCategoriesTable).values(parsed.data).returning();
          return res.status(201).json({ category });
        } catch (err) {
          if (isUniqueViolation5(err)) {
            return res.status(409).json({
              message: "A category with that name or slug already exists."
            });
          }
          throw err;
        }
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.patch("/resources/categories/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        const schema = external_exports.object({
          name: external_exports.string().min(1).optional(),
          slug: external_exports.string().regex(RESOURCE_SLUG_REGEX).optional(),
          sortOrder: external_exports.number().int().min(0).optional()
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success)
          return res.status(400).json({ errors: parsed.error.flatten() });
        try {
          const [updated] = await db.update(resourceCategoriesTable).set(parsed.data).where(eq(resourceCategoriesTable.id, id)).returning();
          if (!updated)
            return res.status(404).json({ message: "Category not found." });
          return res.json({ category: updated });
        } catch (err) {
          if (isUniqueViolation5(err)) {
            return res.status(409).json({
              message: "A category with that name or slug already exists."
            });
          }
          throw err;
        }
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.delete("/resources/categories/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        await db.delete(resourceCategoriesTable).where(eq(resourceCategoriesTable.id, id));
        return res.json({ message: "Category deleted." });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/resources", async (req, res) => {
      try {
        const parsed = createResourceSchema.safeParse(req.body);
        if (!parsed.success)
          return res.status(400).json({ errors: parsed.error.flatten() });
        try {
          const [resource] = await db.insert(resourcesTable).values({
            ...parsed.data,
            fileUrl: parsed.data.resourceKind === "ARTICLE" ? null : parsed.data.fileUrl ?? null,
            fileType: parsed.data.resourceKind === "ARTICLE" ? "OTHER" : parsed.data.fileType,
            contentHtml: parsed.data.resourceKind === "ARTICLE" ? parsed.data.contentHtml ?? null : null,
            uploadedById: req.admin.id,
            publishedAt: parsed.data.isPublished ? /* @__PURE__ */ new Date() : null,
            updatedAt: /* @__PURE__ */ new Date()
          }).returning();
          return res.status(201).json({ resource });
        } catch (err) {
          if (isUniqueViolation5(err)) {
            return res.status(409).json({
              message: "A resource with that slug already exists."
            });
          }
          throw err;
        }
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.patch("/resources/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        const parsed = updateResourceSchema.safeParse(req.body);
        if (!parsed.success)
          return res.status(400).json({ errors: parsed.error.flatten() });
        const [existing] = await db.select().from(resourcesTable).where(eq(resourcesTable.id, id)).limit(1);
        if (!existing)
          return res.status(404).json({ message: "Resource not found." });
        const nextResourceKind = parsed.data.resourceKind ?? existing.resourceKind;
        const nextFileUrl = parsed.data.fileUrl !== void 0 ? parsed.data.fileUrl : existing.fileUrl;
        const nextContentHtml = parsed.data.contentHtml !== void 0 ? parsed.data.contentHtml : existing.contentHtml;
        const nextShowToIndividuals = parsed.data.showToIndividuals ?? existing.showToIndividuals;
        const nextShowToInvestors = parsed.data.showToInvestors ?? existing.showToInvestors;
        const nextShowToOrganizations = parsed.data.showToOrganizations ?? existing.showToOrganizations;
        if (!nextShowToIndividuals && !nextShowToInvestors && !nextShowToOrganizations) {
          return res.status(400).json({
            message: "Select at least one audience."
          });
        }
        if (nextResourceKind === "ARTICLE" && !nextContentHtml) {
          return res.status(400).json({
            message: "Article content is required."
          });
        }
        if (nextResourceKind === "FILE" && !nextFileUrl) {
          return res.status(400).json({
            message: "File URL is required for file resources."
          });
        }
        const updates = {
          ...parsed.data,
          fileUrl: nextResourceKind === "ARTICLE" ? null : nextFileUrl ?? null,
          fileType: nextResourceKind === "ARTICLE" ? "OTHER" : parsed.data.fileType ?? existing.fileType,
          contentHtml: nextResourceKind === "ARTICLE" ? nextContentHtml ?? null : null
        };
        if (parsed.data.isPublished === true) updates.publishedAt = /* @__PURE__ */ new Date();
        if (parsed.data.isPublished === false) updates.publishedAt = null;
        updates.updatedAt = /* @__PURE__ */ new Date();
        try {
          const [updated] = await db.update(resourcesTable).set(updates).where(eq(resourcesTable.id, id)).returning();
          if (!updated)
            return res.status(404).json({ message: "Resource not found." });
          return res.json({ resource: updated });
        } catch (err) {
          if (isUniqueViolation5(err)) {
            return res.status(409).json({
              message: "A resource with that slug already exists."
            });
          }
          throw err;
        }
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.delete("/resources/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        await db.delete(resourcesTable).where(eq(resourcesTable.id, id));
        return res.json({ message: "Resource deleted." });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    ACADEMY_SLUG_REGEX = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
    academyHttpUrl = external_exports.string().url().refine((value) => {
      const url2 = new URL(value);
      return url2.protocol === "http:" || url2.protocol === "https:";
    });
    academyNullableHttpUrl = external_exports.preprocess(
      (value) => {
        if (value == null) return null;
        if (typeof value !== "string") return value;
        const trimmed = value.trim();
        return trimmed.length === 0 ? null : trimmed;
      },
      external_exports.union([academyHttpUrl, external_exports.null()])
    );
    router3.get("/academy/categories", async (_req, res) => {
      try {
        const categories = await db.select().from(academyCategoriesTable).orderBy(academyCategoriesTable.sortOrder);
        return res.json({ categories });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/academy/categories", async (req, res) => {
      try {
        const schema = external_exports.object({
          name: external_exports.string().min(1),
          slug: external_exports.string().regex(ACADEMY_SLUG_REGEX),
          sortOrder: external_exports.number().int().min(0).default(0)
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success)
          return res.status(400).json({ errors: parsed.error.flatten() });
        try {
          const [category] = await db.insert(academyCategoriesTable).values(parsed.data).returning();
          return res.status(201).json({ category });
        } catch (err) {
          if (isUniqueViolation5(err)) {
            return res.status(409).json({
              message: "A category with that name or slug already exists."
            });
          }
          throw err;
        }
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.patch("/academy/categories/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        const schema = external_exports.object({
          name: external_exports.string().min(1).optional(),
          slug: external_exports.string().regex(ACADEMY_SLUG_REGEX).optional(),
          sortOrder: external_exports.number().int().min(0).optional()
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success)
          return res.status(400).json({ errors: parsed.error.flatten() });
        try {
          const [updated] = await db.update(academyCategoriesTable).set(parsed.data).where(eq(academyCategoriesTable.id, id)).returning();
          if (!updated)
            return res.status(404).json({ message: "Category not found." });
          return res.json({ category: updated });
        } catch (err) {
          if (isUniqueViolation5(err)) {
            return res.status(409).json({
              message: "A category with that name or slug already exists."
            });
          }
          throw err;
        }
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.delete("/academy/categories/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        await db.delete(academyCategoriesTable).where(eq(academyCategoriesTable.id, id));
        return res.json({ message: "Category deleted." });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/academy/courses", async (_req, res) => {
      try {
        const courses = await db.select().from(academyCoursesTable).orderBy(desc(academyCoursesTable.createdAt));
        const categories = await db.select().from(academyCategoriesTable).orderBy(academyCategoriesTable.sortOrder);
        return res.json({ courses, categories });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/academy/courses", async (req, res) => {
      try {
        const schema = external_exports.object({
          title: external_exports.string().min(1),
          slug: external_exports.string().regex(ACADEMY_SLUG_REGEX),
          description: external_exports.string().min(1),
          categoryId: external_exports.number().int().positive(),
          instructor: external_exports.string().min(1),
          duration: external_exports.string().min(1),
          level: external_exports.string().min(1),
          externalUrl: academyHttpUrl,
          thumbnailUrl: academyNullableHttpUrl,
          isPublished: external_exports.boolean().default(true),
          sortOrder: external_exports.number().default(0),
          tags: external_exports.array(external_exports.string()).default([])
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success)
          return res.status(400).json({ errors: parsed.error.flatten() });
        try {
          const [course] = await db.insert(academyCoursesTable).values(parsed.data).returning();
          return res.status(201).json({ course });
        } catch (err) {
          if (isUniqueViolation5(err)) {
            return res.status(409).json({
              message: "A course with that slug already exists."
            });
          }
          throw err;
        }
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.patch("/academy/courses/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        const schema = external_exports.object({
          title: external_exports.string().min(1).optional(),
          slug: external_exports.string().regex(ACADEMY_SLUG_REGEX).optional(),
          description: external_exports.string().optional(),
          categoryId: external_exports.number().optional(),
          instructor: external_exports.string().optional(),
          duration: external_exports.string().optional(),
          level: external_exports.string().optional(),
          externalUrl: academyHttpUrl.optional(),
          thumbnailUrl: academyNullableHttpUrl.optional(),
          isPublished: external_exports.boolean().optional(),
          sortOrder: external_exports.number().optional(),
          tags: external_exports.array(external_exports.string()).optional()
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success)
          return res.status(400).json({ errors: parsed.error.flatten() });
        try {
          const [updated] = await db.update(academyCoursesTable).set({ ...parsed.data, updatedAt: /* @__PURE__ */ new Date() }).where(eq(academyCoursesTable.id, id)).returning();
          if (!updated)
            return res.status(404).json({ message: "Course not found." });
          return res.json({ course: updated });
        } catch (err) {
          if (isUniqueViolation5(err)) {
            return res.status(409).json({
              message: "A course with that slug already exists."
            });
          }
          throw err;
        }
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.delete("/academy/courses/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        await db.delete(academyCoursesTable).where(eq(academyCoursesTable.id, id));
        return res.json({ message: "Course deleted." });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/susu/circles", async (_req, res) => {
      try {
        const circles = await db.select().from(savingsCirclesTable).orderBy(desc(savingsCirclesTable.createdAt));
        const memberCounts = await db.select({ circleId: circleMembershipsTable.circleId, count: count() }).from(circleMembershipsTable).groupBy(circleMembershipsTable.circleId);
        const countMap = {};
        for (const row of memberCounts) countMap[row.circleId] = Number(row.count);
        return res.json({
          circles: circles.map((c) => ({
            ...c,
            status: getCircleRuntimeStatus({
              status: c.status,
              startDate: c.startDate
            }),
            endDate: null,
            memberCount: countMap[c.id] ?? 0
          }))
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/susu/circles", async (req, res) => {
      try {
        const schema = external_exports.object({
          name: external_exports.string().min(1),
          description: external_exports.string().optional(),
          termsHtml: external_exports.string().optional().nullable(),
          contributionAmount: external_exports.string().min(1),
          helpingHandMultiplier: external_exports.string().optional(),
          frequency: external_exports.enum(["WEEKLY", "BIWEEKLY", "MONTHLY"]).default("MONTHLY"),
          maxMembers: external_exports.number().int().min(2),
          startDate: external_exports.string().optional(),
          formingTimeoutDays: external_exports.number().int().min(1).default(14),
          isFreeToJoin: external_exports.boolean().default(false)
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success)
          return res.status(400).json({ errors: parsed.error.flatten() });
        const adminId = req.admin.id;
        const normalizedTermsHtml = typeof parsed.data.termsHtml === "string" && parsed.data.termsHtml.trim().length > 0 ? parsed.data.termsHtml.trim() : null;
        const numericAmount = Number(parsed.data.contributionAmount);
        if (!Number.isFinite(numericAmount) || numericAmount <= 0) {
          return res.status(400).json({ message: "Invalid contribution amount." });
        }
        const numericHelpingHandMultiplier = parsed.data.helpingHandMultiplier === void 0 || parsed.data.helpingHandMultiplier.trim() === "" ? null : Number(parsed.data.helpingHandMultiplier);
        if (numericHelpingHandMultiplier !== null && (!Number.isFinite(numericHelpingHandMultiplier) || numericHelpingHandMultiplier <= 0)) {
          return res.status(400).json({ message: "Invalid Matching Fund multiplier." });
        }
        const result = await db.transaction(async (tx) => {
          const adminWallet = await ensureWalletWith5(tx, "USER", adminId);
          const availableBalance = await getWalletAvailableBalanceWith(
            tx,
            adminWallet.id
          );
          if (!parsed.data.isFreeToJoin && availableBalance < numericAmount) {
            return {
              status: 400,
              body: { message: "Fund your wallet to create a circle." }
            };
          }
          const baseStartDate = parsed.data.startDate ? new Date(parsed.data.startDate) : null;
          const startDate = getNextCircleDueDate({
            anchorDate: baseStartDate,
            frequency: parsed.data.frequency
          });
          const [circle] = await tx.insert(savingsCirclesTable).values({
            name: parsed.data.name,
            description: parsed.data.description,
            termsHtml: normalizedTermsHtml,
            contributionAmount: parsed.data.contributionAmount,
            helpingHandMultiplier: numericHelpingHandMultiplier !== null ? String(numericHelpingHandMultiplier) : null,
            frequency: parsed.data.frequency,
            maxMembers: parsed.data.maxMembers,
            formingTimeoutDays: parsed.data.formingTimeoutDays,
            isFreeToJoin: parsed.data.isFreeToJoin,
            status: "FORMING",
            startDate,
            endDate: null,
            createdByAdminId: adminId
          }).returning();
          await tx.insert(circleMembershipsTable).values({
            circleId: circle.id,
            userId: adminId,
            position: 1
          });
          if (!parsed.data.isFreeToJoin) {
            const susuWallet = await ensureSusuWalletWith(tx);
            const [walletTx] = await tx.insert(walletTransactionsTable).values({
              type: "CONTRIBUTION",
              idempotencyKey: `susu:circle-create:${circle.id}:${adminId}:first_contribution`,
              fromWalletId: adminWallet.id,
              toWalletId: susuWallet.id,
              amount: formatMoneyAmount(numericAmount),
              metadata: {
                source: "susu_admin_create_first_contribution",
                circleId: circle.id,
                userId: adminId,
                position: 1,
                dueDate: startDate.toISOString()
              }
            }).returning({ id: walletTransactionsTable.id });
            await tx.insert(savingsContributionsTable).values({
              circleId: circle.id,
              userId: adminId,
              dueDate: startDate,
              paidAt: /* @__PURE__ */ new Date(),
              amount: formatMoneyAmount(numericAmount),
              status: "PAID",
              method: "WALLET",
              receiptRef: `wallet_tx:${walletTx.id}`
            });
          }
          return {
            status: 201,
            body: {
              circle: {
                ...circle,
                memberCount: 1
              }
            }
          };
        });
        return res.status(result.status).json(result.body);
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/susu/circles/:id/schedule", async (req, res) => {
      try {
        const circleId = Number(req.params.id);
        if (!circleId)
          return res.status(400).json({ message: "Invalid circle id." });
        const [circle] = await db.select().from(savingsCirclesTable).where(eq(savingsCirclesTable.id, circleId));
        if (!circle) return res.status(404).json({ message: "Circle not found." });
        await generateCircleSchedule(circleId);
        return res.json({ ok: true });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/wallet", async (req, res) => {
      try {
        const adminId = req.admin.id;
        const wallet = await ensureWallet("USER", adminId);
        const now = /* @__PURE__ */ new Date();
        const [balance, reservedBalance, availableBalance, transactions] = await Promise.all([
          getWalletBalance(wallet.id),
          getWalletReservedBalanceWith(db, wallet.id),
          getWalletAvailableBalanceWith(db, wallet.id),
          getWalletTransactions(wallet.id)
        ]);
        const [overdueSusuDeductions] = await db.select({
          count: count(),
          total: sum(savingsContributionsTable.amount)
        }).from(savingsContributionsTable).innerJoin(
          savingsCirclesTable,
          eq(savingsContributionsTable.circleId, savingsCirclesTable.id)
        ).where(
          and(
            eq(savingsContributionsTable.userId, adminId),
            eq(savingsContributionsTable.status, "PENDING"),
            lte(savingsContributionsTable.dueDate, now),
            inArray(savingsCirclesTable.status, [
              "ACTIVE",
              "UPCOMING",
              "FORMING"
            ])
          )
        );
        return res.json({
          wallet: {
            id: wallet.id,
            ownerType: "USER",
            ownerId: adminId,
            currency: wallet.currency,
            balance,
            reservedBalance,
            availableBalance,
            overdueSusuDeductions: {
              count: Number(overdueSusuDeductions?.count ?? 0),
              total: Number(overdueSusuDeductions?.total ?? 0)
            },
            transactions
          }
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/wallets/catalog", async (_req, res) => {
      try {
        const [susuWallets, investmentWallets, poolWallets] = await Promise.all([
          buildSusuWalletCatalog(),
          buildInvestmentWalletCatalog(),
          buildLendingMasterWalletCatalog()
        ]);
        return res.json({
          susuWallets,
          investmentWallets,
          poolWallets
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/wallets/details", async (req, res) => {
      try {
        const parsed = external_exports.object({
          ownerType: external_exports.enum([
            "USER",
            "SUSU",
            "INVESTMENT",
            "LENDING_MASTER",
            "LENDING_POOL",
            "PLATFORM"
          ]),
          ownerId: external_exports.coerce.number().int().positive()
        }).safeParse(req.query);
        if (!parsed.success) {
          return res.status(400).json({ errors: parsed.error.flatten() });
        }
        const descriptor = await getWalletOwnerDescriptor(
          parsed.data.ownerType,
          parsed.data.ownerId
        );
        if (!descriptor) {
          return res.status(404).json({ message: "Wallet owner not found." });
        }
        const wallet = await ensureWallet(
          parsed.data.ownerType,
          parsed.data.ownerId
        );
        const [balance, reservedBalance, transactions] = await Promise.all([
          getWalletBalance(wallet.id),
          parsed.data.ownerType === "USER" ? getWalletReservedBalanceWith(db, wallet.id) : parsed.data.ownerType === "LENDING_MASTER" ? getReservedMasterAmountWith(db) : Promise.resolve(0),
          getWalletTransactions(wallet.id)
        ]);
        const availableBalance = parsed.data.ownerType === "USER" ? await getWalletAvailableBalanceWith(db, wallet.id) : parsed.data.ownerType === "LENDING_MASTER" ? calculateAvailableToLend(balance, reservedBalance) : balance;
        return res.json({
          wallet: {
            id: wallet.id,
            ownerType: parsed.data.ownerType,
            ownerId: parsed.data.ownerId,
            label: descriptor.label,
            subtitle: descriptor.subtitle,
            currency: wallet.currency,
            balance,
            reservedBalance,
            availableBalance,
            transactions
          }
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/susu/circles/:id/wallet", async (req, res) => {
      try {
        const circleId = Number(req.params.id);
        if (!circleId)
          return res.status(400).json({ message: "Invalid circle id." });
        const [summary, transactions] = await Promise.all([
          getCircleAllocationSummary(circleId),
          getCircleAllocationTransactions(circleId)
        ]);
        if (!summary) {
          return res.status(404).json({ message: "Circle not found." });
        }
        return res.json({
          wallet: {
            id: summary.susuWallet.id,
            ownerType: summary.ownerType,
            ownerId: summary.ownerId,
            isDedicatedWallet: summary.isDedicatedWallet,
            currency: summary.susuWallet.currency,
            balance: summary.allocationBalance,
            treasuryBalance: summary.treasuryBalance,
            transactions
          }
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/susu/circles/:id/reconcile", async (req, res) => {
      try {
        const circleId = Number(req.params.id);
        if (!circleId)
          return res.status(400).json({ message: "Invalid circle id." });
        const [summary, contributionStats, payoutStats] = await Promise.all([
          getCircleAllocationSummary(circleId),
          db.select({
            status: savingsContributionsTable.status,
            count: count(),
            total: sum(savingsContributionsTable.amount)
          }).from(savingsContributionsTable).where(eq(savingsContributionsTable.circleId, circleId)).groupBy(savingsContributionsTable.status),
          db.select({
            status: circlePayoutsTable.status,
            count: count(),
            total: sum(circlePayoutsTable.amount)
          }).from(circlePayoutsTable).where(eq(circlePayoutsTable.circleId, circleId)).groupBy(circlePayoutsTable.status)
        ]);
        if (!summary) {
          return res.status(404).json({ message: "Circle not found." });
        }
        return res.json({
          circleId,
          wallet: {
            id: summary.susuWallet.id,
            ownerType: summary.ownerType,
            ownerId: summary.ownerId,
            isDedicatedWallet: summary.isDedicatedWallet,
            balance: summary.allocationBalance,
            treasuryBalance: summary.treasuryBalance,
            totalIn: summary.totalIn,
            totalOut: summary.totalOut,
            net: summary.totalIn - summary.totalOut
          },
          contributions: contributionStats.map((r) => ({
            status: r.status,
            count: Number(r.count),
            total: Number(r.total ?? 0)
          })),
          payouts: payoutStats.map((r) => ({
            status: r.status,
            count: Number(r.count),
            total: Number(r.total ?? 0)
          }))
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/payments/webhooks", async (req, res) => {
      try {
        const status = req.query.status ? String(req.query.status) : void 0;
        const where = status && (status === "PENDING" || status === "PROCESSED" || status === "FAILED") ? eq(paymentWebhookEventsTable.status, status) : void 0;
        const rows = await db.select().from(paymentWebhookEventsTable).where(where).orderBy(desc(paymentWebhookEventsTable.receivedAt)).limit(100);
        return res.json({
          events: rows.map((e) => ({
            id: e.id,
            provider: e.provider,
            eventId: e.eventId,
            eventType: e.eventType,
            status: e.status,
            attempts: e.attempts,
            error: e.error ?? null,
            receivedAt: e.receivedAt.toISOString(),
            processedAt: e.processedAt?.toISOString() ?? null
          }))
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/payments/webhooks/:id/process", async (req, res) => {
      try {
        const id = Number(req.params.id);
        if (!id) return res.status(400).json({ message: "Invalid webhook id." });
        const result = await db.transaction(async (tx) => {
          const [event] = await tx.select().from(paymentWebhookEventsTable).where(eq(paymentWebhookEventsTable.id, id));
          if (!event)
            return { status: 404, body: { message: "Not found." } };
          if (event.status === "PROCESSED") {
            return {
              status: 200,
              body: {
                message: "Already processed.",
                event: {
                  id: event.id,
                  status: event.status,
                  processedAt: event.processedAt?.toISOString() ?? null
                }
              }
            };
          }
          await tx.update(paymentWebhookEventsTable).set({
            attempts: sql`${paymentWebhookEventsTable.attempts} + 1`
          }).where(eq(paymentWebhookEventsTable.id, id));
          const payload = event.payload;
          const eventType = String(event.eventType ?? "");
          const markFailed = async (message) => {
            await tx.update(paymentWebhookEventsTable).set({
              status: "FAILED",
              error: message,
              processedAt: /* @__PURE__ */ new Date()
            }).where(eq(paymentWebhookEventsTable.id, id));
            return { status: 400, body: { message } };
          };
          const markProcessed = async () => {
            await tx.update(paymentWebhookEventsTable).set({
              status: "PROCESSED",
              error: null,
              processedAt: /* @__PURE__ */ new Date()
            }).where(eq(paymentWebhookEventsTable.id, id));
          };
          if (eventType === "wallet.topup.succeeded") {
            const parsed = external_exports.object({
              data: external_exports.object({
                intentId: external_exports.number().int(),
                providerReference: external_exports.string().optional()
              })
            }).safeParse(payload);
            if (!parsed.success)
              return await markFailed("Invalid payload for topup succeeded.");
            const intentId = parsed.data.data.intentId;
            const [intent] = await tx.select().from(walletPaymentIntentsTable).where(eq(walletPaymentIntentsTable.id, intentId));
            if (!intent) return await markFailed("Unknown intentId.");
            const idempotencyKey = `webhook:${event.provider}:${event.eventId}`;
            const existingTx = await tx.select().from(walletTransactionsTable).where(eq(walletTransactionsTable.idempotencyKey, idempotencyKey));
            if (!existingTx.length) {
              try {
                await tx.insert(walletTransactionsTable).values({
                  type: "TOP_UP",
                  idempotencyKey,
                  toWalletId: intent.walletId,
                  amount: String(intent.amount),
                  metadata: {
                    provider: intent.provider,
                    providerReference: parsed.data.data.providerReference ?? null,
                    intentId: intent.id,
                    eventId: event.eventId
                  }
                });
              } catch (e) {
                if (!isUniqueViolation5(e)) throw e;
              }
            }
            await tx.update(walletPaymentIntentsTable).set({
              status: "SUCCEEDED",
              providerReference: parsed.data.data.providerReference ?? intent.providerReference,
              updatedAt: /* @__PURE__ */ new Date()
            }).where(eq(walletPaymentIntentsTable.id, intent.id));
            await markProcessed();
            return {
              status: 200,
              body: {
                message: "Processed.",
                intentId: intent.id
              }
            };
          }
          if (eventType === "wallet.topup.failed") {
            const parsed = external_exports.object({
              data: external_exports.object({
                intentId: external_exports.number().int(),
                error: external_exports.string().optional()
              })
            }).safeParse(payload);
            if (!parsed.success)
              return await markFailed("Invalid payload for topup failed.");
            const intentId = parsed.data.data.intentId;
            const [intent] = await tx.select().from(walletPaymentIntentsTable).where(eq(walletPaymentIntentsTable.id, intentId));
            if (!intent) return await markFailed("Unknown intentId.");
            await tx.update(walletPaymentIntentsTable).set({
              status: "FAILED",
              metadata: {
                ...intent.metadata ?? {},
                providerError: parsed.data.data.error ?? null,
                eventId: event.eventId
              },
              updatedAt: /* @__PURE__ */ new Date()
            }).where(eq(walletPaymentIntentsTable.id, intent.id));
            await markProcessed();
            return {
              status: 200,
              body: {
                message: "Processed.",
                intentId: intent.id
              }
            };
          }
          return await markFailed(`Unhandled eventType: ${eventType || "unknown"}`);
        });
        return res.status(result.status).json(result.body);
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/payments/intents", async (req, res) => {
      try {
        const status = req.query.status ? String(req.query.status) : void 0;
        const where = status && (status === "CREATED" || status === "PENDING" || status === "SUCCEEDED" || status === "FAILED" || status === "CANCELLED") ? eq(walletPaymentIntentsTable.status, status) : void 0;
        const rows = await db.select().from(walletPaymentIntentsTable).where(where).orderBy(desc(walletPaymentIntentsTable.createdAt)).limit(200);
        return res.json({
          intents: rows.map((i) => ({
            id: i.id,
            userId: i.userId,
            walletId: i.walletId,
            provider: i.provider,
            type: i.type,
            amount: Number(i.amount),
            currency: i.currency,
            status: i.status,
            providerReference: i.providerReference ?? null,
            createdAt: i.createdAt.toISOString(),
            updatedAt: i.updatedAt.toISOString()
          }))
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/wallets/topup-intents", async (req, res) => {
      try {
        const status = req.query.status ? String(req.query.status) : void 0;
        const parsedStatus = status && (status === "CREATED" || status === "PENDING" || status === "SUCCEEDED" || status === "FAILED" || status === "CANCELLED") ? status : void 0;
        const provider = req.query.provider ? String(req.query.provider) : void 0;
        const parsedProvider = provider && (provider === "MANUAL" || provider === "INTERAC") ? provider : void 0;
        const where = and(
          eq(walletPaymentIntentsTable.type, "TOP_UP"),
          inArray(walletPaymentIntentsTable.provider, ["MANUAL", "INTERAC"]),
          sql`coalesce(${walletPaymentIntentsTable.metadata}->>'source', '') != 'organization_member_wallet_funding'`,
          parsedProvider ? eq(walletPaymentIntentsTable.provider, parsedProvider) : void 0,
          parsedStatus ? eq(walletPaymentIntentsTable.status, parsedStatus) : void 0
        );
        const rows = await db.select({
          id: walletPaymentIntentsTable.id,
          userId: walletPaymentIntentsTable.userId,
          walletId: walletPaymentIntentsTable.walletId,
          provider: walletPaymentIntentsTable.provider,
          type: walletPaymentIntentsTable.type,
          amount: walletPaymentIntentsTable.amount,
          currency: walletPaymentIntentsTable.currency,
          status: walletPaymentIntentsTable.status,
          providerReference: walletPaymentIntentsTable.providerReference,
          metadata: walletPaymentIntentsTable.metadata,
          createdAt: walletPaymentIntentsTable.createdAt,
          updatedAt: walletPaymentIntentsTable.updatedAt,
          email: usersTable.email,
          firstName: usersTable.firstName,
          lastName: usersTable.lastName,
          membershipType: usersTable.membershipType,
          membershipStatus: usersTable.membershipStatus
        }).from(walletPaymentIntentsTable).innerJoin(
          usersTable,
          eq(walletPaymentIntentsTable.userId, usersTable.id)
        ).where(where).orderBy(desc(walletPaymentIntentsTable.createdAt)).limit(200);
        return res.json({
          intents: rows.map((i) => ({
            id: i.id,
            userId: i.userId,
            walletId: i.walletId,
            provider: i.provider,
            type: i.type,
            amount: Number(i.amount),
            currency: i.currency,
            status: i.status,
            providerReference: i.providerReference ?? null,
            metadata: i.metadata ?? {},
            createdAt: i.createdAt.toISOString(),
            updatedAt: i.updatedAt.toISOString(),
            user: {
              id: i.userId,
              email: i.email,
              firstName: i.firstName,
              lastName: i.lastName,
              membershipType: i.membershipType ?? null,
              membershipStatus: i.membershipStatus ?? null
            }
          }))
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/wallets/topup-intents/:id/approve", async (req, res) => {
      const adminId = req.admin.id;
      try {
        const id = Number(req.params.id);
        if (!id) return res.status(400).json({ message: "Invalid top-up id." });
        const result = await db.transaction(async (tx) => {
          const [intent] = await tx.select().from(walletPaymentIntentsTable).where(
            and(
              eq(walletPaymentIntentsTable.id, id),
              eq(walletPaymentIntentsTable.type, "TOP_UP")
            )
          ).limit(1);
          if (!intent)
            return { status: 404, body: { message: "Not found." } };
          if (intent.provider !== "MANUAL" && intent.provider !== "INTERAC") {
            return {
              status: 400,
              body: { message: "This top-up is not a bank deposit." }
            };
          }
          const metadata = intent.metadata ?? {};
          if (metadata["source"] === "organization_member_wallet_funding") {
            return {
              status: 400,
              body: {
                message: "Organization-scoped funding must be approved by the organization."
              }
            };
          }
          if (intent.status !== "PENDING" && intent.status !== "CREATED") {
            return {
              status: 400,
              body: {
                message: "This top-up cannot be approved in its current state."
              }
            };
          }
          const idempotencyKey = `wallet-topup-intent:${intent.id}:admin-approve`;
          await tx.insert(walletTransactionsTable).values({
            type: "TOP_UP",
            idempotencyKey,
            toWalletId: intent.walletId,
            amount: String(intent.amount),
            metadata: {
              intentId: intent.id,
              provider: intent.provider,
              providerReference: intent.providerReference ?? null,
              fundingMethod: intent.provider === "MANUAL" ? "BANK_DEPOSIT" : "INTERAC",
              approvedByAdminId: adminId
            }
          }).onConflictDoNothing();
          const [updated] = await tx.update(walletPaymentIntentsTable).set({
            status: "SUCCEEDED",
            metadata: {
              ...intent.metadata ?? {},
              approvedAt: (/* @__PURE__ */ new Date()).toISOString(),
              approvedByAdminId: adminId
            },
            updatedAt: /* @__PURE__ */ new Date()
          }).where(eq(walletPaymentIntentsTable.id, intent.id)).returning();
          return {
            status: 200,
            body: {
              intent: {
                id: updated.id,
                status: updated.status,
                updatedAt: updated.updatedAt.toISOString(),
                metadata: updated.metadata ?? {}
              }
            }
          };
        });
        return res.status(result.status).json(result.body);
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/wallets/topup-intents/:id/cancel", async (req, res) => {
      const adminId = req.admin.id;
      try {
        const id = Number(req.params.id);
        if (!id) return res.status(400).json({ message: "Invalid top-up id." });
        const result = await db.transaction(async (tx) => {
          const [intent] = await tx.select().from(walletPaymentIntentsTable).where(
            and(
              eq(walletPaymentIntentsTable.id, id),
              eq(walletPaymentIntentsTable.type, "TOP_UP")
            )
          ).limit(1);
          if (!intent)
            return { status: 404, body: { message: "Not found." } };
          if (intent.provider !== "MANUAL" && intent.provider !== "INTERAC") {
            return {
              status: 400,
              body: { message: "This top-up is not a bank deposit." }
            };
          }
          const metadata = intent.metadata ?? {};
          if (metadata["source"] === "organization_member_wallet_funding") {
            return {
              status: 400,
              body: {
                message: "Organization-scoped funding must be cancelled by the organization."
              }
            };
          }
          if (intent.status !== "CREATED" && intent.status !== "PENDING" && intent.status !== "FAILED") {
            return {
              status: 400,
              body: {
                message: "This top-up cannot be cancelled in its current state."
              }
            };
          }
          const [updated] = await tx.update(walletPaymentIntentsTable).set({
            status: "CANCELLED",
            metadata: {
              ...intent.metadata ?? {},
              cancelledAt: (/* @__PURE__ */ new Date()).toISOString(),
              cancelledByAdminId: adminId
            },
            updatedAt: /* @__PURE__ */ new Date()
          }).where(eq(walletPaymentIntentsTable.id, intent.id)).returning();
          return {
            status: 200,
            body: {
              intent: {
                id: updated.id,
                status: updated.status,
                updatedAt: updated.updatedAt.toISOString(),
                metadata: updated.metadata ?? {}
              }
            }
          };
        });
        return res.status(result.status).json(result.body);
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/wallets/cashout-intents", async (req, res) => {
      try {
        const status = req.query.status ? String(req.query.status) : void 0;
        const parsedStatus = status && (status === "CREATED" || status === "PENDING" || status === "SUCCEEDED" || status === "FAILED" || status === "CANCELLED") ? status : void 0;
        const where = and(
          eq(walletPaymentIntentsTable.type, "CASH_OUT"),
          parsedStatus ? eq(walletPaymentIntentsTable.status, parsedStatus) : void 0
        );
        const rows = await db.select({
          id: walletPaymentIntentsTable.id,
          userId: walletPaymentIntentsTable.userId,
          walletId: walletPaymentIntentsTable.walletId,
          provider: walletPaymentIntentsTable.provider,
          type: walletPaymentIntentsTable.type,
          amount: walletPaymentIntentsTable.amount,
          currency: walletPaymentIntentsTable.currency,
          status: walletPaymentIntentsTable.status,
          providerReference: walletPaymentIntentsTable.providerReference,
          metadata: walletPaymentIntentsTable.metadata,
          createdAt: walletPaymentIntentsTable.createdAt,
          updatedAt: walletPaymentIntentsTable.updatedAt,
          email: usersTable.email,
          firstName: usersTable.firstName,
          lastName: usersTable.lastName,
          membershipType: usersTable.membershipType,
          membershipStatus: usersTable.membershipStatus
        }).from(walletPaymentIntentsTable).innerJoin(
          usersTable,
          eq(walletPaymentIntentsTable.userId, usersTable.id)
        ).where(where).orderBy(desc(walletPaymentIntentsTable.createdAt)).limit(200);
        return res.json({
          intents: rows.map((i) => ({
            id: i.id,
            userId: i.userId,
            walletId: i.walletId,
            provider: i.provider,
            type: i.type,
            amount: Number(i.amount),
            currency: i.currency,
            status: i.status,
            providerReference: i.providerReference ?? null,
            metadata: i.metadata ?? {},
            createdAt: i.createdAt.toISOString(),
            updatedAt: i.updatedAt.toISOString(),
            user: {
              id: i.userId,
              email: i.email,
              firstName: i.firstName,
              lastName: i.lastName,
              membershipType: i.membershipType ?? null,
              membershipStatus: i.membershipStatus ?? null
            }
          }))
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/wallets/cashout-intents/:id/approve", async (req, res) => {
      const adminId = req.admin.id;
      try {
        const id = Number(req.params.id);
        if (!id) return res.status(400).json({ message: "Invalid withdrawal id." });
        const result = await db.transaction(async (tx) => {
          const [intent] = await tx.select().from(walletPaymentIntentsTable).where(
            and(
              eq(walletPaymentIntentsTable.id, id),
              eq(walletPaymentIntentsTable.type, "CASH_OUT")
            )
          ).limit(1);
          if (!intent)
            return { status: 404, body: { message: "Not found." } };
          if (intent.status !== "CREATED") {
            return {
              status: 400,
              body: {
                message: "This withdrawal cannot be approved in its current state."
              }
            };
          }
          const [updated] = await tx.update(walletPaymentIntentsTable).set({
            status: "PENDING",
            metadata: {
              ...intent.metadata ?? {},
              approvedAt: (/* @__PURE__ */ new Date()).toISOString(),
              approvedByAdminId: adminId
            },
            updatedAt: /* @__PURE__ */ new Date()
          }).where(eq(walletPaymentIntentsTable.id, intent.id)).returning();
          return {
            status: 200,
            body: {
              intent: {
                id: updated.id,
                status: updated.status,
                updatedAt: updated.updatedAt.toISOString(),
                metadata: updated.metadata ?? {}
              }
            }
          };
        });
        return res.status(result.status).json(result.body);
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/wallets/cashout-intents/:id/cancel", async (req, res) => {
      const adminId = req.admin.id;
      try {
        const id = Number(req.params.id);
        if (!id) return res.status(400).json({ message: "Invalid withdrawal id." });
        const result = await db.transaction(async (tx) => {
          const [intent] = await tx.select().from(walletPaymentIntentsTable).where(
            and(
              eq(walletPaymentIntentsTable.id, id),
              eq(walletPaymentIntentsTable.type, "CASH_OUT")
            )
          ).limit(1);
          if (!intent)
            return { status: 404, body: { message: "Not found." } };
          if (intent.status !== "CREATED" && intent.status !== "PENDING") {
            return {
              status: 400,
              body: {
                message: "This withdrawal cannot be cancelled in its current state."
              }
            };
          }
          const [updated] = await tx.update(walletPaymentIntentsTable).set({
            status: "CANCELLED",
            metadata: {
              ...intent.metadata ?? {},
              cancelledAt: (/* @__PURE__ */ new Date()).toISOString(),
              cancelledByAdminId: adminId
            },
            updatedAt: /* @__PURE__ */ new Date()
          }).where(eq(walletPaymentIntentsTable.id, intent.id)).returning();
          return {
            status: 200,
            body: {
              intent: {
                id: updated.id,
                status: updated.status,
                updatedAt: updated.updatedAt.toISOString(),
                metadata: updated.metadata ?? {}
              }
            }
          };
        });
        return res.status(result.status).json(result.body);
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/wallets/cashout-intents/:id/mark-paid", async (req, res) => {
      const adminId = req.admin.id;
      try {
        const id = Number(req.params.id);
        if (!id) return res.status(400).json({ message: "Invalid withdrawal id." });
        const parsed = external_exports.object({
          payoutReference: external_exports.string().max(200).optional(),
          note: external_exports.string().max(500).optional()
        }).safeParse(req.body ?? {});
        if (!parsed.success) {
          return res.status(400).json({ errors: parsed.error.flatten() });
        }
        const result = await db.transaction(async (tx) => {
          const [intent] = await tx.select().from(walletPaymentIntentsTable).where(
            and(
              eq(walletPaymentIntentsTable.id, id),
              eq(walletPaymentIntentsTable.type, "CASH_OUT")
            )
          ).limit(1);
          if (!intent)
            return { status: 404, body: { message: "Not found." } };
          if (intent.status !== "PENDING") {
            return {
              status: 400,
              body: {
                message: "This withdrawal cannot be paid in its current state."
              }
            };
          }
          const wallet = await ensureWalletWith5(tx, "USER", intent.userId);
          const balance = await getWalletBalanceWith3(tx, wallet.id);
          const grossAmount = Number(intent.amount);
          if (!Number.isFinite(grossAmount) || grossAmount <= 0) {
            return {
              status: 400,
              body: { message: "Invalid withdrawal amount." }
            };
          }
          if (balance < grossAmount) {
            return {
              status: 400,
              body: {
                message: "Wallet balance is insufficient to pay this withdrawal."
              }
            };
          }
          const metadata = intent.metadata ?? {};
          const feeAmountRaw = metadata.feeAmount;
          const feeAmount = typeof feeAmountRaw === "number" && Number.isFinite(feeAmountRaw) ? Number(feeAmountRaw.toFixed(2)) : 0;
          const netAmount = Number((grossAmount - feeAmount).toFixed(2));
          if (netAmount <= 0) {
            return {
              status: 400,
              body: { message: "Withdrawal net amount is invalid." }
            };
          }
          const platformWallet = await ensureWalletWith5(
            tx,
            "PLATFORM",
            PLATFORM_WALLET_OWNER_ID
          );
          const netIdempotencyKey = `wallet-cashout-intent:${intent.id}:net`;
          const feeIdempotencyKey = `wallet-cashout-intent:${intent.id}:fee`;
          await tx.insert(walletTransactionsTable).values({
            type: "CASH_OUT",
            idempotencyKey: netIdempotencyKey,
            fromWalletId: wallet.id,
            toWalletId: null,
            amount: netAmount.toFixed(2),
            metadata: {
              source: "wallet_cashout",
              intentId: intent.id,
              userId: intent.userId,
              paidByAdminId: adminId
            }
          }).onConflictDoNothing();
          if (feeAmount > 0) {
            await tx.insert(walletTransactionsTable).values({
              type: "CASH_OUT",
              idempotencyKey: feeIdempotencyKey,
              fromWalletId: wallet.id,
              toWalletId: platformWallet.id,
              amount: feeAmount.toFixed(2),
              metadata: {
                source: "wallet_cashout_fee",
                intentId: intent.id,
                userId: intent.userId,
                paidByAdminId: adminId
              }
            }).onConflictDoNothing();
          }
          const [updated] = await tx.update(walletPaymentIntentsTable).set({
            status: "SUCCEEDED",
            providerReference: parsed.data.payoutReference ?? intent.providerReference,
            metadata: {
              ...intent.metadata ?? {},
              paidAt: (/* @__PURE__ */ new Date()).toISOString(),
              paidByAdminId: adminId,
              payoutReference: parsed.data.payoutReference ?? null,
              adminNote: parsed.data.note ?? null
            },
            updatedAt: /* @__PURE__ */ new Date()
          }).where(eq(walletPaymentIntentsTable.id, intent.id)).returning();
          return {
            status: 200,
            body: {
              intent: {
                id: updated.id,
                status: updated.status,
                updatedAt: updated.updatedAt.toISOString()
              }
            }
          };
        });
        return res.status(result.status).json(result.body);
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/wallets/credit", async (req, res) => {
      try {
        const schema = external_exports.object({
          ownerType: external_exports.enum([
            "USER",
            "SUSU",
            "CIRCLE",
            "INVESTMENT",
            "LENDING_POOL",
            "PLATFORM"
          ]),
          ownerId: external_exports.number().int().optional(),
          amount: external_exports.string().min(1),
          idempotencyKey: external_exports.string().optional(),
          metadata: external_exports.record(external_exports.unknown()).optional()
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success)
          return res.status(400).json({ errors: parsed.error.flatten() });
        const idempotencyKey = parsed.data.idempotencyKey?.trim() || void 0;
        if (idempotencyKey) {
          const existing = await db.select().from(walletTransactionsTable).where(eq(walletTransactionsTable.idempotencyKey, idempotencyKey));
          if (existing.length) {
            const tx2 = existing[0];
            return res.json({
              transaction: {
                id: tx2.id,
                type: tx2.type,
                amount: Number(tx2.amount),
                createdAt: tx2.createdAt.toISOString(),
                reused: true
              }
            });
          }
        }
        const amount = Number(parsed.data.amount);
        if (!Number.isFinite(amount) || amount <= 0)
          return res.status(400).json({ message: "Invalid amount." });
        const resolvedOwnerId = parsed.data.ownerType === "USER" ? parsed.data.ownerId ?? req.admin.id : parsed.data.ownerId;
        if (!resolvedOwnerId) {
          return res.status(400).json({ message: "Wallet owner is required." });
        }
        const wallet = await ensureWallet(parsed.data.ownerType, resolvedOwnerId);
        const [tx] = await db.insert(walletTransactionsTable).values({
          type: "ADJUSTMENT",
          idempotencyKey: idempotencyKey ?? null,
          toWalletId: wallet.id,
          amount: parsed.data.amount,
          metadata: parsed.data.metadata ?? {}
        }).returning();
        return res.status(201).json({
          transaction: {
            id: tx.id,
            walletId: wallet.id,
            type: tx.type,
            amount: Number(tx.amount),
            createdAt: tx.createdAt.toISOString(),
            metadata: tx.metadata ?? {}
          }
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/susu/circles/:id/payout", async (req, res) => {
      try {
        const circleId = Number(req.params.id);
        let payoutNotification = null;
        if (!circleId)
          return res.status(400).json({ message: "Invalid circle id." });
        const schema = external_exports.object({
          userId: external_exports.number().int(),
          amount: external_exports.string().optional(),
          idempotencyKey: external_exports.string().optional(),
          metadata: external_exports.record(external_exports.unknown()).optional()
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success)
          return res.status(400).json({ errors: parsed.error.flatten() });
        const result = await db.transaction(async (tx) => {
          const [circle] = await tx.select().from(savingsCirclesTable).where(eq(savingsCirclesTable.id, circleId));
          if (!circle)
            return { status: 404, body: { message: "Circle not found." } };
          if (getCircleRuntimeStatus({
            status: circle.status,
            startDate: circle.startDate
          }) !== "ACTIVE")
            return {
              status: 400,
              body: { message: "Circle is not active." }
            };
          const membership = await tx.select().from(circleMembershipsTable).where(
            and(
              eq(circleMembershipsTable.circleId, circleId),
              eq(circleMembershipsTable.userId, parsed.data.userId)
            )
          );
          if (!membership.length)
            return {
              status: 400,
              body: { message: "User is not in this circle." }
            };
          await processCircleAutomationWith(tx, circleId);
          const now = /* @__PURE__ */ new Date();
          const potAmount = calculateCirclePayoutAmount(
            circle.contributionAmount,
            circle.maxMembers
          );
          if (parsed.data.amount && parsed.data.amount !== potAmount) {
            return {
              status: 400,
              body: { message: "Invalid payout amount." }
            };
          }
          const amount = potAmount;
          const numericAmount = Number(amount);
          if (!Number.isFinite(numericAmount) || numericAmount <= 0)
            return { status: 400, body: { message: "Invalid amount." } };
          const deterministicKey = `payout:${circleId}:${parsed.data.userId}:${membership[0].position}`;
          const idempotencyKey = deterministicKey;
          const existingTx = await tx.select().from(walletTransactionsTable).where(eq(walletTransactionsTable.idempotencyKey, idempotencyKey));
          if (existingTx.length) {
            const t = existingTx[0];
            return {
              status: 200,
              body: {
                transaction: {
                  id: t.id,
                  type: t.type,
                  amount: Number(t.amount),
                  createdAt: t.createdAt.toISOString(),
                  reused: true
                }
              }
            };
          }
          const [existingPayout] = await tx.select().from(circlePayoutsTable).where(
            and(
              eq(circlePayoutsTable.circleId, circleId),
              eq(circlePayoutsTable.userId, parsed.data.userId),
              eq(circlePayoutsTable.position, membership[0].position)
            )
          ).limit(1);
          if (!existingPayout) {
            return {
              status: 400,
              body: { message: "Payout schedule is not available yet." }
            };
          }
          if (existingPayout?.status === "PAID") {
            return {
              status: 400,
              body: { message: "Payout already sent." }
            };
          }
          if (!isPayoutDue({ scheduledDate: existingPayout.scheduledDate, now })) {
            return {
              status: 400,
              body: { message: "Payout is not due yet." }
            };
          }
          const hasBlockingContributionIssues = await hasBlockingPayoutContributionIssuesWith(
            tx,
            circleId,
            parsed.data.userId,
            now
          );
          if (hasBlockingContributionIssues) {
            return {
              status: 400,
              body: {
                message: "Payout is blocked until all due circle contributions are paid and no missed payments remain."
              }
            };
          }
          const circleTreasuryWallet = await ensureCircleTreasuryWalletWith(
            tx,
            circleId
          );
          if (!circleTreasuryWallet) {
            return {
              status: 404,
              body: { message: "Circle treasury was not found." }
            };
          }
          const userWallet = await ensureWalletWith5(
            tx,
            "USER",
            parsed.data.userId
          );
          const summary = await getCircleAllocationSummaryWith(tx, circleId);
          const circleBalance = summary?.allocationBalance ?? 0;
          if (circleBalance < numericAmount)
            return {
              status: 400,
              body: { message: "Insufficient ROSCA circle (Susu) allocation balance." }
            };
          let insertedTx;
          try {
            const [createdTx] = await tx.insert(walletTransactionsTable).values({
              type: "PAYOUT",
              idempotencyKey,
              fromWalletId: circleTreasuryWallet.id,
              toWalletId: userWallet.id,
              amount,
              metadata: {
                ...parsed.data.metadata ?? {},
                circleId,
                payoutUserId: parsed.data.userId,
                position: membership[0].position
              }
            }).returning();
            insertedTx = createdTx;
          } catch (e) {
            if (!isUniqueViolation5(e)) throw e;
            const [t] = await tx.select().from(walletTransactionsTable).where(eq(walletTransactionsTable.idempotencyKey, idempotencyKey));
            if (!t) throw e;
            const reusedTx = t;
            return {
              status: 200,
              body: {
                transaction: {
                  id: reusedTx.id,
                  type: reusedTx.type,
                  amount: Number(reusedTx.amount),
                  createdAt: reusedTx.createdAt.toISOString(),
                  reused: true
                }
              }
            };
          }
          if (!insertedTx) {
            throw new Error("Failed to create transaction.");
          }
          await tx.update(circlePayoutsTable).set({ paidDate: now, amount, status: "PAID" }).where(eq(circlePayoutsTable.id, existingPayout.id));
          const inApp = await notifyInAppWith(tx, {
            userId: parsed.data.userId,
            category: "SAVINGS",
            severity: "SUCCESS",
            title: "SUSU payout received",
            body: `Your SUSU payout of ${numericAmount.toLocaleString("en-CA", { style: "currency", currency: "CAD" })} for ${circle.name} has been added to your wallet.`,
            actionLabel: "Open Savings",
            actionHref: "/dashboard/savings"
          });
          payoutNotification = {
            userId: parsed.data.userId,
            payoutId: existingPayout.id,
            transactionId: insertedTx.id,
            amount: numericAmount,
            circleName: circle.name ?? null,
            notificationId: inApp.id
          };
          return {
            status: 201,
            body: {
              transaction: {
                id: insertedTx.id,
                type: insertedTx.type,
                amount: Number(insertedTx.amount),
                createdAt: insertedTx.createdAt.toISOString(),
                metadata: insertedTx.metadata ?? {}
              }
            }
          };
        });
        if (result.status === 201) {
          void (async () => {
            const notification = payoutNotification;
            if (notification === null) return;
            const circleSuffix = notification.circleName?.trim() ? ` for ${notification.circleName.trim()}` : "";
            const amountLabel = notification.amount.toLocaleString("en-CA", {
              style: "currency",
              currency: "CAD"
            });
            const pushKey = `susu_payout_paid:${notification.payoutId}:push`;
            const pushReserved = await reserveNotificationDeliveryWith(db, {
              userId: notification.userId,
              channel: "PUSH",
              category: "SAVINGS",
              idempotencyKey: pushKey,
              status: "SKIPPED",
              provider: null,
              metadata: {
                kind: "susu_payout_paid",
                payoutId: notification.payoutId,
                transactionId: notification.transactionId,
                circleName: notification.circleName
              }
            });
            if (pushReserved.reserved) {
              try {
                const pushResult = await deliverPushIfEnabled({
                  userId: notification.userId,
                  category: "SAVINGS",
                  title: "SUSU payout received",
                  body: `Your SUSU payout${circleSuffix} of ${amountLabel} has been added to your wallet.`,
                  data: { actionHref: "/dashboard/savings" }
                });
                await finalizeNotificationDeliveryWith(db, {
                  idempotencyKey: pushKey,
                  status: pushResult.status,
                  provider: pushResult.status === "SENT" ? "EXPO" : null,
                  errorMessage: pushResult.reason ?? null,
                  notificationId: notification.notificationId,
                  metadata: {
                    kind: "susu_payout_paid",
                    reason: pushResult.reason ?? null,
                    payoutId: notification.payoutId,
                    transactionId: notification.transactionId,
                    circleName: notification.circleName
                  }
                });
              } catch (err) {
                await finalizeNotificationDeliveryWith(db, {
                  idempotencyKey: pushKey,
                  status: "FAILED",
                  provider: "EXPO",
                  errorMessage: err instanceof Error ? err.message : String(err),
                  notificationId: notification.notificationId,
                  metadata: {
                    kind: "susu_payout_paid",
                    payoutId: notification.payoutId,
                    transactionId: notification.transactionId,
                    circleName: notification.circleName
                  }
                });
              }
            }
            const emailKey = `susu_payout_paid:${notification.payoutId}:email`;
            const emailReserved = await reserveNotificationDeliveryWith(db, {
              userId: notification.userId,
              channel: "EMAIL",
              category: "SAVINGS",
              idempotencyKey: emailKey,
              status: "SKIPPED",
              provider: null,
              metadata: {
                kind: "susu_payout_paid",
                payoutId: notification.payoutId,
                transactionId: notification.transactionId,
                circleName: notification.circleName
              }
            });
            if (!emailReserved.reserved) return;
            const [user] = await db.select({
              email: usersTable.email,
              firstName: usersTable.firstName
            }).from(usersTable).where(eq(usersTable.id, notification.userId)).limit(1);
            if (!user) return;
            try {
              const emailResult = await deliverReminderEmailIfEnabled({
                userId: notification.userId,
                to: user.email,
                firstName: user.firstName,
                category: "SAVINGS",
                title: "SUSU payout received",
                intro: `Your SUSU payout${circleSuffix} of ${amountLabel} has been added to your wallet.`,
                lines: [
                  "Open Savings to review the payout and your updated wallet balance."
                ],
                actionLabel: "Open Savings",
                actionHref: "/dashboard/savings"
              });
              await finalizeNotificationDeliveryWith(db, {
                idempotencyKey: emailKey,
                status: emailResult.status,
                provider: emailResult.status === "SENT" ? "SMTP" : null,
                errorMessage: emailResult.reason ?? null,
                notificationId: notification.notificationId,
                metadata: {
                  kind: "susu_payout_paid",
                  reason: emailResult.reason ?? null,
                  payoutId: notification.payoutId,
                  transactionId: notification.transactionId,
                  circleName: notification.circleName
                }
              });
            } catch (err) {
              await finalizeNotificationDeliveryWith(db, {
                idempotencyKey: emailKey,
                status: "FAILED",
                provider: "SMTP",
                errorMessage: err instanceof Error ? err.message : String(err),
                notificationId: notification.notificationId,
                metadata: {
                  kind: "susu_payout_paid",
                  payoutId: notification.payoutId,
                  transactionId: notification.transactionId,
                  circleName: notification.circleName
                }
              });
            }
          })();
        }
        return res.status(result.status).json(result.body);
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.patch("/susu/circles/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        const [existingCircle] = await db.select().from(savingsCirclesTable).where(eq(savingsCirclesTable.id, id));
        if (!existingCircle)
          return res.status(404).json({ message: "Circle not found." });
        const schema = external_exports.object({
          name: external_exports.string().min(1).optional(),
          status: external_exports.enum(["UPCOMING", "ACTIVE", "COMPLETED", "CANCELLED"]).optional(),
          description: external_exports.string().optional(),
          termsHtml: external_exports.string().optional().nullable(),
          contributionAmount: external_exports.string().min(1).optional(),
          helpingHandMultiplier: external_exports.string().optional(),
          frequency: external_exports.enum(["WEEKLY", "BIWEEKLY", "MONTHLY"]).optional(),
          maxMembers: external_exports.number().int().min(2).optional(),
          startDate: external_exports.string().optional(),
          isFreeToJoin: external_exports.boolean().optional()
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success)
          return res.status(400).json({ errors: parsed.error.flatten() });
        if (!isManualCircleLifecycleStatusAllowed(parsed.data.status)) {
          return res.status(400).json({
            message: "Manual COMPLETED/CANCELLED status changes are disabled. Circle lifecycle is managed by schedule timing and settlement state."
          });
        }
        if (parsed.data.maxMembers !== void 0 && parsed.data.maxMembers < existingCircle.maxMembers) {
          const [memberCountRow] = await db.select({ count: count() }).from(circleMembershipsTable).where(eq(circleMembershipsTable.circleId, id));
          const currentMembers = Number(memberCountRow?.count ?? 0);
          if (parsed.data.maxMembers < currentMembers) {
            return res.status(400).json({
              message: `Cannot reduce total spots below the current member count (${currentMembers}).`
            });
          }
        }
        const updates = { ...parsed.data, endDate: null };
        if (parsed.data.termsHtml !== void 0) {
          const normalized = typeof parsed.data.termsHtml === "string" && parsed.data.termsHtml.trim().length > 0 ? parsed.data.termsHtml.trim() : null;
          updates.termsHtml = normalized;
        }
        if (parsed.data.helpingHandMultiplier !== void 0) {
          const multiplier = parsed.data.helpingHandMultiplier.trim();
          if (multiplier === "") {
            updates.helpingHandMultiplier = null;
          } else {
            const numericMultiplier = Number(multiplier);
            if (!Number.isFinite(numericMultiplier) || numericMultiplier <= 0) {
              return res.status(400).json({ message: "Invalid Matching Fund multiplier." });
            }
            updates.helpingHandMultiplier = String(numericMultiplier);
          }
        }
        if (parsed.data.startDate !== void 0) {
          updates.startDate = parsed.data.startDate ? new Date(parsed.data.startDate) : null;
        }
        const nextStatusInput = updates.status ?? existingCircle.status;
        const nextStartDateInput = updates.startDate instanceof Date || updates.startDate === null ? updates.startDate : existingCircle.startDate;
        const runtimeStatus = nextStatusInput === "COMPLETED" || nextStatusInput === "CANCELLED" ? nextStatusInput : getCircleRuntimeStatus({
          status: nextStatusInput,
          startDate: nextStartDateInput
        });
        updates.status = runtimeStatus;
        const [updated] = await db.update(savingsCirclesTable).set(updates).where(eq(savingsCirclesTable.id, id)).returning();
        if (!updated) return res.status(404).json({ message: "Circle not found." });
        if (runtimeStatus === "ACTIVE") {
          await generateCircleSchedule(id);
        }
        return res.json({ circle: updated });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/susu/circles/:id/members", async (req, res) => {
      try {
        const circleId = Number(req.params.id);
        if (!circleId)
          return res.status(400).json({ message: "Invalid circle id." });
        const rows = await db.select({
          userId: usersTable.id,
          email: usersTable.email,
          firstName: usersTable.firstName,
          lastName: usersTable.lastName,
          position: circleMembershipsTable.position,
          joinedAt: circleMembershipsTable.joinedAt
        }).from(circleMembershipsTable).innerJoin(usersTable, eq(circleMembershipsTable.userId, usersTable.id)).where(eq(circleMembershipsTable.circleId, circleId)).orderBy(asc(circleMembershipsTable.position));
        return res.json({
          members: rows.map((r) => ({
            userId: r.userId,
            email: r.email,
            firstName: r.firstName,
            lastName: r.lastName,
            position: r.position,
            joinedAt: r.joinedAt.toISOString()
          }))
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    HELPING_HAND_REPAYMENT_CREATEABLE_APPLICATION_STATUSES = /* @__PURE__ */ new Set([
      "FUNDED",
      "REPAYING"
    ]);
    HELPING_HAND_REPAYMENT_SERVICEABLE_APPLICATION_STATUSES = /* @__PURE__ */ new Set([
      "FUNDED",
      "REPAYING",
      "CLOSED"
    ]);
    router3.get("/susu/helping-hand", async (_req, res) => {
      try {
        const applications = await db.select({
          id: helpingHandApplicationsTable.id,
          userId: helpingHandApplicationsTable.userId,
          requestedAmount: helpingHandApplicationsTable.requestedAmount,
          qualifyingCircleId: helpingHandApplicationsTable.qualifyingCircleId,
          qualifyingPayoutAmount: helpingHandApplicationsTable.qualifyingPayoutAmount,
          qualifyingMultiplier: helpingHandApplicationsTable.qualifyingMultiplier,
          purpose: helpingHandApplicationsTable.purpose,
          term: helpingHandApplicationsTable.term,
          repaymentSchedule: helpingHandApplicationsTable.repaymentSchedule,
          notes: helpingHandApplicationsTable.notes,
          status: helpingHandApplicationsTable.status,
          approvedAmount: helpingHandApplicationsTable.approvedAmount,
          disbursedAmount: helpingHandApplicationsTable.disbursedAmount,
          disbursedAt: helpingHandApplicationsTable.disbursedAt,
          reviewNote: helpingHandApplicationsTable.reviewNote,
          createdAt: helpingHandApplicationsTable.createdAt,
          qualifyingCircleName: savingsCirclesTable.name,
          userEmail: usersTable.email,
          userFirstName: usersTable.firstName,
          userLastName: usersTable.lastName
        }).from(helpingHandApplicationsTable).leftJoin(
          usersTable,
          eq(helpingHandApplicationsTable.userId, usersTable.id)
        ).leftJoin(
          savingsCirclesTable,
          eq(
            helpingHandApplicationsTable.qualifyingCircleId,
            savingsCirclesTable.id
          )
        ).orderBy(desc(helpingHandApplicationsTable.createdAt));
        return res.json({ applications, total: applications.length });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.patch("/susu/helping-hand/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        if (!Number.isFinite(id) || id <= 0) {
          return res.status(400).json({ message: "Invalid application id." });
        }
        const schema = external_exports.object({
          status: external_exports.enum([
            "DRAFT",
            "SUBMITTED",
            "UNDER_REVIEW",
            "APPROVED",
            "REJECTED",
            "FUNDED",
            "REPAYING",
            "CLOSED"
          ]).optional(),
          approvedAmount: external_exports.string().optional(),
          disbursedAmount: external_exports.string().optional(),
          reviewNote: external_exports.string().optional()
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success)
          return res.status(400).json({ errors: parsed.error.flatten() });
        const adminId = req.admin.id;
        const updated = await db.transaction(async (tx) => {
          const [existing] = await tx.select().from(helpingHandApplicationsTable).where(eq(helpingHandApplicationsTable.id, id));
          if (!existing) {
            throw new Error("Application not found.");
          }
          const nextStatus = parsed.data.status ?? existing.status;
          if (parsed.data.status && parsed.data.status !== existing.status && !HELPING_HAND_APPLICATION_TRANSITIONS[existing.status]?.includes(
            parsed.data.status
          )) {
            throw new Error(
              `Invalid status transition from ${existing.status} to ${parsed.data.status}.`
            );
          }
          if (nextStatus === "CLOSED") {
            const repayments = await tx.select({
              amount: helpingHandRepaymentsTable.amount,
              paidAmount: helpingHandRepaymentsTable.paidAmount,
              status: helpingHandRepaymentsTable.status
            }).from(helpingHandRepaymentsTable).where(
              eq(
                helpingHandRepaymentsTable.helpingHandApplicationId,
                existing.id
              )
            );
            const hasOutstandingRepayment = repayments.some((repayment) => {
              const scheduledAmount = parseMoneyAmount(repayment.amount);
              const paidAmount = repayment.status === "PAID" ? scheduledAmount : parseMoneyAmount(repayment.paidAmount);
              return repayment.status !== "WAIVED" && paidAmount + 1e-6 < scheduledAmount;
            });
            if (hasOutstandingRepayment) {
              throw new Error(
                "All Matching Fund repayments must be settled or waived before the case can be closed."
              );
            }
          }
          const nextApprovedAmount = parsed.data.approvedAmount !== void 0 ? parsed.data.approvedAmount || null : existing.approvedAmount;
          let disbursedAmount = existing.status === "FUNDED" && existing.disbursedAmount ? existing.disbursedAmount : parsed.data.disbursedAmount ?? existing.disbursedAmount ?? nextApprovedAmount ?? existing.requestedAmount;
          let disbursementTransactionId = existing.disbursementTransactionId ?? null;
          if (nextStatus === "FUNDED" && existing.status !== "FUNDED") {
            const numericDisbursedAmount = parseMoneyAmount(disbursedAmount);
            if (numericDisbursedAmount <= 0) {
              throw new Error("Disbursed amount must be a positive value.");
            }
            const masterWalletBalance = await getLendingMasterWalletBalanceWith(tx);
            if (numericDisbursedAmount > masterWalletBalance) {
              throw new Error(
                `Lending Master Wallet balance is only ${formatMoneyAmount(masterWalletBalance)}. Top up the wallet or reduce the amount before funding.`
              );
            }
            const [memberWallet, masterWallet] = await Promise.all([
              ensureWalletWith5(tx, "USER", existing.userId),
              ensureLendingMasterWalletWith(tx)
            ]);
            const disbursementIdempotencyKey = `helping_hand_disbursement:admin_fund:${existing.id}`;
            const [existingDisbursement] = await tx.select().from(walletTransactionsTable).where(
              eq(
                walletTransactionsTable.idempotencyKey,
                disbursementIdempotencyKey
              )
            );
            const transaction = existingDisbursement ?? (await tx.insert(walletTransactionsTable).values({
              type: "HELPING_HAND_DISBURSEMENT",
              idempotencyKey: disbursementIdempotencyKey,
              fromWalletId: masterWallet.id,
              toWalletId: memberWallet.id,
              amount: formatMoneyAmount(numericDisbursedAmount),
              metadata: {
                helpingHandApplicationId: existing.id,
                userId: existing.userId
              }
            }).returning())[0];
            disbursementTransactionId = transaction.id;
            disbursedAmount = formatMoneyAmount(numericDisbursedAmount);
          }
          const now = /* @__PURE__ */ new Date();
          const updates = {
            status: nextStatus,
            approvedAmount: nextApprovedAmount,
            disbursedAmount: nextStatus === "FUNDED" || existing.disbursedAmount ? disbursedAmount : existing.disbursedAmount,
            reviewNote: parsed.data.reviewNote !== void 0 ? parsed.data.reviewNote || null : existing.reviewNote,
            reviewedByAdminId: adminId,
            reviewedAt: now,
            updatedAt: now
          };
          if (nextStatus === "FUNDED") {
            updates.disbursedAt = existing.disbursedAt ?? now;
            updates.disbursementTransactionId = disbursementTransactionId;
          }
          const [application] = await tx.update(helpingHandApplicationsTable).set(updates).where(eq(helpingHandApplicationsTable.id, id)).returning();
          return application;
        });
        return res.json({ application: updated });
      } catch (err) {
        if (err instanceof Error) {
          if (err.message === "Application not found.") {
            return res.status(404).json({ message: err.message });
          }
          return res.status(400).json({ message: err.message });
        }
        return handleError2(err, res);
      }
    });
    router3.get("/susu/helping-hand/:id/repayments", async (req, res) => {
      try {
        const applicationId = Number(req.params.id);
        const repayments = await db.select().from(helpingHandRepaymentsTable).where(
          eq(helpingHandRepaymentsTable.helpingHandApplicationId, applicationId)
        ).orderBy(asc(helpingHandRepaymentsTable.dueDate));
        return res.json({ repayments });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/susu/helping-hand/:id/repayments/generate", async (req, res) => {
      try {
        const applicationId = Number(req.params.id);
        if (!Number.isFinite(applicationId) || applicationId <= 0) {
          return res.status(400).json({ message: "Invalid application id." });
        }
        const parsed = external_exports.object({
          firstDueDate: external_exports.string().transform((value) => new Date(value)).optional()
        }).safeParse(req.body ?? {});
        if (!parsed.success) {
          return res.status(400).json({ errors: parsed.error.flatten() });
        }
        const [application] = await db.select().from(helpingHandApplicationsTable).where(eq(helpingHandApplicationsTable.id, applicationId));
        if (!application) {
          return res.status(404).json({ message: "Application not found." });
        }
        if (!HELPING_HAND_REPAYMENT_CREATEABLE_APPLICATION_STATUSES.has(
          application.status
        )) {
          return res.status(400).json({
            message: "Repayment schedules can only be generated for funded or repaying Matching Fund cases."
          });
        }
        const existingRepayments = await db.select({ count: count() }).from(helpingHandRepaymentsTable).where(
          eq(helpingHandRepaymentsTable.helpingHandApplicationId, applicationId)
        );
        if (Number(existingRepayments[0]?.count ?? 0) > 0) {
          return res.status(400).json({
            message: "A repayment schedule already exists. Adjust the entries inline instead of generating a new one."
          });
        }
        const totalAmount = Number(
          application.approvedAmount ?? application.requestedAmount
        );
        if (!Number.isFinite(totalAmount) || totalAmount <= 0) {
          return res.status(400).json({
            message: "The application must have a valid approved or requested amount before a repayment schedule can be generated."
          });
        }
        const firstDueDate = parsed.data.firstDueDate ?? addPeriod2(
          application.disbursedAt ?? /* @__PURE__ */ new Date(),
          parseRepaymentFrequency(application.repaymentSchedule),
          1
        );
        const schedule = buildHelpingHandRepaymentSchedule({
          totalAmount,
          term: application.term,
          repaymentSchedule: application.repaymentSchedule,
          firstDueDate
        });
        const inserted = await db.insert(helpingHandRepaymentsTable).values(
          schedule.map((entry) => ({
            helpingHandApplicationId: applicationId,
            dueDate: entry.dueDate,
            amount: entry.amount
          }))
        ).returning();
        return res.status(201).json({ repayments: inserted });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/susu/helping-hand/:id/repayments", async (req, res) => {
      try {
        const applicationId = Number(req.params.id);
        if (!Number.isFinite(applicationId) || applicationId <= 0) {
          return res.status(400).json({ message: "Invalid application id." });
        }
        const schema = external_exports.object({
          dueDate: external_exports.string().transform((s) => new Date(s)),
          amount: external_exports.string()
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success)
          return res.status(400).json({ errors: parsed.error.flatten() });
        const [application] = await db.select({
          id: helpingHandApplicationsTable.id,
          status: helpingHandApplicationsTable.status
        }).from(helpingHandApplicationsTable).where(eq(helpingHandApplicationsTable.id, applicationId));
        if (!application) {
          return res.status(404).json({ message: "Application not found." });
        }
        if (!HELPING_HAND_REPAYMENT_CREATEABLE_APPLICATION_STATUSES.has(
          application.status
        )) {
          return res.status(400).json({
            message: "Repayment entries can only be created for funded or repaying Matching Fund cases."
          });
        }
        const [newRepayment] = await db.insert(helpingHandRepaymentsTable).values({
          helpingHandApplicationId: applicationId,
          dueDate: parsed.data.dueDate,
          amount: parsed.data.amount
        }).returning();
        return res.status(201).json({ repayment: newRepayment });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.patch("/susu/helping-hand/repayments/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        if (!Number.isFinite(id) || id <= 0) {
          return res.status(400).json({ message: "Invalid repayment id." });
        }
        const schema = external_exports.object({
          amount: external_exports.string().optional(),
          dueDate: external_exports.string().transform((s) => new Date(s)).optional(),
          status: external_exports.enum(["PENDING", "PAID", "LATE", "WAIVED"]).optional(),
          method: external_exports.enum(["STRIPE", "EFT", "INTERAC", "WIRE", "WALLET"]).optional(),
          paidAmount: external_exports.string().optional(),
          returnPaidAmount: external_exports.string().optional()
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success)
          return res.status(400).json({ errors: parsed.error.flatten() });
        const [existing] = await db.select().from(helpingHandRepaymentsTable).where(eq(helpingHandRepaymentsTable.id, id));
        if (!existing) {
          return res.status(404).json({ message: "Repayment not found." });
        }
        const [application] = await db.select({
          userId: helpingHandApplicationsTable.userId,
          status: helpingHandApplicationsTable.status
        }).from(helpingHandApplicationsTable).where(
          eq(helpingHandApplicationsTable.id, existing.helpingHandApplicationId)
        );
        if (!application) {
          return res.status(404).json({ message: "Application not found." });
        }
        if (!HELPING_HAND_REPAYMENT_SERVICEABLE_APPLICATION_STATUSES.has(
          application.status
        )) {
          return res.status(400).json({
            message: "Repayments can only be managed for funded, repaying, or closed Matching Fund cases."
          });
        }
        const updates = {
          ...parsed.data,
          ...deriveHelpingHandRepaymentUpdate(existing, parsed.data, /* @__PURE__ */ new Date()),
          updatedAt: /* @__PURE__ */ new Date()
        };
        const [updated] = await db.update(helpingHandRepaymentsTable).set(updates).where(eq(helpingHandRepaymentsTable.id, id)).returning();
        if (!updated)
          return res.status(404).json({ message: "Repayment not found." });
        await updateCreditScore(application.userId);
        return res.json({ repayment: updated });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/lending/applications", async (_req, res) => {
      try {
        const applications = await db.select({
          id: loanApplicationsTable.id,
          loanType: loanApplicationsTable.loanType,
          borrowerId: loanApplicationsTable.borrowerId,
          templateId: loanApplicationsTable.templateId,
          opportunityId: loanApplicationsTable.opportunityId,
          requestedAmount: loanApplicationsTable.requestedAmount,
          purpose: loanApplicationsTable.purpose,
          term: loanApplicationsTable.term,
          repaymentSchedule: loanApplicationsTable.repaymentSchedule,
          termMonths: loanApplicationsTable.termMonths,
          borrowerAppreciationAmount: loanApplicationsTable.borrowerAppreciationAmount,
          repaymentFrequency: loanApplicationsTable.repaymentFrequency,
          processingFeePct: loanApplicationsTable.processingFeePct,
          wwnMarginPct: loanApplicationsTable.wwnMarginPct,
          reserveContributionPct: loanApplicationsTable.reserveContributionPct,
          totalRepayableAmount: loanApplicationsTable.totalRepayableAmount,
          estimatedInstallmentAmount: loanApplicationsTable.estimatedInstallmentAmount,
          funderOpportunityTitle: loanApplicationsTable.funderOpportunityTitle,
          notes: loanApplicationsTable.notes,
          status: loanApplicationsTable.status,
          reservedAt: loanApplicationsTable.reservedAt,
          approvedAmount: loanApplicationsTable.approvedAmount,
          disbursedAmount: loanApplicationsTable.disbursedAmount,
          disbursedAt: loanApplicationsTable.disbursedAt,
          reviewNote: loanApplicationsTable.reviewNote,
          reviewedAt: loanApplicationsTable.reviewedAt,
          poolReassignedAt: loanApplicationsTable.poolReassignedAt,
          poolReassignmentNote: loanApplicationsTable.poolReassignmentNote,
          createdAt: loanApplicationsTable.createdAt,
          updatedAt: loanApplicationsTable.updatedAt,
          templateTitle: lendingTemplatesTable.title,
          borrowerEmail: usersTable.email,
          borrowerFirstName: usersTable.firstName,
          borrowerLastName: usersTable.lastName,
          borrowerMembershipStatus: usersTable.membershipStatus,
          borrowerMembershipType: usersTable.membershipType,
          opportunityTitle: lendingOpportunitiesTable.title
        }).from(loanApplicationsTable).leftJoin(
          lendingTemplatesTable,
          eq(loanApplicationsTable.templateId, lendingTemplatesTable.id)
        ).leftJoin(
          lendingOpportunitiesTable,
          eq(loanApplicationsTable.opportunityId, lendingOpportunitiesTable.id)
        ).leftJoin(usersTable, eq(loanApplicationsTable.borrowerId, usersTable.id)).orderBy(desc(loanApplicationsTable.createdAt));
        return res.json({ applications, total: applications.length });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/lending/applications/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        if (!Number.isFinite(id) || id <= 0) {
          return res.status(400).json({ message: "Invalid application id." });
        }
        const [application] = await db.select({
          id: loanApplicationsTable.id,
          loanType: loanApplicationsTable.loanType,
          borrowerId: loanApplicationsTable.borrowerId,
          templateId: loanApplicationsTable.templateId,
          opportunityId: loanApplicationsTable.opportunityId,
          requestedAmount: loanApplicationsTable.requestedAmount,
          purpose: loanApplicationsTable.purpose,
          term: loanApplicationsTable.term,
          repaymentSchedule: loanApplicationsTable.repaymentSchedule,
          termMonths: loanApplicationsTable.termMonths,
          borrowerAppreciationAmount: loanApplicationsTable.borrowerAppreciationAmount,
          repaymentFrequency: loanApplicationsTable.repaymentFrequency,
          processingFeePct: loanApplicationsTable.processingFeePct,
          wwnMarginPct: loanApplicationsTable.wwnMarginPct,
          reserveContributionPct: loanApplicationsTable.reserveContributionPct,
          totalRepayableAmount: loanApplicationsTable.totalRepayableAmount,
          estimatedInstallmentAmount: loanApplicationsTable.estimatedInstallmentAmount,
          funderOpportunityTitle: loanApplicationsTable.funderOpportunityTitle,
          notes: loanApplicationsTable.notes,
          status: loanApplicationsTable.status,
          poolAssignedAt: loanApplicationsTable.poolAssignedAt,
          poolAssignedByAdminId: loanApplicationsTable.poolAssignedByAdminId,
          poolReassignedAt: loanApplicationsTable.poolReassignedAt,
          poolReassignedByAdminId: loanApplicationsTable.poolReassignedByAdminId,
          poolReassignmentNote: loanApplicationsTable.poolReassignmentNote,
          approvedAmount: loanApplicationsTable.approvedAmount,
          reservedAt: loanApplicationsTable.reservedAt,
          reservedByAdminId: loanApplicationsTable.reservedByAdminId,
          disbursedAmount: loanApplicationsTable.disbursedAmount,
          disbursedAt: loanApplicationsTable.disbursedAt,
          disbursementTransactionId: loanApplicationsTable.disbursementTransactionId,
          reviewNote: loanApplicationsTable.reviewNote,
          reviewedAt: loanApplicationsTable.reviewedAt,
          reviewedByAdminId: loanApplicationsTable.reviewedByAdminId,
          pricingLockedAt: loanApplicationsTable.pricingLockedAt,
          createdAt: loanApplicationsTable.createdAt,
          updatedAt: loanApplicationsTable.updatedAt,
          templateTitle: lendingTemplatesTable.title,
          templateBorrowerType: lendingTemplatesTable.borrowerType,
          minRequestAmount: lendingTemplatesTable.minRequestAmount,
          expectedReturnPct: lendingTemplatesTable.expectedReturnPct,
          borrowerEmail: usersTable.email,
          borrowerFirstName: usersTable.firstName,
          borrowerLastName: usersTable.lastName,
          borrowerMembershipStatus: usersTable.membershipStatus,
          borrowerMembershipType: usersTable.membershipType,
          borrowerSegment: usersTable.segment,
          opportunityTitle: lendingOpportunitiesTable.title
        }).from(loanApplicationsTable).leftJoin(
          lendingTemplatesTable,
          eq(loanApplicationsTable.templateId, lendingTemplatesTable.id)
        ).leftJoin(
          lendingOpportunitiesTable,
          eq(loanApplicationsTable.opportunityId, lendingOpportunitiesTable.id)
        ).leftJoin(usersTable, eq(loanApplicationsTable.borrowerId, usersTable.id)).where(eq(loanApplicationsTable.id, id));
        if (!application) {
          return res.status(404).json({ message: "Application not found." });
        }
        const repayments = await db.select().from(loanRepaymentsTable).where(eq(loanRepaymentsTable.loanApplicationId, id)).orderBy(asc(loanRepaymentsTable.dueDate));
        return res.json({ application, repayments });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    REPAYMENT_CREATEABLE_APPLICATION_STATUSES = /* @__PURE__ */ new Set([
      "FUNDED",
      "REPAYING"
    ]);
    REPAYMENT_SERVICEABLE_APPLICATION_STATUSES = /* @__PURE__ */ new Set([
      "FUNDED",
      "REPAYING",
      "CLOSED"
    ]);
    router3.patch("/lending/applications/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        if (!Number.isFinite(id) || id <= 0) {
          return res.status(400).json({ message: "Invalid application id." });
        }
        const schema = external_exports.object({
          status: external_exports.enum([
            "DRAFT",
            "SUBMITTED",
            "WAITLISTED",
            "UNDER_REVIEW",
            "APPROVED",
            "FUNDED",
            "REPAYING",
            "CLOSED",
            "REJECTED",
            "CANCELLED"
          ]).optional(),
          approvedAmount: external_exports.string().optional(),
          disbursedAmount: external_exports.string().optional(),
          borrowerAppreciationAmount: external_exports.coerce.number().nonnegative().optional(),
          termMonths: external_exports.coerce.number().int().positive().optional(),
          repaymentFrequency: external_exports.enum(["WEEKLY", "BIWEEKLY", "MONTHLY"]).optional(),
          processingFeePct: external_exports.coerce.number().nonnegative().optional(),
          funderOpportunityTitle: external_exports.string().trim().max(200).optional(),
          reviewNote: external_exports.string().optional()
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success)
          return res.status(400).json({ errors: parsed.error.flatten() });
        const adminId = req.admin.id;
        const updated = await db.transaction(async (tx) => {
          const [existing] = await tx.select().from(loanApplicationsTable).where(eq(loanApplicationsTable.id, id));
          if (!existing) return null;
          const nextStatus = parsed.data.status ?? existing.status;
          const shouldAutoPromoteToRepaying = nextStatus === "FUNDED" && existing.status !== "FUNDED";
          const finalStatus = shouldAutoPromoteToRepaying ? "REPAYING" : nextStatus;
          if (!isLendingApplicationTransitionAllowed(existing.status, nextStatus)) {
            throw new Error(
              `Invalid status transition from ${existing.status} to ${nextStatus}.`
            );
          }
          const templateId = existing.templateId ?? null;
          const [template] = templateId ? await tx.select().from(lendingTemplatesTable).where(eq(lendingTemplatesTable.id, templateId)) : [];
          if (!template && !["REJECTED", "CANCELLED"].includes(nextStatus)) {
            throw new Error(
              "A Lending Template must be selected for this application."
            );
          }
          const loanType = normalizeLendingLoanType(
            existing.loanType ?? template?.loanType
          );
          const funderOpportunityTitle = parsed.data.funderOpportunityTitle !== void 0 ? parsed.data.funderOpportunityTitle.trim() || null : existing.funderOpportunityTitle ?? null;
          const resolvedOpportunityTitle = funderOpportunityTitle ?? (template ? `Request - ${template.title}` : null);
          const nextApprovedAmountRaw = parsed.data.approvedAmount ?? existing.approvedAmount ?? existing.requestedAmount;
          const nextApprovedAmount = parseMoneyAmount(nextApprovedAmountRaw);
          const requestedAmount = parseMoneyAmount(existing.requestedAmount);
          const minRequestAmount = parseMoneyAmount(template?.minRequestAmount);
          const templateWwnMarginPct = parseMoneyAmount(template?.wwnMarginPct);
          const templateReserveContributionPct = parseMoneyAmount(
            template?.reserveContributionPct
          );
          const borrowerAppreciationAmountInput = parsed.data.borrowerAppreciationAmount !== void 0 ? parsed.data.borrowerAppreciationAmount : parseMoneyAmount(
            existing.borrowerAppreciationAmount ?? template?.borrowerAppreciationAmount
          );
          const termMonths = parsed.data.termMonths !== void 0 ? parsed.data.termMonths : Number(existing.termMonths ?? template?.borrowerTermMonths ?? 0);
          const repaymentFrequency = parsed.data.repaymentFrequency ?? existing.repaymentFrequency ?? template?.repaymentFrequency ?? "MONTHLY";
          const processingFeePct = parsed.data.processingFeePct !== void 0 ? parsed.data.processingFeePct : parseMoneyAmount(
            existing.processingFeePct ?? template?.processingFeePct
          );
          if (["APPROVED", "FUNDED"].includes(nextStatus) && nextApprovedAmount <= 0) {
            throw new Error("Approved amount must be a positive value.");
          }
          if ((parsed.data.approvedAmount !== void 0 || [
            "APPROVED",
            "APPROVED_RESERVED",
            "FUNDED",
            "REPAYING",
            "CLOSED"
          ].includes(finalStatus)) && nextApprovedAmount > requestedAmount) {
            throw new Error(
              `Approved amount cannot exceed the requested amount of ${formatMoneyAmount(requestedAmount)}.`
            );
          }
          if (minRequestAmount > 0 && (parsed.data.approvedAmount !== void 0 || [
            "APPROVED",
            "APPROVED_RESERVED",
            "FUNDED",
            "REPAYING",
            "CLOSED"
          ].includes(finalStatus)) && nextApprovedAmount < minRequestAmount) {
            throw new Error(
              `Approved amount cannot be below the template minimum of ${formatMoneyAmount(minRequestAmount)}.`
            );
          }
          if (borrowerAppreciationAmountInput < 0 || termMonths <= 0) {
            throw new Error(
              "Borrower appreciation amount and term months must be valid values."
            );
          }
          const now = /* @__PURE__ */ new Date();
          const opportunityRequired = [
            "APPROVED",
            "FUNDED",
            "REPAYING",
            "CLOSED"
          ].includes(finalStatus);
          const pricingPrincipalAmount = opportunityRequired ? nextApprovedAmount : parseMoneyAmount(existing.requestedAmount);
          const p2pPricingSnapshot = loanType === "P2P_LENDING" ? buildP2PRatePricingSnapshot({
            principalAmount: pricingPrincipalAmount,
            termMonths,
            investorRatePct: template?.expectedReturnPct,
            wwnMarginPct: templateWwnMarginPct,
            reserveContributionPct: templateReserveContributionPct
          }) : null;
          const borrowerAppreciationAmount = loanType === "COMMUNITY_LENDING" ? borrowerAppreciationAmountInput : p2pPricingSnapshot?.borrowerRateAmount ?? 0;
          const lockedPlatformAppreciationSharePct = loanType === "COMMUNITY_LENDING" ? parseMoneyAmount(template?.platformAppreciationSharePct) : p2pPricingSnapshot?.platformSharePctOfBorrowerRate ?? 0;
          const opportunityExpectedReturnPct = loanType === "COMMUNITY_LENDING" ? calculateNetExpectedReturnPct({
            principalAmount: nextApprovedAmount,
            appreciationAmount: borrowerAppreciationAmount,
            termMonths,
            platformAppreciationSharePct: lockedPlatformAppreciationSharePct
          }) : parseMoneyAmount(template?.expectedReturnPct);
          const opportunityTermMonths = loanType === "COMMUNITY_LENDING" ? termMonths : Number(template?.termMonths ?? termMonths);
          const opportunityExpectedReturn = loanType === "COMMUNITY_LENDING" ? formatExpectedReturnLabel(opportunityExpectedReturnPct) : template?.expectedReturn ?? formatExpectedReturnLabel(opportunityExpectedReturnPct);
          const opportunityTerm = loanType === "COMMUNITY_LENDING" ? formatTermMonthsLabel(termMonths) : template?.term ?? formatTermMonthsLabel(opportunityTermMonths);
          let opportunityId = existing.opportunityId ?? null;
          if (opportunityRequired && template) {
            const nextOpportunityStatus = ["FUNDED", "REPAYING", "CLOSED"].includes(
              finalStatus
            ) ? "CLOSED" : "OPEN";
            if (!opportunityId) {
              const [created] = await tx.insert(lendingOpportunitiesTable).values({
                templateId: template.id,
                applicationId: existing.id,
                loanType,
                title: resolvedOpportunityTitle ?? `Request - ${template.title}`,
                description: existing.purpose,
                status: nextOpportunityStatus,
                targetAmount: formatMoneyAmount(nextApprovedAmount),
                committedAmount: "0",
                minCommitment: template.minCommitment,
                borrowerAppreciationAmount: formatMoneyAmount(
                  borrowerAppreciationAmount
                ),
                borrowerTermMonths: termMonths,
                repaymentFrequency,
                processingFeePct: parsed.data.processingFeePct !== void 0 || template.processingFeePct !== null ? formatMoneyAmount(processingFeePct) : null,
                wwnMarginPct: formatMoneyAmount(templateWwnMarginPct),
                reserveContributionPct: formatMoneyAmount(
                  templateReserveContributionPct
                ),
                platformAppreciationSharePct: formatMoneyAmount(
                  lockedPlatformAppreciationSharePct
                ),
                minAppreciationType: template.minAppreciationType,
                minAppreciationValue: template.minAppreciationValue,
                minAppreciationTiers: template.minAppreciationTiers,
                expectedReturnPct: formatMoneyAmount(
                  opportunityExpectedReturnPct
                ),
                termMonths: opportunityTermMonths,
                returnModel: template.returnModel,
                expectedReturn: opportunityExpectedReturn,
                term: opportunityTerm,
                minBorrowerPlanTier: template.minBorrowerPlanTier,
                borrowerType: template.borrowerType,
                createdAt: now,
                updatedAt: now
              }).returning();
              opportunityId = created.id;
            } else {
              await tx.update(lendingOpportunitiesTable).set({
                title: resolvedOpportunityTitle ?? `Request - ${template.title}`,
                status: nextOpportunityStatus,
                loanType,
                targetAmount: formatMoneyAmount(nextApprovedAmount),
                borrowerAppreciationAmount: formatMoneyAmount(
                  borrowerAppreciationAmount
                ),
                borrowerTermMonths: termMonths,
                repaymentFrequency,
                processingFeePct: parsed.data.processingFeePct !== void 0 || template.processingFeePct !== null ? formatMoneyAmount(processingFeePct) : null,
                wwnMarginPct: formatMoneyAmount(templateWwnMarginPct),
                reserveContributionPct: formatMoneyAmount(
                  templateReserveContributionPct
                ),
                platformAppreciationSharePct: formatMoneyAmount(
                  lockedPlatformAppreciationSharePct
                ),
                expectedReturnPct: formatMoneyAmount(
                  opportunityExpectedReturnPct
                ),
                termMonths: opportunityTermMonths,
                expectedReturn: opportunityExpectedReturn,
                term: opportunityTerm,
                updatedAt: now
              }).where(eq(lendingOpportunitiesTable.id, opportunityId));
            }
          }
          let disbursementTransactionId = existing.disbursementTransactionId ?? null;
          let disbursedAmount = null;
          if (nextStatus === "FUNDED" && existing.status !== "FUNDED") {
            if (!["APPROVED", "APPROVED_RESERVED"].includes(existing.status)) {
              throw new Error("Only approved applications can be funded.");
            }
            if (opportunityId) {
              const remainingCapacity = await getRemainingPoolCapacityWith(
                tx,
                opportunityId
              );
              if (remainingCapacity > 0) {
                throw new Error(
                  `This loan is not yet fully funded. ${formatMoneyAmount(remainingCapacity)} is still uncommitted.`
                );
              }
            }
            if (parsed.data.disbursedAmount !== void 0 && formatMoneyAmount(parseMoneyAmount(parsed.data.disbursedAmount)) !== formatMoneyAmount(nextApprovedAmount)) {
              throw new Error(
                "Disbursed amount must match the approved amount for funded loans."
              );
            }
            const disbursedAmountRaw = formatMoneyAmount(nextApprovedAmount);
            const numericDisbursedAmount = parseMoneyAmount(disbursedAmountRaw);
            if (numericDisbursedAmount <= 0) {
              throw new Error("Disbursed amount must be a positive value.");
            }
            const availableToLend = await getPoolAvailableToLendWith(
              tx,
              opportunityId ?? 0,
              existing.status === "APPROVED_RESERVED" ? existing.id : void 0
            );
            if (numericDisbursedAmount > availableToLend) {
              throw new Error(
                `Available to lend is ${formatMoneyAmount(availableToLend)}. Top up the wallet or reduce the approved amount before funding.`
              );
            }
            const masterWalletBalance = await getLendingMasterWalletBalanceWith(tx);
            if (numericDisbursedAmount > masterWalletBalance) {
              throw new Error(
                `Lending Master Wallet balance is only ${formatMoneyAmount(masterWalletBalance)}. Top up the wallet or reduce the amount before funding.`
              );
            }
            const [borrowerWallet, masterWallet] = await Promise.all([
              ensureWalletWith5(tx, "USER", existing.borrowerId),
              ensureLendingMasterWalletWith(tx)
            ]);
            const disbursementIdempotencyKey = `loan_disbursement:admin_fund:${existing.id}`;
            const [existingDisbursement] = await tx.select().from(walletTransactionsTable).where(
              eq(
                walletTransactionsTable.idempotencyKey,
                disbursementIdempotencyKey
              )
            );
            const transaction = existingDisbursement ?? (await tx.insert(walletTransactionsTable).values({
              type: "LOAN_DISBURSEMENT",
              idempotencyKey: disbursementIdempotencyKey,
              fromWalletId: masterWallet.id,
              toWalletId: borrowerWallet.id,
              amount: formatMoneyAmount(numericDisbursedAmount),
              metadata: {
                applicationId: existing.id,
                opportunityId,
                borrowerId: existing.borrowerId
              }
            }).returning())[0];
            disbursementTransactionId = transaction.id;
            disbursedAmount = formatMoneyAmount(numericDisbursedAmount);
          }
          const pricingSnapshot = buildLoanPricingSnapshot({
            principalAmount: pricingPrincipalAmount,
            appreciationAmount: borrowerAppreciationAmount,
            termMonths,
            repaymentFrequency,
            processingFeePct
          });
          const updates = {
            loanType,
            status: finalStatus,
            opportunityId,
            approvedAmount: parsed.data.approvedAmount !== void 0 ? parsed.data.approvedAmount || null : existing.approvedAmount,
            reviewNote: parsed.data.reviewNote !== void 0 ? parsed.data.reviewNote || null : existing.reviewNote,
            term: pricingSnapshot.termLabel,
            repaymentSchedule: pricingSnapshot.repaymentScheduleLabel,
            termMonths: pricingSnapshot.termMonths,
            borrowerAppreciationAmount: formatMoneyAmount(
              borrowerAppreciationAmount
            ),
            repaymentFrequency,
            processingFeePct: parsed.data.processingFeePct !== void 0 || existing.processingFeePct !== null ? formatMoneyAmount(processingFeePct) : null,
            wwnMarginPct: formatMoneyAmount(templateWwnMarginPct),
            reserveContributionPct: formatMoneyAmount(
              templateReserveContributionPct
            ),
            platformAppreciationSharePct: formatMoneyAmount(
              lockedPlatformAppreciationSharePct
            ),
            pricingLockedAt: now,
            totalRepayableAmount: formatMoneyAmount(
              pricingSnapshot.totalRepayableAmount
            ),
            estimatedInstallmentAmount: formatMoneyAmount(
              pricingSnapshot.estimatedInstallmentAmount
            ),
            funderOpportunityTitle,
            reviewedByAdminId: adminId,
            reviewedAt: now,
            updatedAt: now
          };
          if (existing.status === "APPROVED_RESERVED") {
            updates.reservedAt = null;
            updates.reservedByAdminId = null;
          }
          if (nextStatus === "FUNDED") {
            updates.disbursedAt = existing.disbursedAt ?? now;
            updates.disbursementTransactionId = disbursementTransactionId;
            if (disbursedAmount !== null) {
              updates.disbursedAmount = disbursedAmount;
            }
          }
          const [application] = await tx.update(loanApplicationsTable).set(updates).where(eq(loanApplicationsTable.id, id)).returning();
          if (application && ["FUNDED", "REPAYING"].includes(finalStatus)) {
            const existingRepayments = await tx.select({
              id: loanRepaymentsTable.id,
              dueDate: loanRepaymentsTable.dueDate,
              amount: loanRepaymentsTable.amount,
              paidAmount: loanRepaymentsTable.paidAmount,
              principalPaidAmount: loanRepaymentsTable.principalPaidAmount,
              returnPaidAmount: loanRepaymentsTable.returnPaidAmount,
              feePaidAmount: loanRepaymentsTable.feePaidAmount,
              creditedToPoolAmount: loanRepaymentsTable.creditedToPoolAmount,
              status: loanRepaymentsTable.status
            }).from(loanRepaymentsTable).where(eq(loanRepaymentsTable.loanApplicationId, application.id)).orderBy(asc(loanRepaymentsTable.dueDate));
            const schedule = buildLendingRepaymentSchedule({
              totalAmount: pricingSnapshot.totalRepayableAmount,
              termMonths: pricingSnapshot.termMonths,
              repaymentFrequency,
              firstDueDate: addPeriod2(
                application.disbursedAt ?? now,
                repaymentFrequency,
                1
              )
            });
            const shouldReplaceSchedule = existingRepayments.length > 0 && canReplaceLoanRepaymentSchedule(existingRepayments) && !doesLoanRepaymentScheduleMatch(existingRepayments, schedule);
            if (shouldReplaceSchedule) {
              await tx.delete(loanRepaymentsTable).where(eq(loanRepaymentsTable.loanApplicationId, application.id));
            }
            if (schedule.length > 0 && (existingRepayments.length === 0 || shouldReplaceSchedule)) {
              await tx.insert(loanRepaymentsTable).values(
                schedule.map((entry) => ({
                  loanApplicationId: application.id,
                  dueDate: entry.dueDate,
                  amount: entry.amount
                }))
              );
            }
          }
          return {
            application,
            previousStatus: existing.status,
            borrowerId: existing.borrowerId,
            loanType
          };
        });
        if (!updated) {
          return res.status(404).json({ message: "Application not found." });
        }
        if (updated.previousStatus !== updated.application.status) {
          const notification = buildBorrowerLendingStatusNotification({
            loanType: updated.loanType,
            status: updated.application.status,
            approvedAmount: updated.application.approvedAmount,
            disbursedAmount: updated.application.disbursedAmount
          });
          if (notification) {
            const inApp = await notifyInAppWith(db, {
              userId: updated.borrowerId,
              category: "LENDING",
              severity: notification.severity,
              title: notification.title,
              body: notification.body,
              actionLabel: "Open Lending",
              actionHref: getLendingDashboardHref(updated.loanType, "BORROWER")
            });
            publishLiveEventToUser(updated.borrowerId, {
              kind: "DATA_CHANGED",
              scopes: ["lending"],
              payload: {
                action: "lending_application_updated",
                applicationId: updated.application.id,
                status: updated.application.status,
                loanType: updated.loanType
              }
            });
            queueLendingPushNotification({
              userId: updated.borrowerId,
              idempotencyKey: `lending_application_status:${updated.application.id}:${updated.application.status}`,
              title: notification.title,
              body: notification.body,
              actionHref: getLendingDashboardHref(updated.loanType, "BORROWER"),
              notificationId: inApp.id,
              metadata: {
                kind: "lending_application_status",
                applicationId: updated.application.id,
                loanType: updated.loanType,
                status: updated.application.status
              }
            });
          }
        }
        return res.json({ application: updated.application });
      } catch (err) {
        if (err instanceof Error) {
          return res.status(400).json({ message: err.message });
        }
        return handleError2(err, res);
      }
    });
    router3.post("/lending/applications/:id/repayments", async (req, res) => {
      try {
        const applicationId = Number(req.params.id);
        if (!Number.isFinite(applicationId) || applicationId <= 0) {
          return res.status(400).json({ message: "Invalid application id." });
        }
        const schema = external_exports.object({
          dueDate: external_exports.string().transform((s) => new Date(s)),
          amount: external_exports.string()
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success)
          return res.status(400).json({ errors: parsed.error.flatten() });
        const [application] = await db.select({
          id: loanApplicationsTable.id,
          status: loanApplicationsTable.status
        }).from(loanApplicationsTable).where(eq(loanApplicationsTable.id, applicationId));
        if (!application) {
          return res.status(404).json({ message: "Application not found." });
        }
        if (!REPAYMENT_CREATEABLE_APPLICATION_STATUSES.has(application.status)) {
          return res.status(400).json({
            message: "Repayment entries can only be created for funded or repaying applications."
          });
        }
        const [repayment] = await db.insert(loanRepaymentsTable).values({
          loanApplicationId: applicationId,
          dueDate: parsed.data.dueDate,
          amount: parsed.data.amount
        }).returning();
        return res.status(201).json({ repayment });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.patch("/lending/repayments/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        if (!Number.isFinite(id) || id <= 0) {
          return res.status(400).json({ message: "Invalid repayment id." });
        }
        const schema = external_exports.object({
          amount: external_exports.string().optional(),
          dueDate: external_exports.string().transform((s) => new Date(s)).optional(),
          status: external_exports.enum(["PENDING", "PAID", "LATE", "WAIVED"]).optional(),
          method: external_exports.enum(["STRIPE", "EFT", "INTERAC", "WIRE", "WALLET"]).optional(),
          paidAmount: external_exports.string().optional(),
          returnPaidAmount: external_exports.string().optional()
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success)
          return res.status(400).json({ errors: parsed.error.flatten() });
        const updated = await db.transaction(async (tx) => {
          await tx.execute(
            sql`select 1 from loan_repayments where id = ${id} for update`
          );
          const [existing] = await tx.select().from(loanRepaymentsTable).where(eq(loanRepaymentsTable.id, id));
          if (!existing) {
            throw new Error("Repayment not found.");
          }
          const [application] = await tx.select({
            borrowerId: loanApplicationsTable.borrowerId,
            opportunityId: loanApplicationsTable.opportunityId,
            loanType: loanApplicationsTable.loanType,
            status: loanApplicationsTable.status
          }).from(loanApplicationsTable).where(eq(loanApplicationsTable.id, existing.loanApplicationId));
          if (!application) {
            throw new Error("Application not found.");
          }
          if (!REPAYMENT_SERVICEABLE_APPLICATION_STATUSES.has(application.status)) {
            throw new Error(
              "Repayments can only be managed for funded, repaying, or closed applications."
            );
          }
          const effectiveStatus = parsed.data.status ?? existing.status;
          const updates = { ...parsed.data };
          const nextPaidAmount = parsed.data.paidAmount !== void 0 ? parseMoneyAmount(parsed.data.paidAmount) : effectiveStatus === "PAID" ? parseMoneyAmount(existing.amount) : parseMoneyAmount(existing.paidAmount);
          const previouslyRecognizedReturn = parseMoneyAmount(
            existing.returnPaidAmount
          );
          const nextReturnPaidAmount = parsed.data.returnPaidAmount !== void 0 ? parseMoneyAmount(parsed.data.returnPaidAmount) : parseMoneyAmount(existing.returnPaidAmount);
          if (effectiveStatus === "PAID") {
            updates.paidAt = /* @__PURE__ */ new Date();
            if (!parsed.data.paidAmount) {
              updates.paidAmount = existing.amount;
            }
          } else if (parsed.data.paidAmount !== void 0) {
            updates.paidAmount = parsed.data.paidAmount || null;
            updates.paidAt = null;
          } else if (effectiveStatus === "WAIVED") {
            updates.paidAt = null;
          }
          const previouslyCreditedToPool = parseMoneyAmount(
            existing.creditedToPoolAmount
          );
          if (nextPaidAmount < previouslyCreditedToPool) {
            throw new Error(
              "Paid amount cannot be reduced below the amount already credited back to the pool."
            );
          }
          if (nextReturnPaidAmount < previouslyRecognizedReturn) {
            throw new Error(
              "Return portion cannot be reduced below the amount already recognized for investors."
            );
          }
          if (nextReturnPaidAmount > nextPaidAmount) {
            throw new Error(
              "Return portion cannot exceed the total paid amount for this repayment."
            );
          }
          const creditDelta = Math.max(
            0,
            nextPaidAmount - previouslyCreditedToPool
          );
          const returnDelta = Math.max(
            0,
            nextReturnPaidAmount - previouslyRecognizedReturn
          );
          const principalDelta = Math.max(0, creditDelta - returnDelta);
          let repaymentWalletTransactionId = null;
          if (creditDelta > 0) {
            const masterWallet = await ensureLendingMasterWalletWith(tx);
            const repaymentWalletTransactionIdempotencyKey = `loan_repayment_admin_credit:${existing.id}:${formatMoneyAmount(nextPaidAmount)}:${formatMoneyAmount(nextReturnPaidAmount)}`;
            const [existingTx] = await tx.select().from(walletTransactionsTable).where(
              eq(
                walletTransactionsTable.idempotencyKey,
                repaymentWalletTransactionIdempotencyKey
              )
            );
            if (existingTx) {
              repaymentWalletTransactionId = existingTx.id;
            } else {
              const [repaymentWalletTransaction] = await tx.insert(walletTransactionsTable).values({
                type: "LOAN_REPAYMENT",
                idempotencyKey: repaymentWalletTransactionIdempotencyKey,
                toWalletId: masterWallet.id,
                amount: formatMoneyAmount(creditDelta),
                metadata: {
                  repaymentId: existing.id,
                  applicationId: existing.loanApplicationId,
                  borrowerId: application.borrowerId,
                  opportunityId: application.opportunityId,
                  method: parsed.data.method ?? existing.method ?? null,
                  principalDelta: formatMoneyAmount(principalDelta),
                  returnDelta: formatMoneyAmount(returnDelta)
                }
              }).returning();
              repaymentWalletTransactionId = repaymentWalletTransaction?.id ?? null;
            }
            updates.creditedToPoolAmount = formatMoneyAmount(nextPaidAmount);
          }
          updates.principalPaidAmount = formatMoneyAmount(
            Math.max(0, nextPaidAmount - nextReturnPaidAmount)
          );
          updates.returnPaidAmount = formatMoneyAmount(nextReturnPaidAmount);
          const [repayment] = await tx.update(loanRepaymentsTable).set(updates).where(eq(loanRepaymentsTable.id, id)).returning();
          if (creditDelta > 0) {
            await createLendingReturnAllocationEvent({
              conn: tx,
              opportunityId: application.opportunityId ?? 0,
              applicationId: existing.loanApplicationId,
              repaymentId: existing.id,
              walletTransactionId: repaymentWalletTransactionId,
              grossAmount: creditDelta,
              principalAmount: principalDelta,
              returnAmount: returnDelta,
              occurredAt: repayment.paidAt ?? /* @__PURE__ */ new Date()
            });
          }
          return {
            repayment,
            borrowerId: application.borrowerId,
            opportunityId: application.opportunityId,
            loanType: normalizeLendingLoanType(application.loanType),
            previousStatus: existing.status,
            creditDelta,
            returnDelta
          };
        });
        await updateCreditScore(updated.borrowerId);
        const borrowerProductLabel = getLendingProductLabel(updated.loanType);
        const borrowerActionHref = getLendingDashboardHref(
          updated.loanType,
          "BORROWER"
        );
        const paidAmountLabel = formatMoneyAmount(
          parseMoneyAmount(
            updated.repayment.paidAmount ?? updated.repayment.amount
          )
        );
        let borrowerRepaymentNotification = null;
        if (updated.creditDelta > 0) {
          borrowerRepaymentNotification = {
            severity: "SUCCESS",
            title: `${borrowerProductLabel} repayment received`,
            body: `WWN recorded your ${borrowerProductLabel} repayment of $${paidAmountLabel}.`
          };
        } else if (updated.previousStatus !== updated.repayment.status && updated.repayment.status === "LATE") {
          borrowerRepaymentNotification = {
            severity: "WARNING",
            title: `${borrowerProductLabel} repayment marked late`,
            body: `Your ${borrowerProductLabel} repayment due on ${updated.repayment.dueDate.toISOString()} is marked late.`
          };
        } else if (updated.previousStatus !== updated.repayment.status && updated.repayment.status === "WAIVED") {
          borrowerRepaymentNotification = {
            severity: "INFO",
            title: `${borrowerProductLabel} repayment waived`,
            body: `WWN waived this ${borrowerProductLabel} repayment entry.`
          };
        }
        if (borrowerRepaymentNotification) {
          const inApp = await notifyInAppWith(db, {
            userId: updated.borrowerId,
            category: "LENDING",
            severity: borrowerRepaymentNotification.severity,
            title: borrowerRepaymentNotification.title,
            body: borrowerRepaymentNotification.body,
            actionLabel: "Open Lending",
            actionHref: borrowerActionHref
          });
          publishLiveEventToUser(updated.borrowerId, {
            kind: "DATA_CHANGED",
            scopes: ["lending"],
            payload: {
              action: "lending_repayment_updated",
              repaymentId: updated.repayment.id,
              applicationId: updated.repayment.loanApplicationId,
              loanType: updated.loanType,
              status: updated.repayment.status
            }
          });
          queueLendingPushNotification({
            userId: updated.borrowerId,
            idempotencyKey: `lending_repayment_borrower:${updated.repayment.id}:${updated.repayment.status}:${paidAmountLabel}`,
            title: borrowerRepaymentNotification.title,
            body: borrowerRepaymentNotification.body,
            actionHref: borrowerActionHref,
            notificationId: inApp.id,
            metadata: {
              kind: "lending_repayment_borrower",
              repaymentId: updated.repayment.id,
              applicationId: updated.repayment.loanApplicationId,
              loanType: updated.loanType,
              status: updated.repayment.status
            }
          });
        }
        if (updated.returnDelta > 0 && updated.opportunityId) {
          const allocations = await db.select({
            userId: lendingOpportunityReturnAllocationsTable.userId,
            allocatedReturnAmount: lendingOpportunityReturnAllocationsTable.allocatedReturnAmount
          }).from(lendingOpportunityReturnAllocationsTable).innerJoin(
            lendingOpportunityReturnEventsTable,
            eq(
              lendingOpportunityReturnAllocationsTable.returnEventId,
              lendingOpportunityReturnEventsTable.id
            )
          ).where(
            eq(
              lendingOpportunityReturnEventsTable.repaymentId,
              updated.repayment.id
            )
          );
          for (const allocation of allocations) {
            const allocatedReturnAmount = parseMoneyAmount(
              allocation.allocatedReturnAmount
            );
            if (allocatedReturnAmount <= 0) continue;
            const lenderActionHref = getLendingDashboardHref(
              updated.loanType,
              "FUNDER"
            );
            const amountLabel = formatMoneyAmount(allocatedReturnAmount);
            const title = updated.loanType === "COMMUNITY_LENDING" ? "Member yield recognized" : "Investor return recognized";
            const body = updated.loanType === "COMMUNITY_LENDING" ? `A Community Lending repayment recognized $${amountLabel} in member yield for your funded position.` : `A P2P Lending repayment recognized $${amountLabel} in investor return for your portfolio.`;
            const inApp = await notifyInAppWith(db, {
              userId: allocation.userId,
              category: "LENDING",
              severity: "SUCCESS",
              title,
              body,
              actionLabel: "Open Lending",
              actionHref: lenderActionHref
            });
            publishLiveEventToUser(allocation.userId, {
              kind: "DATA_CHANGED",
              scopes: ["lending"],
              payload: {
                action: "lending_return_recognized",
                repaymentId: updated.repayment.id,
                applicationId: updated.repayment.loanApplicationId,
                loanType: updated.loanType,
                allocatedReturnAmount: amountLabel
              }
            });
            queueLendingPushNotification({
              userId: allocation.userId,
              idempotencyKey: `lending_return_allocation:${updated.repayment.id}:${allocation.userId}:${amountLabel}`,
              title,
              body,
              actionHref: lenderActionHref,
              notificationId: inApp.id,
              metadata: {
                kind: "lending_return_allocation",
                repaymentId: updated.repayment.id,
                applicationId: updated.repayment.loanApplicationId,
                loanType: updated.loanType,
                allocatedReturnAmount: amountLabel
              }
            });
          }
        }
        return res.json({ repayment: updated.repayment });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/lending/pools", async (_req, res) => {
      try {
        const pools = await db.select({
          opportunity: lendingOpportunitiesTable,
          templateMinRequestAmount: lendingTemplatesTable.minRequestAmount,
          templateMaxRequestAmount: lendingTemplatesTable.maxRequestAmount
        }).from(lendingOpportunitiesTable).leftJoin(
          lendingTemplatesTable,
          eq(lendingOpportunitiesTable.templateId, lendingTemplatesTable.id)
        ).orderBy(desc(lendingOpportunitiesTable.createdAt));
        const metricsMap = await getPoolOperationalMetricsMapWith(
          db,
          pools.map((row) => ({
            id: row.opportunity.id,
            committedAmount: row.opportunity.committedAmount,
            expectedReturnPct: row.opportunity.expectedReturnPct,
            termMonths: row.opportunity.termMonths
          }))
        );
        const commitmentCounts = await db.select({
          opportunityId: lendingCommitmentsTable.opportunityId,
          count: count(),
          total: sum(lendingCommitmentsTable.amount)
        }).from(lendingCommitmentsTable).groupBy(lendingCommitmentsTable.opportunityId);
        const countMap = {};
        for (const row of commitmentCounts) {
          countMap[row.opportunityId] = {
            count: Number(row.count),
            total: row.total ?? "0"
          };
        }
        const serializedPools = await Promise.all(
          pools.map(async (row) => {
            const p = row.opportunity;
            const metrics = metricsMap.get(p.id) ?? {
              walletBalance: 0,
              reservedAmount: 0,
              availableToLend: 0,
              outstandingPrincipal: 0,
              repaymentsReceived: 0,
              projectedReturn: 0,
              realizedReturn: 0,
              allocatedReturn: 0,
              unrealizedReturn: 0,
              realizedYieldPct: 0,
              activeLoanCount: 0,
              waitlistedApplicationCount: 0
            };
            return {
              ...p,
              borrowerAppreciationAmount: formatMoneyAmount(
                parseMoneyAmount(p.borrowerAppreciationAmount)
              ),
              minRequestAmount: formatMoneyAmount(
                parseMoneyAmount(row.templateMinRequestAmount ?? "0")
              ),
              maxRequestAmount: formatMoneyAmount(
                parseMoneyAmount(row.templateMaxRequestAmount ?? "0")
              ),
              borrowerTermMonths: p.borrowerTermMonths,
              repaymentFrequency: p.repaymentFrequency,
              processingFeePct: p.processingFeePct !== null ? formatMoneyAmount(parseMoneyAmount(p.processingFeePct)) : null,
              wwnMarginPct: formatMoneyAmount(parseMoneyAmount(p.wwnMarginPct)),
              reserveContributionPct: formatMoneyAmount(
                parseMoneyAmount(p.reserveContributionPct)
              ),
              platformAppreciationSharePct: formatMoneyAmount(
                parseMoneyAmount(p.platformAppreciationSharePct)
              ),
              minAppreciationType: p.minAppreciationType,
              minAppreciationValue: formatMoneyAmount(
                parseMoneyAmount(p.minAppreciationValue)
              ),
              minAppreciationTiers: p.minAppreciationTiers ?? null,
              expectedReturnPct: formatMoneyAmount(
                parseMoneyAmount(p.expectedReturnPct)
              ),
              termMonths: p.termMonths,
              returnModel: p.returnModel,
              commitmentCount: countMap[p.id]?.count ?? 0,
              availableAmount: formatMoneyAmount(
                Math.max(
                  0,
                  parseMoneyAmount(p.targetAmount) - parseMoneyAmount(p.committedAmount)
                )
              ),
              walletBalance: formatMoneyAmount(metrics.walletBalance),
              reservedAmount: formatMoneyAmount(metrics.reservedAmount),
              availableToLend: formatMoneyAmount(metrics.availableToLend),
              outstandingPrincipal: formatMoneyAmount(metrics.outstandingPrincipal),
              repaymentsReceived: formatMoneyAmount(metrics.repaymentsReceived),
              projectedReturn: formatMoneyAmount(metrics.projectedReturn),
              realizedReturn: formatMoneyAmount(metrics.realizedReturn),
              allocatedReturn: formatMoneyAmount(metrics.allocatedReturn),
              unrealizedReturn: formatMoneyAmount(metrics.unrealizedReturn),
              realizedYieldPct: formatMoneyAmount(metrics.realizedYieldPct),
              activeLoanCount: metrics.activeLoanCount,
              waitlistedApplicationCount: metrics.waitlistedApplicationCount
            };
          })
        );
        return res.json({
          pools: serializedPools,
          total: serializedPools.length
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/lending/pools/templates", async (_req, res) => {
      try {
        const pools = await db.select().from(lendingTemplatesTable).where(eq(lendingTemplatesTable.isSnapshot, false)).orderBy(desc(lendingTemplatesTable.createdAt));
        const serializedPools = pools.map((p) => ({
          ...p,
          borrowerAppreciationAmount: formatMoneyAmount(
            parseMoneyAmount(p.borrowerAppreciationAmount)
          ),
          minRequestAmount: formatMoneyAmount(parseMoneyAmount(p.minRequestAmount)),
          maxRequestAmount: formatMoneyAmount(parseMoneyAmount(p.maxRequestAmount)),
          processingFeePct: p.processingFeePct !== null ? formatMoneyAmount(parseMoneyAmount(p.processingFeePct)) : null,
          wwnMarginPct: formatMoneyAmount(parseMoneyAmount(p.wwnMarginPct)),
          reserveContributionPct: formatMoneyAmount(
            parseMoneyAmount(p.reserveContributionPct)
          ),
          platformAppreciationSharePct: formatMoneyAmount(
            parseMoneyAmount(p.platformAppreciationSharePct)
          ),
          minAppreciationValue: formatMoneyAmount(
            parseMoneyAmount(p.minAppreciationValue)
          ),
          expectedReturnPct: formatMoneyAmount(
            parseMoneyAmount(p.expectedReturnPct)
          ),
          minAppreciationTiers: p.minAppreciationTiers ?? null
        }));
        return res.json({ pools: serializedPools, total: serializedPools.length });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/lending/pools", async (req, res) => {
      try {
        const adminId = req.admin.id;
        const schema = external_exports.object({
          title: external_exports.string().min(1),
          description: external_exports.string().min(1),
          termsHtml: external_exports.string().optional().nullable(),
          loanType: external_exports.enum(["COMMUNITY_LENDING", "P2P_LENDING"]).default("P2P_LENDING"),
          minCommitment: external_exports.string().min(1),
          minRequestAmount: external_exports.string().min(1).default("500.00"),
          maxRequestAmount: external_exports.coerce.number().positive().optional(),
          borrowerTermMonths: external_exports.coerce.number().int().positive(),
          repaymentFrequency: external_exports.enum(["WEEKLY", "BIWEEKLY", "MONTHLY"]),
          processingFeePct: external_exports.coerce.number().nonnegative().optional(),
          wwnMarginPct: external_exports.coerce.number().min(0).max(100).optional(),
          reserveContributionPct: external_exports.coerce.number().min(0).max(100).optional(),
          platformAppreciationSharePct: external_exports.coerce.number().min(0).max(50).optional(),
          minAppreciationType: external_exports.enum(["NONE", "FIXED", "PCT_OF_PRINCIPAL", "TERM_TIERED"]).optional(),
          minAppreciationValue: external_exports.coerce.number().nonnegative().optional(),
          minAppreciationTiers: external_exports.any().optional(),
          economicsUpdateReason: external_exports.string().min(1).optional(),
          expectedReturnPct: external_exports.coerce.number().positive().optional(),
          termMonths: external_exports.coerce.number().int().positive().optional(),
          minBorrowerPlanTier: external_exports.enum(["STARTER", "PROFESSIONAL", "ELITE", "ENTREPRENEUR"]).default("STARTER"),
          borrowerType: external_exports.string().optional(),
          status: external_exports.enum(["DRAFT", "OPEN", "PAUSED", "CLOSED"]).default("OPEN")
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success)
          return res.status(400).json({ errors: parsed.error.flatten() });
        const normalizedTermsHtml = typeof parsed.data.termsHtml === "string" && parsed.data.termsHtml.trim().length > 0 ? parsed.data.termsHtml.trim() : null;
        const minCommitment = parseMoneyAmount(parsed.data.minCommitment);
        const minRequestAmount = parseMoneyAmount(parsed.data.minRequestAmount);
        const maxRequestAmount = parsed.data.maxRequestAmount ?? LENDING_POOL_MAX_REQUEST_AMOUNT;
        const borrowerTermMonths = parsed.data.borrowerTermMonths;
        const repaymentFrequency = parsed.data.repaymentFrequency;
        const processingFeePct = parsed.data.processingFeePct;
        const wwnMarginPct = parsed.data.wwnMarginPct ?? 0;
        const reserveContributionPct = parsed.data.reserveContributionPct ?? 0;
        const platformAppreciationSharePct = parsed.data.platformAppreciationSharePct ?? 0;
        const minAppreciationType = parsed.data.minAppreciationType ?? "NONE";
        const minAppreciationValue = parsed.data.minAppreciationValue ?? 0;
        const minAppreciationTiers = parsed.data.minAppreciationTiers ?? null;
        const economicsUpdateReason = parsed.data.economicsUpdateReason ?? null;
        if (minCommitment <= 0 || minRequestAmount <= 0) {
          return res.status(400).json({
            message: "Minimum commitment and minimum request amount must all be positive."
          });
        }
        if (maxRequestAmount < minRequestAmount) {
          return res.status(400).json({
            message: "Maximum request amount cannot be lower than minimum request amount."
          });
        }
        if (maxRequestAmount > LENDING_POOL_MAX_REQUEST_AMOUNT) {
          return res.status(400).json({
            message: `Maximum request amount cannot exceed ${formatMoneyAmount(LENDING_POOL_MAX_REQUEST_AMOUNT)}.`
          });
        }
        if (borrowerTermMonths <= 0) {
          return res.status(400).json({
            message: "Borrower pricing must include a valid positive term."
          });
        }
        const communityTerms = deriveCommunityTemplateReturnTerms({
          minRequestAmount,
          borrowerTermMonths,
          platformAppreciationSharePct,
          minAppreciationType,
          minAppreciationValue,
          minAppreciationTiers
        });
        const expectedReturnPct = parsed.data.loanType === "COMMUNITY_LENDING" ? communityTerms.expectedReturnPct : parsed.data.expectedReturnPct ?? 0;
        const borrowerRatePct = parsed.data.loanType === "COMMUNITY_LENDING" ? 0 : calculateP2PBorrowerRatePct({
          investorRatePct: expectedReturnPct,
          wwnMarginPct,
          reserveContributionPct
        });
        const p2pTemplatePricing = parsed.data.loanType === "COMMUNITY_LENDING" ? null : buildP2PRatePricingSnapshot({
          principalAmount: minRequestAmount,
          termMonths: borrowerTermMonths,
          investorRatePct: expectedReturnPct,
          wwnMarginPct,
          reserveContributionPct
        });
        const lockedPlatformAppreciationSharePct = parsed.data.loanType === "COMMUNITY_LENDING" ? platformAppreciationSharePct : p2pTemplatePricing?.platformSharePctOfBorrowerRate ?? 0;
        const termMonths = parsed.data.loanType === "COMMUNITY_LENDING" ? communityTerms.termMonths : parsed.data.termMonths ?? 0;
        if (isP2PLendingLoanType(parsed.data.loanType) && expectedReturnPct <= 0) {
          return res.status(400).json({
            message: "P2P Lending templates require a positive Investor Rate."
          });
        }
        if (isP2PLendingLoanType(parsed.data.loanType) && borrowerRatePct <= 0) {
          return res.status(400).json({
            message: "P2P Lending templates require a positive Borrower Rate."
          });
        }
        if (isCommunityLendingLoanType(parsed.data.loanType) && (parsed.data.expectedReturnPct !== void 0 || parsed.data.wwnMarginPct !== void 0 || parsed.data.reserveContributionPct !== void 0 || parsed.data.termMonths !== void 0)) {
          return res.status(400).json({
            message: "Community Lending member yield is derived from the appreciation rule and borrower term. Do not set P2P rate fields manually."
          });
        }
        if (termMonths <= 0) {
          return res.status(400).json({
            message: "Investor return terms must include a valid positive term."
          });
        }
        const [pool2] = await db.insert(lendingTemplatesTable).values({
          ...parsed.data,
          termsHtml: normalizedTermsHtml,
          borrowerAppreciationAmount: formatMoneyAmount(0),
          borrowerTermMonths,
          repaymentFrequency,
          maxRequestAmount: formatMoneyAmount(maxRequestAmount),
          processingFeePct: processingFeePct !== void 0 ? formatMoneyAmount(processingFeePct) : null,
          wwnMarginPct: formatMoneyAmount(wwnMarginPct),
          reserveContributionPct: formatMoneyAmount(reserveContributionPct),
          platformAppreciationSharePct: formatMoneyAmount(
            lockedPlatformAppreciationSharePct
          ),
          minAppreciationType,
          minAppreciationValue: formatMoneyAmount(minAppreciationValue),
          minAppreciationTiers,
          economicsUpdatedAt: economicsUpdateReason ? /* @__PURE__ */ new Date() : null,
          economicsUpdatedByAdminId: economicsUpdateReason ? adminId : null,
          economicsUpdateReason,
          expectedReturnPct: formatMoneyAmount(expectedReturnPct),
          termMonths,
          expectedReturn: parsed.data.loanType === "COMMUNITY_LENDING" ? communityTerms.expectedReturn : formatExpectedReturnLabel(expectedReturnPct),
          term: parsed.data.loanType === "COMMUNITY_LENDING" ? communityTerms.term : formatTermMonthsLabel(termMonths)
        }).returning();
        await ensureLendingMasterWallet();
        return res.status(201).json({ pool: pool2 });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.patch("/lending/pools/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        const adminId = req.admin.id;
        const schema = external_exports.object({
          title: external_exports.string().min(1).optional(),
          description: external_exports.string().optional(),
          termsHtml: external_exports.string().optional().nullable(),
          loanType: external_exports.enum(["COMMUNITY_LENDING", "P2P_LENDING"]).optional(),
          minCommitment: external_exports.string().optional(),
          minRequestAmount: external_exports.string().optional(),
          maxRequestAmount: external_exports.coerce.number().positive().optional(),
          borrowerTermMonths: external_exports.coerce.number().int().positive().optional(),
          repaymentFrequency: external_exports.enum(["WEEKLY", "BIWEEKLY", "MONTHLY"]).optional(),
          processingFeePct: external_exports.coerce.number().nonnegative().optional(),
          wwnMarginPct: external_exports.coerce.number().min(0).max(100).optional(),
          reserveContributionPct: external_exports.coerce.number().min(0).max(100).optional(),
          platformAppreciationSharePct: external_exports.coerce.number().min(0).max(50).optional(),
          minAppreciationType: external_exports.enum(["NONE", "FIXED", "PCT_OF_PRINCIPAL", "TERM_TIERED"]).optional(),
          minAppreciationValue: external_exports.coerce.number().nonnegative().optional(),
          minAppreciationTiers: external_exports.any().optional(),
          economicsUpdateReason: external_exports.string().min(1).optional(),
          expectedReturnPct: external_exports.coerce.number().positive().optional(),
          termMonths: external_exports.coerce.number().int().positive().optional(),
          minBorrowerPlanTier: external_exports.enum(["STARTER", "PROFESSIONAL", "ELITE", "ENTREPRENEUR"]).optional(),
          borrowerType: external_exports.string().optional(),
          status: external_exports.enum(["DRAFT", "OPEN", "PAUSED", "CLOSED"]).optional()
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success)
          return res.status(400).json({ errors: parsed.error.flatten() });
        const [existingTemplate] = await db.select().from(lendingTemplatesTable).where(eq(lendingTemplatesTable.id, id));
        if (!existingTemplate) {
          return res.status(404).json({ message: "Template not found." });
        }
        const normalizedTermsHtmlPatch = parsed.data.termsHtml !== void 0 ? typeof parsed.data.termsHtml === "string" && parsed.data.termsHtml.trim().length > 0 ? parsed.data.termsHtml.trim() : null : void 0;
        const minCommitment = parsed.data.minCommitment !== void 0 ? parseMoneyAmount(parsed.data.minCommitment) : parseMoneyAmount(existingTemplate.minCommitment);
        const minRequestAmount = parsed.data.minRequestAmount !== void 0 ? parseMoneyAmount(parsed.data.minRequestAmount) : parseMoneyAmount(existingTemplate.minRequestAmount);
        const maxRequestAmount = parsed.data.maxRequestAmount !== void 0 ? parsed.data.maxRequestAmount : parseMoneyAmount(existingTemplate.maxRequestAmount);
        const borrowerTermMonths = parsed.data.borrowerTermMonths !== void 0 ? parsed.data.borrowerTermMonths : existingTemplate.borrowerTermMonths;
        const repaymentFrequency = parsed.data.repaymentFrequency ?? existingTemplate.repaymentFrequency;
        const processingFeePct = parsed.data.processingFeePct !== void 0 ? parsed.data.processingFeePct : parseMoneyAmount(existingTemplate.processingFeePct);
        const wwnMarginPct = parsed.data.wwnMarginPct !== void 0 ? parsed.data.wwnMarginPct : parseMoneyAmount(existingTemplate.wwnMarginPct);
        const reserveContributionPct = parsed.data.reserveContributionPct !== void 0 ? parsed.data.reserveContributionPct : parseMoneyAmount(existingTemplate.reserveContributionPct);
        const platformAppreciationSharePct = parsed.data.platformAppreciationSharePct !== void 0 ? parsed.data.platformAppreciationSharePct : parseMoneyAmount(existingTemplate.platformAppreciationSharePct);
        const minAppreciationType = parsed.data.minAppreciationType ?? existingTemplate.minAppreciationType;
        const minAppreciationValue = parsed.data.minAppreciationValue !== void 0 ? parsed.data.minAppreciationValue : parseMoneyAmount(existingTemplate.minAppreciationValue);
        const minAppreciationTiers = parsed.data.minAppreciationTiers !== void 0 ? parsed.data.minAppreciationTiers : existingTemplate.minAppreciationTiers;
        const economicsUpdateReason = parsed.data.economicsUpdateReason ?? null;
        const loanType = parsed.data.loanType !== void 0 ? parsed.data.loanType : normalizeLendingLoanType(existingTemplate.loanType);
        if (minCommitment <= 0 || minRequestAmount <= 0) {
          return res.status(400).json({
            message: "Minimum commitment and minimum request amount must all be positive."
          });
        }
        if (maxRequestAmount < minRequestAmount) {
          return res.status(400).json({
            message: "Maximum request amount cannot be lower than minimum request amount."
          });
        }
        if (maxRequestAmount > LENDING_POOL_MAX_REQUEST_AMOUNT) {
          return res.status(400).json({
            message: `Maximum request amount cannot exceed ${formatMoneyAmount(LENDING_POOL_MAX_REQUEST_AMOUNT)}.`
          });
        }
        if (borrowerTermMonths <= 0) {
          return res.status(400).json({
            message: "Borrower pricing must include a valid positive term."
          });
        }
        const communityTerms = deriveCommunityTemplateReturnTerms({
          minRequestAmount,
          borrowerTermMonths,
          platformAppreciationSharePct,
          minAppreciationType: minAppreciationType ?? "NONE",
          minAppreciationValue,
          minAppreciationTiers
        });
        const expectedReturnPct = loanType === "COMMUNITY_LENDING" ? communityTerms.expectedReturnPct : parsed.data.expectedReturnPct !== void 0 ? parsed.data.expectedReturnPct : parseMoneyAmount(existingTemplate.expectedReturnPct);
        const borrowerRatePct = loanType === "COMMUNITY_LENDING" ? 0 : calculateP2PBorrowerRatePct({
          investorRatePct: expectedReturnPct,
          wwnMarginPct,
          reserveContributionPct
        });
        const p2pTemplatePricing = loanType === "COMMUNITY_LENDING" ? null : buildP2PRatePricingSnapshot({
          principalAmount: minRequestAmount,
          termMonths: borrowerTermMonths,
          investorRatePct: expectedReturnPct,
          wwnMarginPct,
          reserveContributionPct
        });
        const lockedPlatformAppreciationSharePct = loanType === "COMMUNITY_LENDING" ? platformAppreciationSharePct : p2pTemplatePricing?.platformSharePctOfBorrowerRate ?? 0;
        const termMonths = loanType === "COMMUNITY_LENDING" ? communityTerms.termMonths : parsed.data.termMonths !== void 0 ? parsed.data.termMonths : existingTemplate.termMonths;
        if (isP2PLendingLoanType(loanType) && expectedReturnPct <= 0) {
          return res.status(400).json({
            message: "P2P Lending templates require a positive Investor Rate."
          });
        }
        if (isP2PLendingLoanType(loanType) && borrowerRatePct <= 0) {
          return res.status(400).json({
            message: "P2P Lending templates require a positive Borrower Rate."
          });
        }
        if (isCommunityLendingLoanType(loanType) && (parsed.data.expectedReturnPct !== void 0 || parsed.data.wwnMarginPct !== void 0 || parsed.data.reserveContributionPct !== void 0 || parsed.data.termMonths !== void 0)) {
          return res.status(400).json({
            message: "Community Lending member yield is derived from the appreciation rule and borrower term. Do not set P2P rate fields manually."
          });
        }
        if (termMonths <= 0) {
          return res.status(400).json({
            message: "Investor return terms must include a valid positive term."
          });
        }
        const isEconomicsUpdate = parsed.data.processingFeePct !== void 0 || parsed.data.wwnMarginPct !== void 0 || parsed.data.reserveContributionPct !== void 0 || parsed.data.platformAppreciationSharePct !== void 0 || parsed.data.minAppreciationType !== void 0 || parsed.data.minAppreciationValue !== void 0 || parsed.data.minAppreciationTiers !== void 0 || parsed.data.expectedReturnPct !== void 0;
        if (isEconomicsUpdate && !economicsUpdateReason) {
          return res.status(400).json({
            message: "Provide economicsUpdateReason when updating template economics."
          });
        }
        const [updated] = await db.update(lendingTemplatesTable).set({
          ...parsed.data,
          ...normalizedTermsHtmlPatch !== void 0 ? { termsHtml: normalizedTermsHtmlPatch } : {},
          loanType,
          borrowerTermMonths,
          repaymentFrequency,
          minCommitment: formatMoneyAmount(minCommitment),
          minRequestAmount: formatMoneyAmount(minRequestAmount),
          maxRequestAmount: formatMoneyAmount(maxRequestAmount),
          processingFeePct: parsed.data.processingFeePct !== void 0 || existingTemplate.processingFeePct !== null ? formatMoneyAmount(processingFeePct) : null,
          wwnMarginPct: formatMoneyAmount(wwnMarginPct),
          reserveContributionPct: formatMoneyAmount(reserveContributionPct),
          platformAppreciationSharePct: formatMoneyAmount(
            lockedPlatformAppreciationSharePct
          ),
          minAppreciationType: minAppreciationType ?? "NONE",
          minAppreciationValue: formatMoneyAmount(minAppreciationValue),
          minAppreciationTiers,
          economicsUpdatedAt: isEconomicsUpdate ? /* @__PURE__ */ new Date() : existingTemplate.economicsUpdatedAt,
          economicsUpdatedByAdminId: isEconomicsUpdate ? adminId : existingTemplate.economicsUpdatedByAdminId,
          economicsUpdateReason: isEconomicsUpdate ? economicsUpdateReason : existingTemplate.economicsUpdateReason,
          expectedReturnPct: formatMoneyAmount(expectedReturnPct),
          termMonths,
          expectedReturn: loanType === "COMMUNITY_LENDING" ? communityTerms.expectedReturn : formatExpectedReturnLabel(expectedReturnPct),
          term: loanType === "COMMUNITY_LENDING" ? communityTerms.term : formatTermMonthsLabel(termMonths),
          updatedAt: /* @__PURE__ */ new Date()
        }).where(eq(lendingTemplatesTable.id, id)).returning();
        return res.json({ pool: updated });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/lending/pools/:id/reconcile", async (req, res) => {
      try {
        const id = Number(req.params.id);
        if (!Number.isFinite(id) || id <= 0) {
          return res.status(400).json({ message: "Invalid pool id." });
        }
        const [opportunity] = await db.select().from(lendingOpportunitiesTable).where(eq(lendingOpportunitiesTable.id, id));
        if (!opportunity) {
          return res.status(404).json({ message: "Opportunity not found." });
        }
        const [confirmedAgg] = await db.select({
          count: count(),
          total: sum(lendingCommitmentsTable.amount)
        }).from(lendingCommitmentsTable).where(
          and(
            eq(lendingCommitmentsTable.opportunityId, id),
            eq(lendingCommitmentsTable.status, "CONFIRMED")
          )
        );
        const confirmedCommitmentCount = Number(confirmedAgg?.count ?? 0);
        const reconciledCommittedAmount = confirmedAgg?.total ?? "0";
        const previousCommittedAmount = opportunity.committedAmount ?? "0";
        const delta = (Number(reconciledCommittedAmount) - Number(previousCommittedAmount)).toFixed(2);
        const updatedPool = await reconcilePoolCommittedAmountWith(db, id);
        return res.json({
          pool: updatedPool,
          reconciliation: {
            opportunityId: id,
            previousCommittedAmount,
            reconciledCommittedAmount,
            delta,
            confirmedCommitmentCount
          }
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    allowedInvestorPlanTiers = new Set(
      MEMBERSHIP_PLAN_TIERS_BY_TYPE.INVESTOR
    );
    investmentOpportunityEligibleInvestorTiersSchema = external_exports.array(external_exports.string().trim().min(1)).default([]).transform(
      (tiers) => Array.from(
        new Set(
          tiers.map((tier) => tier.toUpperCase()).filter((tier) => allowedInvestorPlanTiers.has(tier))
        )
      )
    );
    investmentOpportunityFundingModelSchema = external_exports.enum(["CROWD", "NON_CROWD"]).default("CROWD");
    router3.get("/investments/opportunities", async (_req, res) => {
      try {
        const opportunities = await db.select().from(investmentOpportunitiesTable).orderBy(desc(investmentOpportunitiesTable.createdAt));
        return res.json({
          opportunities: opportunities.map((o) => ({
            ...o,
            fundingModel: o.fundingModel ?? "CROWD",
            eligibleInvestorTiers: Array.isArray(o.eligibleInvestorTiers) ? o.eligibleInvestorTiers : [],
            expectedReturn: `${o.expectedReturnPct}% p.a.`,
            term: formatTermFromDeadline({
              startAt: /* @__PURE__ */ new Date(),
              deadline: o.deadline
            })
          })),
          total: opportunities.length
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/investments/opportunities", async (req, res) => {
      try {
        const schema = external_exports.object({
          title: external_exports.string().min(1),
          slug: external_exports.string().min(1),
          description: external_exports.string().min(1),
          termsHtml: external_exports.string().optional().nullable(),
          category: external_exports.enum([
            "REAL_ESTATE",
            "AGRICULTURE",
            "SMALL_BUSINESS",
            "COMMUNITY_DEVELOPMENT",
            "BONDS",
            "OTHER"
          ]),
          expectedReturnPct: external_exports.number().int().positive(),
          minInvestment: external_exports.string().min(1),
          targetAmount: external_exports.string().min(1),
          deadline: external_exports.string().refine((value) => !Number.isNaN(new Date(value).getTime()), {
            message: "Invalid deadline."
          }),
          riskLevel: external_exports.enum(["LOW", "MEDIUM", "HIGH"]).default("MEDIUM"),
          status: external_exports.enum(["DRAFT", "OPEN", "FUNDED", "CLOSED"]).default("DRAFT"),
          featured: external_exports.boolean().default(false),
          fundingModel: investmentOpportunityFundingModelSchema,
          eligibleInvestorTiers: investmentOpportunityEligibleInvestorTiersSchema,
          videoUrl: external_exports.string().optional(),
          academyLink: external_exports.string().optional()
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success)
          return res.status(400).json({ errors: parsed.error.flatten() });
        const deadline = new Date(parsed.data.deadline);
        const normalizedTermsHtml = typeof parsed.data.termsHtml === "string" && parsed.data.termsHtml.trim().length > 0 ? parsed.data.termsHtml.trim() : null;
        const [opportunity] = await db.insert(investmentOpportunitiesTable).values({
          ...parsed.data,
          termsHtml: normalizedTermsHtml,
          deadline
        }).returning();
        return res.status(201).json({
          opportunity: {
            ...opportunity,
            fundingModel: opportunity.fundingModel ?? "CROWD",
            eligibleInvestorTiers: Array.isArray(opportunity.eligibleInvestorTiers) ? opportunity.eligibleInvestorTiers : [],
            expectedReturn: `${opportunity.expectedReturnPct}% p.a.`,
            term: formatTermFromDeadline({
              startAt: /* @__PURE__ */ new Date(),
              deadline: opportunity.deadline
            })
          }
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.patch("/investments/opportunities/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        const schema = external_exports.object({
          title: external_exports.string().optional(),
          slug: external_exports.string().optional(),
          description: external_exports.string().optional(),
          termsHtml: external_exports.string().optional().nullable(),
          category: external_exports.enum([
            "REAL_ESTATE",
            "AGRICULTURE",
            "SMALL_BUSINESS",
            "COMMUNITY_DEVELOPMENT",
            "BONDS",
            "OTHER"
          ]).optional(),
          riskLevel: external_exports.enum(["LOW", "MEDIUM", "HIGH"]).optional(),
          targetAmount: external_exports.string().optional(),
          minInvestment: external_exports.string().optional(),
          deadline: external_exports.string().refine((value) => !Number.isNaN(new Date(value).getTime()), {
            message: "Invalid deadline."
          }).optional(),
          expectedReturnPct: external_exports.number().int().positive().optional(),
          status: external_exports.enum(["DRAFT", "OPEN", "FUNDED", "CLOSED"]).optional(),
          featured: external_exports.boolean().optional(),
          fundingModel: investmentOpportunityFundingModelSchema.optional(),
          eligibleInvestorTiers: investmentOpportunityEligibleInvestorTiersSchema.optional(),
          raisedAmount: external_exports.string().optional(),
          videoUrl: external_exports.string().optional(),
          academyLink: external_exports.string().optional()
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success)
          return res.status(400).json({ errors: parsed.error.flatten() });
        const updates = { ...parsed.data };
        if (parsed.data.deadline !== void 0) {
          updates.deadline = new Date(parsed.data.deadline);
        }
        if (parsed.data.termsHtml !== void 0) {
          updates.termsHtml = typeof parsed.data.termsHtml === "string" && parsed.data.termsHtml.trim().length > 0 ? parsed.data.termsHtml.trim() : null;
        }
        const [updated] = await db.update(investmentOpportunitiesTable).set(updates).where(eq(investmentOpportunitiesTable.id, id)).returning();
        if (!updated)
          return res.status(404).json({ message: "Opportunity not found." });
        return res.json({
          opportunity: {
            ...updated,
            fundingModel: updated.fundingModel ?? "CROWD",
            eligibleInvestorTiers: Array.isArray(updated.eligibleInvestorTiers) ? updated.eligibleInvestorTiers : [],
            expectedReturn: `${updated.expectedReturnPct}% p.a.`,
            term: formatTermFromDeadline({
              startAt: /* @__PURE__ */ new Date(),
              deadline: updated.deadline
            })
          }
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/lending/commitments", async (_req, res) => {
      try {
        const commitments = await db.select({
          id: lendingCommitmentsTable.id,
          userId: lendingCommitmentsTable.userId,
          opportunityId: lendingCommitmentsTable.opportunityId,
          amount: lendingCommitmentsTable.amount,
          status: lendingCommitmentsTable.status,
          confirmedAt: lendingCommitmentsTable.confirmedAt,
          statusChangedAt: lendingCommitmentsTable.statusChangedAt,
          statusChangedByAdminId: lendingCommitmentsTable.statusChangedByAdminId,
          reviewNote: lendingCommitmentsTable.reviewNote,
          createdAt: lendingCommitmentsTable.createdAt,
          updatedAt: lendingCommitmentsTable.updatedAt,
          opportunityTitle: lendingOpportunitiesTable.title,
          userEmail: usersTable.email,
          userFirstName: usersTable.firstName,
          userLastName: usersTable.lastName
        }).from(lendingCommitmentsTable).leftJoin(
          lendingOpportunitiesTable,
          eq(lendingCommitmentsTable.opportunityId, lendingOpportunitiesTable.id)
        ).leftJoin(usersTable, eq(lendingCommitmentsTable.userId, usersTable.id)).orderBy(desc(lendingCommitmentsTable.createdAt));
        return res.json({ commitments, total: commitments.length });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.patch("/lending/commitments/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        const schema = external_exports.object({
          status: external_exports.enum(["PENDING", "CONFIRMED", "CANCELLED"]),
          reviewNote: external_exports.string().trim().max(1e3).optional()
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success)
          return res.status(400).json({ errors: parsed.error.flatten() });
        const adminId = req.admin?.id;
        const updated = await db.transaction(async (tx) => {
          const [existing] = await tx.select().from(lendingCommitmentsTable).where(eq(lendingCommitmentsTable.id, id));
          if (!existing) return null;
          if (!isCommitmentStatusTransitionAllowed(
            existing.status,
            parsed.data.status
          )) {
            throw new Error(
              `Invalid commitment transition from ${existing.status} to ${parsed.data.status}.`
            );
          }
          const shouldCreateFundingTransaction = parsed.data.status === "CONFIRMED" && existing.status !== "CONFIRMED";
          const commitmentAmount = parseMoneyAmount(existing.amount);
          const [investorWallet, masterWallet] = await Promise.all([
            ensureWalletWith5(tx, "USER", existing.userId),
            ensureLendingMasterWalletWith(tx)
          ]);
          const [existingFundingTx] = await tx.select({ id: walletTransactionsTable.id }).from(walletTransactionsTable).where(
            and(
              eq(walletTransactionsTable.toWalletId, masterWallet.id),
              inArray(walletTransactionsTable.type, [
                "TOP_UP",
                "ADJUSTMENT"
              ]),
              sql`coalesce(${walletTransactionsTable.metadata} ->> 'commitmentId', '') = ${String(
                existing.id
              )}`
            )
          );
          const hasFundingTransaction = Boolean(existingFundingTx);
          if (parsed.data.status === "CONFIRMED" && existing.status !== "CONFIRMED") {
            const remainingCapacity = await getRemainingPoolCapacityWith(
              tx,
              existing.opportunityId
            );
            if (parseMoneyAmount(existing.amount) > remainingCapacity) {
              throw new Error(
                `This confirmation would over-commit the opportunity. Remaining capacity is ${formatMoneyAmount(remainingCapacity)}.`
              );
            }
          }
          if (parsed.data.status === "CANCELLED" && existing.status === "CONFIRMED") {
            if (hasFundingTransaction) {
              const availableToLend = await getPoolAvailableToLendWith(
                tx,
                existing.opportunityId
              );
              if (commitmentAmount > availableToLend) {
                throw new Error(
                  `This confirmed commitment cannot be cancelled because only ${formatMoneyAmount(availableToLend)} is currently unallocated in the Lending Master Wallet.`
                );
              }
            }
          }
          const nextStatusChangedAt = parsed.data.status === existing.status ? existing.statusChangedAt : /* @__PURE__ */ new Date();
          const updates = {
            status: parsed.data.status,
            reviewNote: parsed.data.reviewNote !== void 0 ? parsed.data.reviewNote || null : existing.reviewNote,
            statusChangedAt: nextStatusChangedAt,
            statusChangedByAdminId: parsed.data.status === existing.status ? existing.statusChangedByAdminId : adminId ?? existing.statusChangedByAdminId,
            updatedAt: /* @__PURE__ */ new Date()
          };
          if (parsed.data.status === "CONFIRMED") {
            updates.confirmedAt = existing.confirmedAt ?? nextStatusChangedAt;
          } else {
            updates.confirmedAt = null;
          }
          if (shouldCreateFundingTransaction && !hasFundingTransaction) {
            const investorAvailableBalance = await getWalletAvailableBalanceWith(
              tx,
              investorWallet.id
            );
            if (investorAvailableBalance < commitmentAmount) {
              throw new Error("Insufficient available wallet balance.");
            }
            const commitmentFundingIdempotencyKey = `lending_commitment:admin_confirm:${existing.id}`;
            await tx.insert(walletTransactionsTable).values({
              type: "TOP_UP",
              idempotencyKey: commitmentFundingIdempotencyKey,
              fromWalletId: investorWallet.id,
              toWalletId: masterWallet.id,
              amount: formatMoneyAmount(commitmentAmount),
              metadata: {
                source: "lending_commitment_admin_confirmation",
                commitmentId: existing.id,
                investorId: existing.userId,
                opportunityId: existing.opportunityId
              }
            });
          }
          const [commitment] = await tx.update(lendingCommitmentsTable).set(updates).where(eq(lendingCommitmentsTable.id, id)).returning();
          if (parsed.data.status === "CANCELLED" && existing.status !== "CANCELLED") {
            if (hasFundingTransaction) {
              const refundIdempotencyKey = `lending_commitment:cancel:${existing.id}`;
              const [existingRefund] = await tx.select({ id: walletTransactionsTable.id }).from(walletTransactionsTable).where(
                eq(walletTransactionsTable.idempotencyKey, refundIdempotencyKey)
              );
              if (!existingRefund) {
                await tx.insert(walletTransactionsTable).values({
                  type: "REFUND",
                  idempotencyKey: refundIdempotencyKey,
                  fromWalletId: masterWallet.id,
                  toWalletId: investorWallet.id,
                  amount: existing.amount,
                  metadata: {
                    source: "lending_commitment_cancellation",
                    commitmentId: existing.id,
                    investorId: existing.userId,
                    opportunityId: existing.opportunityId
                  }
                });
              }
            }
          }
          await reconcilePoolCommittedAmountWith(tx, existing.opportunityId);
          return commitment;
        });
        if (!updated) {
          return res.status(404).json({ message: "Commitment not found." });
        }
        return res.json({ commitment: updated });
      } catch (err) {
        if (err instanceof Error) {
          return res.status(400).json({ message: err.message });
        }
        return handleError2(err, res);
      }
    });
    router3.get("/investments/interests", async (_req, res) => {
      try {
        const interests = await db.select({
          id: investmentInterestsTable.id,
          userId: investmentInterestsTable.userId,
          opportunityId: investmentInterestsTable.opportunityId,
          amount: investmentInterestsTable.amount,
          notes: investmentInterestsTable.notes,
          status: investmentInterestsTable.status,
          confirmedAt: investmentInterestsTable.confirmedAt,
          cancelledAt: investmentInterestsTable.cancelledAt,
          createdAt: investmentInterestsTable.createdAt,
          updatedAt: investmentInterestsTable.updatedAt,
          reservationStatus: investmentIntentReservationsTable.status,
          reservedAmount: investmentIntentReservationsTable.amount,
          finalizedAt: investmentIntentReservationsTable.finalizedAt,
          releasedAt: investmentIntentReservationsTable.releasedAt,
          opportunityTitle: investmentOpportunitiesTable.title,
          userEmail: usersTable.email,
          userFirstName: usersTable.firstName,
          userLastName: usersTable.lastName
        }).from(investmentInterestsTable).leftJoin(
          investmentIntentReservationsTable,
          eq(
            investmentIntentReservationsTable.interestId,
            investmentInterestsTable.id
          )
        ).leftJoin(
          investmentOpportunitiesTable,
          eq(
            investmentInterestsTable.opportunityId,
            investmentOpportunitiesTable.id
          )
        ).leftJoin(usersTable, eq(investmentInterestsTable.userId, usersTable.id)).orderBy(desc(investmentInterestsTable.createdAt));
        const ascaInterests = await db.select({
          ascaId: ascasTable.id,
          ascaName: ascasTable.name,
          opportunityId: investmentOpportunitiesTable.id,
          amount: ascasTable.currentAmount,
          confirmedAt: walletTransactionsTable.createdAt,
          createdAt: ascasTable.createdAt,
          updatedAt: ascasTable.updatedAt,
          opportunityTitle: investmentOpportunitiesTable.title
        }).from(ascasTable).innerJoin(
          investmentOpportunitiesTable,
          eq(ascasTable.investmentId, investmentOpportunitiesTable.id)
        ).leftJoin(
          walletTransactionsTable,
          and(
            eq(walletTransactionsTable.fromWalletId, ascasTable.escrowWalletId),
            eq(walletTransactionsTable.type, "ASCA_INVESTMENT")
          )
        ).where(
          and(
            eq(ascasTable.type, "INVESTMENT"),
            eq(ascasTable.status, "INVESTED")
          )
        ).orderBy(
          desc(walletTransactionsTable.createdAt),
          desc(ascasTable.createdAt)
        );
        const now = /* @__PURE__ */ new Date();
        const fundingStates = await Promise.all(
          interests.map(async (interest) => {
            const hasWalletFunding = await hasInvestmentWalletFundingWith(
              db,
              interest.id
            );
            return {
              hasWalletFunding,
              fundingSource: interest.status === "CONFIRMED" ? hasWalletFunding ? interest.reservationStatus === "FINALIZED" ? "RESERVATION_FINALIZED" : "ADMIN_BACKFILL" : "MISSING" : null
            };
          })
        );
        const payoutSnapshots = await Promise.all(
          interests.map(async (interest) => {
            if (interest.status !== "CONFIRMED") return null;
            try {
              return await getInvestmentReturnPayoutSnapshotWith(
                db,
                interest.id,
                now
              );
            } catch {
              return null;
            }
          })
        );
        const syntheticAscaInterests = ascaInterests.map((asca) => {
          const confirmedAt = asca.confirmedAt ?? asca.updatedAt;
          return {
            id: -asca.ascaId,
            userId: 0,
            opportunityId: asca.opportunityId,
            amount: asca.amount,
            notes: `ASCA ${asca.ascaName} invested into this Susunomics opportunity.`,
            status: "CONFIRMED",
            confirmedAt,
            cancelledAt: null,
            createdAt: asca.createdAt,
            updatedAt: asca.updatedAt,
            reservationStatus: null,
            reservedAmount: null,
            finalizedAt: confirmedAt,
            releasedAt: null,
            opportunityTitle: asca.opportunityTitle,
            userEmail: null,
            userFirstName: "ASCA",
            userLastName: asca.ascaName,
            accruedReturnAmount: null,
            paidReturnAmount: null,
            payableReturnAmount: null,
            returnMatured: false,
            hasWalletFunding: true,
            fundingSource: "ASCA_POOL"
          };
        });
        return res.json({
          interests: [
            ...interests.map((interest, index2) => {
              const payout = payoutSnapshots[index2];
              const fundingState = fundingStates[index2];
              return {
                ...interest,
                accruedReturnAmount: payout?.accruedReturnAmount?.toFixed(2) ?? null,
                paidReturnAmount: payout?.paidReturnAmount?.toFixed(2) ?? null,
                payableReturnAmount: payout?.payableReturnAmount?.toFixed(2) ?? null,
                returnMatured: payout?.isMatured ?? false,
                hasWalletFunding: fundingState?.hasWalletFunding ?? false,
                fundingSource: fundingState?.fundingSource ?? null
              };
            }),
            ...syntheticAscaInterests
          ].sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime()),
          total: interests.length + syntheticAscaInterests.length
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.patch("/investments/interests/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        const adminId = req.admin.id;
        const schema = external_exports.object({
          status: external_exports.enum(["CONFIRMED", "CANCELLED"])
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success)
          return res.status(400).json({ errors: parsed.error.flatten() });
        const result = await db.transaction(async (tx) => {
          const [interest] = await tx.select().from(investmentInterestsTable).where(eq(investmentInterestsTable.id, id));
          if (!interest) return null;
          if (interest.status === "CONFIRMED") {
            if (parsed.data.status === "CONFIRMED")
              return { interest, pushKind: null };
            throw new Error("This investment intent has already been approved.");
          }
          if (interest.status === "CANCELLED") {
            if (parsed.data.status === "CANCELLED")
              return { interest, pushKind: null };
            throw new Error("This investment intent has already been cancelled.");
          }
          const [reservation] = await tx.select().from(investmentIntentReservationsTable).where(eq(investmentIntentReservationsTable.interestId, interest.id));
          const now = /* @__PURE__ */ new Date();
          if (parsed.data.status === "CONFIRMED") {
            if (!reservation || reservation.status !== "RESERVED") {
              throw new Error(
                "This investment intent no longer has an active wallet reservation."
              );
            }
            const [opp] = await tx.select({
              targetAmount: investmentOpportunitiesTable.targetAmount
            }).from(investmentOpportunitiesTable).where(eq(investmentOpportunitiesTable.id, interest.opportunityId));
            if (!opp) {
              throw new Error("Opportunity not found.");
            }
            const [confirmedAgg] = await tx.select({ total: sum(investmentInterestsTable.amount) }).from(investmentInterestsTable).where(
              and(
                eq(
                  investmentInterestsTable.opportunityId,
                  interest.opportunityId
                ),
                eq(investmentInterestsTable.status, "CONFIRMED")
              )
            );
            const confirmedTotal = Number(confirmedAgg?.total ?? 0);
            const targetAmount = Number(opp.targetAmount ?? 0);
            const amountToConfirm = Number(reservation.amount ?? 0);
            if (Number.isFinite(targetAmount) && targetAmount > 0 && confirmedTotal + amountToConfirm > targetAmount) {
              throw new Error(
                "This opportunity does not have enough remaining capacity to approve this intent."
              );
            }
            const [confirmed] = await tx.update(investmentInterestsTable).set({
              status: "CONFIRMED",
              confirmedAt: now,
              cancelledAt: null,
              updatedAt: now
            }).where(
              and(
                eq(investmentInterestsTable.id, interest.id),
                eq(investmentInterestsTable.status, "PENDING")
              )
            ).returning();
            if (!confirmed) {
              const [current] = await tx.select().from(investmentInterestsTable).where(eq(investmentInterestsTable.id, interest.id));
              if (!current) return null;
              if (current.status === "CONFIRMED")
                return { interest: current, pushKind: null };
              throw new Error("This investment intent can no longer be approved.");
            }
            const userWallet = await ensureWalletWith5(
              tx,
              "USER",
              interest.userId
            );
            const investmentWallet = await ensureInvestmentWalletWith(tx);
            const idempotencyKey = `investment_purchase:interest:${interest.id}`;
            const [existingWalletTransaction] = await tx.select().from(walletTransactionsTable).where(eq(walletTransactionsTable.idempotencyKey, idempotencyKey));
            let walletTransaction = existingWalletTransaction ?? null;
            if (!walletTransaction) {
              try {
                const [created] = await tx.insert(walletTransactionsTable).values({
                  type: "INVESTMENT_PURCHASE",
                  idempotencyKey,
                  fromWalletId: userWallet.id,
                  toWalletId: investmentWallet.id,
                  amount: reservation.amount,
                  metadata: {
                    investmentInterestId: interest.id,
                    opportunityId: interest.opportunityId,
                    investorId: interest.userId,
                    approvedByAdminId: adminId
                  }
                }).returning();
                walletTransaction = created;
              } catch (err) {
                if (!isUniqueViolation5(err)) throw err;
                const [row] = await tx.select().from(walletTransactionsTable).where(
                  eq(walletTransactionsTable.idempotencyKey, idempotencyKey)
                );
                walletTransaction = row ?? null;
                if (!walletTransaction) throw err;
              }
            }
            const [existingActivity] = await tx.select({ id: investmentTransactionsTable.id }).from(investmentTransactionsTable).where(
              and(
                eq(investmentTransactionsTable.userId, interest.userId),
                eq(
                  investmentTransactionsTable.opportunityId,
                  interest.opportunityId
                ),
                eq(investmentTransactionsTable.type, "INVESTMENT_PURCHASE"),
                eq(investmentTransactionsTable.amount, reservation.amount)
              )
            );
            if (!existingActivity) {
              await tx.insert(investmentTransactionsTable).values({
                userId: interest.userId,
                opportunityId: interest.opportunityId,
                amount: reservation.amount,
                type: "INVESTMENT_PURCHASE",
                description: "Investment intent approved and funded from wallet.",
                processedAt: now,
                createdAt: now
              });
            }
            await tx.update(investmentIntentReservationsTable).set({
              status: "FINALIZED",
              finalizedTransactionId: walletTransaction.id,
              finalizedAt: now,
              releasedAt: null,
              updatedAt: now
            }).where(
              and(
                eq(investmentIntentReservationsTable.id, reservation.id),
                eq(investmentIntentReservationsTable.status, "RESERVED")
              )
            );
            await reconcileInvestmentOpportunityRaisedAmountWith(
              tx,
              interest.opportunityId
            );
            await notifyInAppWith(tx, {
              userId: interest.userId,
              category: "INVESTMENT",
              severity: "SUCCESS",
              title: "Investment approved",
              body: "Your investment intent has been approved and funded from your wallet.",
              actionLabel: "View Susunomics",
              actionHref: "/dashboard/investments"
            });
            return { interest: confirmed, pushKind: "approved" };
          }
          const [cancelled] = await tx.update(investmentInterestsTable).set({
            status: "CANCELLED",
            confirmedAt: null,
            cancelledAt: now,
            updatedAt: now
          }).where(
            and(
              eq(investmentInterestsTable.id, interest.id),
              eq(investmentInterestsTable.status, "PENDING")
            )
          ).returning();
          if (!cancelled) {
            const [current] = await tx.select().from(investmentInterestsTable).where(eq(investmentInterestsTable.id, interest.id));
            if (!current) return null;
            if (current.status === "CANCELLED")
              return { interest: current, pushKind: null };
            throw new Error("This investment intent can no longer be cancelled.");
          }
          if (reservation && reservation.status === "RESERVED") {
            await tx.update(investmentIntentReservationsTable).set({
              status: "RELEASED",
              releasedAt: now,
              updatedAt: now
            }).where(
              and(
                eq(investmentIntentReservationsTable.id, reservation.id),
                eq(investmentIntentReservationsTable.status, "RESERVED")
              )
            );
          }
          await tx.insert(investmentTransactionsTable).values({
            userId: interest.userId,
            opportunityId: interest.opportunityId,
            amount: reservation?.amount ?? interest.amount,
            type: "INVESTMENT_INTENT_RELEASED",
            description: "Investment intent declined and reserved funds released back to wallet.",
            processedAt: now,
            createdAt: now
          });
          await reconcileInvestmentOpportunityRaisedAmountWith(
            tx,
            interest.opportunityId
          );
          await notifyInAppWith(tx, {
            userId: interest.userId,
            category: "INVESTMENT",
            severity: "WARNING",
            title: "Investment declined",
            body: "Your investment intent has been declined and reserved funds released.",
            actionLabel: "View Susunomics",
            actionHref: "/dashboard/investments"
          });
          return { interest: cancelled, pushKind: "declined" };
        });
        if (!result)
          return res.status(404).json({ message: "Investment intent not found." });
        if (result.pushKind === "approved") {
          void (async () => {
            const key = `investment_intent_approved:${id}:push`;
            const reserved = await reserveNotificationDeliveryWith(db, {
              userId: result.interest.userId,
              channel: "PUSH",
              category: "INVESTMENT",
              idempotencyKey: key,
              status: "SKIPPED",
              provider: null,
              metadata: { kind: "investment_intent_approved", intentId: id }
            });
            if (!reserved.reserved) return;
            try {
              const pushResult = await deliverPushIfEnabled({
                userId: result.interest.userId,
                category: "INVESTMENT",
                title: "Investment approved",
                body: "Your investment intent has been approved.",
                data: { actionHref: "/dashboard/investments" }
              });
              await finalizeNotificationDeliveryWith(db, {
                idempotencyKey: key,
                status: pushResult.status,
                provider: pushResult.status === "SENT" ? "EXPO" : null,
                errorMessage: pushResult.reason ?? null,
                notificationId: null,
                metadata: {
                  kind: "investment_intent_approved",
                  reason: pushResult.reason ?? null,
                  intentId: id
                }
              });
            } catch (err) {
              await finalizeNotificationDeliveryWith(db, {
                idempotencyKey: key,
                status: "FAILED",
                provider: "EXPO",
                errorMessage: err instanceof Error ? err.message : String(err),
                notificationId: null,
                metadata: { kind: "investment_intent_approved", intentId: id }
              });
            }
          })();
        }
        if (result.pushKind === "declined") {
          void (async () => {
            const key = `investment_intent_declined:${id}:push`;
            const reserved = await reserveNotificationDeliveryWith(db, {
              userId: result.interest.userId,
              channel: "PUSH",
              category: "INVESTMENT",
              idempotencyKey: key,
              status: "SKIPPED",
              provider: null,
              metadata: { kind: "investment_intent_declined", intentId: id }
            });
            if (!reserved.reserved) return;
            try {
              const pushResult = await deliverPushIfEnabled({
                userId: result.interest.userId,
                category: "INVESTMENT",
                title: "Investment declined",
                body: "Your investment intent was declined.",
                data: { actionHref: "/dashboard/investments" }
              });
              await finalizeNotificationDeliveryWith(db, {
                idempotencyKey: key,
                status: pushResult.status,
                provider: pushResult.status === "SENT" ? "EXPO" : null,
                errorMessage: pushResult.reason ?? null,
                notificationId: null,
                metadata: {
                  kind: "investment_intent_declined",
                  reason: pushResult.reason ?? null,
                  intentId: id
                }
              });
            } catch (err) {
              await finalizeNotificationDeliveryWith(db, {
                idempotencyKey: key,
                status: "FAILED",
                provider: "EXPO",
                errorMessage: err instanceof Error ? err.message : String(err),
                notificationId: null,
                metadata: { kind: "investment_intent_declined", intentId: id }
              });
            }
          })();
        }
        return res.json({ interest: result.interest });
      } catch (err) {
        if (err instanceof Error) {
          return res.status(400).json({ message: err.message });
        }
        return handleError2(err, res);
      }
    });
    router3.post("/investments/interests/:id/return-payout", async (req, res) => {
      try {
        const id = Number(req.params.id);
        const adminId = req.admin.id;
        const schema = external_exports.object({
          amount: external_exports.number().positive().optional()
        });
        const parsed = schema.safeParse(req.body ?? {});
        if (!parsed.success) {
          return res.status(400).json({ errors: parsed.error.flatten() });
        }
        const result = await db.transaction(
          async (tx) => payoutInvestmentReturnWith(tx, {
            interestId: id,
            paidByAdminId: adminId,
            amount: parsed.data.amount,
            asOf: /* @__PURE__ */ new Date(),
            source: "ADMIN_MANUAL"
          })
        );
        const pushTitle = result.principalAmountPaid > 0 && result.returnAmountPaid > 0 ? "Investment principal and return paid" : result.principalAmountPaid > 0 ? "Investment principal paid" : "Investment return paid";
        const pushBody = result.principalAmountPaid > 0 && result.returnAmountPaid > 0 ? "Your investment principal and return have been credited to your wallet." : result.principalAmountPaid > 0 ? "Your investment principal has been credited to your wallet." : "Your investment return has been credited to your wallet.";
        void (async () => {
          const userId = result.snapshot.userId;
          const walletTransactionId = result.walletTransactionId;
          if (!walletTransactionId) return;
          const key = `investment_return_paid:${walletTransactionId}:push`;
          const reserved = await reserveNotificationDeliveryWith(db, {
            userId,
            channel: "PUSH",
            category: "INVESTMENT",
            idempotencyKey: key,
            status: "SKIPPED",
            provider: null,
            metadata: {
              kind: "investment_return_paid",
              interestId: id,
              walletTransactionId,
              source: "ADMIN_MANUAL"
            }
          });
          if (!reserved.reserved) return;
          try {
            const pushResult = await deliverPushIfEnabled({
              userId,
              category: "INVESTMENT",
              title: pushTitle,
              body: pushBody,
              data: { actionHref: "/dashboard/investments" }
            });
            await finalizeNotificationDeliveryWith(db, {
              idempotencyKey: key,
              status: pushResult.status,
              provider: pushResult.status === "SENT" ? "EXPO" : null,
              errorMessage: pushResult.reason ?? null,
              notificationId: null,
              metadata: {
                kind: "investment_return_paid",
                reason: pushResult.reason ?? null,
                interestId: id,
                walletTransactionId,
                source: "ADMIN_MANUAL"
              }
            });
          } catch (err) {
            await finalizeNotificationDeliveryWith(db, {
              idempotencyKey: key,
              status: "FAILED",
              provider: "EXPO",
              errorMessage: err instanceof Error ? err.message : String(err),
              notificationId: null,
              metadata: {
                kind: "investment_return_paid",
                interestId: id,
                walletTransactionId,
                source: "ADMIN_MANUAL"
              }
            });
          }
        })();
        return res.json({
          ok: true,
          amountPaid: result.amountPaid.toFixed(2),
          principalAmountPaid: result.principalAmountPaid.toFixed(2),
          returnAmountPaid: result.returnAmountPaid.toFixed(2),
          walletTransactionId: result.walletTransactionId,
          principalWalletTransactionId: result.principalWalletTransactionId,
          investmentTransactionId: result.investmentTransactionId,
          principalInvestmentTransactionId: result.principalInvestmentTransactionId,
          snapshot: {
            principalAmount: result.snapshot.principalAmount.toFixed(2),
            paidPrincipalAmount: result.snapshot.paidPrincipalAmount.toFixed(2),
            payablePrincipalAmount: result.snapshot.payablePrincipalAmount.toFixed(2),
            accruedReturnAmount: result.snapshot.accruedReturnAmount.toFixed(2),
            paidReturnAmount: result.snapshot.paidReturnAmount.toFixed(2),
            payableReturnAmount: result.snapshot.payableReturnAmount.toFixed(2),
            isMatured: result.snapshot.isMatured
          }
        });
      } catch (err) {
        if (err instanceof Error) {
          return res.status(400).json({ message: err.message });
        }
        return handleError2(err, res);
      }
    });
    router3.post("/investments/interests/:id/funding-backfill", async (req, res) => {
      try {
        const id = Number(req.params.id);
        const adminId = req.admin.id;
        const schema = external_exports.object({
          note: external_exports.string().trim().max(500).optional()
        });
        const parsed = schema.safeParse(req.body ?? {});
        if (!parsed.success) {
          return res.status(400).json({ errors: parsed.error.flatten() });
        }
        const result = await db.transaction(
          async (tx) => backfillConfirmedInvestmentFundingWith(tx, {
            interestId: id,
            approvedByAdminId: adminId,
            note: parsed.data.note ?? null
          })
        );
        await reconcileInvestmentOpportunityRaisedAmountWith(
          db,
          result.opportunityId
        );
        return res.json({
          ok: true,
          backfill: {
            interestId: result.interestId,
            amount: result.amount.toFixed(2),
            creditTransactionId: result.creditTransactionId,
            purchaseActivityId: result.purchaseActivityId
          }
        });
      } catch (err) {
        if (err instanceof Error) {
          return res.status(400).json({ message: err.message });
        }
        return handleError2(err, res);
      }
    });
    router3.get("/reports", async (_req, res) => {
      try {
        const [
          [paymentStats],
          [subscriptionStats],
          [contributionStats],
          lendingPoolStats,
          commitmentStats,
          lendingReturnStats
        ] = await Promise.all([
          db.select({
            total: sql`sum(${paymentsTable.amount}) filter (where ${paymentsTable.status} = 'COMPLETED')`,
            completedPayments: sql`count(*) filter (where ${paymentsTable.status} = 'COMPLETED')`,
            pendingPayments: sql`count(*) filter (where ${paymentsTable.status} = 'PENDING')`
          }).from(paymentsTable),
          db.select({
            total: count(),
            active: sql`count(*) filter (where ${membershipSubscriptionsTable.status} = 'ACTIVE')`
          }).from(membershipSubscriptionsTable),
          db.select({
            totalContributions: sum(savingsContributionsTable.amount),
            paidContributions: sql`sum(${savingsContributionsTable.amount}) filter (where ${savingsContributionsTable.status} = 'PAID')`
          }).from(savingsContributionsTable),
          db.select({
            loanType: lendingOpportunitiesTable.loanType,
            count: count()
          }).from(lendingOpportunitiesTable).groupBy(lendingOpportunitiesTable.loanType),
          db.select({
            loanType: lendingOpportunitiesTable.loanType,
            total: sum(lendingCommitmentsTable.amount)
          }).from(lendingCommitmentsTable).innerJoin(
            lendingOpportunitiesTable,
            eq(
              lendingCommitmentsTable.opportunityId,
              lendingOpportunitiesTable.id
            )
          ).where(eq(lendingCommitmentsTable.status, "CONFIRMED")).groupBy(lendingOpportunitiesTable.loanType),
          db.select({
            loanType: lendingOpportunitiesTable.loanType,
            total: sum(
              lendingOpportunityReturnAllocationsTable.allocatedReturnAmount
            )
          }).from(lendingOpportunityReturnAllocationsTable).innerJoin(
            lendingOpportunitiesTable,
            eq(
              lendingOpportunityReturnAllocationsTable.opportunityId,
              lendingOpportunitiesTable.id
            )
          ).groupBy(lendingOpportunitiesTable.loanType)
        ]);
        const lendingByType = {
          COMMUNITY_LENDING: {
            poolCount: 0,
            totalCommitted: "0",
            recognizedReturn: "0"
          },
          P2P_LENDING: {
            poolCount: 0,
            totalCommitted: "0",
            recognizedReturn: "0"
          }
        };
        for (const row of lendingPoolStats) {
          lendingByType[normalizeLendingLoanType(row.loanType)].poolCount = Number(
            row.count
          );
        }
        for (const row of commitmentStats) {
          lendingByType[normalizeLendingLoanType(row.loanType)].totalCommitted = row.total ?? "0";
        }
        for (const row of lendingReturnStats) {
          lendingByType[normalizeLendingLoanType(row.loanType)].recognizedReturn = row.total ?? "0";
        }
        const recentPayments = await db.select({
          id: paymentsTable.id,
          amount: paymentsTable.amount,
          method: paymentsTable.method,
          status: paymentsTable.status,
          description: paymentsTable.description,
          processedAt: paymentsTable.processedAt,
          userEmail: usersTable.email,
          userFirstName: usersTable.firstName
        }).from(paymentsTable).leftJoin(usersTable, eq(paymentsTable.userId, usersTable.id)).orderBy(desc(paymentsTable.createdAt)).limit(20);
        return res.json({
          revenue: {
            ...buildPlatformRevenueSummary({
              completedPaymentTotal: paymentStats.total
            }),
            completedPayments: Number(paymentStats.completedPayments),
            pendingPayments: Number(paymentStats.pendingPayments)
          },
          subscriptions: {
            total: Number(subscriptionStats.total),
            active: Number(subscriptionStats.active)
          },
          savings: {
            totalContributions: contributionStats.totalContributions ?? "0",
            paidContributions: contributionStats.paidContributions ?? "0"
          },
          lending: {
            community: lendingByType.COMMUNITY_LENDING,
            p2p: lendingByType.P2P_LENDING
          },
          recentPayments
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/membership/payments", async (req, res) => {
      try {
        const statusRaw = String(req.query.status ?? "PENDING").toUpperCase();
        const status = statusRaw === "PENDING" || statusRaw === "COMPLETED" || statusRaw === "FAILED" ? statusRaw : "PENDING";
        const rows = await db.select({
          paymentId: paymentsTable.id,
          paymentStatus: paymentsTable.status,
          paymentMethod: paymentsTable.method,
          paymentReference: paymentsTable.reference,
          paymentMetadata: paymentsTable.metadata,
          paymentCreatedAt: paymentsTable.createdAt,
          userId: usersTable.id,
          userEmail: usersTable.email,
          userFirstName: usersTable.firstName,
          userLastName: usersTable.lastName,
          userMembershipType: usersTable.membershipType,
          userMembershipStatus: usersTable.membershipStatus,
          invoiceId: invoicesTable.id,
          invoiceNumber: invoicesTable.invoiceNumber,
          invoiceStatus: invoicesTable.status,
          invoiceAmount: invoicesTable.amount,
          invoiceCurrency: invoicesTable.currency,
          invoiceDueDate: invoicesTable.dueDate,
          subscriptionId: membershipSubscriptionsTable.id,
          subscriptionStatus: membershipSubscriptionsTable.status,
          planId: membershipPlansTable.id,
          planName: membershipPlansTable.name,
          planTier: membershipPlansTable.tier,
          planMembershipType: membershipPlansTable.membershipType
        }).from(paymentsTable).leftJoin(usersTable, eq(paymentsTable.userId, usersTable.id)).leftJoin(invoicesTable, eq(paymentsTable.invoiceId, invoicesTable.id)).leftJoin(
          membershipSubscriptionsTable,
          eq(invoicesTable.subscriptionId, membershipSubscriptionsTable.id)
        ).leftJoin(
          membershipPlansTable,
          eq(membershipSubscriptionsTable.planId, membershipPlansTable.id)
        ).where(
          and(
            eq(paymentsTable.status, status),
            sql`${paymentsTable.metadata} ->> 'activationType' in ('membership_manual', 'membership_manual_plan_change')`
          )
        ).orderBy(desc(paymentsTable.createdAt)).limit(200);
        return res.json({
          payments: rows.map((row) => ({
            id: row.paymentId,
            status: row.paymentStatus,
            method: row.paymentMethod,
            reference: row.paymentReference ?? null,
            metadata: row.paymentMetadata ?? null,
            createdAt: row.paymentCreatedAt?.toISOString?.() ?? null,
            user: row.userId ? {
              id: row.userId,
              email: row.userEmail,
              firstName: row.userFirstName,
              lastName: row.userLastName,
              membershipType: row.userMembershipType ?? null,
              membershipStatus: row.userMembershipStatus ?? null
            } : null,
            invoice: row.invoiceId ? {
              id: row.invoiceId,
              invoiceNumber: row.invoiceNumber,
              status: row.invoiceStatus,
              amount: Number(row.invoiceAmount),
              currency: row.invoiceCurrency,
              dueDate: row.invoiceDueDate?.toISOString?.() ?? null
            } : null,
            subscription: row.subscriptionId ? {
              id: row.subscriptionId,
              status: row.subscriptionStatus
            } : null,
            plan: row.planId ? {
              id: row.planId,
              name: row.planName,
              tier: row.planTier,
              membershipType: row.planMembershipType
            } : null
          }))
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/membership/payments/:paymentId/approve", async (req, res) => {
      const paymentId = Number(req.params.paymentId);
      if (!Number.isFinite(paymentId) || paymentId <= 0) {
        return res.status(400).json({ message: "Invalid payment id." });
      }
      try {
        const now = /* @__PURE__ */ new Date();
        const result = await db.transaction(async (tx) => {
          const [row] = await tx.select({
            payment: paymentsTable,
            invoice: invoicesTable,
            subscription: membershipSubscriptionsTable,
            plan: membershipPlansTable,
            user: usersTable
          }).from(paymentsTable).leftJoin(invoicesTable, eq(paymentsTable.invoiceId, invoicesTable.id)).leftJoin(
            membershipSubscriptionsTable,
            eq(invoicesTable.subscriptionId, membershipSubscriptionsTable.id)
          ).leftJoin(
            membershipPlansTable,
            eq(membershipSubscriptionsTable.planId, membershipPlansTable.id)
          ).leftJoin(usersTable, eq(paymentsTable.userId, usersTable.id)).where(eq(paymentsTable.id, paymentId));
          if (!row?.payment || !row.invoice || !row.subscription || !row.plan || !row.user) {
            return { kind: "NOT_FOUND" };
          }
          if (!["membership_manual", "membership_manual_plan_change"].includes(
            row.payment.metadata?.activationType
          )) {
            return { kind: "NOT_FOUND" };
          }
          const paymentMetadata = row.payment.metadata ?? {};
          const activationType = String(paymentMetadata.activationType ?? "");
          const targetPlanId = typeof paymentMetadata.toPlanId === "number" ? paymentMetadata.toPlanId : typeof paymentMetadata.planId === "number" ? paymentMetadata.planId : row.plan.id;
          const [targetPlan] = await tx.select().from(membershipPlansTable).where(eq(membershipPlansTable.id, targetPlanId)).limit(1);
          const effectivePlan = targetPlan ?? row.plan;
          const [updatedPayment] = await tx.update(paymentsTable).set({
            status: "COMPLETED",
            processedAt: now,
            updatedAt: now
          }).where(
            and(
              eq(paymentsTable.id, paymentId),
              eq(paymentsTable.status, "PENDING")
            )
          ).returning();
          if (!updatedPayment) {
            return { kind: "ALREADY_PROCESSED" };
          }
          const isPlanChangeApproval = activationType === "membership_manual_plan_change";
          const renewalDate = isPlanChangeApproval ? row.subscription.renewsAt ?? row.subscription.endDate ?? now : (() => {
            const nextDate = new Date(now);
            nextDate.setFullYear(nextDate.getFullYear() + 1);
            return nextDate;
          })();
          const [invoice] = await tx.update(invoicesTable).set({
            status: "PAID",
            paidAt: now,
            updatedAt: now
          }).where(eq(invoicesTable.id, row.invoice.id)).returning();
          const [subscription] = await tx.update(membershipSubscriptionsTable).set({
            status: "ACTIVE",
            planId: effectivePlan.id,
            startDate: isPlanChangeApproval ? row.subscription.startDate : now,
            endDate: isPlanChangeApproval ? row.subscription.endDate : renewalDate,
            renewsAt: isPlanChangeApproval ? row.subscription.renewsAt : renewalDate,
            updatedAt: now
          }).where(eq(membershipSubscriptionsTable.id, row.subscription.id)).returning();
          const [updatedUser] = await tx.update(usersTable).set({
            membershipStatus: "ACTIVE",
            updatedAt: now
          }).where(eq(usersTable.id, row.user.id)).returning();
          await syncOrganizationSubscriptionStateWith(tx, {
            user: updatedUser,
            plan: effectivePlan,
            status: "ACTIVE",
            now,
            startDate: isPlanChangeApproval ? row.subscription.startDate : now,
            endDate: isPlanChangeApproval ? row.subscription.endDate : renewalDate,
            renewsAt: isPlanChangeApproval ? row.subscription.renewsAt : renewalDate,
            stripeCustomerId: row.subscription.stripeCustomerId,
            stripeSubscriptionId: row.subscription.stripeSubscriptionId
          });
          const amountLabel = new Intl.NumberFormat("en-CA", {
            style: "currency",
            currency: effectivePlan.currency,
            maximumFractionDigits: 2
          }).format(Number(row.payment.amount));
          const inApp = await notifyInAppWith(tx, {
            userId: row.user.id,
            category: "MEMBERSHIP",
            severity: "SUCCESS",
            title: isPlanChangeApproval ? "Membership updated" : "Membership activated",
            body: isPlanChangeApproval ? `Your membership has moved to ${effectivePlan.name}. We confirmed your ${amountLabel} upgrade payment.` : `Your ${effectivePlan.name} membership is now active. We confirmed your ${amountLabel} payment.`,
            actionLabel: "Open Billing",
            actionHref: "/dashboard/billing"
          });
          const pushKey = `membership_activated:${paymentId}:push`;
          const emailKey = `membership_activated:${paymentId}:email`;
          const pushReserved = await reserveNotificationDeliveryWith(tx, {
            userId: row.user.id,
            channel: "PUSH",
            category: "MEMBERSHIP",
            idempotencyKey: pushKey,
            status: "SKIPPED",
            provider: null,
            metadata: {
              kind: "membership_activated",
              paymentId,
              invoiceId: row.invoice.id
            }
          });
          const emailReserved = await reserveNotificationDeliveryWith(tx, {
            userId: row.user.id,
            channel: "EMAIL",
            category: "MEMBERSHIP",
            idempotencyKey: emailKey,
            status: "SKIPPED",
            provider: null,
            metadata: {
              kind: "membership_activated",
              paymentId,
              invoiceId: row.invoice.id
            }
          });
          return {
            kind: "APPROVED",
            user: row.user,
            plan: effectivePlan,
            renewalDate,
            notificationId: inApp.id,
            invoice,
            subscription,
            payment: updatedPayment,
            push: { reserved: pushReserved.reserved, key: pushKey },
            email: { reserved: emailReserved.reserved, key: emailKey }
          };
        });
        if (result.kind === "NOT_FOUND") {
          return res.status(404).json({ message: "Payment not found." });
        }
        if (result.kind === "ALREADY_PROCESSED") {
          return res.status(409).json({ message: "Payment already processed." });
        }
        if (result.push.reserved) {
          void (async () => {
            try {
              const pushResult = await deliverPushIfEnabled({
                userId: result.user.id,
                category: "MEMBERSHIP",
                title: "Membership activated",
                body: `Your ${result.plan.name} membership is now active.`,
                data: { actionHref: "/dashboard/billing" }
              });
              await finalizeNotificationDeliveryWith(db, {
                idempotencyKey: result.push.key,
                status: pushResult.status,
                provider: pushResult.status === "SENT" ? "EXPO" : null,
                errorMessage: pushResult.reason ?? null,
                notificationId: result.notificationId,
                metadata: {
                  kind: "membership_activated",
                  reason: pushResult.reason ?? null
                }
              });
            } catch (err) {
              await finalizeNotificationDeliveryWith(db, {
                idempotencyKey: result.push.key,
                status: "FAILED",
                provider: "EXPO",
                errorMessage: err instanceof Error ? err.message : String(err),
                notificationId: result.notificationId,
                metadata: { kind: "membership_activated" }
              });
            }
          })();
        }
        if (result.email.reserved) {
          void (async () => {
            try {
              const emailResult = await deliverMembershipActivatedEmailIfEnabled({
                userId: result.user.id,
                to: result.user.email,
                firstName: result.user.firstName,
                planName: result.plan.name,
                renewalDate: result.renewalDate,
                amount: Number(result.payment.amount),
                currency: result.plan.currency
              });
              await finalizeNotificationDeliveryWith(db, {
                idempotencyKey: result.email.key,
                status: emailResult.status,
                provider: emailResult.status === "SENT" ? "SMTP" : null,
                errorMessage: emailResult.reason ?? null,
                notificationId: result.notificationId,
                metadata: {
                  kind: "membership_activated",
                  reason: emailResult.reason ?? null
                }
              });
            } catch (err) {
              await finalizeNotificationDeliveryWith(db, {
                idempotencyKey: result.email.key,
                status: "FAILED",
                provider: "SMTP",
                errorMessage: err instanceof Error ? err.message : String(err),
                notificationId: result.notificationId,
                metadata: { kind: "membership_activated" }
              });
            }
          })();
        }
        ensureActiveOnboardingEnrollmentForUser(result.user.id).catch(() => {
        });
        return res.json({ ok: true });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/membership/payments/:paymentId/decline", async (req, res) => {
      const paymentId = Number(req.params.paymentId);
      if (!Number.isFinite(paymentId) || paymentId <= 0) {
        return res.status(400).json({ message: "Invalid payment id." });
      }
      try {
        const schema = external_exports.object({
          reason: external_exports.string().trim().max(500).optional().nullable()
        });
        const parsed = schema.safeParse(req.body ?? {});
        if (!parsed.success) {
          return res.status(400).json({ errors: parsed.error.flatten() });
        }
        const now = /* @__PURE__ */ new Date();
        const result = await db.transaction(async (tx) => {
          const [row] = await tx.select({
            payment: paymentsTable,
            invoice: invoicesTable,
            subscription: membershipSubscriptionsTable,
            plan: membershipPlansTable,
            user: usersTable
          }).from(paymentsTable).leftJoin(invoicesTable, eq(paymentsTable.invoiceId, invoicesTable.id)).leftJoin(
            membershipSubscriptionsTable,
            eq(invoicesTable.subscriptionId, membershipSubscriptionsTable.id)
          ).leftJoin(
            membershipPlansTable,
            eq(membershipSubscriptionsTable.planId, membershipPlansTable.id)
          ).leftJoin(usersTable, eq(paymentsTable.userId, usersTable.id)).where(eq(paymentsTable.id, paymentId));
          if (!row?.payment || !row.invoice || !row.subscription || !row.plan || !row.user) {
            return { kind: "NOT_FOUND" };
          }
          if (!["membership_manual", "membership_manual_plan_change"].includes(
            row.payment.metadata?.activationType
          )) {
            return { kind: "NOT_FOUND" };
          }
          const activationType = String(
            (row.payment.metadata ?? {}).activationType ?? ""
          );
          const isPlanChangeDecline = activationType === "membership_manual_plan_change";
          const [updatedPayment] = await tx.update(paymentsTable).set({
            status: "FAILED",
            updatedAt: now,
            metadata: {
              ...row.payment.metadata,
              declineReason: parsed.data.reason?.trim() || null
            }
          }).where(
            and(
              eq(paymentsTable.id, paymentId),
              eq(paymentsTable.status, "PENDING")
            )
          ).returning();
          if (!updatedPayment) {
            return { kind: "ALREADY_PROCESSED" };
          }
          await tx.update(invoicesTable).set({ status: "CANCELLED", updatedAt: now }).where(eq(invoicesTable.id, row.invoice.id));
          if (!isPlanChangeDecline) {
            await tx.update(membershipSubscriptionsTable).set({
              status: "CANCELLED",
              cancelledAt: now,
              updatedAt: now
            }).where(eq(membershipSubscriptionsTable.id, row.subscription.id));
            await tx.update(usersTable).set({
              membershipStatus: "CANCELLED",
              updatedAt: now
            }).where(eq(usersTable.id, row.user.id));
            await syncOrganizationSubscriptionStateWith(tx, {
              user: row.user,
              plan: row.plan,
              status: "CANCELLED",
              now
            });
          }
          const inApp = await notifyInAppWith(tx, {
            userId: row.user.id,
            category: "MEMBERSHIP",
            severity: "ERROR",
            title: "Payment declined",
            body: parsed.data.reason?.trim() ? `Your membership payment was declined: ${parsed.data.reason.trim()}` : "Your membership payment was declined. Please contact support or submit a new payment proof.",
            actionLabel: "Open Billing",
            actionHref: "/dashboard/billing"
          });
          return { kind: "DECLINED", notificationId: inApp.id };
        });
        if (result.kind === "NOT_FOUND") {
          return res.status(404).json({ message: "Payment not found." });
        }
        if (result.kind === "ALREADY_PROCESSED") {
          return res.status(409).json({ message: "Payment already processed." });
        }
        return res.json({ ok: true });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/plans", async (_req, res) => {
      try {
        const plans = await db.select({
          id: membershipPlansTable.id,
          membershipType: membershipPlansTable.membershipType,
          organizationType: membershipPlansTable.organizationType,
          tier: membershipPlansTable.tier,
          name: membershipPlansTable.name,
          description: membershipPlansTable.description,
          priceMonthly: membershipPlansTable.priceMonthly,
          priceAnnual: membershipPlansTable.priceAnnual,
          currency: membershipPlansTable.currency,
          features: membershipPlansTable.features,
          entitlements: membershipPlansTable.entitlements,
          isActive: membershipPlansTable.isActive,
          sortOrder: membershipPlansTable.sortOrder,
          billingMode: membershipPlansTable.billingMode,
          defaultBillingCycle: membershipPlansTable.defaultBillingCycle,
          createdAt: membershipPlansTable.createdAt,
          updatedAt: membershipPlansTable.updatedAt,
          subscriptionCount: sql`(
          select count(*)::int
          from membership_subscriptions ms
          where ms.plan_id = ${membershipPlansTable.id}
        )`
        }).from(membershipPlansTable).orderBy(
          asc(membershipPlansTable.membershipType),
          asc(membershipPlansTable.sortOrder),
          asc(membershipPlansTable.id)
        );
        return res.json({ plans });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    planEntitlementsSchema = external_exports.object({
      member_susu_access: external_exports.boolean().optional(),
      susunomics_access: external_exports.boolean().optional(),
      community_lending_access: external_exports.boolean().optional(),
      p2p_lending_access: external_exports.boolean().optional(),
      tenant_access: external_exports.boolean().optional(),
      member_management: external_exports.boolean().optional(),
      seat_limit: external_exports.number().int().min(0).nullable().optional(),
      org_billing_manage: external_exports.boolean().optional(),
      org_wallet_operate: external_exports.boolean().optional(),
      org_wallet_fund: external_exports.boolean().optional(),
      org_member_contributions: external_exports.boolean().optional(),
      org_financial_reporting: external_exports.boolean().optional(),
      programs_access: external_exports.boolean().optional(),
      resources_access: external_exports.boolean().optional(),
      workshops_access: external_exports.boolean().optional(),
      white_label_resources_access: external_exports.boolean().optional(),
      org_susu_operate: external_exports.boolean().optional(),
      org_susu_education: external_exports.boolean().optional(),
      investment_club_access: external_exports.boolean().optional(),
      p2p_capital_access: external_exports.boolean().optional(),
      asca_access: external_exports.boolean().optional(),
      quote_managed_only: external_exports.boolean().optional()
    }).strict();
    router3.post("/plans", async (req, res) => {
      try {
        const schema = external_exports.object({
          membershipType: external_exports.enum(["INDIVIDUAL", "ORGANIZATION", "INVESTOR"]),
          tier: external_exports.string().min(1),
          name: external_exports.string().min(1),
          description: external_exports.string().optional().default(""),
          priceAnnual: external_exports.string(),
          currency: external_exports.string().optional().default("CAD"),
          features: external_exports.array(external_exports.string()).optional().default([]),
          entitlements: planEntitlementsSchema.optional().default({}),
          isActive: external_exports.boolean().optional().default(true),
          sortOrder: external_exports.number().int().optional().default(0),
          billingMode: external_exports.enum(["ONE_TIME", "RECURRING"]).optional().default("RECURRING"),
          defaultBillingCycle: external_exports.enum(["MONTHLY", "ANNUAL"]).optional().default("ANNUAL")
        }).strict();
        const data = schema.parse(req.body);
        const normalizedTier = data.tier.toUpperCase();
        if (!isAllowedMembershipPlanTier({
          membershipType: data.membershipType,
          tier: normalizedTier
        })) {
          return res.status(400).json({
            message: "Tier is not valid for the selected membership type."
          });
        }
        const plan = await db.transaction(async (tx) => {
          const tierTyped = normalizedTier;
          const tierWhere = tierTyped === null ? isNull(membershipPlansTable.tier) : sql`${membershipPlansTable.tier} = ${tierTyped}::membership_plan_tier_enum`;
          const [duplicate] = await tx.select({ id: membershipPlansTable.id }).from(membershipPlansTable).where(
            and(
              eq(membershipPlansTable.membershipType, data.membershipType),
              tierWhere,
              isNull(membershipPlansTable.organizationType)
            )
          ).limit(1);
          if (duplicate) {
            return res.status(400).json({
              message: "A plan already exists for this membership type and tier. Edit the existing plan instead of creating a duplicate."
            });
          }
          const [inserted] = await tx.insert(membershipPlansTable).values({
            membershipType: data.membershipType,
            organizationType: null,
            tier: normalizedTier,
            name: data.name,
            description: data.description,
            priceMonthly: data.priceAnnual,
            priceAnnual: data.priceAnnual,
            currency: data.currency,
            features: data.features,
            entitlements: normalizePlanEntitlementsForMembershipType(
              data.membershipType,
              data.entitlements
            ),
            isActive: data.isActive,
            sortOrder: data.sortOrder,
            billingMode: data.billingMode,
            defaultBillingCycle: data.defaultBillingCycle
          }).returning();
          return inserted;
        });
        if (plan?.status) return plan;
        return res.status(201).json({ plan });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.patch("/plans/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        const schema = external_exports.object({
          membershipType: external_exports.enum(["INDIVIDUAL", "ORGANIZATION", "INVESTOR"]).optional(),
          tier: external_exports.string().min(1).optional(),
          name: external_exports.string().min(1).optional(),
          description: external_exports.string().optional(),
          priceAnnual: external_exports.string().optional(),
          currency: external_exports.string().optional(),
          features: external_exports.array(external_exports.string()).optional(),
          entitlements: planEntitlementsSchema.optional(),
          isActive: external_exports.boolean().optional(),
          sortOrder: external_exports.number().int().optional(),
          billingMode: external_exports.enum(["ONE_TIME", "RECURRING"]).optional(),
          defaultBillingCycle: external_exports.enum(["MONTHLY", "ANNUAL"]).optional()
        }).strict();
        const data = schema.parse(req.body);
        const plan = await db.transaction(async (tx) => {
          const [existingPlan] = await tx.select({
            id: membershipPlansTable.id,
            membershipType: membershipPlansTable.membershipType,
            tier: membershipPlansTable.tier,
            organizationType: membershipPlansTable.organizationType
          }).from(membershipPlansTable).where(eq(membershipPlansTable.id, id));
          if (!existingPlan) {
            return res.status(404).json({ message: "Plan not found." });
          }
          const effectiveMembershipType = data.membershipType ?? existingPlan.membershipType;
          const effectiveTier = (data.tier ?? existingPlan.tier).toUpperCase();
          if (!isAllowedMembershipPlanTier({
            membershipType: effectiveMembershipType,
            tier: effectiveTier
          })) {
            const isUnchangedLegacyTier = effectiveTier === existingPlan.tier && isLegacyMembershipPlanTier(effectiveTier);
            if (!isUnchangedLegacyTier) {
              return res.status(400).json({
                message: "Tier is not valid for the selected membership type."
              });
            }
          }
          if (data.membershipType !== void 0 || data.tier !== void 0) {
            const tierTyped = effectiveTier;
            const tierWhere = tierTyped === null ? isNull(membershipPlansTable.tier) : sql`${membershipPlansTable.tier} = ${tierTyped}::membership_plan_tier_enum`;
            const [collision] = await tx.select({ id: membershipPlansTable.id }).from(membershipPlansTable).where(
              and(
                eq(membershipPlansTable.membershipType, effectiveMembershipType),
                tierWhere,
                existingPlan.organizationType ? eq(
                  membershipPlansTable.organizationType,
                  existingPlan.organizationType
                ) : isNull(membershipPlansTable.organizationType)
              )
            ).limit(1);
            if (collision && collision.id !== id) {
              return res.status(400).json({
                message: "Another plan already uses this membership type and tier. Edits must be unique per membership type."
              });
            }
          }
          const now = /* @__PURE__ */ new Date();
          const normalizedEntitlements = data.entitlements === void 0 ? void 0 : normalizePlanEntitlementsForMembershipType(
            effectiveMembershipType,
            data.entitlements
          );
          const patchValues = {
            membershipType: data.membershipType,
            name: data.name,
            description: data.description,
            priceAnnual: data.priceAnnual,
            priceMonthly: data.priceAnnual,
            currency: data.currency,
            features: data.features,
            entitlements: normalizedEntitlements,
            isActive: data.isActive,
            sortOrder: data.sortOrder,
            billingMode: data.billingMode,
            defaultBillingCycle: data.defaultBillingCycle,
            updatedAt: now
          };
          if (data.tier) {
            patchValues.tier = effectiveTier;
          }
          const updates = {};
          for (const key of Object.keys(patchValues)) {
            const value = patchValues[key];
            if (value !== void 0) {
              updates[key] = value;
            }
          }
          const [updated] = await tx.update(membershipPlansTable).set(updates).where(eq(membershipPlansTable.id, id)).returning();
          return updated;
        });
        if (plan?.status) return plan;
        return res.json({ plan });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.delete("/plans/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        const result = await db.transaction(async (tx) => {
          const [{ count: subCount } = { count: 0 }] = await tx.select({ count: sql`count(*)::int` }).from(membershipSubscriptionsTable).where(eq(membershipSubscriptionsTable.planId, id));
          if (Number(subCount) > 0) {
            return res.status(400).json({
              message: "Cannot delete a plan that has active or historical subscriptions. Deactivate the plan instead."
            });
          }
          const [deleted] = await tx.delete(membershipPlansTable).where(eq(membershipPlansTable.id, id)).returning();
          if (!deleted) return res.status(404).json({ message: "Plan not found." });
          return deleted;
        });
        if (result?.status) return result;
        return res.json({ ok: true });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/ascas", async (_req, res) => {
      try {
        const ascas = await db.select({
          id: ascasTable.id,
          name: ascasTable.name,
          description: ascasTable.description,
          organizationId: ascasTable.organizationId,
          organizationName: organizationsTable.name,
          type: ascasTable.type,
          status: ascasTable.status,
          investmentId: ascasTable.investmentId,
          escrowWalletId: ascasTable.escrowWalletId,
          targetAmount: ascasTable.targetAmount,
          currentAmount: ascasTable.currentAmount,
          constitution: ascasTable.constitution,
          createdAt: ascasTable.createdAt,
          updatedAt: ascasTable.updatedAt,
          memberCount: sql`(
          select count(*)::int
          from asca_members am
          where am.asca_id = ${ascasTable.id}
        )`,
          contributionCount: sql`(
          select count(*)::int
          from asca_members am
          where am.asca_id = ${ascasTable.id}
            and coalesce(am.contributed_amount, 0) > 0
        )`
        }).from(ascasTable).leftJoin(
          organizationsTable,
          eq(organizationsTable.id, ascasTable.organizationId)
        ).where(isNull(ascasTable.organizationId)).orderBy(desc(ascasTable.createdAt));
        return res.json({ ascas });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/ascas/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        const [asca] = await db.select().from(ascasTable).where(eq(ascasTable.id, id));
        if (!asca) return res.status(404).json({ message: "ASCA not found." });
        const members = await db.select({
          id: ascaMembersTable.id,
          ascaId: ascaMembersTable.ascaId,
          userId: ascaMembersTable.userId,
          targetContribution: ascaMembersTable.targetContribution,
          contributedAmount: ascaMembersTable.contributedAmount,
          status: ascaMembersTable.status,
          joinedAt: ascaMembersTable.joinedAt,
          firstName: usersTable.firstName,
          lastName: usersTable.lastName
        }).from(ascaMembersTable).innerJoin(usersTable, eq(ascaMembersTable.userId, usersTable.id)).where(eq(ascaMembersTable.ascaId, id)).orderBy(desc(ascaMembersTable.contributedAmount));
        const contributions = await db.select().from(ascaContributionsTable).where(eq(ascaContributionsTable.ascaId, id)).orderBy(desc(ascaContributionsTable.createdAt));
        return res.json({ asca, members, contributions });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.patch("/ascas/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        const schema = external_exports.object({
          name: external_exports.string().min(3).optional(),
          description: external_exports.string().optional().nullable(),
          targetAmount: external_exports.string().optional().nullable()
        }).strict();
        const data = schema.parse(req.body);
        const [existing] = await db.select({ id: ascasTable.id }).from(ascasTable).where(eq(ascasTable.id, id));
        if (!existing) return res.status(404).json({ message: "ASCA not found." });
        const [asca] = await db.update(ascasTable).set({ ...data, updatedAt: /* @__PURE__ */ new Date() }).where(eq(ascasTable.id, id)).returning();
        return res.json({ asca });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/ascas/:id/publish", async (req, res) => {
      try {
        const id = Number(req.params.id);
        const asca = await publishAsca(id, { organizationId: null });
        return res.json({ asca });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/ascas/:id/unpublish", async (req, res) => {
      try {
        const id = Number(req.params.id);
        const asca = await unpublishAsca(id, { organizationId: null });
        return res.json({ asca });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/ascas/:id/cancel", async (req, res) => {
      try {
        const id = Number(req.params.id);
        const admin = req.admin;
        await cancelAsca(id, admin.id);
        return res.json({ ok: true });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    onboardingSlideSchema = external_exports.object({
      title: external_exports.string().min(1),
      subtitle: external_exports.string().optional().nullable(),
      body: external_exports.string().optional().nullable(),
      illustrationIcon: external_exports.string().default("diamond-stone"),
      illustrationUrl: external_exports.string().optional().nullable(),
      accentColor: external_exports.string().default("#f27a4a"),
      sortOrder: external_exports.number().int().default(0),
      isActive: external_exports.boolean().default(true)
    });
    router3.get("/onboarding/slides", async (_req, res) => {
      try {
        const slides = await db.select().from(onboardingSlidesTable).orderBy(asc(onboardingSlidesTable.sortOrder));
        return res.json({ slides });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/onboarding/slides", async (req, res) => {
      try {
        const data = onboardingSlideSchema.parse(req.body);
        const [slide] = await db.insert(onboardingSlidesTable).values(data).returning();
        return res.status(201).json({ slide });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.patch("/onboarding/slides/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        const data = onboardingSlideSchema.partial().parse(req.body);
        const [slide] = await db.update(onboardingSlidesTable).set({ ...data, updatedAt: /* @__PURE__ */ new Date() }).where(eq(onboardingSlidesTable.id, id)).returning();
        if (!slide) return res.status(404).json({ message: "Slide not found." });
        return res.json({ slide });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.delete("/onboarding/slides/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        const [deleted] = await db.delete(onboardingSlidesTable).where(eq(onboardingSlidesTable.id, id)).returning();
        if (!deleted) return res.status(404).json({ message: "Slide not found." });
        return res.json({ ok: true });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/onboarding/slides/reorder", async (req, res) => {
      try {
        const { order } = external_exports.object({ order: external_exports.array(external_exports.number().int()) }).parse(req.body);
        await Promise.all(
          order.map(
            (id, index2) => db.update(onboardingSlidesTable).set({ sortOrder: index2, updatedAt: /* @__PURE__ */ new Date() }).where(eq(onboardingSlidesTable.id, id))
          )
        );
        return res.json({ ok: true });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    onboardingProgramSchema = external_exports.object({
      title: external_exports.string().min(1),
      description: external_exports.string().optional().nullable(),
      targetMembershipType: external_exports.enum(["INDIVIDUAL", "INVESTOR", "ORGANIZATION"]),
      durationUnit: external_exports.enum(["WEEK", "DAY"]).default("WEEK"),
      numberOfWeeks: external_exports.coerce.number().int().positive(),
      startDate: external_exports.coerce.date().optional().nullable(),
      endDate: external_exports.coerce.date().optional().nullable(),
      status: external_exports.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]).default("DRAFT")
    });
    onboardingWeekSchema = external_exports.object({
      weekNumber: external_exports.coerce.number().int().positive(),
      title: external_exports.string().min(1),
      description: external_exports.string().optional().nullable(),
      sortOrder: external_exports.coerce.number().int().default(0)
    });
    onboardingActivitySchema = external_exports.object({
      title: external_exports.string().min(1),
      description: external_exports.string().optional().nullable(),
      durationMinutes: external_exports.coerce.number().int().positive().optional().nullable(),
      type: external_exports.enum([
        "VIDEO",
        "FILE",
        "RICH_TEXT",
        "EXTERNAL_LINK",
        "QUIZ",
        "CHECKLIST",
        "SURVEY"
      ]),
      content: external_exports.unknown().optional().nullable(),
      sortOrder: external_exports.coerce.number().int().default(0),
      isRequired: external_exports.coerce.boolean().default(true)
    });
    router3.get("/onboarding/programs", async (_req, res) => {
      try {
        const programs = await db.select().from(onboardingProgramsTable).orderBy(desc(onboardingProgramsTable.createdAt));
        return res.json({ programs });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/onboarding/programs", async (req, res) => {
      try {
        const data = onboardingProgramSchema.parse(req.body);
        if (data.status === "PUBLISHED") {
          return res.status(409).json({
            message: "Create the programme as draft first, then add at least one week and one activity before publishing it."
          });
        }
        await assertNoPublishedOnboardingProgramConflict({
          targetMembershipType: data.targetMembershipType,
          startDate: data.startDate ?? null,
          endDate: data.endDate ?? null,
          status: data.status
        });
        const now = /* @__PURE__ */ new Date();
        const [program] = await db.insert(onboardingProgramsTable).values({
          title: data.title,
          description: data.description ?? null,
          targetMembershipType: data.targetMembershipType,
          durationUnit: data.durationUnit,
          numberOfWeeks: data.numberOfWeeks,
          startDate: data.startDate ?? null,
          endDate: data.endDate ?? null,
          status: data.status,
          createdAt: now,
          updatedAt: now
        }).returning();
        return res.status(201).json({ program });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.get("/onboarding/programs/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        const [program] = await db.select().from(onboardingProgramsTable).where(eq(onboardingProgramsTable.id, id));
        if (!program)
          return res.status(404).json({ message: "Program not found." });
        const weeks = await db.select().from(onboardingProgramWeeksTable).where(eq(onboardingProgramWeeksTable.programId, id)).orderBy(asc(onboardingProgramWeeksTable.sortOrder));
        const weekIds = weeks.map((w) => w.id);
        const activities = weekIds.length ? await db.select().from(onboardingWeekActivitiesTable).where(inArray(onboardingWeekActivitiesTable.weekId, weekIds)).orderBy(asc(onboardingWeekActivitiesTable.sortOrder)) : [];
        return res.json({ program, weeks, activities });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.patch("/onboarding/programs/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        const data = onboardingProgramSchema.partial().parse(req.body);
        const now = /* @__PURE__ */ new Date();
        const result = await db.transaction(async (tx) => {
          const [existingProgram] = await tx.select().from(onboardingProgramsTable).where(eq(onboardingProgramsTable.id, id));
          if (!existingProgram) return null;
          const nextProgram = {
            id,
            targetMembershipType: data.targetMembershipType ?? existingProgram.targetMembershipType,
            startDate: data.startDate ?? existingProgram.startDate ?? null,
            endDate: data.endDate ?? existingProgram.endDate ?? null,
            status: data.status ?? existingProgram.status
          };
          await assertNoPublishedOnboardingProgramConflict(nextProgram, tx);
          const [program] = await tx.update(onboardingProgramsTable).set({ ...data, updatedAt: now }).where(eq(onboardingProgramsTable.id, id)).returning();
          if (!program) return null;
          await tx.delete(onboardingProgramWeeksTable).where(
            and(
              eq(onboardingProgramWeeksTable.programId, id),
              gt(onboardingProgramWeeksTable.weekNumber, program.numberOfWeeks)
            )
          );
          await assertPublishedOnboardingProgramHasContent(
            { id, status: nextProgram.status },
            tx
          );
          return program;
        });
        if (!result) return res.status(404).json({ message: "Program not found." });
        return res.json({ program: result });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.delete("/onboarding/programs/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        const enrollments = await db.select({
          userId: onboardingEnrollmentsTable.userId
        }).from(onboardingEnrollmentsTable).where(eq(onboardingEnrollmentsTable.programId, id));
        const affectedUserIds = Array.from(
          new Set(
            enrollments.map((row) => row.userId).filter((id2) => Number.isFinite(id2))
          )
        );
        const deleted = await db.transaction(async (tx) => {
          if (affectedUserIds.length > 0) {
            await tx.delete(onboardingEnrollmentsTable).where(eq(onboardingEnrollmentsTable.programId, id));
          }
          const [program] = await tx.delete(onboardingProgramsTable).where(eq(onboardingProgramsTable.id, id)).returning();
          return program ?? null;
        });
        if (!deleted)
          return res.status(404).json({ message: "Program not found." });
        if (affectedUserIds.length > 0) {
          await Promise.all(
            affectedUserIds.map(async (userId) => {
              await syncActiveOnboardingCompletionForUser(userId);
              await updateCreditScore(userId);
            })
          );
        }
        return res.json({ ok: true });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post("/onboarding/programs/:programId/weeks", async (req, res) => {
      try {
        const programId = Number(req.params.programId);
        const data = onboardingWeekSchema.parse(req.body);
        const now = /* @__PURE__ */ new Date();
        const [program] = await db.select().from(onboardingProgramsTable).where(eq(onboardingProgramsTable.id, programId));
        if (!program)
          return res.status(404).json({ message: "Program not found." });
        if (data.weekNumber > program.numberOfWeeks) {
          return res.status(400).json({
            message: `This programme is limited to ${program.numberOfWeeks} ${program.durationUnit === "DAY" ? "day" : "week"}${program.numberOfWeeks === 1 ? "" : "s"}.`
          });
        }
        const [countRow] = await db.select({ count: count() }).from(onboardingProgramWeeksTable).where(eq(onboardingProgramWeeksTable.programId, programId));
        const existingCount = Number(countRow?.count ?? 0);
        if (existingCount >= program.numberOfWeeks) {
          return res.status(400).json({
            message: `You have already created the maximum of ${program.numberOfWeeks} ${program.durationUnit === "DAY" ? "day" : "week"}${program.numberOfWeeks === 1 ? "" : "s"} for this programme.`
          });
        }
        const [week] = await db.insert(onboardingProgramWeeksTable).values({
          programId,
          weekNumber: data.weekNumber,
          title: data.title,
          description: data.description ?? null,
          sortOrder: data.sortOrder,
          createdAt: now,
          updatedAt: now
        }).returning();
        return res.status(201).json({ week });
      } catch (err) {
        if (isUniqueViolation5(err)) {
          return res.status(409).json({
            message: "This week number already exists for the selected programme."
          });
        }
        return handleError2(err, res);
      }
    });
    router3.patch("/onboarding/weeks/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        const data = onboardingWeekSchema.partial().parse(req.body);
        if (data.weekNumber != null) {
          const [row] = await db.select({
            programId: onboardingProgramWeeksTable.programId,
            maxWeeks: onboardingProgramsTable.numberOfWeeks,
            unit: onboardingProgramsTable.durationUnit
          }).from(onboardingProgramWeeksTable).innerJoin(
            onboardingProgramsTable,
            eq(onboardingProgramWeeksTable.programId, onboardingProgramsTable.id)
          ).where(eq(onboardingProgramWeeksTable.id, id));
          if (!row) return res.status(404).json({ message: "Week not found." });
          if (data.weekNumber > row.maxWeeks) {
            return res.status(400).json({
              message: `This programme is limited to ${row.maxWeeks} ${row.unit === "DAY" ? "day" : "week"}${row.maxWeeks === 1 ? "" : "s"}.`
            });
          }
        }
        const [week] = await db.update(onboardingProgramWeeksTable).set({ ...data, updatedAt: /* @__PURE__ */ new Date() }).where(eq(onboardingProgramWeeksTable.id, id)).returning();
        if (!week) return res.status(404).json({ message: "Week not found." });
        return res.json({ week });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.delete("/onboarding/weeks/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        const result = await db.transaction(async (tx) => {
          const [week] = await tx.select({
            id: onboardingProgramWeeksTable.id,
            programId: onboardingProgramWeeksTable.programId,
            programStatus: onboardingProgramsTable.status
          }).from(onboardingProgramWeeksTable).innerJoin(
            onboardingProgramsTable,
            eq(onboardingProgramWeeksTable.programId, onboardingProgramsTable.id)
          ).where(eq(onboardingProgramWeeksTable.id, id));
          if (!week) return { missing: true };
          if (week.programStatus === "PUBLISHED") {
            const { weekCount, activityCount } = await getOnboardingProgramStructureCounts(week.programId, tx);
            const [activityRows] = await tx.select({ count: count() }).from(onboardingWeekActivitiesTable).where(eq(onboardingWeekActivitiesTable.weekId, id));
            const deletedWeekActivityCount = Number(activityRows?.count ?? 0);
            if (weekCount <= 1 || activityCount - deletedWeekActivityCount <= 0) {
              throw Object.assign(
                new Error(
                  "A published onboarding program must keep at least one week and one activity. Change the programme back to draft before removing the final content."
                ),
                { status: 409 }
              );
            }
          }
          const [deleted] = await tx.delete(onboardingProgramWeeksTable).where(eq(onboardingProgramWeeksTable.id, id)).returning();
          return { missing: false, deleted };
        });
        if (result.missing || !result.deleted) {
          return res.status(404).json({ message: "Week not found." });
        }
        return res.json({ ok: true });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post(
      "/onboarding/programs/:programId/weeks/reorder",
      async (req, res) => {
        try {
          const { order } = external_exports.object({ order: external_exports.array(external_exports.number().int()) }).parse(req.body);
          await Promise.all(
            order.map(
              (id, index2) => db.update(onboardingProgramWeeksTable).set({ sortOrder: index2, updatedAt: /* @__PURE__ */ new Date() }).where(eq(onboardingProgramWeeksTable.id, id))
            )
          );
          return res.json({ ok: true });
        } catch (err) {
          return handleError2(err, res);
        }
      }
    );
    router3.post("/onboarding/weeks/:weekId/activities", async (req, res) => {
      try {
        const weekId = Number(req.params.weekId);
        const data = onboardingActivitySchema.parse(req.body);
        const now = /* @__PURE__ */ new Date();
        const [activity] = await db.insert(onboardingWeekActivitiesTable).values({
          weekId,
          title: data.title,
          description: data.description ?? null,
          durationMinutes: data.durationMinutes ?? null,
          type: data.type,
          content: data.content && typeof data.content === "object" ? data.content : data.content == null ? null : { value: data.content },
          sortOrder: data.sortOrder,
          isRequired: data.isRequired,
          createdAt: now,
          updatedAt: now
        }).returning();
        return res.status(201).json({ activity });
      } catch (err) {
        if (isUniqueViolation5(err)) {
          return res.status(409).json({
            message: "An activity with this title already exists in the selected week."
          });
        }
        return handleError2(err, res);
      }
    });
    router3.patch("/onboarding/activities/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        const data = onboardingActivitySchema.partial().parse(req.body);
        const updates = {
          ...data,
          ...data.content !== void 0 ? {
            content: data.content && typeof data.content === "object" ? data.content : data.content == null ? null : { value: data.content }
          } : {},
          updatedAt: /* @__PURE__ */ new Date()
        };
        const [activity] = await db.update(onboardingWeekActivitiesTable).set(updates).where(eq(onboardingWeekActivitiesTable.id, id)).returning();
        if (!activity)
          return res.status(404).json({ message: "Activity not found." });
        return res.json({ activity });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.delete("/onboarding/activities/:id", async (req, res) => {
      try {
        const id = Number(req.params.id);
        const result = await db.transaction(async (tx) => {
          const [activity] = await tx.select({
            id: onboardingWeekActivitiesTable.id,
            programId: onboardingProgramWeeksTable.programId,
            programStatus: onboardingProgramsTable.status
          }).from(onboardingWeekActivitiesTable).innerJoin(
            onboardingProgramWeeksTable,
            eq(
              onboardingWeekActivitiesTable.weekId,
              onboardingProgramWeeksTable.id
            )
          ).innerJoin(
            onboardingProgramsTable,
            eq(onboardingProgramWeeksTable.programId, onboardingProgramsTable.id)
          ).where(eq(onboardingWeekActivitiesTable.id, id));
          if (!activity) return { missing: true };
          if (activity.programStatus === "PUBLISHED") {
            const { activityCount } = await getOnboardingProgramStructureCounts(
              activity.programId,
              tx
            );
            if (activityCount <= 1) {
              throw Object.assign(
                new Error(
                  "A published onboarding program must keep at least one activity. Change the programme back to draft before removing the final activity."
                ),
                { status: 409 }
              );
            }
          }
          const [deleted] = await tx.delete(onboardingWeekActivitiesTable).where(eq(onboardingWeekActivitiesTable.id, id)).returning();
          return { missing: false, deleted };
        });
        if (result.missing || !result.deleted)
          return res.status(404).json({ message: "Activity not found." });
        return res.json({ ok: true });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    router3.post(
      "/onboarding/weeks/:weekId/activities/reorder",
      async (req, res) => {
        try {
          const { order } = external_exports.object({ order: external_exports.array(external_exports.number().int()) }).parse(req.body);
          await Promise.all(
            order.map(
              (id, index2) => db.update(onboardingWeekActivitiesTable).set({ sortOrder: index2, updatedAt: /* @__PURE__ */ new Date() }).where(eq(onboardingWeekActivitiesTable.id, id))
            )
          );
          return res.json({ ok: true });
        } catch (err) {
          return handleError2(err, res);
        }
      }
    );
    router3.get("/onboarding/programs/:programId/analytics", async (req, res) => {
      try {
        const programId = Number(req.params.programId);
        const now = /* @__PURE__ */ new Date();
        const threshold = new Date(now);
        threshold.setDate(threshold.getDate() - 14);
        const [stats] = await db.select({
          totalEnrolled: count(),
          completedMembers: sql`count(*) filter (where ${onboardingEnrollmentsTable.completedAt} is not null)`,
          activeMembers: sql`count(*) filter (where ${onboardingEnrollmentsTable.completedAt} is null)`,
          dropoffs: sql`count(*) filter (where ${onboardingEnrollmentsTable.completedAt} is null and ${onboardingEnrollmentsTable.lastActivityAt} is not null and ${onboardingEnrollmentsTable.lastActivityAt} < ${threshold})`,
          avgCompletionSeconds: sql`avg(extract(epoch from (${onboardingEnrollmentsTable.completedAt} - ${onboardingEnrollmentsTable.enrolledAt})))`
        }).from(onboardingEnrollmentsTable).where(eq(onboardingEnrollmentsTable.programId, programId));
        const totalEnrolled = Number(stats?.totalEnrolled ?? 0);
        const completedMembers = Number(stats?.completedMembers ?? 0);
        const activeMembers = Number(stats?.activeMembers ?? 0);
        const dropoffs = Number(stats?.dropoffs ?? 0);
        const avgCompletionSeconds = Number(stats?.avgCompletionSeconds ?? 0);
        const dropOffRate = totalEnrolled === 0 ? 0 : Math.round(dropoffs / totalEnrolled * 100);
        const weeks = await db.select({
          id: onboardingProgramWeeksTable.id,
          weekNumber: onboardingProgramWeeksTable.weekNumber,
          title: onboardingProgramWeeksTable.title
        }).from(onboardingProgramWeeksTable).where(eq(onboardingProgramWeeksTable.programId, programId)).orderBy(asc(onboardingProgramWeeksTable.sortOrder));
        const progressPerWeek = [];
        for (const week of weeks) {
          const activityIds = await db.select({ id: onboardingWeekActivitiesTable.id }).from(onboardingWeekActivitiesTable).where(eq(onboardingWeekActivitiesTable.weekId, week.id)).then((rows) => rows.map((r) => r.id));
          if (!activityIds.length) {
            progressPerWeek.push({
              weekNumber: week.weekNumber,
              title: week.title,
              completedMembers: 0
            });
            continue;
          }
          const completions = await db.select({ enrollmentId: onboardingActivityProgressTable.enrollmentId }).from(onboardingActivityProgressTable).innerJoin(
            onboardingEnrollmentsTable,
            eq(
              onboardingActivityProgressTable.enrollmentId,
              onboardingEnrollmentsTable.id
            )
          ).where(
            and(
              eq(onboardingEnrollmentsTable.programId, programId),
              eq(onboardingActivityProgressTable.status, "COMPLETED"),
              inArray(onboardingActivityProgressTable.activityId, activityIds)
            )
          ).groupBy(onboardingActivityProgressTable.enrollmentId).having(sql`count(*) = ${activityIds.length}`);
          progressPerWeek.push({
            weekNumber: week.weekNumber,
            title: week.title,
            completedMembers: completions.length
          });
        }
        return res.json({
          totals: {
            totalEnrolled,
            activeMembers,
            completedMembers,
            dropOffRate,
            averageCompletionDays: avgCompletionSeconds > 0 ? Math.round(avgCompletionSeconds / (60 * 60 * 24)) : null
          },
          progressPerWeek
        });
      } catch (err) {
        return handleError2(err, res);
      }
    });
    communityStorySchema = external_exports.object({
      title: external_exports.string().min(1),
      slug: external_exports.string().min(1),
      excerpt: external_exports.string().optional().nullable(),
      contentHtml: external_exports.string().min(1),
      coverImageUrl: external_exports.string().optional().nullable(),
      showToIndividuals: external_exports.boolean().default(true),
      showToInvestors: external_exports.boolean().default(true),
      showToOrganizations: external_exports.boolean().default(true),
      isPublished: external_exports.boolean().default(true)
    });
    admin_default = router3;
  }
});

// src/routes/admin-asca.ts
var admin_asca_exports = {};
__export(admin_asca_exports, {
  default: () => admin_asca_default
});
async function requireAdmin2(req, res, next) {
  const user = await resolveAuthenticatedUser(req.cookies?.wwn_token);
  if (!user) {
    return res.status(401).json({ message: "Invalid or expired token." });
  }
  if (user.userRole !== "ADMIN" && user.userRole !== "SUPER_ADMIN") {
    return res.status(403).json({ message: "Admin access required." });
  }
  req.admin = user;
  next();
}
function handleError3(err, res) {
  if (err?.status && err?.message) {
    return res.status(err.status).json({ message: err.message });
  }
  logger.error({ err }, "Admin ASCA route error");
  return res.status(500).json({ message: "Internal server error." });
}
async function listAscas(_req, res) {
  try {
    const ascas = await db.select({
      id: ascasTable.id,
      name: ascasTable.name,
      description: ascasTable.description,
      termsHtml: ascasTable.termsHtml,
      organizationId: ascasTable.organizationId,
      organizationName: organizationsTable.name,
      type: ascasTable.type,
      status: ascasTable.status,
      investmentId: ascasTable.investmentId,
      escrowWalletId: ascasTable.escrowWalletId,
      targetAmount: ascasTable.targetAmount,
      currentAmount: ascasTable.currentAmount,
      fundingStartAt: ascasTable.fundingStartAt,
      fundingEndAt: ascasTable.fundingEndAt,
      constitution: ascasTable.constitution,
      createdAt: ascasTable.createdAt,
      updatedAt: ascasTable.updatedAt,
      memberCount: sql`(
          select count(*)::int
          from asca_members am
          where am.asca_id = ${ascasTable.id}
        )`,
      contributionCount: sql`(
          select count(*)::int
          from asca_members am
          where am.asca_id = ${ascasTable.id}
            and coalesce(am.contributed_amount, 0) > 0
        )`
    }).from(ascasTable).leftJoin(
      organizationsTable,
      eq(organizationsTable.id, ascasTable.organizationId)
    ).where(isNull(ascasTable.organizationId)).orderBy(desc(ascasTable.createdAt));
    return res.json({ ascas });
  } catch (err) {
    return handleError3(err, res);
  }
}
async function getAscaDetails(req, res) {
  try {
    const id = Number(req.params.id);
    if (!Number.isFinite(id) || id <= 0) {
      return res.status(400).json({ message: "Invalid ASCA id." });
    }
    const [asca] = await db.select().from(ascasTable).where(eq(ascasTable.id, id));
    if (!asca) return res.status(404).json({ message: "ASCA not found." });
    const members = await db.select({
      id: ascaMembersTable.id,
      ascaId: ascaMembersTable.ascaId,
      userId: ascaMembersTable.userId,
      targetContribution: ascaMembersTable.targetContribution,
      contributedAmount: ascaMembersTable.contributedAmount,
      status: ascaMembersTable.status,
      joinedAt: ascaMembersTable.joinedAt,
      firstName: usersTable.firstName,
      lastName: usersTable.lastName
    }).from(ascaMembersTable).innerJoin(usersTable, eq(ascaMembersTable.userId, usersTable.id)).where(eq(ascaMembersTable.ascaId, id)).orderBy(desc(ascaMembersTable.contributedAmount));
    const contributions = await db.select().from(ascaContributionsTable).where(eq(ascaContributionsTable.ascaId, id)).orderBy(desc(ascaContributionsTable.createdAt));
    return res.json({ asca, members, contributions });
  } catch (err) {
    return handleError3(err, res);
  }
}
async function updateAsca(req, res) {
  try {
    const id = Number(req.params.id);
    if (!Number.isFinite(id) || id <= 0) {
      return res.status(400).json({ message: "Invalid ASCA id." });
    }
    const schema = external_exports.object({
      name: external_exports.string().min(3).optional(),
      description: external_exports.string().optional().nullable(),
      termsHtml: external_exports.string().optional().nullable(),
      type: external_exports.enum(["GENERAL", "INVESTMENT"]).optional(),
      investmentId: external_exports.number().int().positive().optional().nullable(),
      targetAmount: external_exports.string().optional().nullable(),
      fundingEndAt: external_exports.string().optional().nullable(),
      constitution: external_exports.object({
        allowLateJoin: external_exports.boolean().optional(),
        maxMembers: external_exports.number().int().positive().optional(),
        installmentPolicy: external_exports.enum(["INSTALLMENTS", "FULL"]).optional(),
        contributionFrequency: external_exports.enum(["WEEKLY", "MONTHLY"]).optional(),
        equalContribution: external_exports.boolean().optional(),
        contributionModel: external_exports.enum(["EQUAL", "VARIABLE"]).optional()
      }).passthrough().optional().nullable()
    }).strict();
    const parsed = schema.safeParse(req.body);
    if (!parsed.success) {
      return res.status(400).json({ errors: parsed.error.flatten() });
    }
    const data = parsed.data;
    const [existing] = await db.select({ id: ascasTable.id }).from(ascasTable).where(eq(ascasTable.id, id));
    if (!existing) return res.status(404).json({ message: "ASCA not found." });
    const normalizeMoneyString2 = (input, field) => {
      const parsed2 = Number(String(input).trim());
      if (!Number.isFinite(parsed2)) {
        throw new Error(`${field} must be a valid number.`);
      }
      if (parsed2 < 0) {
        throw new Error(`${field} must be 0 or more.`);
      }
      return parsed2.toFixed(2);
    };
    const normalizeDateInput2 = (input, field) => {
      const trimmed = String(input ?? "").trim();
      const parsed2 = new Date(trimmed);
      if (!trimmed || Number.isNaN(parsed2.getTime())) {
        throw new Error(`${field} must be a valid date.`);
      }
      return parsed2;
    };
    const toContributionModel = (constitution) => {
      if (typeof constitution?.equalContribution === "boolean") {
        return constitution.equalContribution ? "EQUAL" : "VARIABLE";
      }
      return constitution?.contributionModel === "EQUAL" ? "EQUAL" : "VARIABLE";
    };
    const updatePayload = {
      updatedAt: /* @__PURE__ */ new Date()
    };
    if (typeof data.name !== "undefined") updatePayload.name = data.name;
    if (typeof data.description !== "undefined")
      updatePayload.description = data.description;
    if (typeof data.termsHtml !== "undefined") {
      const normalized = typeof data.termsHtml === "string" && data.termsHtml.trim().length > 0 ? data.termsHtml.trim() : null;
      updatePayload.termsHtml = normalized;
    }
    if (typeof data.type !== "undefined") updatePayload.type = data.type;
    if (typeof data.investmentId !== "undefined")
      updatePayload.investmentId = data.investmentId;
    if (typeof data.targetAmount !== "undefined") {
      updatePayload.targetAmount = typeof data.targetAmount === "string" && data.targetAmount.trim().length > 0 ? normalizeMoneyString2(data.targetAmount, "targetAmount") : null;
    }
    if (typeof data.fundingEndAt !== "undefined") {
      updatePayload.fundingEndAt = typeof data.fundingEndAt === "string" && data.fundingEndAt.trim().length ? normalizeDateInput2(data.fundingEndAt, "fundingEndAt") : null;
    }
    if (typeof data.constitution !== "undefined") {
      if (data.constitution === null) {
        updatePayload.constitution = {};
      } else {
        const constitution = data.constitution;
        const contributionModel = toContributionModel(constitution);
        const {
          equalContribution: _equalContribution,
          contributionModel: _contributionModel,
          ...constitutionRest
        } = constitution ?? {};
        updatePayload.constitution = {
          ...constitutionRest,
          equalContribution: contributionModel === "EQUAL"
        };
      }
    }
    if (updatePayload.type === "INVESTMENT" && !updatePayload.investmentId) {
      return res.status(400).json({ message: "investmentId is required when type is INVESTMENT." });
    }
    const [asca] = await db.update(ascasTable).set(updatePayload).where(eq(ascasTable.id, id)).returning();
    return res.json({ asca });
  } catch (err) {
    return handleError3(err, res);
  }
}
async function publishAscaHandler(req, res) {
  try {
    const id = Number(req.params.id);
    if (!Number.isFinite(id) || id <= 0) {
      return res.status(400).json({ message: "Invalid ASCA id." });
    }
    const asca = await publishAsca(id, { organizationId: null });
    return res.json({ asca });
  } catch (err) {
    if (err instanceof Error) {
      return res.status(400).json({ message: err.message });
    }
    return handleError3(err, res);
  }
}
async function unpublishAscaHandler(req, res) {
  try {
    const id = Number(req.params.id);
    if (!Number.isFinite(id) || id <= 0) {
      return res.status(400).json({ message: "Invalid ASCA id." });
    }
    const asca = await unpublishAsca(id, { organizationId: null });
    return res.json({ asca });
  } catch (err) {
    if (err instanceof Error) {
      return res.status(400).json({ message: err.message });
    }
    return handleError3(err, res);
  }
}
async function cancelAscaHandler(req, res) {
  try {
    const id = Number(req.params.id);
    if (!Number.isFinite(id) || id <= 0) {
      return res.status(400).json({ message: "Invalid ASCA id." });
    }
    const admin = req.admin;
    await cancelAsca(id, admin.id);
    return res.json({ ok: true });
  } catch (err) {
    if (err instanceof Error) {
      return res.status(400).json({ message: err.message });
    }
    return handleError3(err, res);
  }
}
async function createAscaHandler(req, res) {
  try {
    const admin = req.admin;
    const parsed = CreateAscaSchema.safeParse(req.body);
    if (!parsed.success) {
      return res.status(400).json({ errors: parsed.error.flatten() });
    }
    const asca = await createAsca(parsed.data, admin.id, {
      organizationId: null
    });
    return res.status(201).json({ asca });
  } catch (err) {
    if (err instanceof Error) {
      return res.status(400).json({ message: err.message });
    }
    return handleError3(err, res);
  }
}
async function moveAscaToWwnHandler(req, res) {
  try {
    const id = Number(req.params.id);
    if (!Number.isFinite(id) || id <= 0) {
      return res.status(400).json({ message: "Invalid ASCA id." });
    }
    const [asca] = await db.select({
      id: ascasTable.id,
      organizationId: ascasTable.organizationId,
      currentAmount: ascasTable.currentAmount
    }).from(ascasTable).where(eq(ascasTable.id, id));
    if (!asca) return res.status(404).json({ message: "ASCA not found." });
    if (asca.organizationId == null) {
      return res.status(400).json({ message: "ASCA is already WWN-scoped." });
    }
    const currentAmount = Number(String(asca.currentAmount ?? "0"));
    if (Number.isFinite(currentAmount) && currentAmount > 0) {
      return res.status(400).json({
        message: "Cannot move ASCA to WWN after funds have been contributed."
      });
    }
    const [memberCount] = await db.select({ count: sql`count(*)::int` }).from(ascaMembersTable).where(eq(ascaMembersTable.ascaId, id));
    if (Number(memberCount?.count ?? 0) > 0) {
      return res.status(400).json({
        message: "Cannot move ASCA to WWN after members have joined."
      });
    }
    const [contributionCount] = await db.select({ count: sql`count(*)::int` }).from(ascaContributionsTable).where(eq(ascaContributionsTable.ascaId, id));
    if (Number(contributionCount?.count ?? 0) > 0) {
      return res.status(400).json({
        message: "Cannot move ASCA to WWN after contributions exist."
      });
    }
    const [updated] = await db.update(ascasTable).set({ organizationId: null }).where(eq(ascasTable.id, id)).returning();
    return res.json({ asca: updated });
  } catch (err) {
    return handleError3(err, res);
  }
}
async function investAscaHandler(req, res) {
  try {
    const id = Number(req.params.id);
    if (!Number.isFinite(id) || id <= 0) {
      return res.status(400).json({ message: "Invalid ASCA id." });
    }
    const bodySchema = external_exports.object({
      investmentId: external_exports.number().int().positive().optional()
    }).strict();
    const parsed = bodySchema.safeParse(req.body);
    if (!parsed.success) {
      return res.status(400).json({ errors: parsed.error.flatten() });
    }
    const [asca] = await db.select().from(ascasTable).where(eq(ascasTable.id, id));
    if (!asca) return res.status(404).json({ message: "ASCA not found." });
    const admin = req.admin;
    const investmentId = parsed.data.investmentId ?? asca.investmentId ?? void 0;
    if (!investmentId) {
      return res.status(400).json({ message: "investmentId is required for this ASCA." });
    }
    await convertAscaToInvestment(id, investmentId, admin.id);
    const [updated] = await db.select().from(ascasTable).where(eq(ascasTable.id, id));
    if (!updated) return res.status(404).json({ message: "ASCA not found." });
    return res.json({ asca: updated });
  } catch (err) {
    if (err instanceof Error) {
      return res.status(400).json({ message: err.message });
    }
    return handleError3(err, res);
  }
}
async function withdrawAscaHandler(req, res) {
  try {
    const id = Number(req.params.id);
    if (!Number.isFinite(id) || id <= 0) {
      return res.status(400).json({ message: "Invalid ASCA id." });
    }
    await withdrawAsca(id, 0);
    return res.json({ message: "ASCA withdrawn successfully" });
  } catch (err) {
    if (err instanceof Error) {
      return res.status(400).json({ message: err.message });
    }
    return handleError3(err, res);
  }
}
async function withdrawAscaOfflineHandler(req, res) {
  try {
    const id = Number(req.params.id);
    if (!Number.isFinite(id) || id <= 0) {
      return res.status(400).json({ message: "Invalid ASCA id." });
    }
    await withdrawAscaOffline(id, 0);
    return res.json({ message: "ASCA withdrawn offline successfully" });
  } catch (err) {
    if (err instanceof Error) {
      return res.status(400).json({ message: err.message });
    }
    return handleError3(err, res);
  }
}
async function deleteAscaHandler(req, res) {
  try {
    const id = Number(req.params.id);
    if (!Number.isFinite(id) || id <= 0) {
      return res.status(400).json({ message: "Invalid ASCA id." });
    }
    const admin = req.admin;
    await deleteAscaGroup({ ascaId: id, triggerUserId: admin.id });
    return res.json({ ok: true });
  } catch (err) {
    if (err instanceof Error) {
      return res.status(400).json({ message: err.message });
    }
    return handleError3(err, res);
  }
}
async function closeAscaHandler(req, res) {
  try {
    const id = Number(req.params.id);
    if (!Number.isFinite(id) || id <= 0) {
      return res.status(400).json({ message: "Invalid ASCA id." });
    }
    const asca = await closeAsca(id);
    return res.json({ asca });
  } catch (err) {
    if (err instanceof Error) {
      return res.status(400).json({ message: err.message });
    }
    return handleError3(err, res);
  }
}
var import_express4, router4, admin_asca_default;
var init_admin_asca = __esm({
  "src/routes/admin-asca.ts"() {
    "use strict";
    import_express4 = __toESM(require_express2(), 1);
    init_zod();
    init_src2();
    init_schema2();
    init_drizzle_orm();
    init_logger();
    init_auth_session();
    init_asca();
    router4 = (0, import_express4.Router)();
    router4.use(requireAdmin2);
    router4.get("/asca/ascas", listAscas);
    router4.post("/asca/ascas", createAscaHandler);
    router4.get("/asca/ascas/:id", getAscaDetails);
    router4.patch("/asca/ascas/:id", updateAsca);
    router4.post("/asca/ascas/:id/move-to-wwn", moveAscaToWwnHandler);
    router4.post("/asca/ascas/:id/publish", publishAscaHandler);
    router4.post("/asca/ascas/:id/unpublish", unpublishAscaHandler);
    router4.post("/asca/ascas/:id/cancel", cancelAscaHandler);
    router4.post("/asca/ascas/:id/withdraw", withdrawAscaHandler);
    router4.post("/asca/ascas/:id/withdraw-offline", withdrawAscaOfflineHandler);
    router4.post("/asca/ascas/:id/invest", investAscaHandler);
    router4.post("/asca/ascas/:id/archive", closeAscaHandler);
    router4.delete("/asca/ascas/:id", deleteAscaHandler);
    router4.get("/ascas", listAscas);
    router4.post("/ascas", createAscaHandler);
    router4.get("/ascas/:id", getAscaDetails);
    router4.patch("/ascas/:id", updateAsca);
    router4.post("/ascas/:id/move-to-wwn", moveAscaToWwnHandler);
    router4.post("/ascas/:id/publish", publishAscaHandler);
    router4.post("/ascas/:id/unpublish", unpublishAscaHandler);
    router4.post("/ascas/:id/cancel", cancelAscaHandler);
    router4.post("/ascas/:id/withdraw", withdrawAscaHandler);
    router4.post("/ascas/:id/withdraw-offline", withdrawAscaOfflineHandler);
    router4.post("/ascas/:id/invest", investAscaHandler);
    router4.post("/ascas/:id/archive", closeAscaHandler);
    router4.delete("/ascas/:id", deleteAscaHandler);
    admin_asca_default = router4;
  }
});

// src/lib/organization-authorization.ts
function authError(message, statusCode = 403, layer = "role_check") {
  return new OrganizationTenantAccessError(message, statusCode, layer);
}
async function requireOrganizationAuthorization(userId, options) {
  const context = await requireOrganizationTenantAccess(userId, options);
  const [user] = await db.select().from(usersTable).where(eq(usersTable.id, userId)).limit(1);
  if (!user) {
    throw authError(
      "Organization tenant access is available only to organization members.",
      401,
      "state_check"
    );
  }
  if (!isUserProfileComplete(user)) {
    throw authError(
      "Complete your profile before accessing organization features.",
      403,
      "state_check"
    );
  }
  const onboardingState = await getActiveOnboardingStateForUserRow(user);
  if (onboardingState.required && !onboardingState.completed) {
    throw authError(
      "Complete onboarding before accessing organization features.",
      403,
      "state_check"
    );
  }
  return context;
}
function assertOrganizationRecordScope(context, recordOrganizationId, notFoundMessage = "Record not found.") {
  if (recordOrganizationId !== context.organization.id) {
    throw authError(notFoundMessage, 404, "record_scope_check");
  }
}
function assertOrganizationRoleTransition(input) {
  if (input.actorRole === "OWNER") {
    return;
  }
  if (input.actorRole !== "ADMIN") {
    throw authError(input.insufficientMessage, 403, "role_check");
  }
  if (input.targetRole === "OWNER" || input.nextRole === "OWNER") {
    throw authError(
      input.authorityOnlyMessage ?? input.insufficientMessage,
      403,
      "role_check"
    );
  }
}
function assertOrganizationOwnerAction(actorRole, message) {
  if (actorRole !== "OWNER") {
    throw authError(message, 403, "role_check");
  }
}
function assertOrganizationNotSelfTarget(actorUserId, targetUserId, message) {
  if (actorUserId === targetUserId) {
    throw authError(message, 409, "role_check");
  }
}
function assertOrganizationOwnerFloor(ownerCount, message) {
  if (ownerCount <= 1) {
    throw authError(message, 409, "role_check");
  }
}
async function requireScopedOrganizationMember(context, memberId) {
  const [member] = await db.select({
    id: organizationMembersTable.id,
    organizationId: organizationMembersTable.organizationId,
    userId: organizationMembersTable.userId,
    role: organizationMembersTable.role,
    membershipStatus: organizationMembersTable.status,
    email: usersTable.email,
    firstName: usersTable.firstName,
    lastName: usersTable.lastName,
    isEmailVerified: usersTable.isEmailVerified,
    createdAt: usersTable.createdAt,
    joinedAt: organizationMembersTable.joinedAt
  }).from(organizationMembersTable).innerJoin(usersTable, eq(organizationMembersTable.userId, usersTable.id)).where(eq(organizationMembersTable.id, memberId));
  if (!member) {
    throw authError("Organization member not found.", 404, "record_scope_check");
  }
  assertOrganizationRecordScope(
    context,
    member.organizationId,
    "Organization member not found."
  );
  return member;
}
async function requireScopedOrganizationInvitation(context, invitationId, options) {
  const [invitation] = await db.select({
    id: organizationInvitationsTable.id,
    organizationId: organizationInvitationsTable.organizationId,
    email: organizationInvitationsTable.email,
    firstName: organizationInvitationsTable.firstName,
    lastName: organizationInvitationsTable.lastName,
    role: organizationInvitationsTable.role,
    status: organizationInvitationsTable.status,
    expiresAt: organizationInvitationsTable.expiresAt,
    createdAt: organizationInvitationsTable.createdAt
  }).from(organizationInvitationsTable).where(eq(organizationInvitationsTable.id, invitationId));
  if (!invitation) {
    throw authError("Invitation not found.", 404, "record_scope_check");
  }
  assertOrganizationRecordScope(context, invitation.organizationId, "Invitation not found.");
  if (options?.pendingOnly && invitation.status !== "PENDING") {
    throw authError("Invitation not found.", 404, "record_scope_check");
  }
  return invitation;
}
async function countOrganizationOwners(organizationId, options) {
  const conditions = [
    eq(organizationMembersTable.organizationId, organizationId),
    eq(organizationMembersTable.role, "OWNER")
  ];
  if (options?.activeOnly) {
    conditions.push(eq(organizationMembersTable.status, "ACTIVE"));
  }
  const rows = await db.select({ id: organizationMembersTable.id }).from(organizationMembersTable).where(and(...conditions));
  return rows.length;
}
var init_organization_authorization = __esm({
  "src/lib/organization-authorization.ts"() {
    "use strict";
    init_src2();
    init_schema2();
    init_drizzle_orm();
    init_organization_context();
    init_member_onboarding_program();
    init_profile();
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/crypto/CryptoProvider.js
var CryptoProvider, CryptoProviderOnlySupportsAsyncError;
var init_CryptoProvider = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/crypto/CryptoProvider.js"() {
    CryptoProvider = class {
      /**
       * Computes a SHA-256 HMAC given a secret and a payload (encoded in UTF-8).
       * The output HMAC should be encoded in hexadecimal.
       *
       * Sample values for implementations:
       * - computeHMACSignature('', 'test_secret') => 'f7f9bd47fb987337b5796fdc1fdb9ba221d0d5396814bfcaf9521f43fd8927fd'
       * - computeHMACSignature('\ud83d\ude00', 'test_secret') => '837da296d05c4fe31f61d5d7ead035099d9585a5bcde87de952012a78f0b0c43
       */
      computeHMACSignature(payload, secret) {
        throw new Error("computeHMACSignature not implemented.");
      }
      /**
       * Asynchronous version of `computeHMACSignature`. Some implementations may
       * only allow support async signature computation.
       *
       * Computes a SHA-256 HMAC given a secret and a payload (encoded in UTF-8).
       * The output HMAC should be encoded in hexadecimal.
       *
       * Sample values for implementations:
       * - computeHMACSignature('', 'test_secret') => 'f7f9bd47fb987337b5796fdc1fdb9ba221d0d5396814bfcaf9521f43fd8927fd'
       * - computeHMACSignature('\ud83d\ude00', 'test_secret') => '837da296d05c4fe31f61d5d7ead035099d9585a5bcde87de952012a78f0b0c43
       */
      computeHMACSignatureAsync(payload, secret) {
        throw new Error("computeHMACSignatureAsync not implemented.");
      }
      /**
       * Computes a SHA-256 hash of the data.
       */
      computeSHA256Async(data) {
        throw new Error("computeSHA256 not implemented.");
      }
    };
    CryptoProviderOnlySupportsAsyncError = class extends Error {
    };
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/crypto/NodeCryptoProvider.js
import * as crypto2 from "crypto";
var NodeCryptoProvider;
var init_NodeCryptoProvider = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/crypto/NodeCryptoProvider.js"() {
    init_CryptoProvider();
    NodeCryptoProvider = class extends CryptoProvider {
      /** @override */
      computeHMACSignature(payload, secret) {
        return crypto2.createHmac("sha256", secret).update(payload, "utf8").digest("hex");
      }
      /** @override */
      async computeHMACSignatureAsync(payload, secret) {
        const signature = await this.computeHMACSignature(payload, secret);
        return signature;
      }
      /** @override */
      async computeSHA256Async(data) {
        return new Uint8Array(await crypto2.createHash("sha256").update(data).digest());
      }
    };
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/net/HttpClient.js
var HttpClient, HttpClientResponse;
var init_HttpClient = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/net/HttpClient.js"() {
    HttpClient = class _HttpClient {
      /** The client name used for diagnostics. */
      getClientName() {
        throw new Error("getClientName not implemented.");
      }
      makeRequest(host, port2, path4, method, headers, requestData, protocol, timeout) {
        throw new Error("makeRequest not implemented.");
      }
      /** Helper to make a consistent timeout error across implementations. */
      static makeTimeoutError() {
        const timeoutErr = new TypeError(_HttpClient.TIMEOUT_ERROR_CODE);
        timeoutErr.code = _HttpClient.TIMEOUT_ERROR_CODE;
        return timeoutErr;
      }
    };
    HttpClient.CONNECTION_CLOSED_ERROR_CODES = ["ECONNRESET", "EPIPE"];
    HttpClient.TIMEOUT_ERROR_CODE = "ETIMEDOUT";
    HttpClientResponse = class {
      constructor(statusCode, headers) {
        this._statusCode = statusCode;
        this._headers = headers;
      }
      getStatusCode() {
        return this._statusCode;
      }
      getHeaders() {
        return this._headers;
      }
      getRawResponse() {
        throw new Error("getRawResponse not implemented.");
      }
      toStream(streamCompleteCallback) {
        throw new Error("toStream not implemented.");
      }
      toJSON() {
        throw new Error("toJSON not implemented.");
      }
    };
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/net/NodeHttpClient.js
import * as http_ from "http";
import * as https_ from "https";
var http, https, defaultHttpAgent, defaultHttpsAgent, NodeHttpClient, NodeHttpClientResponse;
var init_NodeHttpClient = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/net/NodeHttpClient.js"() {
    init_HttpClient();
    http = http_.default || http_;
    https = https_.default || https_;
    defaultHttpAgent = new http.Agent({ keepAlive: true });
    defaultHttpsAgent = new https.Agent({ keepAlive: true });
    NodeHttpClient = class extends HttpClient {
      constructor(agent) {
        super();
        this._agent = agent;
      }
      /** @override. */
      getClientName() {
        return "node";
      }
      makeRequest(host, port2, path4, method, headers, requestData, protocol, timeout) {
        const isInsecureConnection = protocol === "http";
        let agent = this._agent;
        if (!agent) {
          agent = isInsecureConnection ? defaultHttpAgent : defaultHttpsAgent;
        }
        const requestPromise = new Promise((resolve, reject) => {
          const req = (isInsecureConnection ? http : https).request({
            host,
            port: port2,
            path: path4,
            method,
            agent,
            headers,
            ciphers: "DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2:!MD5"
          });
          req.setTimeout(timeout, () => {
            req.destroy(HttpClient.makeTimeoutError());
          });
          req.on("response", (res) => {
            resolve(new NodeHttpClientResponse(res));
          });
          req.on("error", (error40) => {
            reject(error40);
          });
          req.once("socket", (socket) => {
            if (socket.connecting) {
              socket.once(isInsecureConnection ? "connect" : "secureConnect", () => {
                req.write(requestData);
                req.end();
              });
            } else {
              req.write(requestData);
              req.end();
            }
          });
        });
        return requestPromise;
      }
    };
    NodeHttpClientResponse = class extends HttpClientResponse {
      constructor(res) {
        super(res.statusCode, res.headers || {});
        this._res = res;
      }
      getRawResponse() {
        return this._res;
      }
      toStream(streamCompleteCallback) {
        this._res.once("end", () => streamCompleteCallback());
        return this._res;
      }
      toJSON() {
        return new Promise((resolve, reject) => {
          let response = "";
          this._res.setEncoding("utf8");
          this._res.on("data", (chunk2) => {
            response += chunk2;
          });
          this._res.once("end", () => {
            try {
              resolve(JSON.parse(response));
            } catch (e) {
              reject(e);
            }
          });
        });
      }
    };
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/utils.js
function isOptionsHash(o) {
  return o && typeof o === "object" && OPTIONS_KEYS.some((prop) => Object.prototype.hasOwnProperty.call(o, prop));
}
function queryStringifyRequestData(data, _apiMode) {
  return stringifyRequestData(data);
}
function encodeQueryValue(value) {
  return encodeURIComponent(value).replace(/!/g, "%21").replace(/\*/g, "%2A").replace(/\(/g, "%28").replace(/\)/g, "%29").replace(/'/g, "%27").replace(/%5B/g, "[").replace(/%5D/g, "]");
}
function valueToString(value) {
  if (value instanceof Date) {
    return Math.floor(value.getTime() / 1e3).toString();
  }
  if (value === null) {
    return "";
  }
  return String(value);
}
function stringifyRequestData(data) {
  const pairs = [];
  function encode(key, value) {
    if (value === void 0) {
      return;
    }
    if (value === null || typeof value !== "object" || value instanceof Date) {
      pairs.push(encodeQueryValue(key) + "=" + encodeQueryValue(valueToString(value)));
      return;
    }
    if (Array.isArray(value)) {
      for (let i = 0; i < value.length; i++) {
        if (value[i] !== void 0) {
          encode(key + "[" + i + "]", value[i]);
        }
      }
      return;
    }
    for (const k of Object.keys(value)) {
      encode(key + "[" + k + "]", value[k]);
    }
  }
  if (typeof data === "object" && data !== null) {
    for (const key of Object.keys(data)) {
      encode(key, data[key]);
    }
  }
  return pairs.join("&");
}
function isValidEncodeUriComponentType(value) {
  return ["number", "string", "boolean"].includes(typeof value);
}
function extractUrlParams(path4) {
  const params = path4.match(/\{\w+\}/g);
  if (!params) {
    return [];
  }
  return params.map((param) => param.replace(/[{}]/g, ""));
}
function getDataFromArgs(args) {
  if (!Array.isArray(args) || !args[0] || typeof args[0] !== "object") {
    return {};
  }
  if (!isOptionsHash(args[0])) {
    return args.shift();
  }
  const argKeys = Object.keys(args[0]);
  const optionKeysInArgs = argKeys.filter((key) => OPTIONS_KEYS.includes(key));
  if (optionKeysInArgs.length > 0 && optionKeysInArgs.length !== argKeys.length) {
    emitWarning(`Options found in arguments (${optionKeysInArgs.join(", ")}). Did you mean to pass an options object? See https://github.com/stripe/stripe-node/wiki/Passing-Options.`);
  }
  return {};
}
function getOptionsFromArgs(args) {
  const opts = {
    host: null,
    headers: {},
    settings: {},
    streaming: false
  };
  if (args.length > 0) {
    const arg = args[args.length - 1];
    if (typeof arg === "string") {
      opts.authenticator = createApiKeyAuthenticator(args.pop());
    } else if (isOptionsHash(arg)) {
      const params = Object.assign({}, args.pop());
      const extraKeys = Object.keys(params).filter((key) => !OPTIONS_KEYS.includes(key));
      if (extraKeys.length) {
        emitWarning(`Invalid options found (${extraKeys.join(", ")}); ignoring.`);
      }
      if (params.apiKey) {
        opts.authenticator = createApiKeyAuthenticator(params.apiKey);
      }
      if (params.idempotencyKey) {
        opts.headers["Idempotency-Key"] = params.idempotencyKey;
      }
      if (params.stripeAccount) {
        opts.headers["Stripe-Account"] = params.stripeAccount;
      }
      if (params.stripeContext) {
        if (opts.headers["Stripe-Account"]) {
          throw new Error("Can't specify both stripeAccount and stripeContext.");
        }
        opts.headers["Stripe-Context"] = params.stripeContext;
      }
      if (params.apiVersion) {
        opts.headers["Stripe-Version"] = params.apiVersion;
      }
      if (Number.isInteger(params.maxNetworkRetries)) {
        opts.settings.maxNetworkRetries = params.maxNetworkRetries;
      }
      if (Number.isInteger(params.timeout)) {
        opts.settings.timeout = params.timeout;
      }
      if (params.host) {
        opts.host = params.host;
      }
      if (params.authenticator) {
        if (params.apiKey) {
          throw new Error("Can't specify both apiKey and authenticator.");
        }
        if (typeof params.authenticator !== "function") {
          throw new Error("The authenticator must be a function receiving a request as the first parameter.");
        }
        opts.authenticator = params.authenticator;
      }
      if (params.headers) {
        Object.assign(opts.headers, params.headers);
      }
      if (params.additionalHeaders) {
        Object.assign(opts.headers, params.additionalHeaders);
      }
      if (params.streaming) {
        opts.streaming = true;
      }
    }
  }
  return opts;
}
function protoExtend(sub) {
  const Super = this;
  const Constructor = Object.prototype.hasOwnProperty.call(sub, "constructor") ? sub.constructor : function(...args) {
    Super.apply(this, args);
  };
  Object.assign(Constructor, Super);
  Constructor.prototype = Object.create(Super.prototype);
  Object.assign(Constructor.prototype, sub);
  return Constructor;
}
function removeNullish(obj) {
  if (typeof obj !== "object") {
    throw new Error("Argument must be an object");
  }
  return Object.keys(obj).reduce((result, key) => {
    if (obj[key] != null) {
      result[key] = obj[key];
    }
    return result;
  }, {});
}
function normalizeHeaders(obj) {
  if (!(obj && typeof obj === "object")) {
    return obj;
  }
  return Object.keys(obj).reduce((result, header) => {
    result[normalizeHeader(header)] = obj[header];
    return result;
  }, {});
}
function normalizeHeader(header) {
  return header.split("-").map((text2) => text2.charAt(0).toUpperCase() + text2.substr(1).toLowerCase()).join("-");
}
function callbackifyPromiseWithTimeout(promise2, callback) {
  if (callback) {
    return promise2.then((res) => {
      setTimeout(() => {
        callback(null, res);
      }, 0);
    }, (err) => {
      setTimeout(() => {
        callback(err, null);
      }, 0);
    });
  }
  return promise2;
}
function pascalToCamelCase(name) {
  if (name === "OAuth") {
    return "oauth";
  } else {
    return name[0].toLowerCase() + name.substring(1);
  }
}
function emitWarning(warning) {
  if (typeof process.emitWarning !== "function") {
    return console.warn(`Stripe: ${warning}`);
  }
  return process.emitWarning(warning, "Stripe");
}
function isObject2(obj) {
  const type = typeof obj;
  return (type === "function" || type === "object") && !!obj;
}
function flattenAndStringify(data) {
  const result = {};
  const step = (obj, prevKey) => {
    Object.entries(obj).forEach(([key, value]) => {
      const newKey = prevKey ? `${prevKey}[${key}]` : key;
      if (isObject2(value)) {
        if (!(value instanceof Uint8Array) && !Object.prototype.hasOwnProperty.call(value, "data")) {
          return step(value, newKey);
        } else {
          result[newKey] = value;
        }
      } else {
        result[newKey] = String(value);
      }
    });
  };
  step(data, null);
  return result;
}
function validateInteger(name, n, defaultVal) {
  if (!Number.isInteger(n)) {
    if (defaultVal !== void 0) {
      return defaultVal;
    } else {
      throw new Error(`${name} must be an integer`);
    }
  }
  return n;
}
function determineProcessUserAgentProperties() {
  return typeof process === "undefined" ? {} : {
    lang_version: process.version,
    platform: process.platform
  };
}
function detectAIAgent(env) {
  for (const [envVar, agentName] of AI_AGENTS) {
    if (env[envVar]) {
      return agentName;
    }
  }
  return "";
}
function createApiKeyAuthenticator(apiKey) {
  const authenticator = (request) => {
    request.headers.Authorization = "Bearer " + apiKey;
    return Promise.resolve();
  };
  authenticator._apiKey = apiKey;
  return authenticator;
}
function concat(arrays) {
  const totalLength = arrays.reduce((len, array2) => len + array2.length, 0);
  const merged = new Uint8Array(totalLength);
  let offset = 0;
  arrays.forEach((array2) => {
    merged.set(array2, offset);
    offset += array2.length;
  });
  return merged;
}
function dateTimeReplacer(key, value) {
  if (this[key] instanceof Date) {
    return Math.floor(this[key].getTime() / 1e3).toString();
  }
  return value;
}
function jsonStringifyRequestData(data) {
  return JSON.stringify(data, dateTimeReplacer);
}
function getAPIMode(path4) {
  if (!path4) {
    return "v1";
  }
  return path4.startsWith("/v2") ? "v2" : "v1";
}
function parseHttpHeaderAsString(header) {
  if (Array.isArray(header)) {
    return header.join(", ");
  }
  return String(header);
}
function parseHttpHeaderAsNumber(header) {
  const number4 = Array.isArray(header) ? header[0] : header;
  return Number(number4);
}
function parseHeadersForFetch(headers) {
  return Object.entries(headers).map(([key, value]) => {
    return [key, parseHttpHeaderAsString(value)];
  });
}
var OPTIONS_KEYS, makeURLInterpolator, AI_AGENTS;
var init_utils5 = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/utils.js"() {
    OPTIONS_KEYS = [
      "apiKey",
      "idempotencyKey",
      "stripeAccount",
      "apiVersion",
      "maxNetworkRetries",
      "timeout",
      "host",
      "authenticator",
      "stripeContext",
      "headers",
      "additionalHeaders",
      "streaming"
    ];
    makeURLInterpolator = /* @__PURE__ */ (() => {
      const rc = {
        "\n": "\\n",
        '"': '\\"',
        "\u2028": "\\u2028",
        "\u2029": "\\u2029"
      };
      return (str) => {
        const cleanString = str.replace(/["\n\r\u2028\u2029]/g, ($0) => rc[$0]);
        return (outputs) => {
          return cleanString.replace(/\{([\s\S]+?)\}/g, ($0, $1) => {
            const output = outputs[$1];
            if (isValidEncodeUriComponentType(output))
              return encodeURIComponent(output);
            return "";
          });
        };
      };
    })();
    AI_AGENTS = [
      // The beginning of the section generated from our OpenAPI spec
      ["ANTIGRAVITY_CLI_ALIAS", "antigravity"],
      ["CLAUDECODE", "claude_code"],
      ["CLINE_ACTIVE", "cline"],
      ["CODEX_SANDBOX", "codex_cli"],
      ["CODEX_THREAD_ID", "codex_cli"],
      ["CODEX_SANDBOX_NETWORK_DISABLED", "codex_cli"],
      ["CODEX_CI", "codex_cli"],
      ["CURSOR_AGENT", "cursor"],
      ["GEMINI_CLI", "gemini_cli"],
      ["OPENCODE", "open_code"]
      // The end of the section generated from our OpenAPI spec
    ];
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/net/FetchHttpClient.js
var FetchHttpClient, FetchHttpClientResponse;
var init_FetchHttpClient = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/net/FetchHttpClient.js"() {
    init_utils5();
    init_HttpClient();
    FetchHttpClient = class _FetchHttpClient extends HttpClient {
      constructor(fetchFn) {
        super();
        if (!fetchFn) {
          if (!globalThis.fetch) {
            throw new Error("fetch() function not provided and is not defined in the global scope. You must provide a fetch implementation.");
          }
          fetchFn = globalThis.fetch;
        }
        if (globalThis.AbortController) {
          this._fetchFn = _FetchHttpClient.makeFetchWithAbortTimeout(fetchFn);
        } else {
          this._fetchFn = _FetchHttpClient.makeFetchWithRaceTimeout(fetchFn);
        }
      }
      static makeFetchWithRaceTimeout(fetchFn) {
        return (url2, init, timeout) => {
          let pendingTimeoutId;
          const timeoutPromise = new Promise((_, reject) => {
            pendingTimeoutId = setTimeout(() => {
              pendingTimeoutId = null;
              reject(HttpClient.makeTimeoutError());
            }, timeout);
          });
          const fetchPromise = fetchFn(url2, init);
          return Promise.race([fetchPromise, timeoutPromise]).finally(() => {
            if (pendingTimeoutId) {
              clearTimeout(pendingTimeoutId);
            }
          });
        };
      }
      static makeFetchWithAbortTimeout(fetchFn) {
        return async (url2, init, timeout) => {
          const abort = new AbortController();
          let timeoutId = setTimeout(() => {
            timeoutId = null;
            abort.abort(HttpClient.makeTimeoutError());
          }, timeout);
          try {
            return await fetchFn(url2, Object.assign(Object.assign({}, init), { signal: abort.signal }));
          } catch (err) {
            if (err.name === "AbortError") {
              throw HttpClient.makeTimeoutError();
            } else {
              throw err;
            }
          } finally {
            if (timeoutId) {
              clearTimeout(timeoutId);
            }
          }
        };
      }
      /** @override. */
      getClientName() {
        return "fetch";
      }
      async makeRequest(host, port2, path4, method, headers, requestData, protocol, timeout) {
        const isInsecureConnection = protocol === "http";
        const url2 = new URL(path4, `${isInsecureConnection ? "http" : "https"}://${host}`);
        url2.port = port2;
        const methodHasPayload = method == "POST" || method == "PUT" || method == "PATCH";
        const body = requestData || (methodHasPayload ? "" : void 0);
        const res = await this._fetchFn(url2.toString(), {
          method,
          headers: parseHeadersForFetch(headers),
          body
        }, timeout);
        return new FetchHttpClientResponse(res);
      }
    };
    FetchHttpClientResponse = class _FetchHttpClientResponse extends HttpClientResponse {
      constructor(res) {
        super(res.status, _FetchHttpClientResponse._transformHeadersToObject(res.headers));
        this._res = res;
      }
      getRawResponse() {
        return this._res;
      }
      toStream(streamCompleteCallback) {
        streamCompleteCallback();
        return this._res.body;
      }
      toJSON() {
        return this._res.json();
      }
      static _transformHeadersToObject(headers) {
        const headersObj = {};
        for (const entry of headers) {
          if (!Array.isArray(entry) || entry.length != 2) {
            throw new Error("Response objects produced by the fetch function given to FetchHttpClient do not have an iterable headers map. Response#headers should be an iterable object.");
          }
          headersObj[entry[0]] = entry[1];
        }
        return headersObj;
      }
    };
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/crypto/SubtleCryptoProvider.js
var SubtleCryptoProvider, byteHexMapping;
var init_SubtleCryptoProvider = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/crypto/SubtleCryptoProvider.js"() {
    init_CryptoProvider();
    SubtleCryptoProvider = class extends CryptoProvider {
      constructor(subtleCrypto) {
        super();
        this.subtleCrypto = subtleCrypto || crypto.subtle;
      }
      /** @override */
      computeHMACSignature(payload, secret) {
        throw new CryptoProviderOnlySupportsAsyncError("SubtleCryptoProvider cannot be used in a synchronous context.");
      }
      /** @override */
      async computeHMACSignatureAsync(payload, secret) {
        const encoder = new TextEncoder();
        const key = await this.subtleCrypto.importKey("raw", encoder.encode(secret), {
          name: "HMAC",
          hash: { name: "SHA-256" }
        }, false, ["sign"]);
        const signatureBuffer = await this.subtleCrypto.sign("hmac", key, encoder.encode(payload));
        const signatureBytes = new Uint8Array(signatureBuffer);
        const signatureHexCodes = new Array(signatureBytes.length);
        for (let i = 0; i < signatureBytes.length; i++) {
          signatureHexCodes[i] = byteHexMapping[signatureBytes[i]];
        }
        return signatureHexCodes.join("");
      }
      /** @override */
      async computeSHA256Async(data) {
        return new Uint8Array(await this.subtleCrypto.digest("SHA-256", data));
      }
    };
    byteHexMapping = new Array(256);
    for (let i = 0; i < byteHexMapping.length; i++) {
      byteHexMapping[i] = i.toString(16).padStart(2, "0");
    }
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/platform/PlatformFunctions.js
var PlatformFunctions;
var init_PlatformFunctions = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/platform/PlatformFunctions.js"() {
    init_FetchHttpClient();
    init_SubtleCryptoProvider();
    PlatformFunctions = class {
      constructor() {
        this._fetchFn = null;
        this._agent = null;
      }
      /**
       * Gets uname with Node's built-in `exec` function, if available.
       */
      getUname() {
        throw new Error("getUname not implemented.");
      }
      /**
       * Generates a v4 UUID. See https://stackoverflow.com/a/2117523
       */
      uuid4() {
        return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
          const r = Math.random() * 16 | 0;
          const v = c === "x" ? r : r & 3 | 8;
          return v.toString(16);
        });
      }
      /**
       * Compares strings in constant time.
       */
      secureCompare(a, b) {
        if (a.length !== b.length) {
          return false;
        }
        const len = a.length;
        let result = 0;
        for (let i = 0; i < len; ++i) {
          result |= a.charCodeAt(i) ^ b.charCodeAt(i);
        }
        return result === 0;
      }
      /**
       * Creates an event emitter.
       */
      createEmitter() {
        throw new Error("createEmitter not implemented.");
      }
      /**
       * Checks if the request data is a stream. If so, read the entire stream
       * to a buffer and return the buffer.
       */
      tryBufferData(data) {
        throw new Error("tryBufferData not implemented.");
      }
      /**
       * Creates an HTTP client which uses the Node `http` and `https` packages
       * to issue requests.
       */
      createNodeHttpClient(agent) {
        throw new Error("createNodeHttpClient not implemented.");
      }
      /**
       * Creates an HTTP client for issuing Stripe API requests which uses the Web
       * Fetch API.
       *
       * A fetch function can optionally be passed in as a parameter. If none is
       * passed, will default to the default `fetch` function in the global scope.
       */
      createFetchHttpClient(fetchFn) {
        return new FetchHttpClient(fetchFn);
      }
      /**
       * Creates an HTTP client using runtime-specific APIs.
       */
      createDefaultHttpClient() {
        throw new Error("createDefaultHttpClient not implemented.");
      }
      /**
       * Creates a CryptoProvider which uses the Node `crypto` package for its computations.
       */
      createNodeCryptoProvider() {
        throw new Error("createNodeCryptoProvider not implemented.");
      }
      /**
       * Creates a CryptoProvider which uses the SubtleCrypto interface of the Web Crypto API.
       */
      createSubtleCryptoProvider(subtleCrypto) {
        return new SubtleCryptoProvider(subtleCrypto);
      }
      createDefaultCryptoProvider() {
        throw new Error("createDefaultCryptoProvider not implemented.");
      }
    };
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/Error.js
var Error_exports = {};
__export(Error_exports, {
  StripeAPIError: () => StripeAPIError,
  StripeAuthenticationError: () => StripeAuthenticationError,
  StripeCardError: () => StripeCardError,
  StripeConnectionError: () => StripeConnectionError,
  StripeError: () => StripeError,
  StripeIdempotencyError: () => StripeIdempotencyError,
  StripeInvalidGrantError: () => StripeInvalidGrantError,
  StripeInvalidRequestError: () => StripeInvalidRequestError,
  StripePermissionError: () => StripePermissionError,
  StripeRateLimitError: () => StripeRateLimitError,
  StripeSignatureVerificationError: () => StripeSignatureVerificationError,
  StripeUnknownError: () => StripeUnknownError,
  TemporarySessionExpiredError: () => TemporarySessionExpiredError,
  generateV1Error: () => generateV1Error,
  generateV2Error: () => generateV2Error
});
var generateV1Error, generateV2Error, StripeError, StripeCardError, StripeInvalidRequestError, StripeAPIError, StripeAuthenticationError, StripePermissionError, StripeRateLimitError, StripeConnectionError, StripeSignatureVerificationError, StripeIdempotencyError, StripeInvalidGrantError, StripeUnknownError, TemporarySessionExpiredError;
var init_Error = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/Error.js"() {
    generateV1Error = (rawStripeError) => {
      switch (rawStripeError.type) {
        case "card_error":
          return new StripeCardError(rawStripeError);
        case "invalid_request_error":
          return new StripeInvalidRequestError(rawStripeError);
        case "api_error":
          return new StripeAPIError(rawStripeError);
        case "authentication_error":
          return new StripeAuthenticationError(rawStripeError);
        case "rate_limit_error":
          return new StripeRateLimitError(rawStripeError);
        case "idempotency_error":
          return new StripeIdempotencyError(rawStripeError);
        case "invalid_grant":
          return new StripeInvalidGrantError(rawStripeError);
        default:
          return new StripeUnknownError(rawStripeError);
      }
    };
    generateV2Error = (rawStripeError) => {
      switch (rawStripeError.type) {
        // switchCases: The beginning of the section generated from our OpenAPI spec
        case "temporary_session_expired":
          return new TemporarySessionExpiredError(rawStripeError);
      }
      switch (rawStripeError.code) {
        case "invalid_fields":
          return new StripeInvalidRequestError(rawStripeError);
      }
      return generateV1Error(rawStripeError);
    };
    StripeError = class extends Error {
      constructor(raw = {}, type = null) {
        var _a;
        super(raw.message);
        this.type = type || this.constructor.name;
        this.raw = raw;
        this.rawType = raw.type;
        this.code = raw.code;
        this.doc_url = raw.doc_url;
        this.param = raw.param;
        this.detail = raw.detail;
        this.headers = raw.headers;
        this.requestId = raw.requestId;
        this.statusCode = raw.statusCode;
        this.message = (_a = raw.message) !== null && _a !== void 0 ? _a : "";
        this.userMessage = raw.user_message;
        this.charge = raw.charge;
        this.decline_code = raw.decline_code;
        this.payment_intent = raw.payment_intent;
        this.payment_method = raw.payment_method;
        this.payment_method_type = raw.payment_method_type;
        this.setup_intent = raw.setup_intent;
        this.source = raw.source;
      }
    };
    StripeError.generate = generateV1Error;
    StripeCardError = class extends StripeError {
      constructor(raw = {}) {
        super(raw, "StripeCardError");
      }
    };
    StripeInvalidRequestError = class extends StripeError {
      constructor(raw = {}) {
        super(raw, "StripeInvalidRequestError");
      }
    };
    StripeAPIError = class extends StripeError {
      constructor(raw = {}) {
        super(raw, "StripeAPIError");
      }
    };
    StripeAuthenticationError = class extends StripeError {
      constructor(raw = {}) {
        super(raw, "StripeAuthenticationError");
      }
    };
    StripePermissionError = class extends StripeError {
      constructor(raw = {}) {
        super(raw, "StripePermissionError");
      }
    };
    StripeRateLimitError = class extends StripeError {
      constructor(raw = {}) {
        super(raw, "StripeRateLimitError");
      }
    };
    StripeConnectionError = class extends StripeError {
      constructor(raw = {}) {
        super(raw, "StripeConnectionError");
      }
    };
    StripeSignatureVerificationError = class extends StripeError {
      constructor(header, payload, raw = {}) {
        super(raw, "StripeSignatureVerificationError");
        this.header = header;
        this.payload = payload;
      }
    };
    StripeIdempotencyError = class extends StripeError {
      constructor(raw = {}) {
        super(raw, "StripeIdempotencyError");
      }
    };
    StripeInvalidGrantError = class extends StripeError {
      constructor(raw = {}) {
        super(raw, "StripeInvalidGrantError");
      }
    };
    StripeUnknownError = class extends StripeError {
      constructor(raw = {}) {
        super(raw, "StripeUnknownError");
      }
    };
    TemporarySessionExpiredError = class extends StripeError {
      constructor(rawStripeError = {}) {
        super(rawStripeError, "TemporarySessionExpiredError");
      }
    };
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/platform/NodePlatformFunctions.js
import * as crypto3 from "crypto";
import { EventEmitter } from "events";
import { exec } from "child_process";
var StreamProcessingError, NodePlatformFunctions;
var init_NodePlatformFunctions = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/platform/NodePlatformFunctions.js"() {
    init_NodeCryptoProvider();
    init_NodeHttpClient();
    init_PlatformFunctions();
    init_Error();
    init_utils5();
    StreamProcessingError = class extends StripeError {
    };
    NodePlatformFunctions = class extends PlatformFunctions {
      constructor() {
        super();
        this._exec = exec;
        this._UNAME_CACHE = null;
      }
      /** @override */
      uuid4() {
        if (crypto3.randomUUID) {
          return crypto3.randomUUID();
        }
        return super.uuid4();
      }
      /**
       * @override
       * Node's built in `exec` function sometimes throws outright,
       * and sometimes has a callback with an error,
       * depending on the type of error.
       *
       * This unifies that interface by resolving with a null uname
       * if an error is encountered.
       */
      getUname() {
        if (!this._UNAME_CACHE) {
          this._UNAME_CACHE = new Promise((resolve, reject) => {
            try {
              this._exec("uname -a", (err, uname) => {
                if (err) {
                  return resolve(null);
                }
                resolve(uname);
              });
            } catch (e) {
              resolve(null);
            }
          });
        }
        return this._UNAME_CACHE;
      }
      /**
       * @override
       * Secure compare, from https://github.com/freewil/scmp
       */
      secureCompare(a, b) {
        if (!a || !b) {
          throw new Error("secureCompare must receive two arguments");
        }
        if (a.length !== b.length) {
          return false;
        }
        if (crypto3.timingSafeEqual) {
          const textEncoder = new TextEncoder();
          const aEncoded = textEncoder.encode(a);
          const bEncoded = textEncoder.encode(b);
          return crypto3.timingSafeEqual(aEncoded, bEncoded);
        }
        return super.secureCompare(a, b);
      }
      createEmitter() {
        return new EventEmitter();
      }
      /** @override */
      tryBufferData(data) {
        if (!(data.file.data instanceof EventEmitter)) {
          return Promise.resolve(data);
        }
        const bufferArray = [];
        return new Promise((resolve, reject) => {
          data.file.data.on("data", (line2) => {
            bufferArray.push(line2);
          }).once("end", () => {
            const bufferData = Object.assign({}, data);
            bufferData.file.data = concat(bufferArray);
            resolve(bufferData);
          }).on("error", (err) => {
            reject(new StreamProcessingError({
              message: "An error occurred while attempting to process the file for upload.",
              detail: err
            }));
          });
        });
      }
      /** @override */
      createNodeHttpClient(agent) {
        return new NodeHttpClient(agent);
      }
      /** @override */
      createDefaultHttpClient() {
        return new NodeHttpClient();
      }
      /** @override */
      createNodeCryptoProvider() {
        return new NodeCryptoProvider();
      }
      /** @override */
      createDefaultCryptoProvider() {
        return this.createNodeCryptoProvider();
      }
    };
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/RequestSender.js
var MAX_RETRY_AFTER_WAIT, RequestSender;
var init_RequestSender = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/RequestSender.js"() {
    init_Error();
    init_HttpClient();
    init_utils5();
    MAX_RETRY_AFTER_WAIT = 60;
    RequestSender = class _RequestSender {
      constructor(stripe, maxBufferedRequestMetric) {
        this._stripe = stripe;
        this._maxBufferedRequestMetric = maxBufferedRequestMetric;
      }
      _normalizeStripeContext(optsContext, clientContext) {
        if (optsContext) {
          return optsContext.toString() || null;
        }
        return (clientContext === null || clientContext === void 0 ? void 0 : clientContext.toString()) || null;
      }
      _addHeadersDirectlyToObject(obj, headers) {
        obj.requestId = headers["request-id"];
        obj.stripeAccount = obj.stripeAccount || headers["stripe-account"];
        obj.apiVersion = obj.apiVersion || headers["stripe-version"];
        obj.idempotencyKey = obj.idempotencyKey || headers["idempotency-key"];
      }
      _makeResponseEvent(requestEvent, statusCode, headers) {
        const requestEndTime = Date.now();
        const requestDurationMs = requestEndTime - requestEvent.request_start_time;
        return removeNullish({
          api_version: headers["stripe-version"],
          account: headers["stripe-account"],
          idempotency_key: headers["idempotency-key"],
          method: requestEvent.method,
          path: requestEvent.path,
          status: statusCode,
          request_id: this._getRequestId(headers),
          elapsed: requestDurationMs,
          request_start_time: requestEvent.request_start_time,
          request_end_time: requestEndTime
        });
      }
      _getRequestId(headers) {
        return headers["request-id"];
      }
      /**
       * Used by methods with spec.streaming === true. For these methods, we do not
       * buffer successful responses into memory or do parse them into stripe
       * objects, we delegate that all of that to the user and pass back the raw
       * http.Response object to the callback.
       *
       * (Unsuccessful responses shouldn't make it here, they should
       * still be buffered/parsed and handled by _jsonResponseHandler -- see
       * makeRequest)
       */
      _streamingResponseHandler(requestEvent, usage, callback) {
        return (res) => {
          const headers = res.getHeaders();
          const streamCompleteCallback = () => {
            const responseEvent = this._makeResponseEvent(requestEvent, res.getStatusCode(), headers);
            this._stripe._emitter.emit("response", responseEvent);
            this._recordRequestMetrics(this._getRequestId(headers), responseEvent.elapsed, usage);
          };
          const stream = res.toStream(streamCompleteCallback);
          this._addHeadersDirectlyToObject(stream, headers);
          return callback(null, stream);
        };
      }
      /**
       * Default handler for Stripe responses. Buffers the response into memory,
       * parses the JSON and returns it (i.e. passes it to the callback) if there
       * is no "error" field. Otherwise constructs/passes an appropriate Error.
       */
      _jsonResponseHandler(requestEvent, apiMode, usage, callback) {
        return (res) => {
          const headers = res.getHeaders();
          const requestId = this._getRequestId(headers);
          const statusCode = res.getStatusCode();
          const responseEvent = this._makeResponseEvent(requestEvent, statusCode, headers);
          this._stripe._emitter.emit("response", responseEvent);
          res.toJSON().then((jsonResponse) => {
            if (jsonResponse.error) {
              let err;
              if (typeof jsonResponse.error === "string") {
                jsonResponse.error = {
                  type: jsonResponse.error,
                  message: jsonResponse.error_description
                };
              }
              jsonResponse.error.headers = headers;
              jsonResponse.error.statusCode = statusCode;
              jsonResponse.error.requestId = requestId;
              if (statusCode === 401) {
                err = new StripeAuthenticationError(jsonResponse.error);
              } else if (statusCode === 403) {
                err = new StripePermissionError(jsonResponse.error);
              } else if (statusCode === 429) {
                err = new StripeRateLimitError(jsonResponse.error);
              } else if (apiMode === "v2") {
                err = generateV2Error(jsonResponse.error);
              } else {
                err = generateV1Error(jsonResponse.error);
              }
              throw err;
            }
            return jsonResponse;
          }, (e) => {
            throw new StripeAPIError({
              message: "Invalid JSON received from the Stripe API",
              exception: e,
              requestId: headers["request-id"]
            });
          }).then((jsonResponse) => {
            this._recordRequestMetrics(requestId, responseEvent.elapsed, usage);
            const rawResponse = res.getRawResponse();
            this._addHeadersDirectlyToObject(rawResponse, headers);
            Object.defineProperty(jsonResponse, "lastResponse", {
              enumerable: false,
              writable: false,
              value: rawResponse
            });
            callback(null, jsonResponse);
          }, (e) => callback(e, null));
        };
      }
      static _generateConnectionErrorMessage(requestRetries) {
        return `An error occurred with our connection to Stripe.${requestRetries > 0 ? ` Request was retried ${requestRetries} times.` : ""}`;
      }
      // For more on when and how to retry API requests, see https://stripe.com/docs/error-handling#safely-retrying-requests-with-idempotency
      static _shouldRetry(res, numRetries, maxRetries, error40) {
        if (error40 && numRetries === 0 && HttpClient.CONNECTION_CLOSED_ERROR_CODES.includes(error40.code)) {
          return true;
        }
        if (numRetries >= maxRetries) {
          return false;
        }
        if (!res) {
          return true;
        }
        if (res.getHeaders()["stripe-should-retry"] === "false") {
          return false;
        }
        if (res.getHeaders()["stripe-should-retry"] === "true") {
          return true;
        }
        if (res.getStatusCode() === 409) {
          return true;
        }
        if (res.getStatusCode() >= 500) {
          return true;
        }
        return false;
      }
      _getSleepTimeInMS(numRetries, retryAfter = null) {
        const initialNetworkRetryDelay = this._stripe.getInitialNetworkRetryDelay();
        const maxNetworkRetryDelay = this._stripe.getMaxNetworkRetryDelay();
        let sleepSeconds = Math.min(initialNetworkRetryDelay * Math.pow(2, numRetries - 1), maxNetworkRetryDelay);
        sleepSeconds *= 0.5 * (1 + Math.random());
        sleepSeconds = Math.max(initialNetworkRetryDelay, sleepSeconds);
        if (Number.isInteger(retryAfter) && retryAfter <= MAX_RETRY_AFTER_WAIT) {
          sleepSeconds = Math.max(sleepSeconds, retryAfter);
        }
        return sleepSeconds * 1e3;
      }
      // Max retries can be set on a per request basis. Favor those over the global setting
      _getMaxNetworkRetries(settings = {}) {
        return settings.maxNetworkRetries !== void 0 && Number.isInteger(settings.maxNetworkRetries) ? settings.maxNetworkRetries : this._stripe.getMaxNetworkRetries();
      }
      _defaultIdempotencyKey(method, settings, apiMode) {
        const maxRetries = this._getMaxNetworkRetries(settings);
        const genKey = () => `stripe-node-retry-${this._stripe._platformFunctions.uuid4()}`;
        if (apiMode === "v2") {
          if (method === "POST" || method === "DELETE") {
            return genKey();
          }
        } else if (apiMode === "v1") {
          if (method === "POST" && maxRetries > 0) {
            return genKey();
          }
        }
        return null;
      }
      _makeHeaders({ contentType, contentLength, apiVersion, clientUserAgent, method, userSuppliedHeaders, userSuppliedSettings, stripeAccount, stripeContext, apiMode }) {
        const defaultHeaders = {
          Accept: "application/json",
          "Content-Type": contentType,
          "User-Agent": this._getUserAgentString(apiMode),
          "X-Stripe-Client-User-Agent": clientUserAgent,
          "X-Stripe-Client-Telemetry": this._getTelemetryHeader(),
          "Stripe-Version": apiVersion,
          "Stripe-Account": stripeAccount,
          "Stripe-Context": stripeContext,
          "Idempotency-Key": this._defaultIdempotencyKey(method, userSuppliedSettings, apiMode)
        };
        const methodHasPayload = method == "POST" || method == "PUT" || method == "PATCH";
        if (methodHasPayload || contentLength) {
          if (!methodHasPayload) {
            emitWarning(`${method} method had non-zero contentLength but no payload is expected for this verb`);
          }
          defaultHeaders["Content-Length"] = contentLength;
        }
        return Object.assign(
          removeNullish(defaultHeaders),
          // If the user supplied, say 'idempotency-key', override instead of appending by ensuring caps are the same.
          normalizeHeaders(userSuppliedHeaders)
        );
      }
      _getUserAgentString(apiMode) {
        const packageVersion = this._stripe.getConstant("PACKAGE_VERSION");
        const appInfo = this._stripe._appInfo ? this._stripe.getAppInfoAsString() : "";
        const aiAgent = this._stripe.getConstant("AI_AGENT");
        let uaString = `Stripe/${apiMode} NodeBindings/${packageVersion}`;
        if (appInfo) {
          uaString += ` ${appInfo}`;
        }
        if (aiAgent) {
          uaString += ` AIAgent/${aiAgent}`;
        }
        return uaString;
      }
      _getTelemetryHeader() {
        if (this._stripe.getTelemetryEnabled() && this._stripe._prevRequestMetrics.length > 0) {
          const metrics = this._stripe._prevRequestMetrics.shift();
          return JSON.stringify({
            last_request_metrics: metrics
          });
        }
      }
      _recordRequestMetrics(requestId, requestDurationMs, usage) {
        if (this._stripe.getTelemetryEnabled() && requestId) {
          if (this._stripe._prevRequestMetrics.length > this._maxBufferedRequestMetric) {
            emitWarning("Request metrics buffer is full, dropping telemetry message.");
          } else {
            const m = {
              request_id: requestId,
              request_duration_ms: requestDurationMs
            };
            if (usage && usage.length > 0) {
              m.usage = usage;
            }
            this._stripe._prevRequestMetrics.push(m);
          }
        }
      }
      _rawRequest(method, path4, params, options, usage) {
        const requestPromise = new Promise((resolve, reject) => {
          let opts;
          try {
            const requestMethod = method.toUpperCase();
            if (requestMethod !== "POST" && params && Object.keys(params).length !== 0) {
              throw new Error("rawRequest only supports params on POST requests. Please pass null and add your parameters to path.");
            }
            const args = [].slice.call([params, options]);
            const dataFromArgs = getDataFromArgs(args);
            const data = requestMethod === "POST" ? Object.assign({}, dataFromArgs) : null;
            const calculatedOptions = getOptionsFromArgs(args);
            const headers2 = calculatedOptions.headers;
            const authenticator2 = calculatedOptions.authenticator;
            opts = {
              requestMethod,
              requestPath: path4,
              bodyData: data,
              queryData: {},
              authenticator: authenticator2,
              headers: headers2,
              host: calculatedOptions.host,
              streaming: !!calculatedOptions.streaming,
              settings: {},
              // We use this for thin event internals, so we should record the more specific `usage`, when available
              usage: usage || ["raw_request"]
            };
          } catch (err) {
            reject(err);
            return;
          }
          function requestCallback(err, response) {
            if (err) {
              reject(err);
            } else {
              resolve(response);
            }
          }
          const { headers, settings } = opts;
          const authenticator = opts.authenticator;
          this._request(opts.requestMethod, opts.host, path4, opts.bodyData, authenticator, { headers, settings, streaming: opts.streaming }, opts.usage, requestCallback);
        });
        return requestPromise;
      }
      _getContentLength(data) {
        return typeof data === "string" ? new TextEncoder().encode(data).length : data.length;
      }
      _request(method, host, path4, data, authenticator, options, usage = [], callback, requestDataProcessor = null) {
        var _a;
        let requestData;
        authenticator = (_a = authenticator !== null && authenticator !== void 0 ? authenticator : this._stripe._authenticator) !== null && _a !== void 0 ? _a : null;
        const apiMode = getAPIMode(path4);
        const retryRequest = (requestFn, apiVersion, headers, requestRetries, retryAfter) => {
          return setTimeout(requestFn, this._getSleepTimeInMS(requestRetries, retryAfter), apiVersion, headers, requestRetries + 1);
        };
        const makeRequest = (apiVersion, headers, numRetries) => {
          const timeout = options.settings && options.settings.timeout && Number.isInteger(options.settings.timeout) && options.settings.timeout >= 0 ? options.settings.timeout : this._stripe.getApiField("timeout");
          const request = {
            host: host || this._stripe.getApiField("host"),
            port: this._stripe.getApiField("port"),
            path: path4,
            method,
            headers: Object.assign({}, headers),
            body: requestData,
            protocol: this._stripe.getApiField("protocol")
          };
          authenticator(request).then(() => {
            const req = this._stripe.getApiField("httpClient").makeRequest(request.host, request.port, request.path, request.method, request.headers, request.body, request.protocol, timeout);
            const requestStartTime = Date.now();
            const requestEvent = removeNullish({
              api_version: apiVersion,
              account: parseHttpHeaderAsString(headers["Stripe-Account"]),
              idempotency_key: parseHttpHeaderAsString(headers["Idempotency-Key"]),
              method,
              path: path4,
              request_start_time: requestStartTime
            });
            const requestRetries = numRetries || 0;
            const maxRetries = this._getMaxNetworkRetries(options.settings || {});
            this._stripe._emitter.emit("request", requestEvent);
            req.then((res) => {
              if (_RequestSender._shouldRetry(res, requestRetries, maxRetries)) {
                return retryRequest(makeRequest, apiVersion, headers, requestRetries, parseHttpHeaderAsNumber(res.getHeaders()["retry-after"]));
              } else if (options.streaming && res.getStatusCode() < 400) {
                return this._streamingResponseHandler(requestEvent, usage, callback)(res);
              } else {
                return this._jsonResponseHandler(requestEvent, apiMode, usage, callback)(res);
              }
            }).catch((error40) => {
              if (_RequestSender._shouldRetry(null, requestRetries, maxRetries, error40)) {
                return retryRequest(makeRequest, apiVersion, headers, requestRetries, null);
              } else {
                const isTimeoutError = error40.code && error40.code === HttpClient.TIMEOUT_ERROR_CODE;
                return callback(new StripeConnectionError({
                  message: isTimeoutError ? `Request aborted due to timeout being reached (${timeout}ms)` : _RequestSender._generateConnectionErrorMessage(requestRetries),
                  detail: error40
                }));
              }
            });
          }).catch((e) => {
            throw new StripeError({
              message: "Unable to authenticate the request",
              exception: e
            });
          });
        };
        const prepareAndMakeRequest = (error40, data2) => {
          if (error40) {
            return callback(error40);
          }
          requestData = data2;
          this._stripe.getClientUserAgent((clientUserAgent) => {
            var _a2, _b, _c;
            const apiVersion = this._stripe.getApiField("version");
            const headers = this._makeHeaders({
              contentType: apiMode == "v2" ? "application/json" : "application/x-www-form-urlencoded",
              contentLength: this._getContentLength(data2),
              apiVersion,
              clientUserAgent,
              method,
              // other callers expect null, but .headers being optional means it's undefined if not supplied. So we normalize to null.
              userSuppliedHeaders: (_a2 = options.headers) !== null && _a2 !== void 0 ? _a2 : null,
              userSuppliedSettings: (_b = options.settings) !== null && _b !== void 0 ? _b : {},
              stripeAccount: (_c = options.stripeAccount) !== null && _c !== void 0 ? _c : this._stripe.getApiField("stripeAccount"),
              stripeContext: this._normalizeStripeContext(options.stripeContext, this._stripe.getApiField("stripeContext")),
              apiMode
            });
            makeRequest(apiVersion, headers, 0);
          });
        };
        if (requestDataProcessor) {
          requestDataProcessor(method, data, options.headers, prepareAndMakeRequest);
        } else {
          let stringifiedData;
          if (apiMode == "v2") {
            stringifiedData = data ? jsonStringifyRequestData(data) : "";
          } else {
            stringifiedData = queryStringifyRequestData(data || {});
          }
          prepareAndMakeRequest(null, stringifiedData);
        }
      }
    };
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/autoPagination.js
function getAsyncIteratorSymbol() {
  if (typeof Symbol !== "undefined" && Symbol.asyncIterator) {
    return Symbol.asyncIterator;
  }
  return "@@asyncIterator";
}
function getDoneCallback(args) {
  if (args.length < 2) {
    return null;
  }
  const onDone = args[1];
  if (typeof onDone !== "function") {
    throw Error(`The second argument to autoPagingEach, if present, must be a callback function; received ${typeof onDone}`);
  }
  return onDone;
}
function getItemCallback(args) {
  if (args.length === 0) {
    return void 0;
  }
  const onItem = args[0];
  if (typeof onItem !== "function") {
    throw Error(`The first argument to autoPagingEach, if present, must be a callback function; received ${typeof onItem}`);
  }
  if (onItem.length === 2) {
    return onItem;
  }
  if (onItem.length > 2) {
    throw Error(`The \`onItem\` callback function passed to autoPagingEach must accept at most two arguments; got ${onItem}`);
  }
  return function _onItem(item, next) {
    const shouldContinue = onItem(item);
    next(shouldContinue);
  };
}
function getLastId(listResult, reverseIteration) {
  const lastIdx = reverseIteration ? 0 : listResult.data.length - 1;
  const lastItem = listResult.data[lastIdx];
  const lastId = lastItem && lastItem.id;
  if (!lastId) {
    throw Error("Unexpected: No `id` found on the last item while auto-paging a list.");
  }
  return lastId;
}
function makeAutoPagingEach(asyncIteratorNext) {
  return function autoPagingEach() {
    const args = [].slice.call(arguments);
    const onItem = getItemCallback(args);
    const onDone = getDoneCallback(args);
    if (args.length > 2) {
      throw Error(`autoPagingEach takes up to two arguments; received ${args}`);
    }
    const autoPagePromise = wrapAsyncIteratorWithCallback(
      asyncIteratorNext,
      // @ts-ignore we might need a null check
      onItem
    );
    return callbackifyPromiseWithTimeout(autoPagePromise, onDone);
  };
}
function makeAutoPagingToArray(autoPagingEach) {
  return function autoPagingToArray(opts, onDone) {
    const limit = opts && opts.limit;
    if (!limit) {
      throw Error("You must pass a `limit` option to autoPagingToArray, e.g., `autoPagingToArray({limit: 1000});`.");
    }
    if (limit > 1e4) {
      throw Error("You cannot specify a limit of more than 10,000 items to fetch in `autoPagingToArray`; use `autoPagingEach` to iterate through longer lists.");
    }
    const promise2 = new Promise((resolve, reject) => {
      const items = [];
      autoPagingEach((item) => {
        items.push(item);
        if (items.length >= limit) {
          return false;
        }
      }).then(() => {
        resolve(items);
      }).catch(reject);
    });
    return callbackifyPromiseWithTimeout(promise2, onDone);
  };
}
function wrapAsyncIteratorWithCallback(asyncIteratorNext, onItem) {
  return new Promise((resolve, reject) => {
    function handleIteration(iterResult) {
      if (iterResult.done) {
        resolve();
        return;
      }
      const item = iterResult.value;
      return new Promise((next) => {
        onItem(item, next);
      }).then((shouldContinue) => {
        if (shouldContinue === false) {
          return handleIteration({ done: true, value: void 0 });
        } else {
          return asyncIteratorNext().then(handleIteration);
        }
      });
    }
    asyncIteratorNext().then(handleIteration).catch(reject);
  });
}
function isReverseIteration(requestArgs) {
  const args = [].slice.call(requestArgs);
  const dataFromArgs = getDataFromArgs(args);
  return !!dataFromArgs.ending_before;
}
var V1Iterator, V1ListIterator, V1SearchIterator, V2ListIterator, makeAutoPaginationMethods, makeAutoPaginationMethodsFromIterator;
var init_autoPagination = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/autoPagination.js"() {
    init_utils5();
    V1Iterator = class {
      constructor(firstPagePromise, requestArgs, spec, stripeResource) {
        this.index = 0;
        this.pagePromise = firstPagePromise;
        this.promiseCache = { currentPromise: null };
        this.requestArgs = requestArgs;
        this.spec = spec;
        this.stripeResource = stripeResource;
      }
      async iterate(pageResult) {
        if (!(pageResult && pageResult.data && typeof pageResult.data.length === "number")) {
          throw Error("Unexpected: Stripe API response does not have a well-formed `data` array.");
        }
        const reverseIteration = isReverseIteration(this.requestArgs);
        if (this.index < pageResult.data.length) {
          const idx = reverseIteration ? pageResult.data.length - 1 - this.index : this.index;
          const value = pageResult.data[idx];
          this.index += 1;
          return { value, done: false };
        } else if (pageResult.has_more) {
          this.index = 0;
          this.pagePromise = this.getNextPage(pageResult);
          const nextPageResult = await this.pagePromise;
          return this.iterate(nextPageResult);
        }
        return { done: true, value: void 0 };
      }
      /** @abstract */
      getNextPage(_pageResult) {
        throw new Error("Unimplemented");
      }
      async _next() {
        return this.iterate(await this.pagePromise);
      }
      next() {
        if (this.promiseCache.currentPromise) {
          return this.promiseCache.currentPromise;
        }
        const nextPromise = (async () => {
          const ret = await this._next();
          this.promiseCache.currentPromise = null;
          return ret;
        })();
        this.promiseCache.currentPromise = nextPromise;
        return nextPromise;
      }
    };
    V1ListIterator = class extends V1Iterator {
      getNextPage(pageResult) {
        const reverseIteration = isReverseIteration(this.requestArgs);
        const lastId = getLastId(pageResult, reverseIteration);
        return this.stripeResource._makeRequest(this.requestArgs, this.spec, {
          [reverseIteration ? "ending_before" : "starting_after"]: lastId
        });
      }
    };
    V1SearchIterator = class extends V1Iterator {
      getNextPage(pageResult) {
        if (!pageResult.next_page) {
          throw Error("Unexpected: Stripe API response does not have a well-formed `next_page` field, but `has_more` was true.");
        }
        return this.stripeResource._makeRequest(this.requestArgs, this.spec, {
          page: pageResult.next_page
        });
      }
    };
    V2ListIterator = class {
      constructor(firstPagePromise, requestArgs, spec, stripeResource) {
        this.firstPagePromise = firstPagePromise;
        this.currentPageIterator = null;
        this.nextPageUrl = null;
        this.requestArgs = requestArgs;
        this.spec = spec;
        this.stripeResource = stripeResource;
      }
      async initFirstPage() {
        if (this.firstPagePromise) {
          const page = await this.firstPagePromise;
          this.firstPagePromise = null;
          this.currentPageIterator = page.data[Symbol.iterator]();
          this.nextPageUrl = page.next_page_url || null;
        }
      }
      async turnPage() {
        if (!this.nextPageUrl)
          return null;
        this.spec.fullPath = this.nextPageUrl;
        const page = await this.stripeResource._makeRequest([], this.spec, {});
        this.nextPageUrl = page.next_page_url || null;
        this.currentPageIterator = page.data[Symbol.iterator]();
        return this.currentPageIterator;
      }
      async next() {
        await this.initFirstPage();
        if (this.currentPageIterator) {
          const result2 = this.currentPageIterator.next();
          if (!result2.done)
            return { done: false, value: result2.value };
        }
        const nextPageIterator = await this.turnPage();
        if (!nextPageIterator) {
          return { done: true, value: void 0 };
        }
        const result = nextPageIterator.next();
        if (!result.done)
          return { done: false, value: result.value };
        return { done: true, value: void 0 };
      }
    };
    makeAutoPaginationMethods = (stripeResource, requestArgs, spec, firstPagePromise) => {
      const apiMode = getAPIMode(spec.fullPath || spec.path);
      if (apiMode !== "v2" && spec.methodType === "search") {
        return makeAutoPaginationMethodsFromIterator(new V1SearchIterator(firstPagePromise, requestArgs, spec, stripeResource));
      }
      if (apiMode !== "v2" && spec.methodType === "list") {
        return makeAutoPaginationMethodsFromIterator(new V1ListIterator(firstPagePromise, requestArgs, spec, stripeResource));
      }
      if (apiMode === "v2" && spec.methodType === "list") {
        return makeAutoPaginationMethodsFromIterator(new V2ListIterator(firstPagePromise, requestArgs, spec, stripeResource));
      }
      return null;
    };
    makeAutoPaginationMethodsFromIterator = (iterator) => {
      const autoPagingEach = makeAutoPagingEach((...args) => iterator.next(...args));
      const autoPagingToArray = makeAutoPagingToArray(autoPagingEach);
      const autoPaginationMethods = {
        autoPagingEach,
        autoPagingToArray,
        // Async iterator functions:
        next: () => iterator.next(),
        return: () => {
          return {};
        },
        [getAsyncIteratorSymbol()]: () => {
          return autoPaginationMethods;
        }
      };
      return autoPaginationMethods;
    };
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/StripeMethod.js
function stripeMethod(spec) {
  if (spec.path !== void 0 && spec.fullPath !== void 0) {
    throw new Error(`Method spec specified both a 'path' (${spec.path}) and a 'fullPath' (${spec.fullPath}).`);
  }
  return function(...args) {
    const callback = typeof args[args.length - 1] == "function" && args.pop();
    spec.urlParams = extractUrlParams(spec.fullPath || this.createResourcePathWithSymbols(spec.path || ""));
    const requestPromise = callbackifyPromiseWithTimeout(this._makeRequest(args, spec, {}), callback);
    Object.assign(requestPromise, makeAutoPaginationMethods(this, args, spec, requestPromise));
    return requestPromise;
  };
}
var init_StripeMethod = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/StripeMethod.js"() {
    init_utils5();
    init_autoPagination();
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/StripeResource.js
function StripeResource(stripe, deprecatedUrlData) {
  this._stripe = stripe;
  if (deprecatedUrlData) {
    throw new Error("Support for curried url params was dropped in stripe-node v7.0.0. Instead, pass two ids.");
  }
  this.basePath = makeURLInterpolator(
    // @ts-ignore changing type of basePath
    this.basePath || stripe.getApiField("basePath")
  );
  this.resourcePath = this.path;
  this.path = makeURLInterpolator(this.path);
  this.initialize(...arguments);
}
var init_StripeResource = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/StripeResource.js"() {
    init_utils5();
    init_StripeMethod();
    StripeResource.extend = protoExtend;
    StripeResource.method = stripeMethod;
    StripeResource.MAX_BUFFERED_REQUEST_METRICS = 100;
    StripeResource.prototype = {
      _stripe: null,
      // @ts-ignore the type of path changes in ctor
      path: "",
      resourcePath: "",
      // Methods that don't use the API's default '/v1' path can override it with this setting.
      basePath: null,
      initialize() {
      },
      // Function to override the default data processor. This allows full control
      // over how a StripeResource's request data will get converted into an HTTP
      // body. This is useful for non-standard HTTP requests. The function should
      // take method name, data, and headers as arguments.
      requestDataProcessor: null,
      // Function to add a validation checks before sending the request, errors should
      // be thrown, and they will be passed to the callback/promise.
      validateRequest: null,
      createFullPath(commandPath, urlData) {
        const urlParts = [this.basePath(urlData), this.path(urlData)];
        if (typeof commandPath === "function") {
          const computedCommandPath = commandPath(urlData);
          if (computedCommandPath) {
            urlParts.push(computedCommandPath);
          }
        } else {
          urlParts.push(commandPath);
        }
        return this._joinUrlParts(urlParts);
      },
      // Creates a relative resource path with symbols left in (unlike
      // createFullPath which takes some data to replace them with). For example it
      // might produce: /invoices/{id}
      createResourcePathWithSymbols(pathWithSymbols) {
        if (pathWithSymbols) {
          return `/${this._joinUrlParts([this.resourcePath, pathWithSymbols])}`;
        } else {
          return `/${this.resourcePath}`;
        }
      },
      _joinUrlParts(parts) {
        return parts.join("/").replace(/\/{2,}/g, "/");
      },
      _getRequestOpts(requestArgs, spec, overrideData) {
        var _a;
        const requestMethod = (spec.method || "GET").toUpperCase();
        const usage = spec.usage || [];
        const urlParams = spec.urlParams || [];
        const encode = spec.encode || ((data2) => data2);
        const isUsingFullPath = !!spec.fullPath;
        const commandPath = makeURLInterpolator(isUsingFullPath ? spec.fullPath : spec.path || "");
        const path4 = isUsingFullPath ? spec.fullPath : this.createResourcePathWithSymbols(spec.path);
        const args = [].slice.call(requestArgs);
        const urlData = urlParams.reduce((urlData2, param) => {
          const arg = args.shift();
          if (typeof arg !== "string") {
            throw new Error(`Stripe: Argument "${param}" must be a string, but got: ${arg} (on API request to \`${requestMethod} ${path4}\`)`);
          }
          urlData2[param] = arg;
          return urlData2;
        }, {});
        const dataFromArgs = getDataFromArgs(args);
        const data = encode(Object.assign({}, dataFromArgs, overrideData));
        const options = getOptionsFromArgs(args);
        const host = options.host || spec.host;
        const streaming = !!spec.streaming || !!options.streaming;
        if (args.filter((x) => x != null).length) {
          throw new Error(`Stripe: Unknown arguments (${args}). Did you mean to pass an options object? See https://github.com/stripe/stripe-node/wiki/Passing-Options. (on API request to ${requestMethod} \`${path4}\`)`);
        }
        const requestPath = isUsingFullPath ? commandPath(urlData) : this.createFullPath(commandPath, urlData);
        const headers = Object.assign(options.headers, spec.headers);
        if (spec.validator) {
          spec.validator(data, { headers });
        }
        const dataInQuery = spec.method === "GET" || spec.method === "DELETE";
        const bodyData = dataInQuery ? null : data;
        const queryData = dataInQuery ? data : {};
        return {
          requestMethod,
          requestPath,
          bodyData,
          queryData,
          authenticator: (_a = options.authenticator) !== null && _a !== void 0 ? _a : null,
          headers,
          host: host !== null && host !== void 0 ? host : null,
          streaming,
          settings: options.settings,
          usage
        };
      },
      _makeRequest(requestArgs, spec, overrideData) {
        return new Promise((resolve, reject) => {
          var _a;
          let opts;
          try {
            opts = this._getRequestOpts(requestArgs, spec, overrideData);
          } catch (err) {
            reject(err);
            return;
          }
          function requestCallback(err, response) {
            if (err) {
              reject(err);
            } else {
              resolve(spec.transformResponseData ? spec.transformResponseData(response) : response);
            }
          }
          const emptyQuery = Object.keys(opts.queryData).length === 0;
          const path4 = [
            opts.requestPath,
            emptyQuery ? "" : "?",
            queryStringifyRequestData(opts.queryData)
          ].join("");
          const { headers, settings } = opts;
          this._stripe._requestSender._request(opts.requestMethod, opts.host, path4, opts.bodyData, opts.authenticator, {
            headers,
            settings,
            streaming: opts.streaming
          }, opts.usage, requestCallback, (_a = this.requestDataProcessor) === null || _a === void 0 ? void 0 : _a.bind(this));
        });
      }
    };
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/StripeContext.js
var StripeContext;
var init_StripeContext = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/StripeContext.js"() {
    StripeContext = class _StripeContext {
      /**
       * Creates a new StripeContext with the given segments.
       */
      constructor(segments = []) {
        this._segments = [...segments];
      }
      /**
       * Gets a copy of the segments of this Context.
       */
      get segments() {
        return [...this._segments];
      }
      /**
       * Creates a new StripeContext with an additional segment appended.
       */
      push(segment) {
        if (!segment) {
          throw new Error("Segment cannot be null or undefined");
        }
        return new _StripeContext([...this._segments, segment]);
      }
      /**
       * Creates a new StripeContext with the last segment removed.
       * If there are no segments, throws an error.
       */
      pop() {
        if (this._segments.length === 0) {
          throw new Error("Cannot pop from an empty context");
        }
        return new _StripeContext(this._segments.slice(0, -1));
      }
      /**
       * Converts this context to its string representation.
       */
      toString() {
        return this._segments.join("/");
      }
      /**
       * Parses a context string into a StripeContext instance.
       */
      static parse(contextStr) {
        if (!contextStr) {
          return new _StripeContext([]);
        }
        return new _StripeContext(contextStr.split("/"));
      }
    };
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/Webhooks.js
function createWebhooks(platformFunctions) {
  const Webhook = {
    DEFAULT_TOLERANCE: 300,
    signature: null,
    constructEvent(payload, header, secret, tolerance, cryptoProvider, receivedAt) {
      try {
        if (!this.signature) {
          throw new Error("ERR: missing signature helper, unable to verify");
        }
        this.signature.verifyHeader(payload, header, secret, tolerance || Webhook.DEFAULT_TOLERANCE, cryptoProvider, receivedAt);
      } catch (e) {
        if (e instanceof CryptoProviderOnlySupportsAsyncError) {
          e.message += "\nUse `await constructEventAsync(...)` instead of `constructEvent(...)`";
        }
        throw e;
      }
      const jsonPayload = payload instanceof Uint8Array ? JSON.parse(new TextDecoder("utf8").decode(payload)) : JSON.parse(payload);
      return jsonPayload;
    },
    async constructEventAsync(payload, header, secret, tolerance, cryptoProvider, receivedAt) {
      if (!this.signature) {
        throw new Error("ERR: missing signature helper, unable to verify");
      }
      await this.signature.verifyHeaderAsync(payload, header, secret, tolerance || Webhook.DEFAULT_TOLERANCE, cryptoProvider, receivedAt);
      const jsonPayload = payload instanceof Uint8Array ? JSON.parse(new TextDecoder("utf8").decode(payload)) : JSON.parse(payload);
      return jsonPayload;
    },
    /**
     * Generates a header to be used for webhook mocking
     *
     * @typedef {object} opts
     * @property {number} timestamp - Timestamp of the header. Defaults to Date.now()
     * @property {string} payload - JSON stringified payload object, containing the 'id' and 'object' parameters
     * @property {string} secret - Stripe webhook secret 'whsec_...'
     * @property {string} scheme - Version of API to hit. Defaults to 'v1'.
     * @property {string} signature - Computed webhook signature
     * @property {CryptoProvider} cryptoProvider - Crypto provider to use for computing the signature if none was provided. Defaults to NodeCryptoProvider.
     */
    generateTestHeaderString: function(opts) {
      const preparedOpts = prepareOptions(opts);
      const signature2 = preparedOpts.signature || preparedOpts.cryptoProvider.computeHMACSignature(preparedOpts.payloadString, preparedOpts.secret);
      return preparedOpts.generateHeaderString(signature2);
    },
    generateTestHeaderStringAsync: async function(opts) {
      const preparedOpts = prepareOptions(opts);
      const signature2 = preparedOpts.signature || await preparedOpts.cryptoProvider.computeHMACSignatureAsync(preparedOpts.payloadString, preparedOpts.secret);
      return preparedOpts.generateHeaderString(signature2);
    }
  };
  const signature = {
    EXPECTED_SCHEME: "v1",
    verifyHeader(encodedPayload, encodedHeader, secret, tolerance, cryptoProvider, receivedAt) {
      const { decodedHeader: header, decodedPayload: payload, details, suspectPayloadType } = parseEventDetails(encodedPayload, encodedHeader, this.EXPECTED_SCHEME);
      const secretContainsWhitespace = /\s/.test(secret);
      cryptoProvider = cryptoProvider || getCryptoProvider();
      const expectedSignature = cryptoProvider.computeHMACSignature(makeHMACContent(payload, details), secret);
      validateComputedSignature(payload, header, details, expectedSignature, tolerance, suspectPayloadType, secretContainsWhitespace, receivedAt);
      return true;
    },
    async verifyHeaderAsync(encodedPayload, encodedHeader, secret, tolerance, cryptoProvider, receivedAt) {
      const { decodedHeader: header, decodedPayload: payload, details, suspectPayloadType } = parseEventDetails(encodedPayload, encodedHeader, this.EXPECTED_SCHEME);
      const secretContainsWhitespace = /\s/.test(secret);
      cryptoProvider = cryptoProvider || getCryptoProvider();
      const expectedSignature = await cryptoProvider.computeHMACSignatureAsync(makeHMACContent(payload, details), secret);
      return validateComputedSignature(payload, header, details, expectedSignature, tolerance, suspectPayloadType, secretContainsWhitespace, receivedAt);
    }
  };
  function makeHMACContent(payload, details) {
    return `${details.timestamp}.${payload}`;
  }
  function parseEventDetails(encodedPayload, encodedHeader, expectedScheme) {
    if (!encodedPayload) {
      throw new StripeSignatureVerificationError(encodedHeader, encodedPayload, {
        message: "No webhook payload was provided."
      });
    }
    const suspectPayloadType = typeof encodedPayload != "string" && !(encodedPayload instanceof Uint8Array);
    const textDecoder2 = new TextDecoder("utf8");
    const decodedPayload = encodedPayload instanceof Uint8Array ? textDecoder2.decode(encodedPayload) : encodedPayload;
    if (Array.isArray(encodedHeader)) {
      throw new Error("Unexpected: An array was passed as a header, which should not be possible for the stripe-signature header.");
    }
    if (encodedHeader == null || encodedHeader == "") {
      throw new StripeSignatureVerificationError(encodedHeader, encodedPayload, {
        message: "No stripe-signature header value was provided."
      });
    }
    const decodedHeader = encodedHeader instanceof Uint8Array ? textDecoder2.decode(encodedHeader) : encodedHeader;
    const details = parseHeader(decodedHeader, expectedScheme);
    if (!details || details.timestamp === -1) {
      throw new StripeSignatureVerificationError(decodedHeader, decodedPayload, {
        message: "Unable to extract timestamp and signatures from header"
      });
    }
    if (!details.signatures.length) {
      throw new StripeSignatureVerificationError(decodedHeader, decodedPayload, {
        message: "No signatures found with expected scheme"
      });
    }
    return {
      decodedPayload,
      decodedHeader,
      details,
      suspectPayloadType
    };
  }
  function validateComputedSignature(payload, header, details, expectedSignature, tolerance, suspectPayloadType, secretContainsWhitespace, receivedAt) {
    const signatureFound = !!details.signatures.filter(platformFunctions.secureCompare.bind(platformFunctions, expectedSignature)).length;
    const docsLocation = "\nLearn more about webhook signing and explore webhook integration examples for various frameworks at https://docs.stripe.com/webhooks/signature";
    const whitespaceMessage = secretContainsWhitespace ? "\n\nNote: The provided signing secret contains whitespace. This often indicates an extra newline or space is in the value" : "";
    if (!signatureFound) {
      if (suspectPayloadType) {
        throw new StripeSignatureVerificationError(header, payload, {
          message: "Webhook payload must be provided as a string or a Buffer (https://nodejs.org/api/buffer.html) instance representing the _raw_ request body.Payload was provided as a parsed JavaScript object instead. \nSignature verification is impossible without access to the original signed material. \n" + docsLocation + "\n" + whitespaceMessage
        });
      }
      throw new StripeSignatureVerificationError(header, payload, {
        message: "No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe? \n If a webhook request is being forwarded by a third-party tool, ensure that the exact request body, including JSON formatting and new line style, is preserved.\n" + docsLocation + "\n" + whitespaceMessage
      });
    }
    const timestampAge = Math.floor((typeof receivedAt === "number" ? receivedAt : Date.now()) / 1e3) - details.timestamp;
    if (tolerance > 0 && timestampAge > tolerance) {
      throw new StripeSignatureVerificationError(header, payload, {
        message: "Timestamp outside the tolerance zone"
      });
    }
    return true;
  }
  function parseHeader(header, scheme) {
    if (typeof header !== "string") {
      return null;
    }
    return header.split(",").reduce((accum, item) => {
      const kv = item.split("=");
      if (kv[0] === "t") {
        accum.timestamp = parseInt(kv[1], 10);
      }
      if (kv[0] === scheme) {
        accum.signatures.push(kv[1]);
      }
      return accum;
    }, {
      timestamp: -1,
      signatures: []
    });
  }
  let webhooksCryptoProviderInstance = null;
  function getCryptoProvider() {
    if (!webhooksCryptoProviderInstance) {
      webhooksCryptoProviderInstance = platformFunctions.createDefaultCryptoProvider();
    }
    return webhooksCryptoProviderInstance;
  }
  function prepareOptions(opts) {
    if (!opts) {
      throw new StripeError({
        message: "Options are required"
      });
    }
    const timestamp2 = Math.floor(opts.timestamp) || Math.floor(Date.now() / 1e3);
    const scheme = opts.scheme || signature.EXPECTED_SCHEME;
    const cryptoProvider = opts.cryptoProvider || getCryptoProvider();
    const payloadString = `${timestamp2}.${opts.payload}`;
    const generateHeaderString = (signature2) => {
      return `t=${timestamp2},${scheme}=${signature2}`;
    };
    return Object.assign(Object.assign({}, opts), {
      timestamp: timestamp2,
      scheme,
      cryptoProvider,
      payloadString,
      generateHeaderString
    });
  }
  Webhook.signature = signature;
  return Webhook;
}
var init_Webhooks = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/Webhooks.js"() {
    init_Error();
    init_CryptoProvider();
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/apiVersion.js
var ApiVersion;
var init_apiVersion = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/apiVersion.js"() {
    ApiVersion = "2026-02-25.clover";
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/ResourceNamespace.js
function ResourceNamespace(stripe, resources) {
  for (const name in resources) {
    if (!Object.prototype.hasOwnProperty.call(resources, name)) {
      continue;
    }
    const camelCaseName = name[0].toLowerCase() + name.substring(1);
    const resource = new resources[name](stripe);
    this[camelCaseName] = resource;
  }
}
function resourceNamespace(namespace, resources) {
  return function(stripe) {
    return new ResourceNamespace(stripe, resources);
  };
}
var init_ResourceNamespace = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/ResourceNamespace.js"() {
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/V2/Core/AccountLinks.js
var stripeMethod2, AccountLinks;
var init_AccountLinks = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/V2/Core/AccountLinks.js"() {
    init_StripeResource();
    stripeMethod2 = StripeResource.method;
    AccountLinks = StripeResource.extend({
      create: stripeMethod2({ method: "POST", fullPath: "/v2/core/account_links" })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/V2/Core/AccountTokens.js
var stripeMethod3, AccountTokens;
var init_AccountTokens = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/V2/Core/AccountTokens.js"() {
    init_StripeResource();
    stripeMethod3 = StripeResource.method;
    AccountTokens = StripeResource.extend({
      create: stripeMethod3({ method: "POST", fullPath: "/v2/core/account_tokens" }),
      retrieve: stripeMethod3({
        method: "GET",
        fullPath: "/v2/core/account_tokens/{id}"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/FinancialConnections/Accounts.js
var stripeMethod4, Accounts;
var init_Accounts = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/FinancialConnections/Accounts.js"() {
    init_StripeResource();
    stripeMethod4 = StripeResource.method;
    Accounts = StripeResource.extend({
      retrieve: stripeMethod4({
        method: "GET",
        fullPath: "/v1/financial_connections/accounts/{account}"
      }),
      list: stripeMethod4({
        method: "GET",
        fullPath: "/v1/financial_connections/accounts",
        methodType: "list"
      }),
      disconnect: stripeMethod4({
        method: "POST",
        fullPath: "/v1/financial_connections/accounts/{account}/disconnect"
      }),
      listOwners: stripeMethod4({
        method: "GET",
        fullPath: "/v1/financial_connections/accounts/{account}/owners",
        methodType: "list"
      }),
      refresh: stripeMethod4({
        method: "POST",
        fullPath: "/v1/financial_connections/accounts/{account}/refresh"
      }),
      subscribe: stripeMethod4({
        method: "POST",
        fullPath: "/v1/financial_connections/accounts/{account}/subscribe"
      }),
      unsubscribe: stripeMethod4({
        method: "POST",
        fullPath: "/v1/financial_connections/accounts/{account}/unsubscribe"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/V2/Core/Accounts/Persons.js
var stripeMethod5, Persons;
var init_Persons = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/V2/Core/Accounts/Persons.js"() {
    init_StripeResource();
    stripeMethod5 = StripeResource.method;
    Persons = StripeResource.extend({
      create: stripeMethod5({
        method: "POST",
        fullPath: "/v2/core/accounts/{account_id}/persons"
      }),
      retrieve: stripeMethod5({
        method: "GET",
        fullPath: "/v2/core/accounts/{account_id}/persons/{id}"
      }),
      update: stripeMethod5({
        method: "POST",
        fullPath: "/v2/core/accounts/{account_id}/persons/{id}"
      }),
      list: stripeMethod5({
        method: "GET",
        fullPath: "/v2/core/accounts/{account_id}/persons",
        methodType: "list"
      }),
      del: stripeMethod5({
        method: "DELETE",
        fullPath: "/v2/core/accounts/{account_id}/persons/{id}"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/V2/Core/Accounts/PersonTokens.js
var stripeMethod6, PersonTokens;
var init_PersonTokens = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/V2/Core/Accounts/PersonTokens.js"() {
    init_StripeResource();
    stripeMethod6 = StripeResource.method;
    PersonTokens = StripeResource.extend({
      create: stripeMethod6({
        method: "POST",
        fullPath: "/v2/core/accounts/{account_id}/person_tokens"
      }),
      retrieve: stripeMethod6({
        method: "GET",
        fullPath: "/v2/core/accounts/{account_id}/person_tokens/{id}"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/V2/Core/Accounts.js
var stripeMethod7, Accounts2;
var init_Accounts2 = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/V2/Core/Accounts.js"() {
    init_StripeResource();
    init_Persons();
    init_PersonTokens();
    stripeMethod7 = StripeResource.method;
    Accounts2 = StripeResource.extend({
      constructor: function(...args) {
        StripeResource.apply(this, args);
        this.persons = new Persons(...args);
        this.personTokens = new PersonTokens(...args);
      },
      create: stripeMethod7({ method: "POST", fullPath: "/v2/core/accounts" }),
      retrieve: stripeMethod7({ method: "GET", fullPath: "/v2/core/accounts/{id}" }),
      update: stripeMethod7({ method: "POST", fullPath: "/v2/core/accounts/{id}" }),
      list: stripeMethod7({
        method: "GET",
        fullPath: "/v2/core/accounts",
        methodType: "list"
      }),
      close: stripeMethod7({
        method: "POST",
        fullPath: "/v2/core/accounts/{id}/close"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Entitlements/ActiveEntitlements.js
var stripeMethod8, ActiveEntitlements;
var init_ActiveEntitlements = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Entitlements/ActiveEntitlements.js"() {
    init_StripeResource();
    stripeMethod8 = StripeResource.method;
    ActiveEntitlements = StripeResource.extend({
      retrieve: stripeMethod8({
        method: "GET",
        fullPath: "/v1/entitlements/active_entitlements/{id}"
      }),
      list: stripeMethod8({
        method: "GET",
        fullPath: "/v1/entitlements/active_entitlements",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Billing/Alerts.js
var stripeMethod9, Alerts;
var init_Alerts = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Billing/Alerts.js"() {
    init_StripeResource();
    stripeMethod9 = StripeResource.method;
    Alerts = StripeResource.extend({
      create: stripeMethod9({ method: "POST", fullPath: "/v1/billing/alerts" }),
      retrieve: stripeMethod9({ method: "GET", fullPath: "/v1/billing/alerts/{id}" }),
      list: stripeMethod9({
        method: "GET",
        fullPath: "/v1/billing/alerts",
        methodType: "list"
      }),
      activate: stripeMethod9({
        method: "POST",
        fullPath: "/v1/billing/alerts/{id}/activate"
      }),
      archive: stripeMethod9({
        method: "POST",
        fullPath: "/v1/billing/alerts/{id}/archive"
      }),
      deactivate: stripeMethod9({
        method: "POST",
        fullPath: "/v1/billing/alerts/{id}/deactivate"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Tax/Associations.js
var stripeMethod10, Associations;
var init_Associations = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Tax/Associations.js"() {
    init_StripeResource();
    stripeMethod10 = StripeResource.method;
    Associations = StripeResource.extend({
      find: stripeMethod10({ method: "GET", fullPath: "/v1/tax/associations/find" })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Issuing/Authorizations.js
var stripeMethod11, Authorizations;
var init_Authorizations = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Issuing/Authorizations.js"() {
    init_StripeResource();
    stripeMethod11 = StripeResource.method;
    Authorizations = StripeResource.extend({
      retrieve: stripeMethod11({
        method: "GET",
        fullPath: "/v1/issuing/authorizations/{authorization}"
      }),
      update: stripeMethod11({
        method: "POST",
        fullPath: "/v1/issuing/authorizations/{authorization}"
      }),
      list: stripeMethod11({
        method: "GET",
        fullPath: "/v1/issuing/authorizations",
        methodType: "list"
      }),
      approve: stripeMethod11({
        method: "POST",
        fullPath: "/v1/issuing/authorizations/{authorization}/approve"
      }),
      decline: stripeMethod11({
        method: "POST",
        fullPath: "/v1/issuing/authorizations/{authorization}/decline"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TestHelpers/Issuing/Authorizations.js
var stripeMethod12, Authorizations2;
var init_Authorizations2 = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TestHelpers/Issuing/Authorizations.js"() {
    init_StripeResource();
    stripeMethod12 = StripeResource.method;
    Authorizations2 = StripeResource.extend({
      create: stripeMethod12({
        method: "POST",
        fullPath: "/v1/test_helpers/issuing/authorizations"
      }),
      capture: stripeMethod12({
        method: "POST",
        fullPath: "/v1/test_helpers/issuing/authorizations/{authorization}/capture"
      }),
      expire: stripeMethod12({
        method: "POST",
        fullPath: "/v1/test_helpers/issuing/authorizations/{authorization}/expire"
      }),
      finalizeAmount: stripeMethod12({
        method: "POST",
        fullPath: "/v1/test_helpers/issuing/authorizations/{authorization}/finalize_amount"
      }),
      increment: stripeMethod12({
        method: "POST",
        fullPath: "/v1/test_helpers/issuing/authorizations/{authorization}/increment"
      }),
      respond: stripeMethod12({
        method: "POST",
        fullPath: "/v1/test_helpers/issuing/authorizations/{authorization}/fraud_challenges/respond"
      }),
      reverse: stripeMethod12({
        method: "POST",
        fullPath: "/v1/test_helpers/issuing/authorizations/{authorization}/reverse"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Tax/Calculations.js
var stripeMethod13, Calculations;
var init_Calculations = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Tax/Calculations.js"() {
    init_StripeResource();
    stripeMethod13 = StripeResource.method;
    Calculations = StripeResource.extend({
      create: stripeMethod13({ method: "POST", fullPath: "/v1/tax/calculations" }),
      retrieve: stripeMethod13({
        method: "GET",
        fullPath: "/v1/tax/calculations/{calculation}"
      }),
      listLineItems: stripeMethod13({
        method: "GET",
        fullPath: "/v1/tax/calculations/{calculation}/line_items",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Issuing/Cardholders.js
var stripeMethod14, Cardholders;
var init_Cardholders = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Issuing/Cardholders.js"() {
    init_StripeResource();
    stripeMethod14 = StripeResource.method;
    Cardholders = StripeResource.extend({
      create: stripeMethod14({ method: "POST", fullPath: "/v1/issuing/cardholders" }),
      retrieve: stripeMethod14({
        method: "GET",
        fullPath: "/v1/issuing/cardholders/{cardholder}"
      }),
      update: stripeMethod14({
        method: "POST",
        fullPath: "/v1/issuing/cardholders/{cardholder}"
      }),
      list: stripeMethod14({
        method: "GET",
        fullPath: "/v1/issuing/cardholders",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Issuing/Cards.js
var stripeMethod15, Cards;
var init_Cards = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Issuing/Cards.js"() {
    init_StripeResource();
    stripeMethod15 = StripeResource.method;
    Cards = StripeResource.extend({
      create: stripeMethod15({ method: "POST", fullPath: "/v1/issuing/cards" }),
      retrieve: stripeMethod15({ method: "GET", fullPath: "/v1/issuing/cards/{card}" }),
      update: stripeMethod15({ method: "POST", fullPath: "/v1/issuing/cards/{card}" }),
      list: stripeMethod15({
        method: "GET",
        fullPath: "/v1/issuing/cards",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TestHelpers/Issuing/Cards.js
var stripeMethod16, Cards2;
var init_Cards2 = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TestHelpers/Issuing/Cards.js"() {
    init_StripeResource();
    stripeMethod16 = StripeResource.method;
    Cards2 = StripeResource.extend({
      deliverCard: stripeMethod16({
        method: "POST",
        fullPath: "/v1/test_helpers/issuing/cards/{card}/shipping/deliver"
      }),
      failCard: stripeMethod16({
        method: "POST",
        fullPath: "/v1/test_helpers/issuing/cards/{card}/shipping/fail"
      }),
      returnCard: stripeMethod16({
        method: "POST",
        fullPath: "/v1/test_helpers/issuing/cards/{card}/shipping/return"
      }),
      shipCard: stripeMethod16({
        method: "POST",
        fullPath: "/v1/test_helpers/issuing/cards/{card}/shipping/ship"
      }),
      submitCard: stripeMethod16({
        method: "POST",
        fullPath: "/v1/test_helpers/issuing/cards/{card}/shipping/submit"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/BillingPortal/Configurations.js
var stripeMethod17, Configurations;
var init_Configurations = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/BillingPortal/Configurations.js"() {
    init_StripeResource();
    stripeMethod17 = StripeResource.method;
    Configurations = StripeResource.extend({
      create: stripeMethod17({
        method: "POST",
        fullPath: "/v1/billing_portal/configurations"
      }),
      retrieve: stripeMethod17({
        method: "GET",
        fullPath: "/v1/billing_portal/configurations/{configuration}"
      }),
      update: stripeMethod17({
        method: "POST",
        fullPath: "/v1/billing_portal/configurations/{configuration}"
      }),
      list: stripeMethod17({
        method: "GET",
        fullPath: "/v1/billing_portal/configurations",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Terminal/Configurations.js
var stripeMethod18, Configurations2;
var init_Configurations2 = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Terminal/Configurations.js"() {
    init_StripeResource();
    stripeMethod18 = StripeResource.method;
    Configurations2 = StripeResource.extend({
      create: stripeMethod18({
        method: "POST",
        fullPath: "/v1/terminal/configurations"
      }),
      retrieve: stripeMethod18({
        method: "GET",
        fullPath: "/v1/terminal/configurations/{configuration}"
      }),
      update: stripeMethod18({
        method: "POST",
        fullPath: "/v1/terminal/configurations/{configuration}"
      }),
      list: stripeMethod18({
        method: "GET",
        fullPath: "/v1/terminal/configurations",
        methodType: "list"
      }),
      del: stripeMethod18({
        method: "DELETE",
        fullPath: "/v1/terminal/configurations/{configuration}"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TestHelpers/ConfirmationTokens.js
var stripeMethod19, ConfirmationTokens;
var init_ConfirmationTokens = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TestHelpers/ConfirmationTokens.js"() {
    init_StripeResource();
    stripeMethod19 = StripeResource.method;
    ConfirmationTokens = StripeResource.extend({
      create: stripeMethod19({
        method: "POST",
        fullPath: "/v1/test_helpers/confirmation_tokens"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Terminal/ConnectionTokens.js
var stripeMethod20, ConnectionTokens;
var init_ConnectionTokens = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Terminal/ConnectionTokens.js"() {
    init_StripeResource();
    stripeMethod20 = StripeResource.method;
    ConnectionTokens = StripeResource.extend({
      create: stripeMethod20({
        method: "POST",
        fullPath: "/v1/terminal/connection_tokens"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Billing/CreditBalanceSummary.js
var stripeMethod21, CreditBalanceSummary;
var init_CreditBalanceSummary = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Billing/CreditBalanceSummary.js"() {
    init_StripeResource();
    stripeMethod21 = StripeResource.method;
    CreditBalanceSummary = StripeResource.extend({
      retrieve: stripeMethod21({
        method: "GET",
        fullPath: "/v1/billing/credit_balance_summary"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Billing/CreditBalanceTransactions.js
var stripeMethod22, CreditBalanceTransactions;
var init_CreditBalanceTransactions = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Billing/CreditBalanceTransactions.js"() {
    init_StripeResource();
    stripeMethod22 = StripeResource.method;
    CreditBalanceTransactions = StripeResource.extend({
      retrieve: stripeMethod22({
        method: "GET",
        fullPath: "/v1/billing/credit_balance_transactions/{id}"
      }),
      list: stripeMethod22({
        method: "GET",
        fullPath: "/v1/billing/credit_balance_transactions",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Billing/CreditGrants.js
var stripeMethod23, CreditGrants;
var init_CreditGrants = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Billing/CreditGrants.js"() {
    init_StripeResource();
    stripeMethod23 = StripeResource.method;
    CreditGrants = StripeResource.extend({
      create: stripeMethod23({ method: "POST", fullPath: "/v1/billing/credit_grants" }),
      retrieve: stripeMethod23({
        method: "GET",
        fullPath: "/v1/billing/credit_grants/{id}"
      }),
      update: stripeMethod23({
        method: "POST",
        fullPath: "/v1/billing/credit_grants/{id}"
      }),
      list: stripeMethod23({
        method: "GET",
        fullPath: "/v1/billing/credit_grants",
        methodType: "list"
      }),
      expire: stripeMethod23({
        method: "POST",
        fullPath: "/v1/billing/credit_grants/{id}/expire"
      }),
      voidGrant: stripeMethod23({
        method: "POST",
        fullPath: "/v1/billing/credit_grants/{id}/void"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Treasury/CreditReversals.js
var stripeMethod24, CreditReversals;
var init_CreditReversals = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Treasury/CreditReversals.js"() {
    init_StripeResource();
    stripeMethod24 = StripeResource.method;
    CreditReversals = StripeResource.extend({
      create: stripeMethod24({
        method: "POST",
        fullPath: "/v1/treasury/credit_reversals"
      }),
      retrieve: stripeMethod24({
        method: "GET",
        fullPath: "/v1/treasury/credit_reversals/{credit_reversal}"
      }),
      list: stripeMethod24({
        method: "GET",
        fullPath: "/v1/treasury/credit_reversals",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TestHelpers/Customers.js
var stripeMethod25, Customers;
var init_Customers = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TestHelpers/Customers.js"() {
    init_StripeResource();
    stripeMethod25 = StripeResource.method;
    Customers = StripeResource.extend({
      fundCashBalance: stripeMethod25({
        method: "POST",
        fullPath: "/v1/test_helpers/customers/{customer}/fund_cash_balance"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Treasury/DebitReversals.js
var stripeMethod26, DebitReversals;
var init_DebitReversals = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Treasury/DebitReversals.js"() {
    init_StripeResource();
    stripeMethod26 = StripeResource.method;
    DebitReversals = StripeResource.extend({
      create: stripeMethod26({
        method: "POST",
        fullPath: "/v1/treasury/debit_reversals"
      }),
      retrieve: stripeMethod26({
        method: "GET",
        fullPath: "/v1/treasury/debit_reversals/{debit_reversal}"
      }),
      list: stripeMethod26({
        method: "GET",
        fullPath: "/v1/treasury/debit_reversals",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Issuing/Disputes.js
var stripeMethod27, Disputes;
var init_Disputes = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Issuing/Disputes.js"() {
    init_StripeResource();
    stripeMethod27 = StripeResource.method;
    Disputes = StripeResource.extend({
      create: stripeMethod27({ method: "POST", fullPath: "/v1/issuing/disputes" }),
      retrieve: stripeMethod27({
        method: "GET",
        fullPath: "/v1/issuing/disputes/{dispute}"
      }),
      update: stripeMethod27({
        method: "POST",
        fullPath: "/v1/issuing/disputes/{dispute}"
      }),
      list: stripeMethod27({
        method: "GET",
        fullPath: "/v1/issuing/disputes",
        methodType: "list"
      }),
      submit: stripeMethod27({
        method: "POST",
        fullPath: "/v1/issuing/disputes/{dispute}/submit"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Radar/EarlyFraudWarnings.js
var stripeMethod28, EarlyFraudWarnings;
var init_EarlyFraudWarnings = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Radar/EarlyFraudWarnings.js"() {
    init_StripeResource();
    stripeMethod28 = StripeResource.method;
    EarlyFraudWarnings = StripeResource.extend({
      retrieve: stripeMethod28({
        method: "GET",
        fullPath: "/v1/radar/early_fraud_warnings/{early_fraud_warning}"
      }),
      list: stripeMethod28({
        method: "GET",
        fullPath: "/v1/radar/early_fraud_warnings",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/V2/Core/EventDestinations.js
var stripeMethod29, EventDestinations;
var init_EventDestinations = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/V2/Core/EventDestinations.js"() {
    init_StripeResource();
    stripeMethod29 = StripeResource.method;
    EventDestinations = StripeResource.extend({
      create: stripeMethod29({
        method: "POST",
        fullPath: "/v2/core/event_destinations"
      }),
      retrieve: stripeMethod29({
        method: "GET",
        fullPath: "/v2/core/event_destinations/{id}"
      }),
      update: stripeMethod29({
        method: "POST",
        fullPath: "/v2/core/event_destinations/{id}"
      }),
      list: stripeMethod29({
        method: "GET",
        fullPath: "/v2/core/event_destinations",
        methodType: "list"
      }),
      del: stripeMethod29({
        method: "DELETE",
        fullPath: "/v2/core/event_destinations/{id}"
      }),
      disable: stripeMethod29({
        method: "POST",
        fullPath: "/v2/core/event_destinations/{id}/disable"
      }),
      enable: stripeMethod29({
        method: "POST",
        fullPath: "/v2/core/event_destinations/{id}/enable"
      }),
      ping: stripeMethod29({
        method: "POST",
        fullPath: "/v2/core/event_destinations/{id}/ping"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/V2/Core/Events.js
var stripeMethod30, Events;
var init_Events = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/V2/Core/Events.js"() {
    init_StripeResource();
    stripeMethod30 = StripeResource.method;
    Events = StripeResource.extend({
      retrieve(...args) {
        const transformResponseData = (response) => {
          return this.addFetchRelatedObjectIfNeeded(response);
        };
        return stripeMethod30({
          method: "GET",
          fullPath: "/v2/core/events/{id}",
          transformResponseData
        }).apply(this, args);
      },
      list(...args) {
        const transformResponseData = (response) => {
          return Object.assign(Object.assign({}, response), { data: response.data.map(this.addFetchRelatedObjectIfNeeded.bind(this)) });
        };
        return stripeMethod30({
          method: "GET",
          fullPath: "/v2/core/events",
          methodType: "list",
          transformResponseData
        }).apply(this, args);
      },
      /**
       * @private
       *
       * For internal use in stripe-node.
       *
       * @param pulledEvent The retrieved event object
       * @returns The retrieved event object with a fetchRelatedObject method,
       * if pulledEvent.related_object is valid (non-null and has a url)
       */
      addFetchRelatedObjectIfNeeded(pulledEvent) {
        if (!pulledEvent.related_object || !pulledEvent.related_object.url) {
          return pulledEvent;
        }
        return Object.assign(Object.assign({}, pulledEvent), { fetchRelatedObject: () => (
          // call stripeMethod with 'this' resource to fetch
          // the related object. 'this' is needed to construct
          // and send the request, but the method spec controls
          // the url endpoint and method, so it doesn't matter
          // that 'this' is an Events resource object here
          stripeMethod30({
            method: "GET",
            fullPath: pulledEvent.related_object.url
          }).apply(this, [
            {
              stripeContext: pulledEvent.context,
              headers: {
                "Stripe-Request-Trigger": `event=${pulledEvent.id}`
              }
            }
          ])
        ) });
      }
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Entitlements/Features.js
var stripeMethod31, Features;
var init_Features = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Entitlements/Features.js"() {
    init_StripeResource();
    stripeMethod31 = StripeResource.method;
    Features = StripeResource.extend({
      create: stripeMethod31({ method: "POST", fullPath: "/v1/entitlements/features" }),
      retrieve: stripeMethod31({
        method: "GET",
        fullPath: "/v1/entitlements/features/{id}"
      }),
      update: stripeMethod31({
        method: "POST",
        fullPath: "/v1/entitlements/features/{id}"
      }),
      list: stripeMethod31({
        method: "GET",
        fullPath: "/v1/entitlements/features",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Treasury/FinancialAccounts.js
var stripeMethod32, FinancialAccounts;
var init_FinancialAccounts = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Treasury/FinancialAccounts.js"() {
    init_StripeResource();
    stripeMethod32 = StripeResource.method;
    FinancialAccounts = StripeResource.extend({
      create: stripeMethod32({
        method: "POST",
        fullPath: "/v1/treasury/financial_accounts"
      }),
      retrieve: stripeMethod32({
        method: "GET",
        fullPath: "/v1/treasury/financial_accounts/{financial_account}"
      }),
      update: stripeMethod32({
        method: "POST",
        fullPath: "/v1/treasury/financial_accounts/{financial_account}"
      }),
      list: stripeMethod32({
        method: "GET",
        fullPath: "/v1/treasury/financial_accounts",
        methodType: "list"
      }),
      close: stripeMethod32({
        method: "POST",
        fullPath: "/v1/treasury/financial_accounts/{financial_account}/close"
      }),
      retrieveFeatures: stripeMethod32({
        method: "GET",
        fullPath: "/v1/treasury/financial_accounts/{financial_account}/features"
      }),
      updateFeatures: stripeMethod32({
        method: "POST",
        fullPath: "/v1/treasury/financial_accounts/{financial_account}/features"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TestHelpers/Treasury/InboundTransfers.js
var stripeMethod33, InboundTransfers;
var init_InboundTransfers = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TestHelpers/Treasury/InboundTransfers.js"() {
    init_StripeResource();
    stripeMethod33 = StripeResource.method;
    InboundTransfers = StripeResource.extend({
      fail: stripeMethod33({
        method: "POST",
        fullPath: "/v1/test_helpers/treasury/inbound_transfers/{id}/fail"
      }),
      returnInboundTransfer: stripeMethod33({
        method: "POST",
        fullPath: "/v1/test_helpers/treasury/inbound_transfers/{id}/return"
      }),
      succeed: stripeMethod33({
        method: "POST",
        fullPath: "/v1/test_helpers/treasury/inbound_transfers/{id}/succeed"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Treasury/InboundTransfers.js
var stripeMethod34, InboundTransfers2;
var init_InboundTransfers2 = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Treasury/InboundTransfers.js"() {
    init_StripeResource();
    stripeMethod34 = StripeResource.method;
    InboundTransfers2 = StripeResource.extend({
      create: stripeMethod34({
        method: "POST",
        fullPath: "/v1/treasury/inbound_transfers"
      }),
      retrieve: stripeMethod34({
        method: "GET",
        fullPath: "/v1/treasury/inbound_transfers/{id}"
      }),
      list: stripeMethod34({
        method: "GET",
        fullPath: "/v1/treasury/inbound_transfers",
        methodType: "list"
      }),
      cancel: stripeMethod34({
        method: "POST",
        fullPath: "/v1/treasury/inbound_transfers/{inbound_transfer}/cancel"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Terminal/Locations.js
var stripeMethod35, Locations;
var init_Locations = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Terminal/Locations.js"() {
    init_StripeResource();
    stripeMethod35 = StripeResource.method;
    Locations = StripeResource.extend({
      create: stripeMethod35({ method: "POST", fullPath: "/v1/terminal/locations" }),
      retrieve: stripeMethod35({
        method: "GET",
        fullPath: "/v1/terminal/locations/{location}"
      }),
      update: stripeMethod35({
        method: "POST",
        fullPath: "/v1/terminal/locations/{location}"
      }),
      list: stripeMethod35({
        method: "GET",
        fullPath: "/v1/terminal/locations",
        methodType: "list"
      }),
      del: stripeMethod35({
        method: "DELETE",
        fullPath: "/v1/terminal/locations/{location}"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Billing/MeterEventAdjustments.js
var stripeMethod36, MeterEventAdjustments;
var init_MeterEventAdjustments = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Billing/MeterEventAdjustments.js"() {
    init_StripeResource();
    stripeMethod36 = StripeResource.method;
    MeterEventAdjustments = StripeResource.extend({
      create: stripeMethod36({
        method: "POST",
        fullPath: "/v1/billing/meter_event_adjustments"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/V2/Billing/MeterEventAdjustments.js
var stripeMethod37, MeterEventAdjustments2;
var init_MeterEventAdjustments2 = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/V2/Billing/MeterEventAdjustments.js"() {
    init_StripeResource();
    stripeMethod37 = StripeResource.method;
    MeterEventAdjustments2 = StripeResource.extend({
      create: stripeMethod37({
        method: "POST",
        fullPath: "/v2/billing/meter_event_adjustments"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/V2/Billing/MeterEventSession.js
var stripeMethod38, MeterEventSession;
var init_MeterEventSession = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/V2/Billing/MeterEventSession.js"() {
    init_StripeResource();
    stripeMethod38 = StripeResource.method;
    MeterEventSession = StripeResource.extend({
      create: stripeMethod38({
        method: "POST",
        fullPath: "/v2/billing/meter_event_session"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/V2/Billing/MeterEventStream.js
var stripeMethod39, MeterEventStream;
var init_MeterEventStream = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/V2/Billing/MeterEventStream.js"() {
    init_StripeResource();
    stripeMethod39 = StripeResource.method;
    MeterEventStream = StripeResource.extend({
      create: stripeMethod39({
        method: "POST",
        fullPath: "/v2/billing/meter_event_stream",
        host: "meter-events.stripe.com"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Billing/MeterEvents.js
var stripeMethod40, MeterEvents;
var init_MeterEvents = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Billing/MeterEvents.js"() {
    init_StripeResource();
    stripeMethod40 = StripeResource.method;
    MeterEvents = StripeResource.extend({
      create: stripeMethod40({ method: "POST", fullPath: "/v1/billing/meter_events" })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/V2/Billing/MeterEvents.js
var stripeMethod41, MeterEvents2;
var init_MeterEvents2 = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/V2/Billing/MeterEvents.js"() {
    init_StripeResource();
    stripeMethod41 = StripeResource.method;
    MeterEvents2 = StripeResource.extend({
      create: stripeMethod41({ method: "POST", fullPath: "/v2/billing/meter_events" })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Billing/Meters.js
var stripeMethod42, Meters;
var init_Meters = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Billing/Meters.js"() {
    init_StripeResource();
    stripeMethod42 = StripeResource.method;
    Meters = StripeResource.extend({
      create: stripeMethod42({ method: "POST", fullPath: "/v1/billing/meters" }),
      retrieve: stripeMethod42({ method: "GET", fullPath: "/v1/billing/meters/{id}" }),
      update: stripeMethod42({ method: "POST", fullPath: "/v1/billing/meters/{id}" }),
      list: stripeMethod42({
        method: "GET",
        fullPath: "/v1/billing/meters",
        methodType: "list"
      }),
      deactivate: stripeMethod42({
        method: "POST",
        fullPath: "/v1/billing/meters/{id}/deactivate"
      }),
      listEventSummaries: stripeMethod42({
        method: "GET",
        fullPath: "/v1/billing/meters/{id}/event_summaries",
        methodType: "list"
      }),
      reactivate: stripeMethod42({
        method: "POST",
        fullPath: "/v1/billing/meters/{id}/reactivate"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Terminal/OnboardingLinks.js
var stripeMethod43, OnboardingLinks;
var init_OnboardingLinks = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Terminal/OnboardingLinks.js"() {
    init_StripeResource();
    stripeMethod43 = StripeResource.method;
    OnboardingLinks = StripeResource.extend({
      create: stripeMethod43({
        method: "POST",
        fullPath: "/v1/terminal/onboarding_links"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Climate/Orders.js
var stripeMethod44, Orders;
var init_Orders = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Climate/Orders.js"() {
    init_StripeResource();
    stripeMethod44 = StripeResource.method;
    Orders = StripeResource.extend({
      create: stripeMethod44({ method: "POST", fullPath: "/v1/climate/orders" }),
      retrieve: stripeMethod44({
        method: "GET",
        fullPath: "/v1/climate/orders/{order}"
      }),
      update: stripeMethod44({
        method: "POST",
        fullPath: "/v1/climate/orders/{order}"
      }),
      list: stripeMethod44({
        method: "GET",
        fullPath: "/v1/climate/orders",
        methodType: "list"
      }),
      cancel: stripeMethod44({
        method: "POST",
        fullPath: "/v1/climate/orders/{order}/cancel"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TestHelpers/Treasury/OutboundPayments.js
var stripeMethod45, OutboundPayments;
var init_OutboundPayments = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TestHelpers/Treasury/OutboundPayments.js"() {
    init_StripeResource();
    stripeMethod45 = StripeResource.method;
    OutboundPayments = StripeResource.extend({
      update: stripeMethod45({
        method: "POST",
        fullPath: "/v1/test_helpers/treasury/outbound_payments/{id}"
      }),
      fail: stripeMethod45({
        method: "POST",
        fullPath: "/v1/test_helpers/treasury/outbound_payments/{id}/fail"
      }),
      post: stripeMethod45({
        method: "POST",
        fullPath: "/v1/test_helpers/treasury/outbound_payments/{id}/post"
      }),
      returnOutboundPayment: stripeMethod45({
        method: "POST",
        fullPath: "/v1/test_helpers/treasury/outbound_payments/{id}/return"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Treasury/OutboundPayments.js
var stripeMethod46, OutboundPayments2;
var init_OutboundPayments2 = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Treasury/OutboundPayments.js"() {
    init_StripeResource();
    stripeMethod46 = StripeResource.method;
    OutboundPayments2 = StripeResource.extend({
      create: stripeMethod46({
        method: "POST",
        fullPath: "/v1/treasury/outbound_payments"
      }),
      retrieve: stripeMethod46({
        method: "GET",
        fullPath: "/v1/treasury/outbound_payments/{id}"
      }),
      list: stripeMethod46({
        method: "GET",
        fullPath: "/v1/treasury/outbound_payments",
        methodType: "list"
      }),
      cancel: stripeMethod46({
        method: "POST",
        fullPath: "/v1/treasury/outbound_payments/{id}/cancel"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TestHelpers/Treasury/OutboundTransfers.js
var stripeMethod47, OutboundTransfers;
var init_OutboundTransfers = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TestHelpers/Treasury/OutboundTransfers.js"() {
    init_StripeResource();
    stripeMethod47 = StripeResource.method;
    OutboundTransfers = StripeResource.extend({
      update: stripeMethod47({
        method: "POST",
        fullPath: "/v1/test_helpers/treasury/outbound_transfers/{outbound_transfer}"
      }),
      fail: stripeMethod47({
        method: "POST",
        fullPath: "/v1/test_helpers/treasury/outbound_transfers/{outbound_transfer}/fail"
      }),
      post: stripeMethod47({
        method: "POST",
        fullPath: "/v1/test_helpers/treasury/outbound_transfers/{outbound_transfer}/post"
      }),
      returnOutboundTransfer: stripeMethod47({
        method: "POST",
        fullPath: "/v1/test_helpers/treasury/outbound_transfers/{outbound_transfer}/return"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Treasury/OutboundTransfers.js
var stripeMethod48, OutboundTransfers2;
var init_OutboundTransfers2 = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Treasury/OutboundTransfers.js"() {
    init_StripeResource();
    stripeMethod48 = StripeResource.method;
    OutboundTransfers2 = StripeResource.extend({
      create: stripeMethod48({
        method: "POST",
        fullPath: "/v1/treasury/outbound_transfers"
      }),
      retrieve: stripeMethod48({
        method: "GET",
        fullPath: "/v1/treasury/outbound_transfers/{outbound_transfer}"
      }),
      list: stripeMethod48({
        method: "GET",
        fullPath: "/v1/treasury/outbound_transfers",
        methodType: "list"
      }),
      cancel: stripeMethod48({
        method: "POST",
        fullPath: "/v1/treasury/outbound_transfers/{outbound_transfer}/cancel"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Radar/PaymentEvaluations.js
var stripeMethod49, PaymentEvaluations;
var init_PaymentEvaluations = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Radar/PaymentEvaluations.js"() {
    init_StripeResource();
    stripeMethod49 = StripeResource.method;
    PaymentEvaluations = StripeResource.extend({
      create: stripeMethod49({
        method: "POST",
        fullPath: "/v1/radar/payment_evaluations"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Issuing/PersonalizationDesigns.js
var stripeMethod50, PersonalizationDesigns;
var init_PersonalizationDesigns = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Issuing/PersonalizationDesigns.js"() {
    init_StripeResource();
    stripeMethod50 = StripeResource.method;
    PersonalizationDesigns = StripeResource.extend({
      create: stripeMethod50({
        method: "POST",
        fullPath: "/v1/issuing/personalization_designs"
      }),
      retrieve: stripeMethod50({
        method: "GET",
        fullPath: "/v1/issuing/personalization_designs/{personalization_design}"
      }),
      update: stripeMethod50({
        method: "POST",
        fullPath: "/v1/issuing/personalization_designs/{personalization_design}"
      }),
      list: stripeMethod50({
        method: "GET",
        fullPath: "/v1/issuing/personalization_designs",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TestHelpers/Issuing/PersonalizationDesigns.js
var stripeMethod51, PersonalizationDesigns2;
var init_PersonalizationDesigns2 = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TestHelpers/Issuing/PersonalizationDesigns.js"() {
    init_StripeResource();
    stripeMethod51 = StripeResource.method;
    PersonalizationDesigns2 = StripeResource.extend({
      activate: stripeMethod51({
        method: "POST",
        fullPath: "/v1/test_helpers/issuing/personalization_designs/{personalization_design}/activate"
      }),
      deactivate: stripeMethod51({
        method: "POST",
        fullPath: "/v1/test_helpers/issuing/personalization_designs/{personalization_design}/deactivate"
      }),
      reject: stripeMethod51({
        method: "POST",
        fullPath: "/v1/test_helpers/issuing/personalization_designs/{personalization_design}/reject"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Issuing/PhysicalBundles.js
var stripeMethod52, PhysicalBundles;
var init_PhysicalBundles = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Issuing/PhysicalBundles.js"() {
    init_StripeResource();
    stripeMethod52 = StripeResource.method;
    PhysicalBundles = StripeResource.extend({
      retrieve: stripeMethod52({
        method: "GET",
        fullPath: "/v1/issuing/physical_bundles/{physical_bundle}"
      }),
      list: stripeMethod52({
        method: "GET",
        fullPath: "/v1/issuing/physical_bundles",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Climate/Products.js
var stripeMethod53, Products;
var init_Products = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Climate/Products.js"() {
    init_StripeResource();
    stripeMethod53 = StripeResource.method;
    Products = StripeResource.extend({
      retrieve: stripeMethod53({
        method: "GET",
        fullPath: "/v1/climate/products/{product}"
      }),
      list: stripeMethod53({
        method: "GET",
        fullPath: "/v1/climate/products",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Terminal/Readers.js
var stripeMethod54, Readers;
var init_Readers = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Terminal/Readers.js"() {
    init_StripeResource();
    stripeMethod54 = StripeResource.method;
    Readers = StripeResource.extend({
      create: stripeMethod54({ method: "POST", fullPath: "/v1/terminal/readers" }),
      retrieve: stripeMethod54({
        method: "GET",
        fullPath: "/v1/terminal/readers/{reader}"
      }),
      update: stripeMethod54({
        method: "POST",
        fullPath: "/v1/terminal/readers/{reader}"
      }),
      list: stripeMethod54({
        method: "GET",
        fullPath: "/v1/terminal/readers",
        methodType: "list"
      }),
      del: stripeMethod54({
        method: "DELETE",
        fullPath: "/v1/terminal/readers/{reader}"
      }),
      cancelAction: stripeMethod54({
        method: "POST",
        fullPath: "/v1/terminal/readers/{reader}/cancel_action"
      }),
      collectInputs: stripeMethod54({
        method: "POST",
        fullPath: "/v1/terminal/readers/{reader}/collect_inputs"
      }),
      collectPaymentMethod: stripeMethod54({
        method: "POST",
        fullPath: "/v1/terminal/readers/{reader}/collect_payment_method"
      }),
      confirmPaymentIntent: stripeMethod54({
        method: "POST",
        fullPath: "/v1/terminal/readers/{reader}/confirm_payment_intent"
      }),
      processPaymentIntent: stripeMethod54({
        method: "POST",
        fullPath: "/v1/terminal/readers/{reader}/process_payment_intent"
      }),
      processSetupIntent: stripeMethod54({
        method: "POST",
        fullPath: "/v1/terminal/readers/{reader}/process_setup_intent"
      }),
      refundPayment: stripeMethod54({
        method: "POST",
        fullPath: "/v1/terminal/readers/{reader}/refund_payment"
      }),
      setReaderDisplay: stripeMethod54({
        method: "POST",
        fullPath: "/v1/terminal/readers/{reader}/set_reader_display"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TestHelpers/Terminal/Readers.js
var stripeMethod55, Readers2;
var init_Readers2 = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TestHelpers/Terminal/Readers.js"() {
    init_StripeResource();
    stripeMethod55 = StripeResource.method;
    Readers2 = StripeResource.extend({
      presentPaymentMethod: stripeMethod55({
        method: "POST",
        fullPath: "/v1/test_helpers/terminal/readers/{reader}/present_payment_method"
      }),
      succeedInputCollection: stripeMethod55({
        method: "POST",
        fullPath: "/v1/test_helpers/terminal/readers/{reader}/succeed_input_collection"
      }),
      timeoutInputCollection: stripeMethod55({
        method: "POST",
        fullPath: "/v1/test_helpers/terminal/readers/{reader}/timeout_input_collection"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TestHelpers/Treasury/ReceivedCredits.js
var stripeMethod56, ReceivedCredits;
var init_ReceivedCredits = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TestHelpers/Treasury/ReceivedCredits.js"() {
    init_StripeResource();
    stripeMethod56 = StripeResource.method;
    ReceivedCredits = StripeResource.extend({
      create: stripeMethod56({
        method: "POST",
        fullPath: "/v1/test_helpers/treasury/received_credits"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Treasury/ReceivedCredits.js
var stripeMethod57, ReceivedCredits2;
var init_ReceivedCredits2 = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Treasury/ReceivedCredits.js"() {
    init_StripeResource();
    stripeMethod57 = StripeResource.method;
    ReceivedCredits2 = StripeResource.extend({
      retrieve: stripeMethod57({
        method: "GET",
        fullPath: "/v1/treasury/received_credits/{id}"
      }),
      list: stripeMethod57({
        method: "GET",
        fullPath: "/v1/treasury/received_credits",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TestHelpers/Treasury/ReceivedDebits.js
var stripeMethod58, ReceivedDebits;
var init_ReceivedDebits = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TestHelpers/Treasury/ReceivedDebits.js"() {
    init_StripeResource();
    stripeMethod58 = StripeResource.method;
    ReceivedDebits = StripeResource.extend({
      create: stripeMethod58({
        method: "POST",
        fullPath: "/v1/test_helpers/treasury/received_debits"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Treasury/ReceivedDebits.js
var stripeMethod59, ReceivedDebits2;
var init_ReceivedDebits2 = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Treasury/ReceivedDebits.js"() {
    init_StripeResource();
    stripeMethod59 = StripeResource.method;
    ReceivedDebits2 = StripeResource.extend({
      retrieve: stripeMethod59({
        method: "GET",
        fullPath: "/v1/treasury/received_debits/{id}"
      }),
      list: stripeMethod59({
        method: "GET",
        fullPath: "/v1/treasury/received_debits",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TestHelpers/Refunds.js
var stripeMethod60, Refunds;
var init_Refunds = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TestHelpers/Refunds.js"() {
    init_StripeResource();
    stripeMethod60 = StripeResource.method;
    Refunds = StripeResource.extend({
      expire: stripeMethod60({
        method: "POST",
        fullPath: "/v1/test_helpers/refunds/{refund}/expire"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Tax/Registrations.js
var stripeMethod61, Registrations;
var init_Registrations = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Tax/Registrations.js"() {
    init_StripeResource();
    stripeMethod61 = StripeResource.method;
    Registrations = StripeResource.extend({
      create: stripeMethod61({ method: "POST", fullPath: "/v1/tax/registrations" }),
      retrieve: stripeMethod61({
        method: "GET",
        fullPath: "/v1/tax/registrations/{id}"
      }),
      update: stripeMethod61({
        method: "POST",
        fullPath: "/v1/tax/registrations/{id}"
      }),
      list: stripeMethod61({
        method: "GET",
        fullPath: "/v1/tax/registrations",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Reporting/ReportRuns.js
var stripeMethod62, ReportRuns;
var init_ReportRuns = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Reporting/ReportRuns.js"() {
    init_StripeResource();
    stripeMethod62 = StripeResource.method;
    ReportRuns = StripeResource.extend({
      create: stripeMethod62({ method: "POST", fullPath: "/v1/reporting/report_runs" }),
      retrieve: stripeMethod62({
        method: "GET",
        fullPath: "/v1/reporting/report_runs/{report_run}"
      }),
      list: stripeMethod62({
        method: "GET",
        fullPath: "/v1/reporting/report_runs",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Reporting/ReportTypes.js
var stripeMethod63, ReportTypes;
var init_ReportTypes = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Reporting/ReportTypes.js"() {
    init_StripeResource();
    stripeMethod63 = StripeResource.method;
    ReportTypes = StripeResource.extend({
      retrieve: stripeMethod63({
        method: "GET",
        fullPath: "/v1/reporting/report_types/{report_type}"
      }),
      list: stripeMethod63({
        method: "GET",
        fullPath: "/v1/reporting/report_types",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Forwarding/Requests.js
var stripeMethod64, Requests;
var init_Requests = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Forwarding/Requests.js"() {
    init_StripeResource();
    stripeMethod64 = StripeResource.method;
    Requests = StripeResource.extend({
      create: stripeMethod64({ method: "POST", fullPath: "/v1/forwarding/requests" }),
      retrieve: stripeMethod64({
        method: "GET",
        fullPath: "/v1/forwarding/requests/{id}"
      }),
      list: stripeMethod64({
        method: "GET",
        fullPath: "/v1/forwarding/requests",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Sigma/ScheduledQueryRuns.js
var stripeMethod65, ScheduledQueryRuns;
var init_ScheduledQueryRuns = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Sigma/ScheduledQueryRuns.js"() {
    init_StripeResource();
    stripeMethod65 = StripeResource.method;
    ScheduledQueryRuns = StripeResource.extend({
      retrieve: stripeMethod65({
        method: "GET",
        fullPath: "/v1/sigma/scheduled_query_runs/{scheduled_query_run}"
      }),
      list: stripeMethod65({
        method: "GET",
        fullPath: "/v1/sigma/scheduled_query_runs",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Apps/Secrets.js
var stripeMethod66, Secrets;
var init_Secrets = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Apps/Secrets.js"() {
    init_StripeResource();
    stripeMethod66 = StripeResource.method;
    Secrets = StripeResource.extend({
      create: stripeMethod66({ method: "POST", fullPath: "/v1/apps/secrets" }),
      list: stripeMethod66({
        method: "GET",
        fullPath: "/v1/apps/secrets",
        methodType: "list"
      }),
      deleteWhere: stripeMethod66({
        method: "POST",
        fullPath: "/v1/apps/secrets/delete"
      }),
      find: stripeMethod66({ method: "GET", fullPath: "/v1/apps/secrets/find" })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/BillingPortal/Sessions.js
var stripeMethod67, Sessions;
var init_Sessions = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/BillingPortal/Sessions.js"() {
    init_StripeResource();
    stripeMethod67 = StripeResource.method;
    Sessions = StripeResource.extend({
      create: stripeMethod67({
        method: "POST",
        fullPath: "/v1/billing_portal/sessions"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Checkout/Sessions.js
var stripeMethod68, Sessions2;
var init_Sessions2 = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Checkout/Sessions.js"() {
    init_StripeResource();
    stripeMethod68 = StripeResource.method;
    Sessions2 = StripeResource.extend({
      create: stripeMethod68({ method: "POST", fullPath: "/v1/checkout/sessions" }),
      retrieve: stripeMethod68({
        method: "GET",
        fullPath: "/v1/checkout/sessions/{session}"
      }),
      update: stripeMethod68({
        method: "POST",
        fullPath: "/v1/checkout/sessions/{session}"
      }),
      list: stripeMethod68({
        method: "GET",
        fullPath: "/v1/checkout/sessions",
        methodType: "list"
      }),
      expire: stripeMethod68({
        method: "POST",
        fullPath: "/v1/checkout/sessions/{session}/expire"
      }),
      listLineItems: stripeMethod68({
        method: "GET",
        fullPath: "/v1/checkout/sessions/{session}/line_items",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/FinancialConnections/Sessions.js
var stripeMethod69, Sessions3;
var init_Sessions3 = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/FinancialConnections/Sessions.js"() {
    init_StripeResource();
    stripeMethod69 = StripeResource.method;
    Sessions3 = StripeResource.extend({
      create: stripeMethod69({
        method: "POST",
        fullPath: "/v1/financial_connections/sessions"
      }),
      retrieve: stripeMethod69({
        method: "GET",
        fullPath: "/v1/financial_connections/sessions/{session}"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Tax/Settings.js
var stripeMethod70, Settings;
var init_Settings = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Tax/Settings.js"() {
    init_StripeResource();
    stripeMethod70 = StripeResource.method;
    Settings = StripeResource.extend({
      retrieve: stripeMethod70({ method: "GET", fullPath: "/v1/tax/settings" }),
      update: stripeMethod70({ method: "POST", fullPath: "/v1/tax/settings" })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Climate/Suppliers.js
var stripeMethod71, Suppliers;
var init_Suppliers = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Climate/Suppliers.js"() {
    init_StripeResource();
    stripeMethod71 = StripeResource.method;
    Suppliers = StripeResource.extend({
      retrieve: stripeMethod71({
        method: "GET",
        fullPath: "/v1/climate/suppliers/{supplier}"
      }),
      list: stripeMethod71({
        method: "GET",
        fullPath: "/v1/climate/suppliers",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TestHelpers/TestClocks.js
var stripeMethod72, TestClocks;
var init_TestClocks = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TestHelpers/TestClocks.js"() {
    init_StripeResource();
    stripeMethod72 = StripeResource.method;
    TestClocks = StripeResource.extend({
      create: stripeMethod72({
        method: "POST",
        fullPath: "/v1/test_helpers/test_clocks"
      }),
      retrieve: stripeMethod72({
        method: "GET",
        fullPath: "/v1/test_helpers/test_clocks/{test_clock}"
      }),
      list: stripeMethod72({
        method: "GET",
        fullPath: "/v1/test_helpers/test_clocks",
        methodType: "list"
      }),
      del: stripeMethod72({
        method: "DELETE",
        fullPath: "/v1/test_helpers/test_clocks/{test_clock}"
      }),
      advance: stripeMethod72({
        method: "POST",
        fullPath: "/v1/test_helpers/test_clocks/{test_clock}/advance"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Issuing/Tokens.js
var stripeMethod73, Tokens;
var init_Tokens = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Issuing/Tokens.js"() {
    init_StripeResource();
    stripeMethod73 = StripeResource.method;
    Tokens = StripeResource.extend({
      retrieve: stripeMethod73({
        method: "GET",
        fullPath: "/v1/issuing/tokens/{token}"
      }),
      update: stripeMethod73({
        method: "POST",
        fullPath: "/v1/issuing/tokens/{token}"
      }),
      list: stripeMethod73({
        method: "GET",
        fullPath: "/v1/issuing/tokens",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Treasury/TransactionEntries.js
var stripeMethod74, TransactionEntries;
var init_TransactionEntries = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Treasury/TransactionEntries.js"() {
    init_StripeResource();
    stripeMethod74 = StripeResource.method;
    TransactionEntries = StripeResource.extend({
      retrieve: stripeMethod74({
        method: "GET",
        fullPath: "/v1/treasury/transaction_entries/{id}"
      }),
      list: stripeMethod74({
        method: "GET",
        fullPath: "/v1/treasury/transaction_entries",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/FinancialConnections/Transactions.js
var stripeMethod75, Transactions;
var init_Transactions = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/FinancialConnections/Transactions.js"() {
    init_StripeResource();
    stripeMethod75 = StripeResource.method;
    Transactions = StripeResource.extend({
      retrieve: stripeMethod75({
        method: "GET",
        fullPath: "/v1/financial_connections/transactions/{transaction}"
      }),
      list: stripeMethod75({
        method: "GET",
        fullPath: "/v1/financial_connections/transactions",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Issuing/Transactions.js
var stripeMethod76, Transactions2;
var init_Transactions2 = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Issuing/Transactions.js"() {
    init_StripeResource();
    stripeMethod76 = StripeResource.method;
    Transactions2 = StripeResource.extend({
      retrieve: stripeMethod76({
        method: "GET",
        fullPath: "/v1/issuing/transactions/{transaction}"
      }),
      update: stripeMethod76({
        method: "POST",
        fullPath: "/v1/issuing/transactions/{transaction}"
      }),
      list: stripeMethod76({
        method: "GET",
        fullPath: "/v1/issuing/transactions",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Tax/Transactions.js
var stripeMethod77, Transactions3;
var init_Transactions3 = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Tax/Transactions.js"() {
    init_StripeResource();
    stripeMethod77 = StripeResource.method;
    Transactions3 = StripeResource.extend({
      retrieve: stripeMethod77({
        method: "GET",
        fullPath: "/v1/tax/transactions/{transaction}"
      }),
      createFromCalculation: stripeMethod77({
        method: "POST",
        fullPath: "/v1/tax/transactions/create_from_calculation"
      }),
      createReversal: stripeMethod77({
        method: "POST",
        fullPath: "/v1/tax/transactions/create_reversal"
      }),
      listLineItems: stripeMethod77({
        method: "GET",
        fullPath: "/v1/tax/transactions/{transaction}/line_items",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TestHelpers/Issuing/Transactions.js
var stripeMethod78, Transactions4;
var init_Transactions4 = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TestHelpers/Issuing/Transactions.js"() {
    init_StripeResource();
    stripeMethod78 = StripeResource.method;
    Transactions4 = StripeResource.extend({
      createForceCapture: stripeMethod78({
        method: "POST",
        fullPath: "/v1/test_helpers/issuing/transactions/create_force_capture"
      }),
      createUnlinkedRefund: stripeMethod78({
        method: "POST",
        fullPath: "/v1/test_helpers/issuing/transactions/create_unlinked_refund"
      }),
      refund: stripeMethod78({
        method: "POST",
        fullPath: "/v1/test_helpers/issuing/transactions/{transaction}/refund"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Treasury/Transactions.js
var stripeMethod79, Transactions5;
var init_Transactions5 = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Treasury/Transactions.js"() {
    init_StripeResource();
    stripeMethod79 = StripeResource.method;
    Transactions5 = StripeResource.extend({
      retrieve: stripeMethod79({
        method: "GET",
        fullPath: "/v1/treasury/transactions/{id}"
      }),
      list: stripeMethod79({
        method: "GET",
        fullPath: "/v1/treasury/transactions",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Radar/ValueListItems.js
var stripeMethod80, ValueListItems;
var init_ValueListItems = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Radar/ValueListItems.js"() {
    init_StripeResource();
    stripeMethod80 = StripeResource.method;
    ValueListItems = StripeResource.extend({
      create: stripeMethod80({
        method: "POST",
        fullPath: "/v1/radar/value_list_items"
      }),
      retrieve: stripeMethod80({
        method: "GET",
        fullPath: "/v1/radar/value_list_items/{item}"
      }),
      list: stripeMethod80({
        method: "GET",
        fullPath: "/v1/radar/value_list_items",
        methodType: "list"
      }),
      del: stripeMethod80({
        method: "DELETE",
        fullPath: "/v1/radar/value_list_items/{item}"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Radar/ValueLists.js
var stripeMethod81, ValueLists;
var init_ValueLists = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Radar/ValueLists.js"() {
    init_StripeResource();
    stripeMethod81 = StripeResource.method;
    ValueLists = StripeResource.extend({
      create: stripeMethod81({ method: "POST", fullPath: "/v1/radar/value_lists" }),
      retrieve: stripeMethod81({
        method: "GET",
        fullPath: "/v1/radar/value_lists/{value_list}"
      }),
      update: stripeMethod81({
        method: "POST",
        fullPath: "/v1/radar/value_lists/{value_list}"
      }),
      list: stripeMethod81({
        method: "GET",
        fullPath: "/v1/radar/value_lists",
        methodType: "list"
      }),
      del: stripeMethod81({
        method: "DELETE",
        fullPath: "/v1/radar/value_lists/{value_list}"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Identity/VerificationReports.js
var stripeMethod82, VerificationReports;
var init_VerificationReports = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Identity/VerificationReports.js"() {
    init_StripeResource();
    stripeMethod82 = StripeResource.method;
    VerificationReports = StripeResource.extend({
      retrieve: stripeMethod82({
        method: "GET",
        fullPath: "/v1/identity/verification_reports/{report}"
      }),
      list: stripeMethod82({
        method: "GET",
        fullPath: "/v1/identity/verification_reports",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Identity/VerificationSessions.js
var stripeMethod83, VerificationSessions;
var init_VerificationSessions = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Identity/VerificationSessions.js"() {
    init_StripeResource();
    stripeMethod83 = StripeResource.method;
    VerificationSessions = StripeResource.extend({
      create: stripeMethod83({
        method: "POST",
        fullPath: "/v1/identity/verification_sessions"
      }),
      retrieve: stripeMethod83({
        method: "GET",
        fullPath: "/v1/identity/verification_sessions/{session}"
      }),
      update: stripeMethod83({
        method: "POST",
        fullPath: "/v1/identity/verification_sessions/{session}"
      }),
      list: stripeMethod83({
        method: "GET",
        fullPath: "/v1/identity/verification_sessions",
        methodType: "list"
      }),
      cancel: stripeMethod83({
        method: "POST",
        fullPath: "/v1/identity/verification_sessions/{session}/cancel"
      }),
      redact: stripeMethod83({
        method: "POST",
        fullPath: "/v1/identity/verification_sessions/{session}/redact"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Accounts.js
var stripeMethod84, Accounts3;
var init_Accounts3 = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Accounts.js"() {
    init_StripeResource();
    stripeMethod84 = StripeResource.method;
    Accounts3 = StripeResource.extend({
      create: stripeMethod84({ method: "POST", fullPath: "/v1/accounts" }),
      retrieve(id, ...args) {
        if (typeof id === "string") {
          return stripeMethod84({
            method: "GET",
            fullPath: "/v1/accounts/{id}"
          }).apply(this, [id, ...args]);
        } else {
          if (id === null || id === void 0) {
            [].shift.apply([id, ...args]);
          }
          return stripeMethod84({
            method: "GET",
            fullPath: "/v1/account"
          }).apply(this, [id, ...args]);
        }
      },
      update: stripeMethod84({ method: "POST", fullPath: "/v1/accounts/{account}" }),
      list: stripeMethod84({
        method: "GET",
        fullPath: "/v1/accounts",
        methodType: "list"
      }),
      del: stripeMethod84({ method: "DELETE", fullPath: "/v1/accounts/{account}" }),
      createExternalAccount: stripeMethod84({
        method: "POST",
        fullPath: "/v1/accounts/{account}/external_accounts"
      }),
      createLoginLink: stripeMethod84({
        method: "POST",
        fullPath: "/v1/accounts/{account}/login_links"
      }),
      createPerson: stripeMethod84({
        method: "POST",
        fullPath: "/v1/accounts/{account}/persons"
      }),
      deleteExternalAccount: stripeMethod84({
        method: "DELETE",
        fullPath: "/v1/accounts/{account}/external_accounts/{id}"
      }),
      deletePerson: stripeMethod84({
        method: "DELETE",
        fullPath: "/v1/accounts/{account}/persons/{person}"
      }),
      listCapabilities: stripeMethod84({
        method: "GET",
        fullPath: "/v1/accounts/{account}/capabilities",
        methodType: "list"
      }),
      listExternalAccounts: stripeMethod84({
        method: "GET",
        fullPath: "/v1/accounts/{account}/external_accounts",
        methodType: "list"
      }),
      listPersons: stripeMethod84({
        method: "GET",
        fullPath: "/v1/accounts/{account}/persons",
        methodType: "list"
      }),
      reject: stripeMethod84({
        method: "POST",
        fullPath: "/v1/accounts/{account}/reject"
      }),
      retrieveCurrent: stripeMethod84({ method: "GET", fullPath: "/v1/account" }),
      retrieveCapability: stripeMethod84({
        method: "GET",
        fullPath: "/v1/accounts/{account}/capabilities/{capability}"
      }),
      retrieveExternalAccount: stripeMethod84({
        method: "GET",
        fullPath: "/v1/accounts/{account}/external_accounts/{id}"
      }),
      retrievePerson: stripeMethod84({
        method: "GET",
        fullPath: "/v1/accounts/{account}/persons/{person}"
      }),
      updateCapability: stripeMethod84({
        method: "POST",
        fullPath: "/v1/accounts/{account}/capabilities/{capability}"
      }),
      updateExternalAccount: stripeMethod84({
        method: "POST",
        fullPath: "/v1/accounts/{account}/external_accounts/{id}"
      }),
      updatePerson: stripeMethod84({
        method: "POST",
        fullPath: "/v1/accounts/{account}/persons/{person}"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/AccountLinks.js
var stripeMethod85, AccountLinks2;
var init_AccountLinks2 = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/AccountLinks.js"() {
    init_StripeResource();
    stripeMethod85 = StripeResource.method;
    AccountLinks2 = StripeResource.extend({
      create: stripeMethod85({ method: "POST", fullPath: "/v1/account_links" })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/AccountSessions.js
var stripeMethod86, AccountSessions;
var init_AccountSessions = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/AccountSessions.js"() {
    init_StripeResource();
    stripeMethod86 = StripeResource.method;
    AccountSessions = StripeResource.extend({
      create: stripeMethod86({ method: "POST", fullPath: "/v1/account_sessions" })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/ApplePayDomains.js
var stripeMethod87, ApplePayDomains;
var init_ApplePayDomains = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/ApplePayDomains.js"() {
    init_StripeResource();
    stripeMethod87 = StripeResource.method;
    ApplePayDomains = StripeResource.extend({
      create: stripeMethod87({ method: "POST", fullPath: "/v1/apple_pay/domains" }),
      retrieve: stripeMethod87({
        method: "GET",
        fullPath: "/v1/apple_pay/domains/{domain}"
      }),
      list: stripeMethod87({
        method: "GET",
        fullPath: "/v1/apple_pay/domains",
        methodType: "list"
      }),
      del: stripeMethod87({
        method: "DELETE",
        fullPath: "/v1/apple_pay/domains/{domain}"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/ApplicationFees.js
var stripeMethod88, ApplicationFees;
var init_ApplicationFees = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/ApplicationFees.js"() {
    init_StripeResource();
    stripeMethod88 = StripeResource.method;
    ApplicationFees = StripeResource.extend({
      retrieve: stripeMethod88({
        method: "GET",
        fullPath: "/v1/application_fees/{id}"
      }),
      list: stripeMethod88({
        method: "GET",
        fullPath: "/v1/application_fees",
        methodType: "list"
      }),
      createRefund: stripeMethod88({
        method: "POST",
        fullPath: "/v1/application_fees/{id}/refunds"
      }),
      listRefunds: stripeMethod88({
        method: "GET",
        fullPath: "/v1/application_fees/{id}/refunds",
        methodType: "list"
      }),
      retrieveRefund: stripeMethod88({
        method: "GET",
        fullPath: "/v1/application_fees/{fee}/refunds/{id}"
      }),
      updateRefund: stripeMethod88({
        method: "POST",
        fullPath: "/v1/application_fees/{fee}/refunds/{id}"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Balance.js
var stripeMethod89, Balance;
var init_Balance = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Balance.js"() {
    init_StripeResource();
    stripeMethod89 = StripeResource.method;
    Balance = StripeResource.extend({
      retrieve: stripeMethod89({ method: "GET", fullPath: "/v1/balance" })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/BalanceSettings.js
var stripeMethod90, BalanceSettings;
var init_BalanceSettings = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/BalanceSettings.js"() {
    init_StripeResource();
    stripeMethod90 = StripeResource.method;
    BalanceSettings = StripeResource.extend({
      retrieve: stripeMethod90({ method: "GET", fullPath: "/v1/balance_settings" }),
      update: stripeMethod90({ method: "POST", fullPath: "/v1/balance_settings" })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/BalanceTransactions.js
var stripeMethod91, BalanceTransactions;
var init_BalanceTransactions = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/BalanceTransactions.js"() {
    init_StripeResource();
    stripeMethod91 = StripeResource.method;
    BalanceTransactions = StripeResource.extend({
      retrieve: stripeMethod91({
        method: "GET",
        fullPath: "/v1/balance_transactions/{id}"
      }),
      list: stripeMethod91({
        method: "GET",
        fullPath: "/v1/balance_transactions",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Charges.js
var stripeMethod92, Charges;
var init_Charges = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Charges.js"() {
    init_StripeResource();
    stripeMethod92 = StripeResource.method;
    Charges = StripeResource.extend({
      create: stripeMethod92({ method: "POST", fullPath: "/v1/charges" }),
      retrieve: stripeMethod92({ method: "GET", fullPath: "/v1/charges/{charge}" }),
      update: stripeMethod92({ method: "POST", fullPath: "/v1/charges/{charge}" }),
      list: stripeMethod92({
        method: "GET",
        fullPath: "/v1/charges",
        methodType: "list"
      }),
      capture: stripeMethod92({
        method: "POST",
        fullPath: "/v1/charges/{charge}/capture"
      }),
      search: stripeMethod92({
        method: "GET",
        fullPath: "/v1/charges/search",
        methodType: "search"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/ConfirmationTokens.js
var stripeMethod93, ConfirmationTokens2;
var init_ConfirmationTokens2 = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/ConfirmationTokens.js"() {
    init_StripeResource();
    stripeMethod93 = StripeResource.method;
    ConfirmationTokens2 = StripeResource.extend({
      retrieve: stripeMethod93({
        method: "GET",
        fullPath: "/v1/confirmation_tokens/{confirmation_token}"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/CountrySpecs.js
var stripeMethod94, CountrySpecs;
var init_CountrySpecs = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/CountrySpecs.js"() {
    init_StripeResource();
    stripeMethod94 = StripeResource.method;
    CountrySpecs = StripeResource.extend({
      retrieve: stripeMethod94({
        method: "GET",
        fullPath: "/v1/country_specs/{country}"
      }),
      list: stripeMethod94({
        method: "GET",
        fullPath: "/v1/country_specs",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Coupons.js
var stripeMethod95, Coupons;
var init_Coupons = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Coupons.js"() {
    init_StripeResource();
    stripeMethod95 = StripeResource.method;
    Coupons = StripeResource.extend({
      create: stripeMethod95({ method: "POST", fullPath: "/v1/coupons" }),
      retrieve: stripeMethod95({ method: "GET", fullPath: "/v1/coupons/{coupon}" }),
      update: stripeMethod95({ method: "POST", fullPath: "/v1/coupons/{coupon}" }),
      list: stripeMethod95({
        method: "GET",
        fullPath: "/v1/coupons",
        methodType: "list"
      }),
      del: stripeMethod95({ method: "DELETE", fullPath: "/v1/coupons/{coupon}" })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/CreditNotes.js
var stripeMethod96, CreditNotes;
var init_CreditNotes = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/CreditNotes.js"() {
    init_StripeResource();
    stripeMethod96 = StripeResource.method;
    CreditNotes = StripeResource.extend({
      create: stripeMethod96({ method: "POST", fullPath: "/v1/credit_notes" }),
      retrieve: stripeMethod96({ method: "GET", fullPath: "/v1/credit_notes/{id}" }),
      update: stripeMethod96({ method: "POST", fullPath: "/v1/credit_notes/{id}" }),
      list: stripeMethod96({
        method: "GET",
        fullPath: "/v1/credit_notes",
        methodType: "list"
      }),
      listLineItems: stripeMethod96({
        method: "GET",
        fullPath: "/v1/credit_notes/{credit_note}/lines",
        methodType: "list"
      }),
      listPreviewLineItems: stripeMethod96({
        method: "GET",
        fullPath: "/v1/credit_notes/preview/lines",
        methodType: "list"
      }),
      preview: stripeMethod96({ method: "GET", fullPath: "/v1/credit_notes/preview" }),
      voidCreditNote: stripeMethod96({
        method: "POST",
        fullPath: "/v1/credit_notes/{id}/void"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/CustomerSessions.js
var stripeMethod97, CustomerSessions;
var init_CustomerSessions = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/CustomerSessions.js"() {
    init_StripeResource();
    stripeMethod97 = StripeResource.method;
    CustomerSessions = StripeResource.extend({
      create: stripeMethod97({ method: "POST", fullPath: "/v1/customer_sessions" })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Customers.js
var stripeMethod98, Customers2;
var init_Customers2 = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Customers.js"() {
    init_StripeResource();
    stripeMethod98 = StripeResource.method;
    Customers2 = StripeResource.extend({
      create: stripeMethod98({ method: "POST", fullPath: "/v1/customers" }),
      retrieve: stripeMethod98({ method: "GET", fullPath: "/v1/customers/{customer}" }),
      update: stripeMethod98({ method: "POST", fullPath: "/v1/customers/{customer}" }),
      list: stripeMethod98({
        method: "GET",
        fullPath: "/v1/customers",
        methodType: "list"
      }),
      del: stripeMethod98({ method: "DELETE", fullPath: "/v1/customers/{customer}" }),
      createBalanceTransaction: stripeMethod98({
        method: "POST",
        fullPath: "/v1/customers/{customer}/balance_transactions"
      }),
      createFundingInstructions: stripeMethod98({
        method: "POST",
        fullPath: "/v1/customers/{customer}/funding_instructions"
      }),
      createSource: stripeMethod98({
        method: "POST",
        fullPath: "/v1/customers/{customer}/sources"
      }),
      createTaxId: stripeMethod98({
        method: "POST",
        fullPath: "/v1/customers/{customer}/tax_ids"
      }),
      deleteDiscount: stripeMethod98({
        method: "DELETE",
        fullPath: "/v1/customers/{customer}/discount"
      }),
      deleteSource: stripeMethod98({
        method: "DELETE",
        fullPath: "/v1/customers/{customer}/sources/{id}"
      }),
      deleteTaxId: stripeMethod98({
        method: "DELETE",
        fullPath: "/v1/customers/{customer}/tax_ids/{id}"
      }),
      listBalanceTransactions: stripeMethod98({
        method: "GET",
        fullPath: "/v1/customers/{customer}/balance_transactions",
        methodType: "list"
      }),
      listCashBalanceTransactions: stripeMethod98({
        method: "GET",
        fullPath: "/v1/customers/{customer}/cash_balance_transactions",
        methodType: "list"
      }),
      listPaymentMethods: stripeMethod98({
        method: "GET",
        fullPath: "/v1/customers/{customer}/payment_methods",
        methodType: "list"
      }),
      listSources: stripeMethod98({
        method: "GET",
        fullPath: "/v1/customers/{customer}/sources",
        methodType: "list"
      }),
      listTaxIds: stripeMethod98({
        method: "GET",
        fullPath: "/v1/customers/{customer}/tax_ids",
        methodType: "list"
      }),
      retrieveBalanceTransaction: stripeMethod98({
        method: "GET",
        fullPath: "/v1/customers/{customer}/balance_transactions/{transaction}"
      }),
      retrieveCashBalance: stripeMethod98({
        method: "GET",
        fullPath: "/v1/customers/{customer}/cash_balance"
      }),
      retrieveCashBalanceTransaction: stripeMethod98({
        method: "GET",
        fullPath: "/v1/customers/{customer}/cash_balance_transactions/{transaction}"
      }),
      retrievePaymentMethod: stripeMethod98({
        method: "GET",
        fullPath: "/v1/customers/{customer}/payment_methods/{payment_method}"
      }),
      retrieveSource: stripeMethod98({
        method: "GET",
        fullPath: "/v1/customers/{customer}/sources/{id}"
      }),
      retrieveTaxId: stripeMethod98({
        method: "GET",
        fullPath: "/v1/customers/{customer}/tax_ids/{id}"
      }),
      search: stripeMethod98({
        method: "GET",
        fullPath: "/v1/customers/search",
        methodType: "search"
      }),
      updateBalanceTransaction: stripeMethod98({
        method: "POST",
        fullPath: "/v1/customers/{customer}/balance_transactions/{transaction}"
      }),
      updateCashBalance: stripeMethod98({
        method: "POST",
        fullPath: "/v1/customers/{customer}/cash_balance"
      }),
      updateSource: stripeMethod98({
        method: "POST",
        fullPath: "/v1/customers/{customer}/sources/{id}"
      }),
      verifySource: stripeMethod98({
        method: "POST",
        fullPath: "/v1/customers/{customer}/sources/{id}/verify"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Disputes.js
var stripeMethod99, Disputes2;
var init_Disputes2 = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Disputes.js"() {
    init_StripeResource();
    stripeMethod99 = StripeResource.method;
    Disputes2 = StripeResource.extend({
      retrieve: stripeMethod99({ method: "GET", fullPath: "/v1/disputes/{dispute}" }),
      update: stripeMethod99({ method: "POST", fullPath: "/v1/disputes/{dispute}" }),
      list: stripeMethod99({
        method: "GET",
        fullPath: "/v1/disputes",
        methodType: "list"
      }),
      close: stripeMethod99({
        method: "POST",
        fullPath: "/v1/disputes/{dispute}/close"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/EphemeralKeys.js
var stripeMethod100, EphemeralKeys;
var init_EphemeralKeys = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/EphemeralKeys.js"() {
    init_StripeResource();
    stripeMethod100 = StripeResource.method;
    EphemeralKeys = StripeResource.extend({
      create: stripeMethod100({
        method: "POST",
        fullPath: "/v1/ephemeral_keys",
        validator: (data, options) => {
          if (!options.headers || !options.headers["Stripe-Version"]) {
            throw new Error("Passing apiVersion in a separate options hash is required to create an ephemeral key. See https://stripe.com/docs/api/versioning?lang=node");
          }
        }
      }),
      del: stripeMethod100({ method: "DELETE", fullPath: "/v1/ephemeral_keys/{key}" })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Events.js
var stripeMethod101, Events2;
var init_Events2 = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Events.js"() {
    init_StripeResource();
    stripeMethod101 = StripeResource.method;
    Events2 = StripeResource.extend({
      retrieve: stripeMethod101({ method: "GET", fullPath: "/v1/events/{id}" }),
      list: stripeMethod101({
        method: "GET",
        fullPath: "/v1/events",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/ExchangeRates.js
var stripeMethod102, ExchangeRates;
var init_ExchangeRates = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/ExchangeRates.js"() {
    init_StripeResource();
    stripeMethod102 = StripeResource.method;
    ExchangeRates = StripeResource.extend({
      retrieve: stripeMethod102({
        method: "GET",
        fullPath: "/v1/exchange_rates/{rate_id}"
      }),
      list: stripeMethod102({
        method: "GET",
        fullPath: "/v1/exchange_rates",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/FileLinks.js
var stripeMethod103, FileLinks;
var init_FileLinks = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/FileLinks.js"() {
    init_StripeResource();
    stripeMethod103 = StripeResource.method;
    FileLinks = StripeResource.extend({
      create: stripeMethod103({ method: "POST", fullPath: "/v1/file_links" }),
      retrieve: stripeMethod103({ method: "GET", fullPath: "/v1/file_links/{link}" }),
      update: stripeMethod103({ method: "POST", fullPath: "/v1/file_links/{link}" }),
      list: stripeMethod103({
        method: "GET",
        fullPath: "/v1/file_links",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/multipart.js
function multipartRequestDataProcessor(method, data, headers, callback) {
  data = data || {};
  if (method !== "POST") {
    return callback(null, queryStringifyRequestData(data));
  }
  this._stripe._platformFunctions.tryBufferData(data).then((bufferedData) => {
    const buffer = multipartDataGenerator(method, bufferedData, headers);
    return callback(null, buffer);
  }).catch((err) => callback(err, null));
}
var multipartDataGenerator;
var init_multipart = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/multipart.js"() {
    init_utils5();
    multipartDataGenerator = (method, data, headers) => {
      const segno = (Math.round(Math.random() * 1e16) + Math.round(Math.random() * 1e16)).toString();
      headers["Content-Type"] = `multipart/form-data; boundary=${segno}`;
      const textEncoder = new TextEncoder();
      let buffer = new Uint8Array(0);
      const endBuffer = textEncoder.encode("\r\n");
      function push(l) {
        const prevBuffer = buffer;
        const newBuffer = l instanceof Uint8Array ? l : new Uint8Array(textEncoder.encode(l));
        buffer = new Uint8Array(prevBuffer.length + newBuffer.length + 2);
        buffer.set(prevBuffer);
        buffer.set(newBuffer, prevBuffer.length);
        buffer.set(endBuffer, buffer.length - 2);
      }
      function q(s) {
        return `"${s.replace(/"|"/g, "%22").replace(/\r\n|\r|\n/g, " ")}"`;
      }
      const flattenedData = flattenAndStringify(data);
      for (const k in flattenedData) {
        if (!Object.prototype.hasOwnProperty.call(flattenedData, k)) {
          continue;
        }
        const v = flattenedData[k];
        push(`--${segno}`);
        if (Object.prototype.hasOwnProperty.call(v, "data")) {
          const typedEntry = v;
          push(`Content-Disposition: form-data; name=${q(k)}; filename=${q(typedEntry.name || "blob")}`);
          push(`Content-Type: ${typedEntry.type || "application/octet-stream"}`);
          push("");
          push(typedEntry.data);
        } else {
          push(`Content-Disposition: form-data; name=${q(k)}`);
          push("");
          push(v);
        }
      }
      push(`--${segno}--`);
      return buffer;
    };
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Files.js
var stripeMethod104, Files;
var init_Files = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Files.js"() {
    init_multipart();
    init_StripeResource();
    stripeMethod104 = StripeResource.method;
    Files = StripeResource.extend({
      create: stripeMethod104({
        method: "POST",
        fullPath: "/v1/files",
        headers: {
          "Content-Type": "multipart/form-data"
        },
        host: "files.stripe.com"
      }),
      retrieve: stripeMethod104({ method: "GET", fullPath: "/v1/files/{file}" }),
      list: stripeMethod104({
        method: "GET",
        fullPath: "/v1/files",
        methodType: "list"
      }),
      requestDataProcessor: multipartRequestDataProcessor
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/InvoiceItems.js
var stripeMethod105, InvoiceItems;
var init_InvoiceItems = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/InvoiceItems.js"() {
    init_StripeResource();
    stripeMethod105 = StripeResource.method;
    InvoiceItems = StripeResource.extend({
      create: stripeMethod105({ method: "POST", fullPath: "/v1/invoiceitems" }),
      retrieve: stripeMethod105({
        method: "GET",
        fullPath: "/v1/invoiceitems/{invoiceitem}"
      }),
      update: stripeMethod105({
        method: "POST",
        fullPath: "/v1/invoiceitems/{invoiceitem}"
      }),
      list: stripeMethod105({
        method: "GET",
        fullPath: "/v1/invoiceitems",
        methodType: "list"
      }),
      del: stripeMethod105({
        method: "DELETE",
        fullPath: "/v1/invoiceitems/{invoiceitem}"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/InvoicePayments.js
var stripeMethod106, InvoicePayments;
var init_InvoicePayments = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/InvoicePayments.js"() {
    init_StripeResource();
    stripeMethod106 = StripeResource.method;
    InvoicePayments = StripeResource.extend({
      retrieve: stripeMethod106({
        method: "GET",
        fullPath: "/v1/invoice_payments/{invoice_payment}"
      }),
      list: stripeMethod106({
        method: "GET",
        fullPath: "/v1/invoice_payments",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/InvoiceRenderingTemplates.js
var stripeMethod107, InvoiceRenderingTemplates;
var init_InvoiceRenderingTemplates = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/InvoiceRenderingTemplates.js"() {
    init_StripeResource();
    stripeMethod107 = StripeResource.method;
    InvoiceRenderingTemplates = StripeResource.extend({
      retrieve: stripeMethod107({
        method: "GET",
        fullPath: "/v1/invoice_rendering_templates/{template}"
      }),
      list: stripeMethod107({
        method: "GET",
        fullPath: "/v1/invoice_rendering_templates",
        methodType: "list"
      }),
      archive: stripeMethod107({
        method: "POST",
        fullPath: "/v1/invoice_rendering_templates/{template}/archive"
      }),
      unarchive: stripeMethod107({
        method: "POST",
        fullPath: "/v1/invoice_rendering_templates/{template}/unarchive"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Invoices.js
var stripeMethod108, Invoices;
var init_Invoices = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Invoices.js"() {
    init_StripeResource();
    stripeMethod108 = StripeResource.method;
    Invoices = StripeResource.extend({
      create: stripeMethod108({ method: "POST", fullPath: "/v1/invoices" }),
      retrieve: stripeMethod108({ method: "GET", fullPath: "/v1/invoices/{invoice}" }),
      update: stripeMethod108({ method: "POST", fullPath: "/v1/invoices/{invoice}" }),
      list: stripeMethod108({
        method: "GET",
        fullPath: "/v1/invoices",
        methodType: "list"
      }),
      del: stripeMethod108({ method: "DELETE", fullPath: "/v1/invoices/{invoice}" }),
      addLines: stripeMethod108({
        method: "POST",
        fullPath: "/v1/invoices/{invoice}/add_lines"
      }),
      attachPayment: stripeMethod108({
        method: "POST",
        fullPath: "/v1/invoices/{invoice}/attach_payment"
      }),
      createPreview: stripeMethod108({
        method: "POST",
        fullPath: "/v1/invoices/create_preview"
      }),
      finalizeInvoice: stripeMethod108({
        method: "POST",
        fullPath: "/v1/invoices/{invoice}/finalize"
      }),
      listLineItems: stripeMethod108({
        method: "GET",
        fullPath: "/v1/invoices/{invoice}/lines",
        methodType: "list"
      }),
      markUncollectible: stripeMethod108({
        method: "POST",
        fullPath: "/v1/invoices/{invoice}/mark_uncollectible"
      }),
      pay: stripeMethod108({ method: "POST", fullPath: "/v1/invoices/{invoice}/pay" }),
      removeLines: stripeMethod108({
        method: "POST",
        fullPath: "/v1/invoices/{invoice}/remove_lines"
      }),
      search: stripeMethod108({
        method: "GET",
        fullPath: "/v1/invoices/search",
        methodType: "search"
      }),
      sendInvoice: stripeMethod108({
        method: "POST",
        fullPath: "/v1/invoices/{invoice}/send"
      }),
      updateLines: stripeMethod108({
        method: "POST",
        fullPath: "/v1/invoices/{invoice}/update_lines"
      }),
      updateLineItem: stripeMethod108({
        method: "POST",
        fullPath: "/v1/invoices/{invoice}/lines/{line_item_id}"
      }),
      voidInvoice: stripeMethod108({
        method: "POST",
        fullPath: "/v1/invoices/{invoice}/void"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Mandates.js
var stripeMethod109, Mandates;
var init_Mandates = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Mandates.js"() {
    init_StripeResource();
    stripeMethod109 = StripeResource.method;
    Mandates = StripeResource.extend({
      retrieve: stripeMethod109({ method: "GET", fullPath: "/v1/mandates/{mandate}" })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/OAuth.js
var stripeMethod110, oAuthHost, OAuth;
var init_OAuth = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/OAuth.js"() {
    "use strict";
    init_StripeResource();
    init_utils5();
    stripeMethod110 = StripeResource.method;
    oAuthHost = "connect.stripe.com";
    OAuth = StripeResource.extend({
      basePath: "/",
      authorizeUrl(params, options) {
        params = params || {};
        options = options || {};
        let path4 = "oauth/authorize";
        if (options.express) {
          path4 = `express/${path4}`;
        }
        if (!params.response_type) {
          params.response_type = "code";
        }
        if (!params.client_id) {
          params.client_id = this._stripe.getClientId();
        }
        if (!params.scope) {
          params.scope = "read_write";
        }
        return `https://${oAuthHost}/${path4}?${queryStringifyRequestData(params)}`;
      },
      token: stripeMethod110({
        method: "POST",
        path: "oauth/token",
        host: oAuthHost
      }),
      deauthorize(spec, ...args) {
        if (!spec.client_id) {
          spec.client_id = this._stripe.getClientId();
        }
        return stripeMethod110({
          method: "POST",
          path: "oauth/deauthorize",
          host: oAuthHost
        }).apply(this, [spec, ...args]);
      }
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/PaymentAttemptRecords.js
var stripeMethod111, PaymentAttemptRecords;
var init_PaymentAttemptRecords = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/PaymentAttemptRecords.js"() {
    init_StripeResource();
    stripeMethod111 = StripeResource.method;
    PaymentAttemptRecords = StripeResource.extend({
      retrieve: stripeMethod111({
        method: "GET",
        fullPath: "/v1/payment_attempt_records/{id}"
      }),
      list: stripeMethod111({
        method: "GET",
        fullPath: "/v1/payment_attempt_records",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/PaymentIntents.js
var stripeMethod112, PaymentIntents;
var init_PaymentIntents = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/PaymentIntents.js"() {
    init_StripeResource();
    stripeMethod112 = StripeResource.method;
    PaymentIntents = StripeResource.extend({
      create: stripeMethod112({ method: "POST", fullPath: "/v1/payment_intents" }),
      retrieve: stripeMethod112({
        method: "GET",
        fullPath: "/v1/payment_intents/{intent}"
      }),
      update: stripeMethod112({
        method: "POST",
        fullPath: "/v1/payment_intents/{intent}"
      }),
      list: stripeMethod112({
        method: "GET",
        fullPath: "/v1/payment_intents",
        methodType: "list"
      }),
      applyCustomerBalance: stripeMethod112({
        method: "POST",
        fullPath: "/v1/payment_intents/{intent}/apply_customer_balance"
      }),
      cancel: stripeMethod112({
        method: "POST",
        fullPath: "/v1/payment_intents/{intent}/cancel"
      }),
      capture: stripeMethod112({
        method: "POST",
        fullPath: "/v1/payment_intents/{intent}/capture"
      }),
      confirm: stripeMethod112({
        method: "POST",
        fullPath: "/v1/payment_intents/{intent}/confirm"
      }),
      incrementAuthorization: stripeMethod112({
        method: "POST",
        fullPath: "/v1/payment_intents/{intent}/increment_authorization"
      }),
      listAmountDetailsLineItems: stripeMethod112({
        method: "GET",
        fullPath: "/v1/payment_intents/{intent}/amount_details_line_items",
        methodType: "list"
      }),
      search: stripeMethod112({
        method: "GET",
        fullPath: "/v1/payment_intents/search",
        methodType: "search"
      }),
      verifyMicrodeposits: stripeMethod112({
        method: "POST",
        fullPath: "/v1/payment_intents/{intent}/verify_microdeposits"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/PaymentLinks.js
var stripeMethod113, PaymentLinks;
var init_PaymentLinks = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/PaymentLinks.js"() {
    init_StripeResource();
    stripeMethod113 = StripeResource.method;
    PaymentLinks = StripeResource.extend({
      create: stripeMethod113({ method: "POST", fullPath: "/v1/payment_links" }),
      retrieve: stripeMethod113({
        method: "GET",
        fullPath: "/v1/payment_links/{payment_link}"
      }),
      update: stripeMethod113({
        method: "POST",
        fullPath: "/v1/payment_links/{payment_link}"
      }),
      list: stripeMethod113({
        method: "GET",
        fullPath: "/v1/payment_links",
        methodType: "list"
      }),
      listLineItems: stripeMethod113({
        method: "GET",
        fullPath: "/v1/payment_links/{payment_link}/line_items",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/PaymentMethodConfigurations.js
var stripeMethod114, PaymentMethodConfigurations;
var init_PaymentMethodConfigurations = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/PaymentMethodConfigurations.js"() {
    init_StripeResource();
    stripeMethod114 = StripeResource.method;
    PaymentMethodConfigurations = StripeResource.extend({
      create: stripeMethod114({
        method: "POST",
        fullPath: "/v1/payment_method_configurations"
      }),
      retrieve: stripeMethod114({
        method: "GET",
        fullPath: "/v1/payment_method_configurations/{configuration}"
      }),
      update: stripeMethod114({
        method: "POST",
        fullPath: "/v1/payment_method_configurations/{configuration}"
      }),
      list: stripeMethod114({
        method: "GET",
        fullPath: "/v1/payment_method_configurations",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/PaymentMethodDomains.js
var stripeMethod115, PaymentMethodDomains;
var init_PaymentMethodDomains = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/PaymentMethodDomains.js"() {
    init_StripeResource();
    stripeMethod115 = StripeResource.method;
    PaymentMethodDomains = StripeResource.extend({
      create: stripeMethod115({
        method: "POST",
        fullPath: "/v1/payment_method_domains"
      }),
      retrieve: stripeMethod115({
        method: "GET",
        fullPath: "/v1/payment_method_domains/{payment_method_domain}"
      }),
      update: stripeMethod115({
        method: "POST",
        fullPath: "/v1/payment_method_domains/{payment_method_domain}"
      }),
      list: stripeMethod115({
        method: "GET",
        fullPath: "/v1/payment_method_domains",
        methodType: "list"
      }),
      validate: stripeMethod115({
        method: "POST",
        fullPath: "/v1/payment_method_domains/{payment_method_domain}/validate"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/PaymentMethods.js
var stripeMethod116, PaymentMethods;
var init_PaymentMethods = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/PaymentMethods.js"() {
    init_StripeResource();
    stripeMethod116 = StripeResource.method;
    PaymentMethods = StripeResource.extend({
      create: stripeMethod116({ method: "POST", fullPath: "/v1/payment_methods" }),
      retrieve: stripeMethod116({
        method: "GET",
        fullPath: "/v1/payment_methods/{payment_method}"
      }),
      update: stripeMethod116({
        method: "POST",
        fullPath: "/v1/payment_methods/{payment_method}"
      }),
      list: stripeMethod116({
        method: "GET",
        fullPath: "/v1/payment_methods",
        methodType: "list"
      }),
      attach: stripeMethod116({
        method: "POST",
        fullPath: "/v1/payment_methods/{payment_method}/attach"
      }),
      detach: stripeMethod116({
        method: "POST",
        fullPath: "/v1/payment_methods/{payment_method}/detach"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/PaymentRecords.js
var stripeMethod117, PaymentRecords;
var init_PaymentRecords = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/PaymentRecords.js"() {
    init_StripeResource();
    stripeMethod117 = StripeResource.method;
    PaymentRecords = StripeResource.extend({
      retrieve: stripeMethod117({ method: "GET", fullPath: "/v1/payment_records/{id}" }),
      reportPayment: stripeMethod117({
        method: "POST",
        fullPath: "/v1/payment_records/report_payment"
      }),
      reportPaymentAttempt: stripeMethod117({
        method: "POST",
        fullPath: "/v1/payment_records/{id}/report_payment_attempt"
      }),
      reportPaymentAttemptCanceled: stripeMethod117({
        method: "POST",
        fullPath: "/v1/payment_records/{id}/report_payment_attempt_canceled"
      }),
      reportPaymentAttemptFailed: stripeMethod117({
        method: "POST",
        fullPath: "/v1/payment_records/{id}/report_payment_attempt_failed"
      }),
      reportPaymentAttemptGuaranteed: stripeMethod117({
        method: "POST",
        fullPath: "/v1/payment_records/{id}/report_payment_attempt_guaranteed"
      }),
      reportPaymentAttemptInformational: stripeMethod117({
        method: "POST",
        fullPath: "/v1/payment_records/{id}/report_payment_attempt_informational"
      }),
      reportRefund: stripeMethod117({
        method: "POST",
        fullPath: "/v1/payment_records/{id}/report_refund"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Payouts.js
var stripeMethod118, Payouts;
var init_Payouts = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Payouts.js"() {
    init_StripeResource();
    stripeMethod118 = StripeResource.method;
    Payouts = StripeResource.extend({
      create: stripeMethod118({ method: "POST", fullPath: "/v1/payouts" }),
      retrieve: stripeMethod118({ method: "GET", fullPath: "/v1/payouts/{payout}" }),
      update: stripeMethod118({ method: "POST", fullPath: "/v1/payouts/{payout}" }),
      list: stripeMethod118({
        method: "GET",
        fullPath: "/v1/payouts",
        methodType: "list"
      }),
      cancel: stripeMethod118({
        method: "POST",
        fullPath: "/v1/payouts/{payout}/cancel"
      }),
      reverse: stripeMethod118({
        method: "POST",
        fullPath: "/v1/payouts/{payout}/reverse"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Plans.js
var stripeMethod119, Plans;
var init_Plans = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Plans.js"() {
    init_StripeResource();
    stripeMethod119 = StripeResource.method;
    Plans = StripeResource.extend({
      create: stripeMethod119({ method: "POST", fullPath: "/v1/plans" }),
      retrieve: stripeMethod119({ method: "GET", fullPath: "/v1/plans/{plan}" }),
      update: stripeMethod119({ method: "POST", fullPath: "/v1/plans/{plan}" }),
      list: stripeMethod119({
        method: "GET",
        fullPath: "/v1/plans",
        methodType: "list"
      }),
      del: stripeMethod119({ method: "DELETE", fullPath: "/v1/plans/{plan}" })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Prices.js
var stripeMethod120, Prices;
var init_Prices = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Prices.js"() {
    init_StripeResource();
    stripeMethod120 = StripeResource.method;
    Prices = StripeResource.extend({
      create: stripeMethod120({ method: "POST", fullPath: "/v1/prices" }),
      retrieve: stripeMethod120({ method: "GET", fullPath: "/v1/prices/{price}" }),
      update: stripeMethod120({ method: "POST", fullPath: "/v1/prices/{price}" }),
      list: stripeMethod120({
        method: "GET",
        fullPath: "/v1/prices",
        methodType: "list"
      }),
      search: stripeMethod120({
        method: "GET",
        fullPath: "/v1/prices/search",
        methodType: "search"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Products.js
var stripeMethod121, Products2;
var init_Products2 = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Products.js"() {
    init_StripeResource();
    stripeMethod121 = StripeResource.method;
    Products2 = StripeResource.extend({
      create: stripeMethod121({ method: "POST", fullPath: "/v1/products" }),
      retrieve: stripeMethod121({ method: "GET", fullPath: "/v1/products/{id}" }),
      update: stripeMethod121({ method: "POST", fullPath: "/v1/products/{id}" }),
      list: stripeMethod121({
        method: "GET",
        fullPath: "/v1/products",
        methodType: "list"
      }),
      del: stripeMethod121({ method: "DELETE", fullPath: "/v1/products/{id}" }),
      createFeature: stripeMethod121({
        method: "POST",
        fullPath: "/v1/products/{product}/features"
      }),
      deleteFeature: stripeMethod121({
        method: "DELETE",
        fullPath: "/v1/products/{product}/features/{id}"
      }),
      listFeatures: stripeMethod121({
        method: "GET",
        fullPath: "/v1/products/{product}/features",
        methodType: "list"
      }),
      retrieveFeature: stripeMethod121({
        method: "GET",
        fullPath: "/v1/products/{product}/features/{id}"
      }),
      search: stripeMethod121({
        method: "GET",
        fullPath: "/v1/products/search",
        methodType: "search"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/PromotionCodes.js
var stripeMethod122, PromotionCodes;
var init_PromotionCodes = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/PromotionCodes.js"() {
    init_StripeResource();
    stripeMethod122 = StripeResource.method;
    PromotionCodes = StripeResource.extend({
      create: stripeMethod122({ method: "POST", fullPath: "/v1/promotion_codes" }),
      retrieve: stripeMethod122({
        method: "GET",
        fullPath: "/v1/promotion_codes/{promotion_code}"
      }),
      update: stripeMethod122({
        method: "POST",
        fullPath: "/v1/promotion_codes/{promotion_code}"
      }),
      list: stripeMethod122({
        method: "GET",
        fullPath: "/v1/promotion_codes",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Quotes.js
var stripeMethod123, Quotes;
var init_Quotes = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Quotes.js"() {
    init_StripeResource();
    stripeMethod123 = StripeResource.method;
    Quotes = StripeResource.extend({
      create: stripeMethod123({ method: "POST", fullPath: "/v1/quotes" }),
      retrieve: stripeMethod123({ method: "GET", fullPath: "/v1/quotes/{quote}" }),
      update: stripeMethod123({ method: "POST", fullPath: "/v1/quotes/{quote}" }),
      list: stripeMethod123({
        method: "GET",
        fullPath: "/v1/quotes",
        methodType: "list"
      }),
      accept: stripeMethod123({ method: "POST", fullPath: "/v1/quotes/{quote}/accept" }),
      cancel: stripeMethod123({ method: "POST", fullPath: "/v1/quotes/{quote}/cancel" }),
      finalizeQuote: stripeMethod123({
        method: "POST",
        fullPath: "/v1/quotes/{quote}/finalize"
      }),
      listComputedUpfrontLineItems: stripeMethod123({
        method: "GET",
        fullPath: "/v1/quotes/{quote}/computed_upfront_line_items",
        methodType: "list"
      }),
      listLineItems: stripeMethod123({
        method: "GET",
        fullPath: "/v1/quotes/{quote}/line_items",
        methodType: "list"
      }),
      pdf: stripeMethod123({
        method: "GET",
        fullPath: "/v1/quotes/{quote}/pdf",
        host: "files.stripe.com",
        streaming: true
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Refunds.js
var stripeMethod124, Refunds2;
var init_Refunds2 = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Refunds.js"() {
    init_StripeResource();
    stripeMethod124 = StripeResource.method;
    Refunds2 = StripeResource.extend({
      create: stripeMethod124({ method: "POST", fullPath: "/v1/refunds" }),
      retrieve: stripeMethod124({ method: "GET", fullPath: "/v1/refunds/{refund}" }),
      update: stripeMethod124({ method: "POST", fullPath: "/v1/refunds/{refund}" }),
      list: stripeMethod124({
        method: "GET",
        fullPath: "/v1/refunds",
        methodType: "list"
      }),
      cancel: stripeMethod124({
        method: "POST",
        fullPath: "/v1/refunds/{refund}/cancel"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Reviews.js
var stripeMethod125, Reviews;
var init_Reviews = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Reviews.js"() {
    init_StripeResource();
    stripeMethod125 = StripeResource.method;
    Reviews = StripeResource.extend({
      retrieve: stripeMethod125({ method: "GET", fullPath: "/v1/reviews/{review}" }),
      list: stripeMethod125({
        method: "GET",
        fullPath: "/v1/reviews",
        methodType: "list"
      }),
      approve: stripeMethod125({
        method: "POST",
        fullPath: "/v1/reviews/{review}/approve"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/SetupAttempts.js
var stripeMethod126, SetupAttempts;
var init_SetupAttempts = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/SetupAttempts.js"() {
    init_StripeResource();
    stripeMethod126 = StripeResource.method;
    SetupAttempts = StripeResource.extend({
      list: stripeMethod126({
        method: "GET",
        fullPath: "/v1/setup_attempts",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/SetupIntents.js
var stripeMethod127, SetupIntents;
var init_SetupIntents = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/SetupIntents.js"() {
    init_StripeResource();
    stripeMethod127 = StripeResource.method;
    SetupIntents = StripeResource.extend({
      create: stripeMethod127({ method: "POST", fullPath: "/v1/setup_intents" }),
      retrieve: stripeMethod127({
        method: "GET",
        fullPath: "/v1/setup_intents/{intent}"
      }),
      update: stripeMethod127({
        method: "POST",
        fullPath: "/v1/setup_intents/{intent}"
      }),
      list: stripeMethod127({
        method: "GET",
        fullPath: "/v1/setup_intents",
        methodType: "list"
      }),
      cancel: stripeMethod127({
        method: "POST",
        fullPath: "/v1/setup_intents/{intent}/cancel"
      }),
      confirm: stripeMethod127({
        method: "POST",
        fullPath: "/v1/setup_intents/{intent}/confirm"
      }),
      verifyMicrodeposits: stripeMethod127({
        method: "POST",
        fullPath: "/v1/setup_intents/{intent}/verify_microdeposits"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/ShippingRates.js
var stripeMethod128, ShippingRates;
var init_ShippingRates = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/ShippingRates.js"() {
    init_StripeResource();
    stripeMethod128 = StripeResource.method;
    ShippingRates = StripeResource.extend({
      create: stripeMethod128({ method: "POST", fullPath: "/v1/shipping_rates" }),
      retrieve: stripeMethod128({
        method: "GET",
        fullPath: "/v1/shipping_rates/{shipping_rate_token}"
      }),
      update: stripeMethod128({
        method: "POST",
        fullPath: "/v1/shipping_rates/{shipping_rate_token}"
      }),
      list: stripeMethod128({
        method: "GET",
        fullPath: "/v1/shipping_rates",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Sources.js
var stripeMethod129, Sources;
var init_Sources = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Sources.js"() {
    init_StripeResource();
    stripeMethod129 = StripeResource.method;
    Sources = StripeResource.extend({
      create: stripeMethod129({ method: "POST", fullPath: "/v1/sources" }),
      retrieve: stripeMethod129({ method: "GET", fullPath: "/v1/sources/{source}" }),
      update: stripeMethod129({ method: "POST", fullPath: "/v1/sources/{source}" }),
      listSourceTransactions: stripeMethod129({
        method: "GET",
        fullPath: "/v1/sources/{source}/source_transactions",
        methodType: "list"
      }),
      verify: stripeMethod129({
        method: "POST",
        fullPath: "/v1/sources/{source}/verify"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/SubscriptionItems.js
var stripeMethod130, SubscriptionItems;
var init_SubscriptionItems = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/SubscriptionItems.js"() {
    init_StripeResource();
    stripeMethod130 = StripeResource.method;
    SubscriptionItems = StripeResource.extend({
      create: stripeMethod130({ method: "POST", fullPath: "/v1/subscription_items" }),
      retrieve: stripeMethod130({
        method: "GET",
        fullPath: "/v1/subscription_items/{item}"
      }),
      update: stripeMethod130({
        method: "POST",
        fullPath: "/v1/subscription_items/{item}"
      }),
      list: stripeMethod130({
        method: "GET",
        fullPath: "/v1/subscription_items",
        methodType: "list"
      }),
      del: stripeMethod130({
        method: "DELETE",
        fullPath: "/v1/subscription_items/{item}"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/SubscriptionSchedules.js
var stripeMethod131, SubscriptionSchedules;
var init_SubscriptionSchedules = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/SubscriptionSchedules.js"() {
    init_StripeResource();
    stripeMethod131 = StripeResource.method;
    SubscriptionSchedules = StripeResource.extend({
      create: stripeMethod131({
        method: "POST",
        fullPath: "/v1/subscription_schedules"
      }),
      retrieve: stripeMethod131({
        method: "GET",
        fullPath: "/v1/subscription_schedules/{schedule}"
      }),
      update: stripeMethod131({
        method: "POST",
        fullPath: "/v1/subscription_schedules/{schedule}"
      }),
      list: stripeMethod131({
        method: "GET",
        fullPath: "/v1/subscription_schedules",
        methodType: "list"
      }),
      cancel: stripeMethod131({
        method: "POST",
        fullPath: "/v1/subscription_schedules/{schedule}/cancel"
      }),
      release: stripeMethod131({
        method: "POST",
        fullPath: "/v1/subscription_schedules/{schedule}/release"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Subscriptions.js
var stripeMethod132, Subscriptions;
var init_Subscriptions = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Subscriptions.js"() {
    init_StripeResource();
    stripeMethod132 = StripeResource.method;
    Subscriptions = StripeResource.extend({
      create: stripeMethod132({ method: "POST", fullPath: "/v1/subscriptions" }),
      retrieve: stripeMethod132({
        method: "GET",
        fullPath: "/v1/subscriptions/{subscription_exposed_id}"
      }),
      update: stripeMethod132({
        method: "POST",
        fullPath: "/v1/subscriptions/{subscription_exposed_id}"
      }),
      list: stripeMethod132({
        method: "GET",
        fullPath: "/v1/subscriptions",
        methodType: "list"
      }),
      cancel: stripeMethod132({
        method: "DELETE",
        fullPath: "/v1/subscriptions/{subscription_exposed_id}"
      }),
      deleteDiscount: stripeMethod132({
        method: "DELETE",
        fullPath: "/v1/subscriptions/{subscription_exposed_id}/discount"
      }),
      migrate: stripeMethod132({
        method: "POST",
        fullPath: "/v1/subscriptions/{subscription}/migrate"
      }),
      resume: stripeMethod132({
        method: "POST",
        fullPath: "/v1/subscriptions/{subscription}/resume"
      }),
      search: stripeMethod132({
        method: "GET",
        fullPath: "/v1/subscriptions/search",
        methodType: "search"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TaxCodes.js
var stripeMethod133, TaxCodes;
var init_TaxCodes = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TaxCodes.js"() {
    init_StripeResource();
    stripeMethod133 = StripeResource.method;
    TaxCodes = StripeResource.extend({
      retrieve: stripeMethod133({ method: "GET", fullPath: "/v1/tax_codes/{id}" }),
      list: stripeMethod133({
        method: "GET",
        fullPath: "/v1/tax_codes",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TaxIds.js
var stripeMethod134, TaxIds;
var init_TaxIds = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TaxIds.js"() {
    init_StripeResource();
    stripeMethod134 = StripeResource.method;
    TaxIds = StripeResource.extend({
      create: stripeMethod134({ method: "POST", fullPath: "/v1/tax_ids" }),
      retrieve: stripeMethod134({ method: "GET", fullPath: "/v1/tax_ids/{id}" }),
      list: stripeMethod134({
        method: "GET",
        fullPath: "/v1/tax_ids",
        methodType: "list"
      }),
      del: stripeMethod134({ method: "DELETE", fullPath: "/v1/tax_ids/{id}" })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TaxRates.js
var stripeMethod135, TaxRates;
var init_TaxRates = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/TaxRates.js"() {
    init_StripeResource();
    stripeMethod135 = StripeResource.method;
    TaxRates = StripeResource.extend({
      create: stripeMethod135({ method: "POST", fullPath: "/v1/tax_rates" }),
      retrieve: stripeMethod135({ method: "GET", fullPath: "/v1/tax_rates/{tax_rate}" }),
      update: stripeMethod135({ method: "POST", fullPath: "/v1/tax_rates/{tax_rate}" }),
      list: stripeMethod135({
        method: "GET",
        fullPath: "/v1/tax_rates",
        methodType: "list"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Tokens.js
var stripeMethod136, Tokens2;
var init_Tokens2 = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Tokens.js"() {
    init_StripeResource();
    stripeMethod136 = StripeResource.method;
    Tokens2 = StripeResource.extend({
      create: stripeMethod136({ method: "POST", fullPath: "/v1/tokens" }),
      retrieve: stripeMethod136({ method: "GET", fullPath: "/v1/tokens/{token}" })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Topups.js
var stripeMethod137, Topups;
var init_Topups = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Topups.js"() {
    init_StripeResource();
    stripeMethod137 = StripeResource.method;
    Topups = StripeResource.extend({
      create: stripeMethod137({ method: "POST", fullPath: "/v1/topups" }),
      retrieve: stripeMethod137({ method: "GET", fullPath: "/v1/topups/{topup}" }),
      update: stripeMethod137({ method: "POST", fullPath: "/v1/topups/{topup}" }),
      list: stripeMethod137({
        method: "GET",
        fullPath: "/v1/topups",
        methodType: "list"
      }),
      cancel: stripeMethod137({ method: "POST", fullPath: "/v1/topups/{topup}/cancel" })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Transfers.js
var stripeMethod138, Transfers;
var init_Transfers = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/Transfers.js"() {
    init_StripeResource();
    stripeMethod138 = StripeResource.method;
    Transfers = StripeResource.extend({
      create: stripeMethod138({ method: "POST", fullPath: "/v1/transfers" }),
      retrieve: stripeMethod138({ method: "GET", fullPath: "/v1/transfers/{transfer}" }),
      update: stripeMethod138({ method: "POST", fullPath: "/v1/transfers/{transfer}" }),
      list: stripeMethod138({
        method: "GET",
        fullPath: "/v1/transfers",
        methodType: "list"
      }),
      createReversal: stripeMethod138({
        method: "POST",
        fullPath: "/v1/transfers/{id}/reversals"
      }),
      listReversals: stripeMethod138({
        method: "GET",
        fullPath: "/v1/transfers/{id}/reversals",
        methodType: "list"
      }),
      retrieveReversal: stripeMethod138({
        method: "GET",
        fullPath: "/v1/transfers/{transfer}/reversals/{id}"
      }),
      updateReversal: stripeMethod138({
        method: "POST",
        fullPath: "/v1/transfers/{transfer}/reversals/{id}"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/WebhookEndpoints.js
var stripeMethod139, WebhookEndpoints;
var init_WebhookEndpoints = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources/WebhookEndpoints.js"() {
    init_StripeResource();
    stripeMethod139 = StripeResource.method;
    WebhookEndpoints = StripeResource.extend({
      create: stripeMethod139({ method: "POST", fullPath: "/v1/webhook_endpoints" }),
      retrieve: stripeMethod139({
        method: "GET",
        fullPath: "/v1/webhook_endpoints/{webhook_endpoint}"
      }),
      update: stripeMethod139({
        method: "POST",
        fullPath: "/v1/webhook_endpoints/{webhook_endpoint}"
      }),
      list: stripeMethod139({
        method: "GET",
        fullPath: "/v1/webhook_endpoints",
        methodType: "list"
      }),
      del: stripeMethod139({
        method: "DELETE",
        fullPath: "/v1/webhook_endpoints/{webhook_endpoint}"
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources.js
var resources_exports = {};
__export(resources_exports, {
  Account: () => Accounts3,
  AccountLinks: () => AccountLinks2,
  AccountSessions: () => AccountSessions,
  Accounts: () => Accounts3,
  ApplePayDomains: () => ApplePayDomains,
  ApplicationFees: () => ApplicationFees,
  Apps: () => Apps,
  Balance: () => Balance,
  BalanceSettings: () => BalanceSettings,
  BalanceTransactions: () => BalanceTransactions,
  Billing: () => Billing,
  BillingPortal: () => BillingPortal,
  Charges: () => Charges,
  Checkout: () => Checkout,
  Climate: () => Climate,
  ConfirmationTokens: () => ConfirmationTokens2,
  CountrySpecs: () => CountrySpecs,
  Coupons: () => Coupons,
  CreditNotes: () => CreditNotes,
  CustomerSessions: () => CustomerSessions,
  Customers: () => Customers2,
  Disputes: () => Disputes2,
  Entitlements: () => Entitlements,
  EphemeralKeys: () => EphemeralKeys,
  Events: () => Events2,
  ExchangeRates: () => ExchangeRates,
  FileLinks: () => FileLinks,
  Files: () => Files,
  FinancialConnections: () => FinancialConnections,
  Forwarding: () => Forwarding,
  Identity: () => Identity,
  InvoiceItems: () => InvoiceItems,
  InvoicePayments: () => InvoicePayments,
  InvoiceRenderingTemplates: () => InvoiceRenderingTemplates,
  Invoices: () => Invoices,
  Issuing: () => Issuing,
  Mandates: () => Mandates,
  OAuth: () => OAuth,
  PaymentAttemptRecords: () => PaymentAttemptRecords,
  PaymentIntents: () => PaymentIntents,
  PaymentLinks: () => PaymentLinks,
  PaymentMethodConfigurations: () => PaymentMethodConfigurations,
  PaymentMethodDomains: () => PaymentMethodDomains,
  PaymentMethods: () => PaymentMethods,
  PaymentRecords: () => PaymentRecords,
  Payouts: () => Payouts,
  Plans: () => Plans,
  Prices: () => Prices,
  Products: () => Products2,
  PromotionCodes: () => PromotionCodes,
  Quotes: () => Quotes,
  Radar: () => Radar,
  Refunds: () => Refunds2,
  Reporting: () => Reporting,
  Reviews: () => Reviews,
  SetupAttempts: () => SetupAttempts,
  SetupIntents: () => SetupIntents,
  ShippingRates: () => ShippingRates,
  Sigma: () => Sigma,
  Sources: () => Sources,
  SubscriptionItems: () => SubscriptionItems,
  SubscriptionSchedules: () => SubscriptionSchedules,
  Subscriptions: () => Subscriptions,
  Tax: () => Tax,
  TaxCodes: () => TaxCodes,
  TaxIds: () => TaxIds,
  TaxRates: () => TaxRates,
  Terminal: () => Terminal,
  TestHelpers: () => TestHelpers,
  Tokens: () => Tokens2,
  Topups: () => Topups,
  Transfers: () => Transfers,
  Treasury: () => Treasury,
  V2: () => V2,
  WebhookEndpoints: () => WebhookEndpoints
});
var Apps, Billing, BillingPortal, Checkout, Climate, Entitlements, FinancialConnections, Forwarding, Identity, Issuing, Radar, Reporting, Sigma, Tax, Terminal, TestHelpers, Treasury, V2;
var init_resources = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/resources.js"() {
    init_ResourceNamespace();
    init_AccountLinks();
    init_AccountTokens();
    init_Accounts();
    init_Accounts2();
    init_ActiveEntitlements();
    init_Alerts();
    init_Associations();
    init_Authorizations();
    init_Authorizations2();
    init_Calculations();
    init_Cardholders();
    init_Cards();
    init_Cards2();
    init_Configurations();
    init_Configurations2();
    init_ConfirmationTokens();
    init_ConnectionTokens();
    init_CreditBalanceSummary();
    init_CreditBalanceTransactions();
    init_CreditGrants();
    init_CreditReversals();
    init_Customers();
    init_DebitReversals();
    init_Disputes();
    init_EarlyFraudWarnings();
    init_EventDestinations();
    init_Events();
    init_Features();
    init_FinancialAccounts();
    init_InboundTransfers();
    init_InboundTransfers2();
    init_Locations();
    init_MeterEventAdjustments();
    init_MeterEventAdjustments2();
    init_MeterEventSession();
    init_MeterEventStream();
    init_MeterEvents();
    init_MeterEvents2();
    init_Meters();
    init_OnboardingLinks();
    init_Orders();
    init_OutboundPayments();
    init_OutboundPayments2();
    init_OutboundTransfers();
    init_OutboundTransfers2();
    init_PaymentEvaluations();
    init_PersonalizationDesigns();
    init_PersonalizationDesigns2();
    init_PhysicalBundles();
    init_Products();
    init_Readers();
    init_Readers2();
    init_ReceivedCredits();
    init_ReceivedCredits2();
    init_ReceivedDebits();
    init_ReceivedDebits2();
    init_Refunds();
    init_Registrations();
    init_ReportRuns();
    init_ReportTypes();
    init_Requests();
    init_ScheduledQueryRuns();
    init_Secrets();
    init_Sessions();
    init_Sessions2();
    init_Sessions3();
    init_Settings();
    init_Suppliers();
    init_TestClocks();
    init_Tokens();
    init_TransactionEntries();
    init_Transactions();
    init_Transactions2();
    init_Transactions3();
    init_Transactions4();
    init_Transactions5();
    init_ValueListItems();
    init_ValueLists();
    init_VerificationReports();
    init_VerificationSessions();
    init_Accounts3();
    init_AccountLinks2();
    init_AccountSessions();
    init_Accounts3();
    init_ApplePayDomains();
    init_ApplicationFees();
    init_Balance();
    init_BalanceSettings();
    init_BalanceTransactions();
    init_Charges();
    init_ConfirmationTokens2();
    init_CountrySpecs();
    init_Coupons();
    init_CreditNotes();
    init_CustomerSessions();
    init_Customers2();
    init_Disputes2();
    init_EphemeralKeys();
    init_Events2();
    init_ExchangeRates();
    init_FileLinks();
    init_Files();
    init_InvoiceItems();
    init_InvoicePayments();
    init_InvoiceRenderingTemplates();
    init_Invoices();
    init_Mandates();
    init_OAuth();
    init_PaymentAttemptRecords();
    init_PaymentIntents();
    init_PaymentLinks();
    init_PaymentMethodConfigurations();
    init_PaymentMethodDomains();
    init_PaymentMethods();
    init_PaymentRecords();
    init_Payouts();
    init_Plans();
    init_Prices();
    init_Products2();
    init_PromotionCodes();
    init_Quotes();
    init_Refunds2();
    init_Reviews();
    init_SetupAttempts();
    init_SetupIntents();
    init_ShippingRates();
    init_Sources();
    init_SubscriptionItems();
    init_SubscriptionSchedules();
    init_Subscriptions();
    init_TaxCodes();
    init_TaxIds();
    init_TaxRates();
    init_Tokens2();
    init_Topups();
    init_Transfers();
    init_WebhookEndpoints();
    Apps = resourceNamespace("apps", { Secrets });
    Billing = resourceNamespace("billing", {
      Alerts,
      CreditBalanceSummary,
      CreditBalanceTransactions,
      CreditGrants,
      MeterEventAdjustments,
      MeterEvents,
      Meters
    });
    BillingPortal = resourceNamespace("billingPortal", {
      Configurations,
      Sessions
    });
    Checkout = resourceNamespace("checkout", {
      Sessions: Sessions2
    });
    Climate = resourceNamespace("climate", {
      Orders,
      Products,
      Suppliers
    });
    Entitlements = resourceNamespace("entitlements", {
      ActiveEntitlements,
      Features
    });
    FinancialConnections = resourceNamespace("financialConnections", {
      Accounts,
      Sessions: Sessions3,
      Transactions
    });
    Forwarding = resourceNamespace("forwarding", {
      Requests
    });
    Identity = resourceNamespace("identity", {
      VerificationReports,
      VerificationSessions
    });
    Issuing = resourceNamespace("issuing", {
      Authorizations,
      Cardholders,
      Cards,
      Disputes,
      PersonalizationDesigns,
      PhysicalBundles,
      Tokens,
      Transactions: Transactions2
    });
    Radar = resourceNamespace("radar", {
      EarlyFraudWarnings,
      PaymentEvaluations,
      ValueListItems,
      ValueLists
    });
    Reporting = resourceNamespace("reporting", {
      ReportRuns,
      ReportTypes
    });
    Sigma = resourceNamespace("sigma", {
      ScheduledQueryRuns
    });
    Tax = resourceNamespace("tax", {
      Associations,
      Calculations,
      Registrations,
      Settings,
      Transactions: Transactions3
    });
    Terminal = resourceNamespace("terminal", {
      Configurations: Configurations2,
      ConnectionTokens,
      Locations,
      OnboardingLinks,
      Readers
    });
    TestHelpers = resourceNamespace("testHelpers", {
      ConfirmationTokens,
      Customers,
      Refunds,
      TestClocks,
      Issuing: resourceNamespace("issuing", {
        Authorizations: Authorizations2,
        Cards: Cards2,
        PersonalizationDesigns: PersonalizationDesigns2,
        Transactions: Transactions4
      }),
      Terminal: resourceNamespace("terminal", {
        Readers: Readers2
      }),
      Treasury: resourceNamespace("treasury", {
        InboundTransfers,
        OutboundPayments,
        OutboundTransfers,
        ReceivedCredits,
        ReceivedDebits
      })
    });
    Treasury = resourceNamespace("treasury", {
      CreditReversals,
      DebitReversals,
      FinancialAccounts,
      InboundTransfers: InboundTransfers2,
      OutboundPayments: OutboundPayments2,
      OutboundTransfers: OutboundTransfers2,
      ReceivedCredits: ReceivedCredits2,
      ReceivedDebits: ReceivedDebits2,
      TransactionEntries,
      Transactions: Transactions5
    });
    V2 = resourceNamespace("v2", {
      Billing: resourceNamespace("billing", {
        MeterEventAdjustments: MeterEventAdjustments2,
        MeterEventSession,
        MeterEventStream,
        MeterEvents: MeterEvents2
      }),
      Core: resourceNamespace("core", {
        AccountLinks,
        AccountTokens,
        Accounts: Accounts2,
        EventDestinations,
        Events
      })
    });
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/stripe.core.js
function createStripe(platformFunctions, requestSender = defaultRequestSenderFactory) {
  Stripe2.PACKAGE_VERSION = "20.4.1";
  Stripe2.API_VERSION = ApiVersion;
  const aiAgent = typeof process !== "undefined" && process.env ? detectAIAgent(process.env) : "";
  Stripe2.AI_AGENT = aiAgent;
  Stripe2.USER_AGENT = Object.assign(Object.assign({ bindings_version: Stripe2.PACKAGE_VERSION, lang: "node", publisher: "stripe", uname: null, typescript: false }, determineProcessUserAgentProperties()), aiAgent ? { ai_agent: aiAgent } : {});
  Stripe2.StripeResource = StripeResource;
  Stripe2.StripeContext = StripeContext;
  Stripe2.resources = resources_exports;
  Stripe2.HttpClient = HttpClient;
  Stripe2.HttpClientResponse = HttpClientResponse;
  Stripe2.CryptoProvider = CryptoProvider;
  Stripe2.webhooks = createWebhooks(platformFunctions);
  function Stripe2(key, config2 = {}) {
    if (!(this instanceof Stripe2)) {
      return new Stripe2(key, config2);
    }
    const props = this._getPropsFromConfig(config2);
    this._platformFunctions = platformFunctions;
    Object.defineProperty(this, "_emitter", {
      value: this._platformFunctions.createEmitter(),
      enumerable: false,
      configurable: false,
      writable: false
    });
    this.VERSION = Stripe2.PACKAGE_VERSION;
    this.on = this._emitter.on.bind(this._emitter);
    this.once = this._emitter.once.bind(this._emitter);
    this.off = this._emitter.removeListener.bind(this._emitter);
    const agent = props.httpAgent || null;
    this._api = {
      host: props.host || DEFAULT_HOST,
      port: props.port || DEFAULT_PORT,
      protocol: props.protocol || "https",
      basePath: DEFAULT_BASE_PATH,
      version: props.apiVersion || DEFAULT_API_VERSION,
      timeout: validateInteger("timeout", props.timeout, DEFAULT_TIMEOUT),
      maxNetworkRetries: validateInteger("maxNetworkRetries", props.maxNetworkRetries, 2),
      agent,
      httpClient: props.httpClient || (agent ? this._platformFunctions.createNodeHttpClient(agent) : this._platformFunctions.createDefaultHttpClient()),
      dev: false,
      stripeAccount: props.stripeAccount || null,
      stripeContext: props.stripeContext || null
    };
    const typescript = props.typescript || false;
    if (typescript !== Stripe2.USER_AGENT.typescript) {
      Stripe2.USER_AGENT.typescript = typescript;
    }
    if (props.appInfo) {
      this._setAppInfo(props.appInfo);
    }
    this._prepResources();
    this._setAuthenticator(key, props.authenticator);
    this.errors = Error_exports;
    this.webhooks = Stripe2.webhooks;
    this._prevRequestMetrics = [];
    this._enableTelemetry = props.telemetry !== false;
    this._requestSender = requestSender(this);
    this.StripeResource = Stripe2.StripeResource;
  }
  Stripe2.errors = Error_exports;
  Stripe2.createNodeHttpClient = platformFunctions.createNodeHttpClient;
  Stripe2.createFetchHttpClient = platformFunctions.createFetchHttpClient;
  Stripe2.createNodeCryptoProvider = platformFunctions.createNodeCryptoProvider;
  Stripe2.createSubtleCryptoProvider = platformFunctions.createSubtleCryptoProvider;
  Stripe2.prototype = {
    // Properties are set in the constructor above
    _appInfo: void 0,
    on: null,
    off: null,
    once: null,
    VERSION: null,
    StripeResource: null,
    webhooks: null,
    errors: null,
    _api: null,
    _prevRequestMetrics: null,
    _emitter: null,
    _enableTelemetry: null,
    _requestSender: null,
    _platformFunctions: null,
    rawRequest(method, path4, params, options) {
      return this._requestSender._rawRequest(method, path4, params, options);
    },
    /**
     * @private
     */
    _setAuthenticator(key, authenticator) {
      if (key && authenticator) {
        throw new Error("Can't specify both apiKey and authenticator");
      }
      if (!key && !authenticator) {
        throw new Error("Neither apiKey nor config.authenticator provided");
      }
      this._authenticator = key ? createApiKeyAuthenticator(key) : authenticator;
    },
    /**
     * @private
     * This may be removed in the future.
     */
    _setAppInfo(info) {
      if (info && typeof info !== "object") {
        throw new Error("AppInfo must be an object.");
      }
      if (info && !info.name) {
        throw new Error("AppInfo.name is required");
      }
      info = info || {};
      this._appInfo = APP_INFO_PROPERTIES.reduce((accum, prop) => {
        if (typeof info[prop] == "string") {
          accum = accum || {};
          accum[prop] = info[prop];
        }
        return accum;
      }, {});
    },
    /**
     * @private
     * This may be removed in the future.
     */
    _setApiField(key, value) {
      this._api[key] = value;
    },
    /**
     * @private
     * Please open or upvote an issue at github.com/stripe/stripe-node
     * if you use this, detailing your use-case.
     *
     * It may be deprecated and removed in the future.
     */
    getApiField(key) {
      return this._api[key];
    },
    setClientId(clientId) {
      this._clientId = clientId;
    },
    getClientId() {
      return this._clientId;
    },
    /**
     * @private
     * Please open or upvote an issue at github.com/stripe/stripe-node
     * if you use this, detailing your use-case.
     *
     * It may be deprecated and removed in the future.
     */
    getConstant: (c) => {
      switch (c) {
        case "DEFAULT_HOST":
          return DEFAULT_HOST;
        case "DEFAULT_PORT":
          return DEFAULT_PORT;
        case "DEFAULT_BASE_PATH":
          return DEFAULT_BASE_PATH;
        case "DEFAULT_API_VERSION":
          return DEFAULT_API_VERSION;
        case "DEFAULT_TIMEOUT":
          return DEFAULT_TIMEOUT;
        case "MAX_NETWORK_RETRY_DELAY_SEC":
          return MAX_NETWORK_RETRY_DELAY_SEC;
        case "INITIAL_NETWORK_RETRY_DELAY_SEC":
          return INITIAL_NETWORK_RETRY_DELAY_SEC;
      }
      return Stripe2[c];
    },
    getMaxNetworkRetries() {
      return this.getApiField("maxNetworkRetries");
    },
    /**
     * @private
     * This may be removed in the future.
     */
    _setApiNumberField(prop, n, defaultVal) {
      const val = validateInteger(prop, n, defaultVal);
      this._setApiField(prop, val);
    },
    getMaxNetworkRetryDelay() {
      return MAX_NETWORK_RETRY_DELAY_SEC;
    },
    getInitialNetworkRetryDelay() {
      return INITIAL_NETWORK_RETRY_DELAY_SEC;
    },
    /**
     * @private
     * Please open or upvote an issue at github.com/stripe/stripe-node
     * if you use this, detailing your use-case.
     *
     * It may be deprecated and removed in the future.
     *
     * Gets a JSON version of a User-Agent and uses a cached version for a slight
     * speed advantage.
     */
    getClientUserAgent(cb) {
      return this.getClientUserAgentSeeded(Stripe2.USER_AGENT, cb);
    },
    /**
     * @private
     * Please open or upvote an issue at github.com/stripe/stripe-node
     * if you use this, detailing your use-case.
     *
     * It may be deprecated and removed in the future.
     *
     * Gets a JSON version of a User-Agent by encoding a seeded object and
     * fetching a uname from the system.
     */
    getClientUserAgentSeeded(seed, cb) {
      this._platformFunctions.getUname().then((uname) => {
        var _a;
        const userAgent = {};
        for (const field in seed) {
          if (!Object.prototype.hasOwnProperty.call(seed, field)) {
            continue;
          }
          userAgent[field] = encodeURIComponent((_a = seed[field]) !== null && _a !== void 0 ? _a : "null");
        }
        userAgent.uname = encodeURIComponent(uname || "UNKNOWN");
        const client = this.getApiField("httpClient");
        if (client) {
          userAgent.httplib = encodeURIComponent(client.getClientName());
        }
        if (this._appInfo) {
          userAgent.application = this._appInfo;
        }
        cb(JSON.stringify(userAgent));
      });
    },
    /**
     * @private
     * Please open or upvote an issue at github.com/stripe/stripe-node
     * if you use this, detailing your use-case.
     *
     * It may be deprecated and removed in the future.
     */
    getAppInfoAsString() {
      if (!this._appInfo) {
        return "";
      }
      let formatted = this._appInfo.name;
      if (this._appInfo.version) {
        formatted += `/${this._appInfo.version}`;
      }
      if (this._appInfo.url) {
        formatted += ` (${this._appInfo.url})`;
      }
      return formatted;
    },
    getTelemetryEnabled() {
      return this._enableTelemetry;
    },
    /**
     * @private
     * This may be removed in the future.
     */
    _prepResources() {
      for (const name in resources_exports) {
        if (!Object.prototype.hasOwnProperty.call(resources_exports, name)) {
          continue;
        }
        this[pascalToCamelCase(name)] = new resources_exports[name](this);
      }
    },
    /**
     * @private
     * This may be removed in the future.
     */
    _getPropsFromConfig(config2) {
      if (!config2) {
        return {};
      }
      const isString = typeof config2 === "string";
      const isObject3 = config2 === Object(config2) && !Array.isArray(config2);
      if (!isObject3 && !isString) {
        throw new Error("Config must either be an object or a string");
      }
      if (isString) {
        return {
          apiVersion: config2
        };
      }
      const values = Object.keys(config2).filter((value) => !ALLOWED_CONFIG_PROPERTIES.includes(value));
      if (values.length > 0) {
        throw new Error(`Config object may only contain the following: ${ALLOWED_CONFIG_PROPERTIES.join(", ")}`);
      }
      return config2;
    },
    parseEventNotification(payload, header, secret, tolerance, cryptoProvider, receivedAt) {
      const eventNotification = this.webhooks.constructEvent(payload, header, secret, tolerance, cryptoProvider, receivedAt);
      if (eventNotification.context) {
        eventNotification.context = StripeContext.parse(eventNotification.context);
      }
      eventNotification.fetchEvent = () => {
        return this._requestSender._rawRequest("GET", `/v2/core/events/${eventNotification.id}`, void 0, {
          stripeContext: eventNotification.context,
          headers: {
            "Stripe-Request-Trigger": `event=${eventNotification.id}`
          }
        }, ["fetch_event"]);
      };
      eventNotification.fetchRelatedObject = () => {
        if (!eventNotification.related_object) {
          return Promise.resolve(null);
        }
        return this._requestSender._rawRequest("GET", eventNotification.related_object.url, void 0, {
          stripeContext: eventNotification.context,
          headers: {
            "Stripe-Request-Trigger": `event=${eventNotification.id}`
          }
        }, ["fetch_related_object"]);
      };
      return eventNotification;
    }
  };
  return Stripe2;
}
var DEFAULT_HOST, DEFAULT_PORT, DEFAULT_BASE_PATH, DEFAULT_API_VERSION, DEFAULT_TIMEOUT, MAX_NETWORK_RETRY_DELAY_SEC, INITIAL_NETWORK_RETRY_DELAY_SEC, APP_INFO_PROPERTIES, ALLOWED_CONFIG_PROPERTIES, defaultRequestSenderFactory;
var init_stripe_core = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/stripe.core.js"() {
    init_Error();
    init_RequestSender();
    init_StripeResource();
    init_StripeContext();
    init_Webhooks();
    init_apiVersion();
    init_CryptoProvider();
    init_HttpClient();
    init_resources();
    init_utils5();
    DEFAULT_HOST = "api.stripe.com";
    DEFAULT_PORT = "443";
    DEFAULT_BASE_PATH = "/v1/";
    DEFAULT_API_VERSION = ApiVersion;
    DEFAULT_TIMEOUT = 8e4;
    MAX_NETWORK_RETRY_DELAY_SEC = 5;
    INITIAL_NETWORK_RETRY_DELAY_SEC = 0.5;
    APP_INFO_PROPERTIES = ["name", "version", "url", "partner_id"];
    ALLOWED_CONFIG_PROPERTIES = [
      "authenticator",
      "apiVersion",
      "typescript",
      "maxNetworkRetries",
      "httpAgent",
      "httpClient",
      "timeout",
      "host",
      "port",
      "protocol",
      "telemetry",
      "appInfo",
      "stripeAccount",
      "stripeContext"
    ];
    defaultRequestSenderFactory = (stripe) => new RequestSender(stripe, StripeResource.MAX_BUFFERED_REQUEST_METRICS);
  }
});

// ../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/stripe.esm.node.js
var Stripe, stripe_esm_node_default;
var init_stripe_esm_node = __esm({
  "../../node_modules/.pnpm/stripe@20.4.1_@types+node@25.6.2/node_modules/stripe/esm/stripe.esm.node.js"() {
    init_NodePlatformFunctions();
    init_stripe_core();
    Stripe = createStripe(new NodePlatformFunctions());
    stripe_esm_node_default = Stripe;
  }
});

// src/lib/stripe.ts
function getStripeClient() {
  if (!STRIPE_SECRET_KEY) {
    throw new Error("Stripe is not configured.");
  }
  if (!stripeClient) {
    stripeClient = new stripe_esm_node_default(STRIPE_SECRET_KEY);
  }
  return stripeClient;
}
function getStripeWebhookSecret() {
  if (!STRIPE_WEBHOOK_SECRET) {
    throw new Error("Stripe webhook secret is not configured.");
  }
  return STRIPE_WEBHOOK_SECRET;
}
var stripeClient;
var init_stripe = __esm({
  "src/lib/stripe.ts"() {
    "use strict";
    init_stripe_esm_node();
    init_config();
    stripeClient = null;
  }
});

// src/lib/admin-notifications.ts
async function listAdminUserIdsWith(session) {
  const rows = await session.select({ id: usersTable.id }).from(usersTable).where(inArray(usersTable.userRole, ["ADMIN", "SUPER_ADMIN"]));
  return rows.map((r) => r.id);
}
async function listAdminRecipientsWith(session) {
  return session.select({
    id: usersTable.id,
    email: usersTable.email,
    firstName: usersTable.firstName
  }).from(usersTable).where(inArray(usersTable.userRole, ["ADMIN", "SUPER_ADMIN"]));
}
async function notifyAdminsWith(session, input) {
  const adminIds = await listAdminUserIdsWith(session);
  if (adminIds.length === 0) return { notified: 0 };
  await Promise.all(
    adminIds.map(
      (adminId) => notifyInAppWith(session, {
        userId: adminId,
        category: input.category,
        severity: input.severity,
        title: input.title,
        body: input.body,
        actionLabel: input.actionLabel ?? null,
        actionHref: input.actionHref ?? null,
        ...input.metadata ? { metadata: input.metadata } : {}
      }).catch(() => null)
    )
  );
  return { notified: adminIds.length };
}
async function emailAdminsWith(session, input) {
  const recipients = await listAdminRecipientsWith(session);
  if (recipients.length === 0) {
    return { attempted: 0, sent: 0, skipped: 0, failed: 0 };
  }
  let sent = 0;
  let skipped = 0;
  let failed = 0;
  await Promise.all(
    recipients.map(async (recipient) => {
      const idempotencyKey = `${input.idempotencyKeyPrefix}:admin:${recipient.id}:email`;
      const reserved = await reserveNotificationDeliveryWith(session, {
        userId: recipient.id,
        channel: "EMAIL",
        category: input.category,
        idempotencyKey,
        status: "SKIPPED",
        provider: null,
        metadata: {
          kind: "admin_operational_email",
          ...input.metadata ?? {}
        }
      });
      if (!reserved.reserved) {
        skipped += 1;
        return;
      }
      const to = recipient.email.trim();
      if (!to) {
        await finalizeNotificationDeliveryWith(session, {
          idempotencyKey,
          status: "SKIPPED",
          provider: null,
          metadata: {
            ...reserved.row.metadata,
            reason: "no_email"
          }
        });
        skipped += 1;
        return;
      }
      try {
        const result = await deliverReminderEmailIgnoringPreferences({
          userId: recipient.id,
          to,
          firstName: recipient.firstName,
          category: input.category,
          title: input.title,
          intro: input.intro,
          lines: input.lines,
          actionLabel: input.actionLabel ?? null,
          actionHref: input.actionHref ?? null
        });
        await finalizeNotificationDeliveryWith(session, {
          idempotencyKey,
          status: result.status,
          provider: result.status === "SENT" ? "SMTP" : null,
          metadata: {
            ...reserved.row.metadata,
            reason: result.reason ?? null
          }
        });
        if (result.status === "SENT") {
          sent += 1;
        } else {
          skipped += 1;
        }
      } catch (error40) {
        await finalizeNotificationDeliveryWith(session, {
          idempotencyKey,
          status: "FAILED",
          provider: "SMTP",
          errorMessage: error40 instanceof Error ? error40.message : "Email failed.",
          metadata: reserved.row.metadata
        });
        failed += 1;
      }
    })
  );
  return { attempted: recipients.length, sent, skipped, failed };
}
var init_admin_notifications = __esm({
  "src/lib/admin-notifications.ts"() {
    "use strict";
    init_schema2();
    init_drizzle_orm();
    init_notification_dispatcher();
    init_notification_deliveries();
    init_notification_dispatcher();
  }
});

// src/routes/org.ts
var org_exports = {};
__export(org_exports, {
  default: () => org_default
});
function requireAuth(req, res, next) {
  void (async () => {
    const user = await resolveAuthenticatedUser(req.cookies?.wwn_token);
    if (!user) {
      res.status(401).json({ message: "Invalid or expired token." });
      return;
    }
    req.userId = user.id;
    next();
  })();
}
function normalizeEmail(value) {
  return value.toLowerCase().trim();
}
function getOrganizationMemberStatus(value) {
  return value === "PENDING" ? "PENDING" : "ACTIVE";
}
function handleError4(err, res) {
  if (err instanceof OrganizationTenantAccessError) {
    return res.status(err.statusCode).json({ message: err.message });
  }
  if (err instanceof external_exports.ZodError) {
    return res.status(400).json({
      message: "Invalid request payload.",
      errors: err.flatten()
    });
  }
  logger.error({ err }, "Unhandled organization member management error");
  return res.status(500).json({ message: "Internal server error." });
}
async function getSeatUsageWith(conn, organizationId) {
  const now = /* @__PURE__ */ new Date();
  const [membersRow, invitesRow] = await Promise.all([
    conn.select({ count: count() }).from(organizationMembersTable).where(eq(organizationMembersTable.organizationId, organizationId)).then((rows) => Number(rows[0]?.count ?? 0)),
    conn.select({ count: count() }).from(organizationInvitationsTable).where(
      and(
        eq(organizationInvitationsTable.organizationId, organizationId),
        eq(organizationInvitationsTable.status, "PENDING"),
        gt(organizationInvitationsTable.expiresAt, now)
      )
    ).then((rows) => Number(rows[0]?.count ?? 0))
  ]);
  return {
    seatsUsed: membersRow + invitesRow,
    memberCount: membersRow,
    pendingInvitationCount: invitesRow
  };
}
async function getSeatUsage(organizationId) {
  return getSeatUsageWith(db, organizationId);
}
function isUniqueViolation6(err) {
  if (typeof err !== "object" || err === null) return false;
  const record2 = err;
  const directCode = typeof record2.code === "string" ? record2.code : null;
  const cause = record2.cause;
  const causeCode = typeof cause === "object" && cause !== null && "code" in cause && typeof cause.code === "string" ? cause.code : null;
  return directCode === "23505" || causeCode === "23505";
}
function assertSeatAvailable(seatLimit, seatsUsed) {
  if (seatLimit !== null && seatsUsed >= seatLimit) {
    throw Object.assign(
      new OrganizationTenantAccessError(
        "Your organization has reached its seat limit. Upgrade the plan or remove a pending seat before adding another member.",
        409
      )
    );
  }
}
function toIsoStringOrNull2(value) {
  return value ? value.toISOString() : null;
}
function assertOrganizationSusuManager(context) {
  if (!context.permissions.isOwner && !context.permissions.isAdmin) {
    throw new OrganizationTenantAccessError(
      "Only the organization authority and admins can manage organization ROSCA circles (Susu).",
      403,
      "role_check"
    );
  }
}
function assertOrganizationAscaManager(context) {
  if (!context.permissions.isOwner && !context.permissions.isAdmin) {
    throw new OrganizationTenantAccessError(
      "Only the organization authority and admins can manage organization ASCA groups.",
      403,
      "role_check"
    );
  }
}
function assertOrganizationLendingPoolManager(context) {
  if (!context.permissions.isOwner && !context.permissions.isAdmin) {
    throw new OrganizationTenantAccessError(
      "Only the organization authority and admins can manage organization lending pools.",
      403,
      "role_check"
    );
  }
}
function assertOrganizationProductAccess(context, feature) {
  const entry = context.productAccess[feature];
  if (!entry?.allowed) {
    throw new OrganizationTenantAccessError(
      entry?.reason ?? `Your organization plan does not include access to this feature.`,
      403,
      "entitlement_check"
    );
  }
}
async function requireOrganizationLendingParticipantAccess(userId) {
  return requireOrganizationAuthorization(userId, {
    capability: "asca_lending_pool_access",
    productFeature: "ASCA_LENDING_POOL",
    roleAction: "tenant_operate"
  });
}
function addPeriod3(start, frequency, index2) {
  if (frequency === "WEEKLY") return addDays5(start, 7 * index2);
  if (frequency === "BIWEEKLY") return addDays5(start, 14 * index2);
  return addMonths5(start, index2);
}
async function ensureLendingMasterWalletWith2(conn) {
  return ensureWalletWith3(
    conn,
    "LENDING_MASTER",
    LENDING_MASTER_WALLET_OWNER_ID2
  );
}
async function getLendingMasterWalletBalanceWith2(conn) {
  const wallet = await ensureLendingMasterWalletWith2(conn);
  return getWalletBalanceWith2(conn, wallet.id);
}
function serializeHelpingHandRepayment(repayment) {
  const amount = Number(repayment.amount);
  const rawPaidAmount = repayment.paidAmount !== null ? Number(repayment.paidAmount) : null;
  const normalizedPaidAmount = repayment.status === "PAID" && (rawPaidAmount === null || !Number.isFinite(rawPaidAmount) || rawPaidAmount <= 0) ? amount : rawPaidAmount;
  return {
    id: repayment.id,
    dueDate: repayment.dueDate.toISOString(),
    amount: String(repayment.amount),
    paidAmount: normalizedPaidAmount !== null ? String(normalizedPaidAmount) : null,
    paidAt: repayment.paidAt?.toISOString() ?? null,
    status: repayment.status,
    method: repayment.method ?? null,
    createdAt: repayment.createdAt.toISOString(),
    updatedAt: repayment.updatedAt.toISOString()
  };
}
function assertOrganizationSusuMatchingFundManager(context) {
  if (!context.permissions.isOwner && !context.permissions.isAdmin) {
    throw new OrganizationTenantAccessError(
      "Only the organization authority and admins can manage organization Susu Matching Fund applications.",
      403,
      "role_check"
    );
  }
}
async function requireOrganizationMatchingFundAccess(userId) {
  return requireOrganizationAuthorization(userId, {
    capability: "susu_matching_fund_access",
    productFeature: "SUSU_MATCHING_FUND",
    roleAction: "tenant_operate"
  });
}
async function getOrgHelpingHandEligibilitySnapshot(userId, organizationId) {
  const [
    circleRows,
    contributionRows,
    payoutRows,
    activeHelpingHandRows,
    outstandingRepaymentRows
  ] = await Promise.all([
    db.select({
      circleId: savingsCirclesTable.id,
      circleName: savingsCirclesTable.name,
      helpingHandMultiplier: savingsCirclesTable.helpingHandMultiplier
    }).from(circleMembershipsTable).innerJoin(
      savingsCirclesTable,
      eq(circleMembershipsTable.circleId, savingsCirclesTable.id)
    ).where(
      and(
        eq(circleMembershipsTable.userId, userId),
        eq(savingsCirclesTable.organizationId, organizationId)
      )
    ),
    db.select({
      circleId: savingsContributionsTable.circleId,
      total: count(),
      missed: sql`count(*) filter (where ${savingsContributionsTable.status} = 'MISSED')`
    }).from(savingsContributionsTable).innerJoin(
      savingsCirclesTable,
      eq(savingsContributionsTable.circleId, savingsCirclesTable.id)
    ).where(
      and(
        eq(savingsContributionsTable.userId, userId),
        eq(savingsCirclesTable.organizationId, organizationId)
      )
    ).groupBy(savingsContributionsTable.circleId),
    db.select({
      circleId: circlePayoutsTable.circleId,
      payoutId: circlePayoutsTable.id,
      scheduledDate: circlePayoutsTable.scheduledDate,
      paidDate: circlePayoutsTable.paidDate,
      amount: circlePayoutsTable.amount
    }).from(circlePayoutsTable).innerJoin(
      savingsCirclesTable,
      eq(circlePayoutsTable.circleId, savingsCirclesTable.id)
    ).where(
      and(
        eq(circlePayoutsTable.userId, userId),
        eq(circlePayoutsTable.status, "PAID"),
        eq(savingsCirclesTable.organizationId, organizationId)
      )
    ).orderBy(desc(circlePayoutsTable.paidDate), desc(circlePayoutsTable.id)),
    db.select({ count: count() }).from(helpingHandApplicationsTable).where(
      and(
        eq(helpingHandApplicationsTable.userId, userId),
        eq(helpingHandApplicationsTable.organizationId, organizationId),
        inArray(helpingHandApplicationsTable.status, [
          ...BLOCKING_HELPING_HAND_DEBT_STATUSES
        ])
      )
    ),
    db.select({
      count: count()
    }).from(helpingHandRepaymentsTable).innerJoin(
      helpingHandApplicationsTable,
      eq(
        helpingHandRepaymentsTable.helpingHandApplicationId,
        helpingHandApplicationsTable.id
      )
    ).where(
      and(
        eq(helpingHandApplicationsTable.userId, userId),
        eq(helpingHandApplicationsTable.organizationId, organizationId),
        inArray(helpingHandRepaymentsTable.status, ["PENDING", "LATE"])
      )
    )
  ]);
  const susuParticipationCount = circleRows.length;
  const payoutContextCount = payoutRows.length;
  const contributionByCircleId = new Map(
    contributionRows.map((row) => [
      row.circleId,
      {
        total: Number(row.total ?? 0),
        missed: Number(row.missed ?? 0)
      }
    ])
  );
  const payoutByCircleId = new Map(
    payoutRows.map((row) => [
      row.circleId,
      {
        payoutId: row.payoutId,
        amount: Number(row.amount),
        scheduledDate: row.scheduledDate,
        paidDate: row.paidDate
      }
    ])
  );
  const totalContributionCount = contributionRows.reduce(
    (sum3, row) => sum3 + Number(row.total ?? 0),
    0
  );
  const missedContributionCount = contributionRows.reduce(
    (sum3, row) => sum3 + Number(row.missed ?? 0),
    0
  );
  const activeHelpingHandDebtCount = Number(
    activeHelpingHandRows[0]?.count ?? 0
  );
  const outstandingHelpingHandRepaymentCount = Number(
    outstandingRepaymentRows[0]?.count ?? 0
  );
  const payoutContextOptions = circleRows.map((circle) => {
    const contributionStats = contributionByCircleId.get(circle.circleId) ?? {
      total: 0,
      missed: 0
    };
    const payout = payoutByCircleId.get(circle.circleId) ?? null;
    const multiplier = circle.helpingHandMultiplier !== null ? Number(circle.helpingHandMultiplier) : null;
    const maxRequestAmount = payout && multiplier !== null && Number.isFinite(multiplier) && multiplier > 0 ? Number((payout.amount * multiplier).toFixed(2)) : null;
    return {
      circleId: circle.circleId,
      circleName: circle.circleName,
      payoutId: payout?.payoutId ?? null,
      payoutAmount: payout?.amount ?? null,
      payoutPaidDate: payout?.paidDate ?? null,
      payoutScheduledDate: payout?.scheduledDate ?? null,
      contributionCount: contributionStats.total,
      missedContributionCount: contributionStats.missed,
      multiplier,
      maxRequestAmount
    };
  }).filter((option) => option.payoutId !== null).sort(
    (a, b) => new Date(b.payoutPaidDate ?? 0).getTime() - new Date(a.payoutPaidDate ?? 0).getTime()
  );
  const qualifyingOptions = payoutContextOptions.filter(
    (option) => option.missedContributionCount === 0 && option.maxRequestAmount !== null
  ).sort((a, b) => {
    if ((b.maxRequestAmount ?? 0) !== (a.maxRequestAmount ?? 0)) {
      return (b.maxRequestAmount ?? 0) - (a.maxRequestAmount ?? 0);
    }
    return new Date(b.payoutPaidDate ?? 0).getTime() - new Date(a.payoutPaidDate ?? 0).getTime();
  });
  const qualifyingOption = qualifyingOptions[0] ?? null;
  const payoutContextOption = payoutContextOptions[0] ?? null;
  const reasons = [];
  if (activeHelpingHandDebtCount > 0) {
    reasons.push(
      "Finish repaying your current SUSU Matching Fund balance first."
    );
  }
  if (outstandingHelpingHandRepaymentCount > 0) {
    reasons.push("Clear your outstanding SUSU Matching Fund repayments first.");
  }
  if (susuParticipationCount === 0) {
    reasons.push("Join a ROSCA circle (Susu) first.");
  }
  if (susuParticipationCount > 0 && payoutContextCount === 0) {
    reasons.push("Receive your SUSU payout first.");
  }
  if (susuParticipationCount > 0 && qualifyingOption === null) {
    const hasMissedCirclePayments = circleRows.some(
      (circle) => (contributionByCircleId.get(circle.circleId)?.missed ?? 0) > 0
    );
    const hasPaidPayoutWithoutMultiplier = circleRows.some((circle) => {
      const payout = payoutByCircleId.get(circle.circleId);
      const multiplier = circle.helpingHandMultiplier !== null ? Number(circle.helpingHandMultiplier) : null;
      return payout && (multiplier === null || !Number.isFinite(multiplier) || multiplier <= 0);
    });
    if (hasMissedCirclePayments) {
      reasons.push("Complete your qualifying circle with no missed payments.");
    }
    if (hasPaidPayoutWithoutMultiplier) {
      reasons.push(
        "Matching Fund is not configured for your payout circle yet."
      );
    }
  }
  if (qualifyingOption === null && reasons.length === 0) {
    reasons.push("You do not have a qualifying SUSU payout yet.");
  }
  return {
    eligible: reasons.length === 0,
    reasons,
    inputs: {
      susuParticipationCount,
      payoutContextCount,
      maxRequestAmount: qualifyingOption?.maxRequestAmount ?? null,
      qualifyingCircleId: qualifyingOption?.circleId ?? payoutContextOption?.circleId ?? null,
      qualifyingCircleName: qualifyingOption?.circleName ?? payoutContextOption?.circleName ?? null,
      qualifyingPayoutId: qualifyingOption?.payoutId ?? payoutContextOption?.payoutId ?? null,
      qualifyingPayoutAmount: qualifyingOption?.payoutAmount ?? payoutContextOption?.payoutAmount ?? null,
      qualifyingMultiplier: qualifyingOption?.multiplier ?? null,
      latestPayoutScheduledDate: toIsoStringOrNull2(
        qualifyingOption?.payoutScheduledDate ?? payoutContextOption?.payoutScheduledDate ?? null
      ),
      latestPayoutPaidDate: toIsoStringOrNull2(
        qualifyingOption?.payoutPaidDate ?? payoutContextOption?.payoutPaidDate ?? null
      ),
      totalContributionCount,
      missedContributionCount,
      activeHelpingHandCount: activeHelpingHandDebtCount,
      outstandingHelpingHandRepaymentCount
    }
  };
}
function assertOrganizationBillingReadAccess(context) {
  if (!context.permissions.canManageBilling && !context.permissions.canViewFinancialReports) {
    throw new OrganizationTenantAccessError(
      "Your organization role is not allowed to access tenant billing records.",
      403,
      "role_check"
    );
  }
}
function assertOrganizationTreasuryAccess(context) {
  if (!context.permissions.canFundWallet && !context.permissions.canOperateWallet && !context.permissions.canViewFinancialReports) {
    throw new OrganizationTenantAccessError(
      "Your organization role is not allowed to access tenant treasury records.",
      403,
      "role_check"
    );
  }
}
async function requireOrganizationSusuParticipantAccess(userId) {
  return requireOrganizationAuthorization(userId, {
    capability: "org_susu_operate",
    productFeature: "ORG_SUSU",
    roleAction: "tenant_operate"
  });
}
async function requireOrganizationAscaParticipantAccess(userId) {
  return requireOrganizationAuthorization(userId, {
    capability: "asca_access",
    productFeature: "ASCA",
    roleAction: "tenant_operate"
  });
}
async function getOrganizationAscaForBorrowing(organizationId, ascaId) {
  const [asca] = await db.select().from(ascasTable).where(eq(ascasTable.id, ascaId));
  if (!asca || asca.organizationId !== organizationId) {
    return null;
  }
  const borrowingPolicy = getAscaBorrowingPolicy(asca.constitution);
  return { asca, borrowingPolicy };
}
async function getOrganizationAscaMemberRecord(ascaId, userId) {
  const [member] = await db.select().from(ascaMembersTable).where(
    and(
      eq(ascaMembersTable.ascaId, ascaId),
      eq(ascaMembersTable.userId, userId)
    )
  );
  return member ?? null;
}
async function getAscaReservedBorrowAmountWith(conn, ascaId) {
  const [row] = await conn.select({ total: sum(loanApplicationsTable.approvedAmount) }).from(loanApplicationsTable).where(
    and(
      eq(loanApplicationsTable.ascaId, ascaId),
      inArray(loanApplicationsTable.status, [
        "APPROVED",
        "APPROVED_RESERVED"
      ])
    )
  );
  return Number(row?.total ?? 0);
}
async function getAscaOutstandingBorrowAmountWith(conn, ascaId) {
  const [row] = await conn.select({ total: sum(loanApplicationsTable.disbursedAmount) }).from(loanApplicationsTable).where(
    and(
      eq(loanApplicationsTable.ascaId, ascaId),
      inArray(loanApplicationsTable.status, [
        ...OUTSTANDING_ASCA_BORROW_STATUSES
      ])
    )
  );
  return Number(row?.total ?? 0);
}
async function getAscaBorrowLiquiditySnapshotWith(conn, input) {
  const [walletFunds, reservedApprovals, outstandingAmount] = await Promise.all(
    [
      getWalletFundsWith(conn, input.escrowWalletId),
      getAscaReservedBorrowAmountWith(conn, input.ascaId),
      getAscaOutstandingBorrowAmountWith(conn, input.ascaId)
    ]
  );
  const reserveAmount = Math.max(
    0,
    walletFunds.balance * (input.liquidityReservePct / 100)
  );
  const availableToBorrow = Math.max(
    0,
    walletFunds.availableBalance - reserveAmount - reservedApprovals
  );
  return {
    balance: walletFunds.balance,
    availableBalance: walletFunds.availableBalance,
    reserveAmount,
    reservedApprovals,
    outstandingAmount,
    availableToBorrow
  };
}
function serializeAscaBorrowApplicationRow(row) {
  return {
    id: row.id,
    ascaId: row.ascaId,
    borrowerId: row.borrowerId,
    borrowerName: [row.borrowerFirstName, row.borrowerLastName].filter(Boolean).join(" ") || `Member #${row.borrowerId}`,
    requestedAmount: row.requestedAmount,
    approvedAmount: row.approvedAmount,
    disbursedAmount: row.disbursedAmount,
    borrowerAppreciationAmount: row.borrowerAppreciationAmount,
    totalRepayableAmount: row.totalRepayableAmount,
    estimatedInstallmentAmount: row.estimatedInstallmentAmount,
    repaymentFrequency: row.repaymentFrequency,
    termMonths: row.termMonths,
    purpose: row.purpose,
    notes: row.notes,
    status: row.status,
    reviewNote: row.reviewNote,
    createdAt: row.createdAt,
    reviewedAt: row.reviewedAt,
    disbursedAt: row.disbursedAt
  };
}
function addDays5(date6, days) {
  const next = new Date(date6);
  next.setDate(next.getDate() + days);
  return next;
}
function addMonths5(date6, months) {
  const next = new Date(date6);
  next.setMonth(next.getMonth() + months);
  return next;
}
function addAscaBorrowRepaymentPeriod(start, frequency, index2) {
  if (frequency === "WEEKLY") return addDays5(start, 7 * index2);
  if (frequency === "BIWEEKLY") return addDays5(start, 14 * index2);
  return addMonths5(start, index2);
}
function serializeAscaBorrowRepaymentRow(repayment) {
  return {
    id: repayment.id,
    dueDate: repayment.dueDate.toISOString(),
    amount: Number(repayment.amount),
    paidAmount: repayment.paidAmount ? Number(repayment.paidAmount) : null,
    paidAt: repayment.paidAt?.toISOString() ?? null,
    status: repayment.status,
    method: repayment.method ?? null,
    principalPaidAmount: Number(repayment.principalPaidAmount ?? 0),
    returnPaidAmount: Number(repayment.returnPaidAmount ?? 0),
    feePaidAmount: Number(repayment.feePaidAmount ?? 0),
    creditedToPoolAmount: Number(repayment.creditedToPoolAmount ?? 0),
    createdAt: repayment.createdAt.toISOString(),
    updatedAt: repayment.updatedAt.toISOString()
  };
}
function summarizeAscaBorrowRepayments(repayments) {
  let totalScheduledAmount = 0;
  let totalPaidAmount = 0;
  let outstandingBalance = 0;
  let repaymentsReturnedToPool = 0;
  let overdueCount = 0;
  let settledRepaymentCount = 0;
  let nextDueAt = null;
  const now = Date.now();
  for (const repayment of repayments) {
    const amount = parseMoneyAmount(repayment.amount);
    const paidAmount = parseMoneyAmount(repayment.paidAmount);
    const remaining = Math.max(0, amount - paidAmount);
    totalScheduledAmount += amount;
    totalPaidAmount += paidAmount;
    outstandingBalance += remaining;
    repaymentsReturnedToPool += parseMoneyAmount(
      repayment.creditedToPoolAmount
    );
    if (["PAID", "WAIVED"].includes(repayment.status)) {
      settledRepaymentCount += 1;
      continue;
    }
    if (repayment.dueDate.getTime() < now) {
      overdueCount += 1;
    }
    if (!nextDueAt || repayment.dueDate.getTime() < new Date(nextDueAt).getTime()) {
      nextDueAt = repayment.dueDate.toISOString();
    }
  }
  return {
    totalRepayments: repayments.length,
    settledRepaymentCount,
    outstandingRepaymentCount: Math.max(
      0,
      repayments.length - settledRepaymentCount
    ),
    totalScheduledAmount: Number(formatMoneyAmount(totalScheduledAmount)),
    totalPaidAmount: Number(formatMoneyAmount(totalPaidAmount)),
    outstandingBalance: Number(formatMoneyAmount(outstandingBalance)),
    repaymentsReturnedToPool: Number(
      formatMoneyAmount(repaymentsReturnedToPool)
    ),
    overdueCount,
    nextDueAt
  };
}
async function ensureAscaBorrowRepaymentsWith(conn, application) {
  let repayments = await conn.select().from(loanRepaymentsTable).where(eq(loanRepaymentsTable.loanApplicationId, application.id)).orderBy(asc(loanRepaymentsTable.dueDate));
  if (!["FUNDED", "REPAYING", "CLOSED"].includes(application.status)) {
    return repayments;
  }
  const totalRepayableAmount = parseMoneyAmount(
    application.totalRepayableAmount
  );
  const termMonths = Number(application.termMonths ?? 0);
  const repaymentFrequency = application.repaymentFrequency ?? "MONTHLY";
  if (!(totalRepayableAmount > 0 && termMonths > 0)) {
    return repayments;
  }
  const schedule = buildLendingRepaymentSchedule({
    totalAmount: totalRepayableAmount,
    termMonths,
    repaymentFrequency,
    firstDueDate: addAscaBorrowRepaymentPeriod(
      application.disbursedAt ?? application.reviewedAt ?? /* @__PURE__ */ new Date(),
      repaymentFrequency,
      1
    )
  });
  const shouldReplaceSchedule = repayments.length > 0 && canReplaceLoanRepaymentSchedule(repayments) && !doesLoanRepaymentScheduleMatch(repayments, schedule);
  if (shouldReplaceSchedule) {
    await conn.delete(loanRepaymentsTable).where(eq(loanRepaymentsTable.loanApplicationId, application.id));
  }
  if (schedule.length > 0 && (repayments.length === 0 || shouldReplaceSchedule)) {
    await conn.insert(loanRepaymentsTable).values(
      schedule.map((entry) => ({
        loanApplicationId: application.id,
        dueDate: entry.dueDate,
        amount: entry.amount
      }))
    );
    repayments = await conn.select().from(loanRepaymentsTable).where(eq(loanRepaymentsTable.loanApplicationId, application.id)).orderBy(asc(loanRepaymentsTable.dueDate));
  }
  return repayments;
}
async function getAscaBorrowMetricsWith(conn, ascaId) {
  const [applications, repaymentRows] = await Promise.all([
    conn.select({
      id: loanApplicationsTable.id,
      status: loanApplicationsTable.status,
      disbursedAmount: loanApplicationsTable.disbursedAmount
    }).from(loanApplicationsTable).where(eq(loanApplicationsTable.ascaId, ascaId)),
    conn.select({
      applicationId: loanRepaymentsTable.loanApplicationId,
      status: loanRepaymentsTable.status,
      principalPaidAmount: loanRepaymentsTable.principalPaidAmount,
      creditedToPoolAmount: loanRepaymentsTable.creditedToPoolAmount
    }).from(loanRepaymentsTable).innerJoin(
      loanApplicationsTable,
      eq(loanRepaymentsTable.loanApplicationId, loanApplicationsTable.id)
    ).where(eq(loanApplicationsTable.ascaId, ascaId))
  ]);
  const principalPaidByApplication = /* @__PURE__ */ new Map();
  const overdueApplicationIds = /* @__PURE__ */ new Set();
  let repaymentsReturnedToPool = 0;
  for (const row of repaymentRows) {
    principalPaidByApplication.set(
      row.applicationId,
      (principalPaidByApplication.get(row.applicationId) ?? 0) + parseMoneyAmount(row.principalPaidAmount)
    );
    repaymentsReturnedToPool += parseMoneyAmount(row.creditedToPoolAmount);
    if (row.status === "LATE") {
      overdueApplicationIds.add(row.applicationId);
    }
  }
  let lentOutAmount = 0;
  let activeLoanCount = 0;
  for (const application of applications) {
    const disbursedAmount = parseMoneyAmount(application.disbursedAmount);
    const principalPaid = principalPaidByApplication.get(application.id) ?? 0;
    lentOutAmount += Math.max(0, disbursedAmount - principalPaid);
    if (["FUNDED", "REPAYING"].includes(application.status)) {
      activeLoanCount += 1;
    }
  }
  return {
    lentOutAmount: Number(formatMoneyAmount(lentOutAmount)),
    activeLoanCount,
    overdueLoanCount: overdueApplicationIds.size,
    repaymentsReturnedToPool: Number(
      formatMoneyAmount(repaymentsReturnedToPool)
    )
  };
}
async function requireOrganizationInvestmentParticipantAccess(userId) {
  const context = await requireOrganizationAuthorization(userId, {
    roleAction: "tenant_operate"
  });
  if (!context.productAccess.INVESTMENT_CLUB.allowed && !context.productAccess.P2P_CAPITAL.allowed) {
    throw new OrganizationTenantAccessError(
      "Your organization plan does not include investment access.",
      403,
      "entitlement_check"
    );
  }
  return context;
}
function normalizeOrgInvestmentOpportunity(opportunity, organizationName) {
  const pct = Number(opportunity.expectedReturnPct ?? 0);
  return {
    ...opportunity,
    id: String(opportunity.id),
    organization: organizationName,
    category: opportunity.category,
    fundingModel: opportunity.fundingModel ?? "CROWD",
    riskLevel: opportunity.riskLevel,
    minInvestment: Number(opportunity.minInvestment ?? 0),
    targetAmount: Number(opportunity.targetAmount ?? 0),
    raisedAmount: Number(opportunity.raisedAmount ?? 0),
    returnRateLow: Number.isFinite(pct) ? pct : null,
    returnRateHigh: Number.isFinite(pct) ? pct : null,
    closingDate: opportunity.deadline ? new Date(opportunity.deadline).toISOString().split("T")[0] : null,
    description: opportunity.description,
    termsHtml: opportunity.termsHtml ?? null,
    highlights: Array.isArray(opportunity.highlights) ? opportunity.highlights : [],
    eligibleInvestorTiers: Array.isArray(opportunity.eligibleInvestorTiers) ? opportunity.eligibleInvestorTiers : [],
    expectedReturn: `${opportunity.expectedReturnPct}% p.a.`,
    term: formatTermFromDeadline({
      startAt: /* @__PURE__ */ new Date(),
      deadline: opportunity.deadline
    })
  };
}
async function getWalletCashoutReservedBalanceWith(conn, walletId, excludeIntentId) {
  const whereClause = excludeIntentId ? and(
    eq(walletPaymentIntentsTable.walletId, walletId),
    eq(walletPaymentIntentsTable.type, "CASH_OUT"),
    inArray(walletPaymentIntentsTable.status, [
      "CREATED",
      "PENDING"
    ]),
    ne(walletPaymentIntentsTable.id, excludeIntentId)
  ) : and(
    eq(walletPaymentIntentsTable.walletId, walletId),
    eq(walletPaymentIntentsTable.type, "CASH_OUT"),
    inArray(walletPaymentIntentsTable.status, [
      "CREATED",
      "PENDING"
    ])
  );
  const [row] = await conn.select({ total: sum(walletPaymentIntentsTable.amount) }).from(walletPaymentIntentsTable).where(whereClause);
  return Number(row?.total ?? 0);
}
async function getWalletReservedBalanceWith2(conn, walletId, excludeInterestId) {
  const whereClause = excludeInterestId ? and(
    eq(investmentIntentReservationsTable.walletId, walletId),
    eq(investmentIntentReservationsTable.status, "RESERVED"),
    eq(investmentInterestsTable.status, "PENDING"),
    ne(investmentIntentReservationsTable.interestId, excludeInterestId)
  ) : and(
    eq(investmentIntentReservationsTable.walletId, walletId),
    eq(investmentIntentReservationsTable.status, "RESERVED"),
    eq(investmentInterestsTable.status, "PENDING")
  );
  const [row] = await conn.select({ total: sum(investmentIntentReservationsTable.amount) }).from(investmentIntentReservationsTable).innerJoin(
    investmentInterestsTable,
    eq(
      investmentIntentReservationsTable.interestId,
      investmentInterestsTable.id
    )
  ).where(whereClause);
  return Number(row?.total ?? 0);
}
async function getWalletFundsWith(conn, walletId, excludeInterestId) {
  const [balance, reservedBalance, cashoutReservedBalance] = await Promise.all([
    getWalletBalanceWith2(conn, walletId),
    getWalletReservedBalanceWith2(conn, walletId, excludeInterestId),
    getWalletCashoutReservedBalanceWith(conn, walletId)
  ]);
  const totalReservedBalance = reservedBalance + cashoutReservedBalance;
  return {
    balance,
    reservedBalance: totalReservedBalance,
    availableBalance: Math.max(0, balance - totalReservedBalance)
  };
}
async function getInvestmentOpportunityCapacityWith(conn, input) {
  const [opp] = await conn.select({
    id: investmentOpportunitiesTable.id,
    targetAmount: investmentOpportunitiesTable.targetAmount
  }).from(investmentOpportunitiesTable).where(eq(investmentOpportunitiesTable.id, input.opportunityId));
  if (!opp) return null;
  const [confirmedRows, reservedRows] = await Promise.all([
    conn.select({ total: sum(investmentInterestsTable.amount) }).from(investmentInterestsTable).where(
      and(
        eq(investmentInterestsTable.opportunityId, input.opportunityId),
        eq(investmentInterestsTable.status, "CONFIRMED")
      )
    ),
    conn.select({ total: sum(investmentIntentReservationsTable.amount) }).from(investmentIntentReservationsTable).innerJoin(
      investmentInterestsTable,
      eq(
        investmentIntentReservationsTable.interestId,
        investmentInterestsTable.id
      )
    ).where(
      and(
        eq(investmentInterestsTable.opportunityId, input.opportunityId),
        eq(investmentIntentReservationsTable.status, "RESERVED"),
        eq(investmentInterestsTable.status, "PENDING"),
        input.excludePendingInterestId ? ne(investmentInterestsTable.id, input.excludePendingInterestId) : void 0
      )
    )
  ]);
  return {
    targetAmount: Number(opp.targetAmount ?? 0),
    confirmedTotal: Number(confirmedRows[0]?.total ?? 0),
    reservedPendingTotal: Number(reservedRows[0]?.total ?? 0)
  };
}
function formatDisplayName(firstName, lastName) {
  return [firstName, lastName].filter(Boolean).join(" ").trim();
}
function toNullableTrimmed(value) {
  const trimmed = value?.trim();
  return trimmed ? trimmed : null;
}
function serializeOrganizationQuoteRequest(intake) {
  if (!intake) return null;
  return {
    id: intake.id,
    status: intake.status,
    programInterests: intake.programInterests ?? null,
    annualBudget: intake.annualBudget ?? null,
    staffCount: intake.staffCount ?? null,
    goals: intake.goals ?? null,
    additionalNotes: intake.additionalNotes ?? null,
    quoteAmount: intake.quoteAmount?.toString() ?? null,
    quoteNote: intake.quoteNote ?? null,
    quoteLink: intake.quoteLink ?? null,
    reviewedAt: toIsoStringOrNull2(intake.reviewedAt),
    createdAt: intake.createdAt.toISOString(),
    updatedAt: intake.updatedAt.toISOString()
  };
}
async function getOrganizationBillingOwners(organizationId) {
  return db.select({
    userId: organizationMembersTable.userId,
    role: organizationMembersTable.role,
    firstName: usersTable.firstName,
    lastName: usersTable.lastName,
    email: usersTable.email,
    phone: usersTable.phone
  }).from(organizationMembersTable).innerJoin(usersTable, eq(organizationMembersTable.userId, usersTable.id)).where(
    and(
      eq(organizationMembersTable.organizationId, organizationId),
      eq(organizationMembersTable.role, "OWNER")
    )
  ).orderBy(asc(organizationMembersTable.joinedAt));
}
async function getOrganizationBillingSummary(context) {
  const [owners, subscriptionHistory, intake] = await Promise.all([
    getOrganizationBillingOwners(context.organization.id),
    db.select({
      id: organizationSubscriptionsTable.id,
      status: organizationSubscriptionsTable.status,
      startDate: organizationSubscriptionsTable.startDate,
      endDate: organizationSubscriptionsTable.endDate,
      renewsAt: organizationSubscriptionsTable.renewsAt,
      cancelledAt: organizationSubscriptionsTable.cancelledAt,
      stripeCustomerId: organizationSubscriptionsTable.stripeCustomerId,
      stripeSubscriptionId: organizationSubscriptionsTable.stripeSubscriptionId,
      createdAt: organizationSubscriptionsTable.createdAt,
      updatedAt: organizationSubscriptionsTable.updatedAt,
      planId: membershipPlansTable.id,
      planName: membershipPlansTable.name,
      planTier: membershipPlansTable.tier,
      planDescription: membershipPlansTable.description,
      planOrganizationType: membershipPlansTable.organizationType
    }).from(organizationSubscriptionsTable).leftJoin(
      membershipPlansTable,
      eq(organizationSubscriptionsTable.planId, membershipPlansTable.id)
    ).where(
      eq(
        organizationSubscriptionsTable.organizationId,
        context.organization.id
      )
    ).orderBy(desc(organizationSubscriptionsTable.createdAt)),
    db.select().from(organizationIntakesTable).where(
      eq(organizationIntakesTable.organizationId, context.organization.id)
    ).orderBy(desc(organizationIntakesTable.updatedAt)).limit(1).then((rows) => rows[0] ?? null)
  ]);
  const primaryOwner = owners[0] ?? null;
  const [organization] = await db.select({
    contactName: organizationsTable.contactName,
    contactTitle: organizationsTable.contactTitle
  }).from(organizationsTable).where(eq(organizationsTable.id, context.organization.id)).limit(1);
  const resolvedContactName = organization?.contactName?.trim() || (primaryOwner ? formatDisplayName(primaryOwner.firstName, primaryOwner.lastName) : null);
  const resolvedContactTitle = organization?.contactTitle?.trim() || (primaryOwner ? formatOrganizationRoleLabel(primaryOwner.role) : null);
  const contactSource = organization?.contactName?.trim() ? "organization_record" : primaryOwner ? "owner_profile" : "unassigned";
  const currentHistory = subscriptionHistory[0] ?? null;
  const billingMode = context.entitlements.quote_managed_only ? "quote_managed" : currentHistory?.stripeCustomerId || currentHistory?.stripeSubscriptionId ? "self_serve_stripe" : "manual_review";
  return {
    organization: context.organization,
    permissions: context.permissions,
    entitlements: context.entitlements,
    plan: context.plan,
    subscription: context.subscription,
    billing: {
      canManage: context.permissions.canManageBilling,
      canViewReports: context.permissions.canViewFinancialReports,
      billingMode,
      contact: {
        name: resolvedContactName,
        title: resolvedContactTitle,
        email: primaryOwner?.email ?? null,
        phone: primaryOwner?.phone ?? null,
        source: contactSource
      },
      owners: owners.map((owner) => ({
        userId: owner.userId,
        role: owner.role,
        roleLabel: formatOrganizationRoleLabel(owner.role),
        firstName: owner.firstName,
        lastName: owner.lastName ?? null,
        email: owner.email,
        phone: owner.phone ?? null
      }))
    },
    quoteRequest: serializeOrganizationQuoteRequest(intake),
    subscriptionHistory: subscriptionHistory.map((row) => ({
      id: row.id,
      status: row.status,
      startDate: toIsoStringOrNull2(row.startDate),
      endDate: toIsoStringOrNull2(row.endDate),
      renewsAt: toIsoStringOrNull2(row.renewsAt),
      cancelledAt: toIsoStringOrNull2(row.cancelledAt),
      createdAt: row.createdAt.toISOString(),
      updatedAt: row.updatedAt.toISOString(),
      stripeCustomerId: row.stripeCustomerId ?? null,
      stripeSubscriptionId: row.stripeSubscriptionId ?? null,
      plan: row.planId ? {
        id: row.planId,
        name: row.planName ?? "Unknown plan",
        tier: row.planTier ?? "Custom",
        description: row.planDescription ?? null,
        organizationType: row.planOrganizationType ?? null
      } : null
    }))
  };
}
async function ensureOrganizationTreasuryWallet(context) {
  return ensureWalletWith3(db, "ORGANIZATION", context.organization.id);
}
async function getOrganizationTreasuryTransactions(walletId) {
  const transactions = await db.select().from(walletTransactionsTable).where(
    or(
      eq(walletTransactionsTable.fromWalletId, walletId),
      eq(walletTransactionsTable.toWalletId, walletId)
    )
  ).orderBy(desc(walletTransactionsTable.createdAt)).limit(50);
  return transactions.map((transaction) => ({
    id: transaction.id,
    type: transaction.type,
    amount: Number(transaction.amount),
    direction: transaction.toWalletId === walletId ? "IN" : "OUT",
    createdAt: transaction.createdAt.toISOString(),
    metadata: transaction.metadata ?? {}
  }));
}
async function getOrganizationBankSettings(organizationId) {
  const [bankSettings] = await db.select().from(organizationBankSettingsTable).where(eq(organizationBankSettingsTable.organizationId, organizationId)).limit(1);
  return bankSettings ?? null;
}
function serializeOrganizationBankSettings(bankSettings) {
  return {
    configured: Boolean(bankSettings),
    eft: bankSettings ? {
      accountName: bankSettings.eftAccountName,
      institutionNumber: bankSettings.eftInstitutionNumber,
      transitNumber: bankSettings.eftTransitNumber,
      accountNumber: bankSettings.eftAccountNumber
    } : null,
    interac: bankSettings ? {
      recipientName: bankSettings.interacRecipientName,
      email: bankSettings.interacEmail
    } : null,
    charges: bankSettings ? {
      cashoutMinAmount: Number(bankSettings.cashoutMinAmount),
      cashoutFeePct: Number(bankSettings.cashoutFeePct),
      cashoutFeeFixed: Number(bankSettings.cashoutFeeFixed)
    } : null,
    updatedAt: bankSettings ? bankSettings.updatedAt.toISOString() : null
  };
}
async function getOrganizationTreasurySummary(context) {
  const wallet = await ensureOrganizationTreasuryWallet(context);
  const [balance, availableBalance, transactions, bankSettings] = await Promise.all([
    getWalletBalanceWith2(db, wallet.id),
    getWalletAvailableBalanceWith(db, wallet.id),
    getOrganizationTreasuryTransactions(wallet.id),
    getOrganizationBankSettings(context.organization.id)
  ]);
  return {
    organization: context.organization,
    permissions: context.permissions,
    entitlements: context.entitlements,
    treasury: {
      walletId: wallet.id,
      currency: wallet.currency,
      balance,
      reservedBalance: Math.max(0, balance - availableBalance),
      availableBalance,
      canOperate: context.permissions.canOperateWallet,
      canFund: context.permissions.canFundWallet,
      canViewReports: context.permissions.canViewFinancialReports,
      bankSettings: {
        canManage: context.permissions.canOperateWallet || context.permissions.canFundWallet,
        ...serializeOrganizationBankSettings(bankSettings)
      },
      transactions
    }
  };
}
async function listOrganizationMemberFundingIntents(context) {
  const rows = await db.select({
    id: walletPaymentIntentsTable.id,
    userId: walletPaymentIntentsTable.userId,
    walletId: walletPaymentIntentsTable.walletId,
    provider: walletPaymentIntentsTable.provider,
    type: walletPaymentIntentsTable.type,
    amount: walletPaymentIntentsTable.amount,
    currency: walletPaymentIntentsTable.currency,
    status: walletPaymentIntentsTable.status,
    providerReference: walletPaymentIntentsTable.providerReference,
    metadata: walletPaymentIntentsTable.metadata,
    createdAt: walletPaymentIntentsTable.createdAt,
    updatedAt: walletPaymentIntentsTable.updatedAt,
    email: usersTable.email,
    firstName: usersTable.firstName,
    lastName: usersTable.lastName,
    membershipRole: organizationMembersTable.role
  }).from(walletPaymentIntentsTable).innerJoin(usersTable, eq(walletPaymentIntentsTable.userId, usersTable.id)).innerJoin(
    organizationMembersTable,
    and(
      eq(organizationMembersTable.userId, walletPaymentIntentsTable.userId),
      eq(organizationMembersTable.organizationId, context.organization.id)
    )
  ).where(
    and(
      eq(walletPaymentIntentsTable.type, "TOP_UP"),
      inArray(walletPaymentIntentsTable.provider, [
        "MANUAL",
        "INTERAC"
      ]),
      sql`${walletPaymentIntentsTable.metadata} ->> 'source' = 'organization_member_wallet_funding'`,
      sql`${walletPaymentIntentsTable.metadata} ->> 'organizationId' = ${String(context.organization.id)}`
    )
  ).orderBy(desc(walletPaymentIntentsTable.createdAt)).limit(200);
  return rows.map((row) => ({
    id: row.id,
    userId: row.userId,
    walletId: row.walletId,
    provider: row.provider,
    type: row.type,
    amount: Number(row.amount),
    currency: row.currency,
    status: row.status,
    providerReference: row.providerReference ?? null,
    metadata: row.metadata ?? {},
    createdAt: row.createdAt.toISOString(),
    updatedAt: row.updatedAt.toISOString(),
    user: {
      id: row.userId,
      email: row.email,
      firstName: row.firstName,
      lastName: row.lastName,
      role: row.membershipRole
    }
  }));
}
function assertOrganizationContributionManager(context) {
  if (!context.permissions.canManageMemberContributions) {
    throw new OrganizationTenantAccessError(
      "Only the organization authority and admins can assign member obligations.",
      403,
      "role_check"
    );
  }
}
async function ensureOrganizationFinanceWalletWith(conn, context) {
  return ensureWalletWith3(conn, "ORGANIZATION", context.organization.id);
}
async function getOrganizationContributionMembers(organizationId) {
  return db.select({
    userId: organizationMembersTable.userId,
    role: organizationMembersTable.role,
    firstName: usersTable.firstName,
    lastName: usersTable.lastName,
    email: usersTable.email
  }).from(organizationMembersTable).innerJoin(usersTable, eq(organizationMembersTable.userId, usersTable.id)).where(eq(organizationMembersTable.organizationId, organizationId)).orderBy(
    asc(usersTable.firstName),
    asc(usersTable.lastName),
    asc(usersTable.email)
  );
}
async function getOrganizationContributionSummary(context, viewerUserId) {
  const canAssign = context.permissions.canManageMemberContributions;
  const [obligations, memberRoster, susuHistory, bankSettings, paymentRows] = await Promise.all([
    db.select({
      id: organizationMemberObligationsTable.id,
      memberUserId: organizationMemberObligationsTable.memberUserId,
      assignedByUserId: organizationMemberObligationsTable.assignedByUserId,
      kind: organizationMemberObligationsTable.kind,
      title: organizationMemberObligationsTable.title,
      description: organizationMemberObligationsTable.description,
      amount: organizationMemberObligationsTable.amount,
      currency: organizationMemberObligationsTable.currency,
      status: organizationMemberObligationsTable.status,
      dueDate: organizationMemberObligationsTable.dueDate,
      paidAt: organizationMemberObligationsTable.paidAt,
      createdAt: organizationMemberObligationsTable.createdAt,
      memberFirstName: usersTable.firstName,
      memberLastName: usersTable.lastName,
      memberEmail: usersTable.email
    }).from(organizationMemberObligationsTable).innerJoin(
      usersTable,
      eq(organizationMemberObligationsTable.memberUserId, usersTable.id)
    ).where(
      and(
        eq(
          organizationMemberObligationsTable.organizationId,
          context.organization.id
        ),
        canAssign ? sql`true` : eq(
          organizationMemberObligationsTable.memberUserId,
          viewerUserId
        )
      )
    ).orderBy(
      asc(organizationMemberObligationsTable.status),
      desc(organizationMemberObligationsTable.createdAt)
    ),
    canAssign ? getOrganizationContributionMembers(context.organization.id) : Promise.resolve([]),
    db.select({
      id: savingsContributionsTable.id,
      circleId: savingsContributionsTable.circleId,
      circleName: savingsCirclesTable.name,
      amount: savingsContributionsTable.amount,
      status: savingsContributionsTable.status,
      dueDate: savingsContributionsTable.dueDate,
      paidAt: savingsContributionsTable.paidAt,
      method: savingsContributionsTable.method,
      receiptRef: savingsContributionsTable.receiptRef,
      createdAt: savingsContributionsTable.createdAt
    }).from(savingsContributionsTable).innerJoin(
      savingsCirclesTable,
      eq(savingsContributionsTable.circleId, savingsCirclesTable.id)
    ).where(
      and(
        eq(savingsContributionsTable.userId, viewerUserId),
        eq(savingsCirclesTable.organizationId, context.organization.id)
      )
    ).orderBy(desc(savingsContributionsTable.createdAt)).limit(50),
    db.select().from(organizationBankSettingsTable).where(
      eq(
        organizationBankSettingsTable.organizationId,
        context.organization.id
      )
    ).limit(1).then((rows) => rows[0] ?? null),
    db.select({
      id: paymentsTable.id,
      userId: paymentsTable.userId,
      amount: paymentsTable.amount,
      currency: paymentsTable.currency,
      status: paymentsTable.status,
      method: paymentsTable.method,
      reference: paymentsTable.reference,
      processedAt: paymentsTable.processedAt,
      createdAt: paymentsTable.createdAt,
      metadata: paymentsTable.metadata,
      firstName: usersTable.firstName,
      lastName: usersTable.lastName,
      email: usersTable.email
    }).from(paymentsTable).innerJoin(usersTable, eq(paymentsTable.userId, usersTable.id)).where(
      and(
        inArray(paymentsTable.status, ["PENDING", "COMPLETED"]),
        sql`${paymentsTable.metadata} ->> 'source' = 'organization_member_obligation_bank_payment'`,
        sql`${paymentsTable.metadata} ->> 'organizationId' = ${String(context.organization.id)}`,
        canAssign ? sql`true` : eq(paymentsTable.userId, viewerUserId)
      )
    ).orderBy(desc(paymentsTable.createdAt)).limit(100)
  ]);
  const paymentByObligationId = /* @__PURE__ */ new Map();
  for (const payment of paymentRows) {
    const metadata = payment.metadata ?? {};
    const obligationId = Number(metadata["obligationId"]);
    if (Number.isFinite(obligationId) && !paymentByObligationId.has(obligationId)) {
      paymentByObligationId.set(obligationId, payment);
    }
  }
  const obligationHistory = obligations.filter((obligation) => obligation.memberUserId === viewerUserId).filter((obligation) => !paymentByObligationId.has(obligation.id)).map((obligation) => ({
    id: `obligation-${obligation.id}`,
    source: "OBLIGATION",
    title: obligation.title,
    amount: Number(obligation.amount),
    currency: obligation.currency,
    status: obligation.status,
    dueDate: toIsoStringOrNull2(obligation.dueDate),
    paidAt: toIsoStringOrNull2(obligation.paidAt),
    createdAt: obligation.createdAt.toISOString(),
    method: "WALLET",
    reference: obligation.kind
  }));
  const obligationPaymentHistory = paymentRows.map((payment) => {
    const metadata = payment.metadata ?? {};
    const title = typeof metadata["title"] === "string" && metadata["title"].trim().length ? metadata["title"] : "Organization obligation";
    const dueDate = typeof metadata["dueDate"] === "string" ? metadata["dueDate"] : null;
    return {
      id: `payment-${payment.id}`,
      source: "OBLIGATION",
      title,
      amount: Number(payment.amount),
      currency: payment.currency,
      status: payment.status,
      dueDate,
      paidAt: toIsoStringOrNull2(payment.processedAt),
      createdAt: payment.createdAt.toISOString(),
      method: payment.method,
      reference: payment.reference ?? null
    };
  });
  const susuContributionHistory = susuHistory.map((entry) => ({
    id: `org-susu-${entry.id}`,
    source: "ORG_SUSU",
    title: entry.circleName,
    amount: Number(entry.amount),
    currency: "CAD",
    status: entry.status,
    dueDate: entry.dueDate.toISOString(),
    paidAt: toIsoStringOrNull2(entry.paidAt),
    createdAt: entry.createdAt.toISOString(),
    method: entry.method,
    reference: entry.receiptRef ?? null
  }));
  return {
    organization: context.organization,
    permissions: context.permissions,
    entitlements: context.entitlements,
    assignment: {
      canAssign,
      members: memberRoster.map((member) => ({
        userId: member.userId,
        role: member.role,
        roleLabel: formatOrganizationRoleLabel(member.role),
        displayName: formatDisplayName(member.firstName, member.lastName),
        email: member.email
      }))
    },
    paymentMethods: {
      configured: Boolean(bankSettings),
      eft: bankSettings ? {
        accountName: bankSettings.eftAccountName,
        institutionNumber: bankSettings.eftInstitutionNumber,
        transitNumber: bankSettings.eftTransitNumber,
        accountNumber: bankSettings.eftAccountNumber
      } : null,
      interac: bankSettings ? {
        recipientName: bankSettings.interacRecipientName,
        email: bankSettings.interacEmail
      } : null,
      charges: bankSettings ? {
        cashoutMinAmount: Number(bankSettings.cashoutMinAmount),
        cashoutFeePct: Number(bankSettings.cashoutFeePct),
        cashoutFeeFixed: Number(bankSettings.cashoutFeeFixed)
      } : null,
      updatedAt: bankSettings ? bankSettings.updatedAt.toISOString() : null
    },
    obligations: obligations.map((obligation) => ({
      id: obligation.id,
      memberUserId: obligation.memberUserId,
      memberDisplayName: formatDisplayName(
        obligation.memberFirstName,
        obligation.memberLastName
      ),
      memberEmail: obligation.memberEmail,
      kind: obligation.kind,
      title: obligation.title,
      description: obligation.description ?? null,
      amount: Number(obligation.amount),
      currency: obligation.currency,
      status: obligation.status,
      dueDate: toIsoStringOrNull2(obligation.dueDate),
      paidAt: toIsoStringOrNull2(obligation.paidAt),
      createdAt: obligation.createdAt.toISOString(),
      canPay: obligation.memberUserId === viewerUserId && obligation.status === "PENDING" && !paymentByObligationId.has(obligation.id),
      submittedPaymentMethod: paymentByObligationId.get(obligation.id)?.method ?? null,
      submittedPaymentReference: paymentByObligationId.get(obligation.id)?.reference ?? null,
      submittedPaymentStatus: paymentByObligationId.get(obligation.id)?.status ?? null
    })),
    pendingPayments: canAssign ? paymentRows.filter((payment) => payment.status === "PENDING").map((payment) => {
      const metadata = payment.metadata ?? {};
      return {
        id: payment.id,
        title: typeof metadata["title"] === "string" ? metadata["title"] : "Organization obligation",
        memberDisplayName: formatDisplayName(
          payment.firstName,
          payment.lastName
        ),
        memberEmail: payment.email,
        amount: Number(payment.amount),
        currency: payment.currency,
        method: payment.method,
        reference: payment.reference ?? null,
        createdAt: payment.createdAt.toISOString(),
        obligationId: Number(metadata["obligationId"])
      };
    }) : [],
    myHistory: [
      ...obligationPaymentHistory,
      ...obligationHistory,
      ...susuContributionHistory
    ].sort((a, b) => b.createdAt.localeCompare(a.createdAt))
  };
}
async function getScopedOrganizationCircle(context, circleId) {
  const [circle] = await db.select().from(savingsCirclesTable).where(eq(savingsCirclesTable.id, circleId));
  if (!circle || circle.organizationId !== context.organization.id) {
    throw new OrganizationTenantAccessError(
      "Organization ROSCA circle (Susu) not found.",
      404,
      "record_scope_check"
    );
  }
  return circle;
}
async function getOrganizationSusuPreLaunchState(conn, context, circleId) {
  const [circle] = await conn.select().from(savingsCirclesTable).where(eq(savingsCirclesTable.id, circleId)).limit(1);
  if (!circle || circle.organizationId !== context.organization.id) {
    throw new OrganizationTenantAccessError(
      "Organization ROSCA circle (Susu) not found.",
      404,
      "record_scope_check"
    );
  }
  const runtimeStatus = getCircleRuntimeStatus({
    status: circle.status,
    startDate: circle.startDate
  });
  if (runtimeStatus !== "FORMING") {
    throw new OrganizationTenantAccessError(
      "Only forming organization circles can be updated or cancelled.",
      409,
      "state_check"
    );
  }
  const [memberCountRow] = await conn.select({ count: count() }).from(circleMembershipsTable).where(eq(circleMembershipsTable.circleId, circleId));
  const memberCount = Number(memberCountRow?.count ?? 0);
  if (memberCount > 1) {
    throw new OrganizationTenantAccessError(
      "This organization circle already has joined members and can no longer be changed before launch.",
      409,
      "state_check"
    );
  }
  const [seedMembership] = await conn.select().from(circleMembershipsTable).where(
    and(
      eq(circleMembershipsTable.circleId, circleId),
      eq(circleMembershipsTable.position, 1)
    )
  ).limit(1);
  if (!seedMembership) {
    throw new OrganizationTenantAccessError(
      "The founding circle membership could not be resolved.",
      409,
      "state_check"
    );
  }
  const [seedContribution] = await conn.select().from(savingsContributionsTable).where(
    and(
      eq(savingsContributionsTable.circleId, circleId),
      eq(savingsContributionsTable.userId, seedMembership.userId),
      eq(savingsContributionsTable.status, "PAID")
    )
  ).orderBy(
    asc(savingsContributionsTable.dueDate),
    asc(savingsContributionsTable.createdAt)
  ).limit(1);
  if (!seedContribution) {
    throw new OrganizationTenantAccessError(
      "The founding contribution could not be resolved.",
      409,
      "state_check"
    );
  }
  const circleTreasuryWallet = await ensureCircleTreasuryWalletWith(
    conn,
    circle
  );
  if (!circleTreasuryWallet) {
    throw new OrganizationTenantAccessError(
      "Organization circle treasury was not found.",
      404,
      "state_check"
    );
  }
  return {
    circle,
    memberCount,
    seedMembership,
    seedContribution,
    circleTreasuryWallet
  };
}
async function getOrganizationSusuCirclesSnapshot(context, userId) {
  const circles = await db.select().from(savingsCirclesTable).where(eq(savingsCirclesTable.organizationId, context.organization.id)).orderBy(desc(savingsCirclesTable.createdAt));
  if (!circles.length) {
    return [];
  }
  const circleIds = circles.map((circle) => circle.id);
  const [membershipRows, payoutRows, pendingContributionRows, walletSummaries] = await Promise.all([
    db.select({
      circleId: circleMembershipsTable.circleId,
      userId: circleMembershipsTable.userId,
      position: circleMembershipsTable.position,
      joinedAt: circleMembershipsTable.joinedAt,
      firstName: usersTable.firstName,
      lastName: usersTable.lastName,
      email: usersTable.email
    }).from(circleMembershipsTable).innerJoin(usersTable, eq(circleMembershipsTable.userId, usersTable.id)).where(inArray(circleMembershipsTable.circleId, circleIds)).orderBy(
      asc(circleMembershipsTable.circleId),
      asc(circleMembershipsTable.position)
    ),
    db.select({
      circleId: circlePayoutsTable.circleId,
      userId: circlePayoutsTable.userId,
      position: circlePayoutsTable.position,
      status: circlePayoutsTable.status,
      scheduledDate: circlePayoutsTable.scheduledDate,
      paidDate: circlePayoutsTable.paidDate,
      amount: circlePayoutsTable.amount
    }).from(circlePayoutsTable).where(inArray(circlePayoutsTable.circleId, circleIds)),
    db.select({
      circleId: savingsContributionsTable.circleId,
      id: savingsContributionsTable.id,
      dueDate: savingsContributionsTable.dueDate
    }).from(savingsContributionsTable).where(
      and(
        inArray(savingsContributionsTable.circleId, circleIds),
        eq(savingsContributionsTable.userId, userId),
        eq(savingsContributionsTable.status, "PENDING")
      )
    ).orderBy(asc(savingsContributionsTable.dueDate)),
    context.permissions.isOwner || context.permissions.isAdmin ? Promise.all(
      circles.map(
        (circle) => getCircleAllocationSummaryWith(db, circle.id)
      )
    ) : Promise.resolve([])
  ]);
  const membershipsByCircleId = /* @__PURE__ */ new Map();
  for (const row of membershipRows) {
    const current = membershipsByCircleId.get(row.circleId) ?? [];
    current.push(row);
    membershipsByCircleId.set(row.circleId, current);
  }
  const payoutsByCircleId = /* @__PURE__ */ new Map();
  for (const row of payoutRows) {
    const current = payoutsByCircleId.get(row.circleId) ?? [];
    current.push(row);
    payoutsByCircleId.set(row.circleId, current);
  }
  const pendingByCircleId = /* @__PURE__ */ new Map();
  for (const row of pendingContributionRows) {
    const current = pendingByCircleId.get(row.circleId) ?? [];
    current.push(row);
    pendingByCircleId.set(row.circleId, current);
  }
  const walletSummaryByCircleId = new Map(
    walletSummaries.filter(
      (summary) => Boolean(summary)
    ).map((summary) => [summary.owner.ownerId, summary])
  );
  const now = Date.now();
  return circles.map((circle) => {
    const runtimeStatus = getCircleRuntimeStatus({
      status: circle.status,
      startDate: circle.startDate
    });
    const members = membershipsByCircleId.get(circle.id) ?? [];
    const myMembership = members.find((member) => member.userId === userId) ?? null;
    const pendingRows = pendingByCircleId.get(circle.id) ?? [];
    const payoutRowsForCircle = payoutsByCircleId.get(circle.id) ?? [];
    const myPayout = payoutRowsForCircle.find(
      (payout) => payout.userId === userId && payout.position === (myMembership?.position ?? payout.position)
    ) ?? payoutRowsForCircle.find((payout) => payout.userId === userId) ?? null;
    const payoutAmount = Number(
      calculateCirclePayoutAmount(circle.contributionAmount, circle.maxMembers)
    );
    const nextDueRow = pendingRows[0] ?? null;
    const dueNowCount = pendingRows.filter(
      (row) => row.dueDate.getTime() <= now
    ).length;
    const walletSummary = walletSummaryByCircleId.get(circle.id) ?? null;
    return {
      id: circle.id,
      name: circle.name,
      description: circle.description ?? null,
      contributionAmount: Number(circle.contributionAmount),
      helpingHandMultiplier: circle.helpingHandMultiplier !== null ? Number(circle.helpingHandMultiplier) : null,
      frequency: circle.frequency,
      orgAutoDeductEnabled: circle.orgAutoDeductEnabled,
      maxMembers: circle.maxMembers,
      formingTimeoutDays: circle.formingTimeoutDays,
      isFreeToJoin: circle.isFreeToJoin,
      status: runtimeStatus,
      startDate: toIsoStringOrNull2(circle.startDate),
      endDate: toIsoStringOrNull2(circle.endDate),
      createdAt: circle.createdAt.toISOString(),
      currentMembers: members.length,
      canJoin: !myMembership && runtimeStatus === "FORMING" && isCircleCreatorSeatIntact({ circle, members }),
      canContribute: Boolean(myMembership) && runtimeStatus === "ACTIVE" && dueNowCount > 0,
      joinedAt: myMembership ? myMembership.joinedAt.toISOString() : null,
      myPosition: myMembership?.position ?? null,
      myPendingContributionCount: pendingRows.length,
      myDueContributionCount: dueNowCount,
      myNextDueDate: nextDueRow ? nextDueRow.dueDate.toISOString() : null,
      myPayoutAmount: payoutAmount,
      myPayoutReceived: myPayout?.status === "PAID",
      myPayoutDate: toIsoStringOrNull2(myPayout?.paidDate),
      members: members.map((member) => ({
        userId: member.userId,
        email: member.email,
        position: member.position,
        joinedAt: member.joinedAt.toISOString(),
        displayName: `${member.firstName}${member.lastName ? ` ${member.lastName[0]}.` : ""}`
      })),
      wallet: walletSummary ? {
        id: walletSummary.wallet.id,
        ownerType: walletSummary.owner.ownerType,
        ownerId: walletSummary.owner.ownerId,
        isDedicatedWallet: walletSummary.owner.isDedicatedWallet,
        balance: walletSummary.allocationBalance,
        treasuryBalance: walletSummary.treasuryBalance
      } : null
    };
  });
}
async function getOrganizationServiceRequestPayload(userId) {
  const context = await requireOrganizationAuthorization(userId);
  const intakes = await db.select().from(organizationIntakesTable).where(eq(organizationIntakesTable.organizationId, context.organization.id)).orderBy(
    desc(organizationIntakesTable.updatedAt),
    desc(organizationIntakesTable.createdAt),
    desc(organizationIntakesTable.id)
  );
  const latestIntake = intakes[0] ?? null;
  const serviceRequests = intakes.map(
    (intake) => serializeOrganizationQuoteRequest(intake)
  );
  return {
    context,
    serviceRequest: serializeOrganizationQuoteRequest(latestIntake),
    serviceRequests
  };
}
async function submitOrganizationServiceRequestWith(userId, payload) {
  const context = await requireOrganizationAuthorization(userId);
  const body = organizationQuoteRequestSchema.parse(payload ?? {});
  const now = /* @__PURE__ */ new Date();
  const [saved] = await db.insert(organizationIntakesTable).values({
    organizationId: context.organization.id,
    programInterests: body.programInterests,
    annualBudget: toNullableTrimmed(body.annualBudget),
    staffCount: toNullableTrimmed(body.staffCount),
    goals: toNullableTrimmed(body.goals),
    additionalNotes: toNullableTrimmed(body.additionalNotes),
    status: "PENDING",
    quoteAmount: null,
    quoteNote: null,
    quoteLink: null,
    reviewedByAdminId: null,
    reviewedAt: null,
    createdAt: now,
    updatedAt: now
  }).returning();
  const title = "New organization service request";
  const intro = `${context.organization.name} submitted a service request for WWN team services.`;
  const lines = [
    `Organization: ${context.organization.name}`,
    `Services requested: ${saved.programInterests ?? "Not provided"}`,
    `Budget: ${saved.annualBudget ?? "Not provided"}`,
    `Team size: ${saved.staffCount ?? "Not provided"}`
  ];
  void notifyAdminsWith(db, {
    category: "SYSTEM",
    severity: "INFO",
    title,
    body: `${context.organization.name} submitted a service request for WWN team services.`,
    actionLabel: "Open Organizations",
    actionHref: "/admin/organizations",
    metadata: {
      kind: "organization_service_request",
      organizationId: context.organization.id,
      intakeId: saved.id
    }
  }).catch(() => null);
  void emailAdminsWith(db, {
    category: "SYSTEM",
    title,
    intro,
    lines,
    actionLabel: "Open Organizations",
    actionHref: "/admin/organizations",
    idempotencyKeyPrefix: `organization_service_request:${context.organization.id}:${saved.updatedAt.getTime()}`,
    metadata: {
      kind: "organization_service_request",
      organizationId: context.organization.id,
      intakeId: saved.id
    }
  }).catch(() => null);
  const serviceRequest = serializeOrganizationQuoteRequest(saved);
  const serviceRequestPayload = await getOrganizationServiceRequestPayload(userId);
  return {
    quoteRequest: serviceRequest,
    serviceRequest,
    serviceRequests: serviceRequestPayload.serviceRequests,
    message: "Service request submitted."
  };
}
async function getIndividualPlanEntitlements(userId) {
  const [subscription] = await db.select({
    planEntitlements: membershipPlansTable.entitlements
  }).from(membershipSubscriptionsTable).innerJoin(
    membershipPlansTable,
    eq(membershipSubscriptionsTable.planId, membershipPlansTable.id)
  ).where(
    and(
      eq(membershipSubscriptionsTable.userId, userId),
      eq(membershipSubscriptionsTable.status, "ACTIVE")
    )
  ).limit(1);
  return normalizeIndividualPlanEntitlements(subscription?.planEntitlements);
}
async function getPoolReservedApprovalAmountWith(conn, poolId) {
  const [row] = await conn.select({ total: sum(loanApplicationsTable.approvedAmount) }).from(loanApplicationsTable).where(
    and(
      eq(loanApplicationsTable.opportunityId, poolId),
      inArray(loanApplicationsTable.status, [
        "APPROVED",
        "APPROVED_RESERVED"
      ])
    )
  );
  return Number(row?.total ?? 0);
}
async function getPoolOutstandingAmountWith(conn, poolId) {
  const [row] = await conn.select({ total: sum(loanApplicationsTable.disbursedAmount) }).from(loanApplicationsTable).where(
    and(
      eq(loanApplicationsTable.opportunityId, poolId),
      inArray(loanApplicationsTable.status, [
        "FUNDED",
        "REPAYING"
      ])
    )
  );
  return Number(row?.total ?? 0);
}
var import_express5, router5, ORG_MEMBER_INVITE_LOCK_KEY_A, ORG_ASCA_BORROW_REPAYMENT_LOCK_KEY_A, ORG_ROLE_VALUES, ORG_MEMBER_STATUS_VALUES, HELPING_HAND_REPAYMENT_CREATEABLE_APPLICATION_STATUSES2, HELPING_HAND_REPAYMENT_SERVICEABLE_APPLICATION_STATUSES2, BLOCKING_HELPING_HAND_DEBT_STATUSES, LENDING_MASTER_WALLET_OWNER_ID2, ACTIVE_ASCA_BORROW_APPLICATION_STATUSES, OUTSTANDING_ASCA_BORROW_STATUSES, updateOrganizationBillingSchema, organizationQuoteRequestSchema, createOrganizationTreasuryTopupIntentSchema, updateOrganizationBankSettingsV2Schema, updateOrganizationBankSettingsV1Schema, updateOrganizationBankSettingsSchema, updateOrganizationMembershipIdSettingsSchema, updateOrganizationSusuCircleSchema, createOrganizationMemberObligationSchema, organizationMemberObligationPaymentSchema, organizationLendingPoolUpsertSchema, org_default;
var init_org = __esm({
  "src/routes/org.ts"() {
    "use strict";
    import_express5 = __toESM(require_express2(), 1);
    init_zod();
    init_src2();
    init_investment_funding();
    init_schema2();
    init_drizzle_orm();
    init_mailer();
    init_auth_session();
    init_organization_invitations();
    init_organization_context();
    init_member_access();
    init_organization_authorization();
    init_logger();
    init_susu();
    init_stripe();
    init_admin_notifications();
    init_notification_dispatcher();
    init_asca();
    init_investments();
    init_lending();
    init_credit_score();
    init_helping_hand();
    init_individual_plan_entitlements();
    router5 = (0, import_express5.Router)();
    ORG_MEMBER_INVITE_LOCK_KEY_A = 41021;
    ORG_ASCA_BORROW_REPAYMENT_LOCK_KEY_A = 41037;
    ORG_ROLE_VALUES = ["OWNER", "ADMIN", "MEMBER"];
    ORG_MEMBER_STATUS_VALUES = ["PENDING", "ACTIVE"];
    HELPING_HAND_REPAYMENT_CREATEABLE_APPLICATION_STATUSES2 = /* @__PURE__ */ new Set([
      "FUNDED",
      "REPAYING"
    ]);
    HELPING_HAND_REPAYMENT_SERVICEABLE_APPLICATION_STATUSES2 = /* @__PURE__ */ new Set([
      "FUNDED",
      "REPAYING",
      "CLOSED"
    ]);
    BLOCKING_HELPING_HAND_DEBT_STATUSES = ["FUNDED", "REPAYING"];
    LENDING_MASTER_WALLET_OWNER_ID2 = 1;
    ACTIVE_ASCA_BORROW_APPLICATION_STATUSES = [
      "SUBMITTED",
      "WAITLISTED",
      "UNDER_REVIEW",
      "APPROVED",
      "APPROVED_RESERVED",
      "FUNDED",
      "REPAYING"
    ];
    OUTSTANDING_ASCA_BORROW_STATUSES = ["FUNDED", "REPAYING"];
    updateOrganizationBillingSchema = external_exports.object({
      contactName: external_exports.string().trim().min(1).max(120),
      contactTitle: external_exports.string().trim().max(120).optional().nullable()
    });
    organizationQuoteRequestSchema = external_exports.object({
      programInterests: external_exports.string().trim().min(1).max(2e3),
      annualBudget: external_exports.string().trim().max(120).optional().nullable(),
      staffCount: external_exports.string().trim().max(120).optional().nullable(),
      goals: external_exports.string().trim().max(2e3).optional().nullable(),
      additionalNotes: external_exports.string().trim().max(4e3).optional().nullable()
    });
    createOrganizationTreasuryTopupIntentSchema = external_exports.object({
      amount: external_exports.string().trim().min(1),
      provider: external_exports.enum(["STRIPE", "INTERAC", "MANUAL"]).optional(),
      metadata: external_exports.record(external_exports.unknown()).optional()
    });
    updateOrganizationBankSettingsV2Schema = external_exports.object({
      eft: external_exports.object({
        accountName: external_exports.string().trim().min(1).max(160),
        institutionNumber: external_exports.string().trim().min(1).max(32),
        transitNumber: external_exports.string().trim().min(1).max(32),
        accountNumber: external_exports.string().trim().min(1).max(32)
      }),
      interac: external_exports.object({
        recipientName: external_exports.string().trim().min(1).max(160),
        email: external_exports.string().trim().email().max(160)
      }),
      charges: external_exports.object({
        cashoutMinAmount: external_exports.coerce.number().min(0),
        cashoutFeePct: external_exports.coerce.number().min(0),
        cashoutFeeFixed: external_exports.coerce.number().min(0)
      })
    });
    updateOrganizationBankSettingsV1Schema = external_exports.object({
      eftAccountName: external_exports.string().trim().min(1).max(160),
      eftInstitutionNumber: external_exports.string().trim().min(1).max(32),
      eftTransitNumber: external_exports.string().trim().min(1).max(32),
      eftAccountNumber: external_exports.string().trim().min(1).max(32),
      interacRecipientName: external_exports.string().trim().min(1).max(160),
      interacEmail: external_exports.string().trim().email().max(160),
      cashoutMinAmount: external_exports.coerce.number().min(0).optional(),
      cashoutFeePct: external_exports.coerce.number().min(0).optional(),
      cashoutFeeFixed: external_exports.coerce.number().min(0).optional()
    });
    updateOrganizationBankSettingsSchema = external_exports.union([
      updateOrganizationBankSettingsV2Schema,
      updateOrganizationBankSettingsV1Schema
    ]);
    updateOrganizationMembershipIdSettingsSchema = external_exports.object({
      prefix: external_exports.string().trim().min(1).max(12).regex(/^[a-zA-Z0-9]+$/).transform((value) => value.toUpperCase()),
      digits: external_exports.coerce.number().int().min(4).max(12)
    });
    updateOrganizationSusuCircleSchema = external_exports.object({
      name: external_exports.string().trim().min(1).max(160),
      description: external_exports.string().trim().max(500).optional().nullable(),
      contributionAmount: external_exports.string().trim().min(1),
      helpingHandMultiplier: external_exports.string().trim().optional().nullable(),
      frequency: external_exports.enum(["WEEKLY", "BIWEEKLY", "MONTHLY"]),
      orgAutoDeductEnabled: external_exports.boolean().optional(),
      maxMembers: external_exports.number().int().min(2),
      startDate: external_exports.string().trim().optional().nullable(),
      formingTimeoutDays: external_exports.number().int().min(1),
      isFreeToJoin: external_exports.boolean().optional()
    });
    createOrganizationMemberObligationSchema = external_exports.object({
      memberUserId: external_exports.number().int().positive(),
      title: external_exports.string().trim().min(1).max(160),
      description: external_exports.string().trim().max(500).optional().nullable(),
      amount: external_exports.string().trim().min(1),
      dueDate: external_exports.string().datetime().optional().nullable()
    });
    organizationMemberObligationPaymentSchema = external_exports.object({
      method: external_exports.enum(["INTERAC", "EFT"])
    });
    router5.get("/org/invitations/:token", async (req, res) => {
      try {
        const token = req.params.token?.trim();
        if (!token) {
          return res.status(400).json({ message: "Invitation token is required." });
        }
        const invitation = await getActiveOrganizationInvitationByToken(token);
        if (!invitation) {
          return res.status(404).json({
            message: "This organization invitation is invalid or has expired."
          });
        }
        return res.json({
          invitation: {
            email: invitation.email,
            firstName: invitation.firstName ?? null,
            lastName: invitation.lastName ?? null,
            role: invitation.role,
            roleLabel: formatOrganizationRoleLabel(invitation.role),
            organization: {
              id: invitation.organizationId,
              name: invitation.organizationName,
              organizationType: invitation.organizationType,
              operationalStatus: invitation.operationalStatus
            },
            expiresAt: invitation.expiresAt.toISOString()
          }
        });
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.get("/org/members", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const context = await requireOrganizationAuthorization(userId, {
          capability: "member_management",
          roleAction: "members_manage"
        });
        const now = /* @__PURE__ */ new Date();
        const [members, invitations, seatUsage] = await Promise.all([
          db.select({
            id: organizationMembersTable.id,
            role: organizationMembersTable.role,
            membershipStatus: organizationMembersTable.status,
            joinedAt: organizationMembersTable.joinedAt,
            userId: usersTable.id,
            email: usersTable.email,
            firstName: usersTable.firstName,
            lastName: usersTable.lastName,
            isEmailVerified: usersTable.isEmailVerified,
            createdAt: usersTable.createdAt
          }).from(organizationMembersTable).innerJoin(
            usersTable,
            eq(organizationMembersTable.userId, usersTable.id)
          ).where(
            eq(organizationMembersTable.organizationId, context.organization.id)
          ).orderBy(
            sql`case ${organizationMembersTable.role}
            when 'OWNER' then 0
            when 'ADMIN' then 1
            else 2
          end`,
            usersTable.firstName,
            usersTable.lastName
          ),
          db.select({
            id: organizationInvitationsTable.id,
            email: organizationInvitationsTable.email,
            firstName: organizationInvitationsTable.firstName,
            lastName: organizationInvitationsTable.lastName,
            role: organizationInvitationsTable.role,
            status: organizationInvitationsTable.status,
            expiresAt: organizationInvitationsTable.expiresAt,
            createdAt: organizationInvitationsTable.createdAt
          }).from(organizationInvitationsTable).where(
            and(
              eq(
                organizationInvitationsTable.organizationId,
                context.organization.id
              ),
              eq(organizationInvitationsTable.status, "PENDING"),
              gt(organizationInvitationsTable.expiresAt, now)
            )
          ).orderBy(desc(organizationInvitationsTable.createdAt)),
          getSeatUsage(context.organization.id)
        ]);
        return res.json({
          organization: context.organization,
          permissions: context.permissions,
          entitlements: context.entitlements,
          seatUsage: {
            ...seatUsage,
            seatLimit: context.entitlements.seat_limit,
            seatsRemaining: context.entitlements.seat_limit === null ? null : Math.max(
              context.entitlements.seat_limit - seatUsage.seatsUsed,
              0
            )
          },
          members: members.map((member) => ({
            id: member.id,
            userId: member.userId,
            email: member.email,
            firstName: member.firstName,
            lastName: member.lastName ?? null,
            role: member.role,
            roleLabel: formatOrganizationRoleLabel(member.role),
            membershipStatus: getOrganizationMemberStatus(member.membershipStatus),
            isEmailVerified: member.isEmailVerified,
            joinedAt: member.joinedAt.toISOString(),
            createdAt: member.createdAt.toISOString()
          })),
          invitations: invitations.map((invitation) => ({
            id: invitation.id,
            email: invitation.email,
            firstName: invitation.firstName ?? null,
            lastName: invitation.lastName ?? null,
            role: invitation.role,
            roleLabel: formatOrganizationRoleLabel(invitation.role),
            status: invitation.status,
            expiresAt: invitation.expiresAt.toISOString(),
            createdAt: invitation.createdAt.toISOString()
          }))
        });
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.get("/org/resources", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        await requireOrganizationAuthorization(userId, {
          productFeature: "RESOURCES"
        });
        const [categories, resources] = await Promise.all([
          db.select({
            id: resourceCategoriesTable.id,
            name: resourceCategoriesTable.name,
            slug: resourceCategoriesTable.slug,
            sortOrder: resourceCategoriesTable.sortOrder
          }).from(resourceCategoriesTable).orderBy(asc(resourceCategoriesTable.sortOrder)),
          db.select({
            id: resourcesTable.id,
            title: resourcesTable.title,
            slug: resourcesTable.slug,
            description: resourcesTable.description,
            resourceKind: resourcesTable.resourceKind,
            categoryId: resourcesTable.categoryId,
            categoryName: resourceCategoriesTable.name,
            categorySlug: resourceCategoriesTable.slug,
            fileUrl: resourcesTable.fileUrl,
            fileType: resourcesTable.fileType,
            fileSize: resourcesTable.fileSize,
            coverImageUrl: resourcesTable.coverImageUrl,
            authorName: resourcesTable.authorName,
            contentHtml: resourcesTable.contentHtml,
            downloads: resourcesTable.downloads,
            publishedAt: resourcesTable.publishedAt,
            createdAt: resourcesTable.createdAt
          }).from(resourcesTable).leftJoin(
            resourceCategoriesTable,
            eq(resourcesTable.categoryId, resourceCategoriesTable.id)
          ).where(
            and(
              eq(resourcesTable.isPublished, true),
              eq(resourcesTable.showToOrganizations, true)
            )
          ).orderBy(
            desc(resourcesTable.publishedAt),
            desc(resourcesTable.createdAt)
          )
        ]);
        return res.json({
          categories,
          resources: resources.map((resource) => ({
            id: resource.id,
            title: resource.title,
            slug: resource.slug,
            description: resource.description ?? null,
            resourceKind: resource.resourceKind,
            category: resource.categoryName ? {
              id: resource.categoryId,
              name: resource.categoryName,
              slug: resource.categorySlug ?? null
            } : null,
            fileUrl: resource.fileUrl ?? null,
            fileType: resource.fileType,
            fileSize: resource.fileSize ?? null,
            coverImageUrl: resource.coverImageUrl ?? null,
            authorName: resource.authorName ?? null,
            contentHtml: resource.contentHtml ?? null,
            downloads: resource.downloads,
            publishedAt: toIsoStringOrNull2(resource.publishedAt),
            createdAt: toIsoStringOrNull2(resource.createdAt)
          }))
        });
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.get("/org/billing", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const context = await requireOrganizationAuthorization(userId);
        assertOrganizationBillingReadAccess(context);
        const summary = await getOrganizationBillingSummary(context);
        return res.json(summary);
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.patch("/org/billing", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const context = await requireOrganizationAuthorization(userId, {
          capability: "org_billing_manage",
          roleAction: "billing_manage"
        });
        const body = updateOrganizationBillingSchema.parse(req.body ?? {});
        await db.update(organizationsTable).set({
          contactName: body.contactName,
          contactTitle: body.contactTitle?.trim() || null,
          updatedAt: /* @__PURE__ */ new Date()
        }).where(eq(organizationsTable.id, context.organization.id));
        const summary = await getOrganizationBillingSummary(context);
        return res.json({
          billing: {
            contact: summary.billing.contact
          }
        });
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.get("/org/quote-request", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const payload = await getOrganizationServiceRequestPayload(userId);
        return res.json({
          quoteRequest: payload.serviceRequest,
          quoteRequests: payload.serviceRequests
        });
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.get("/org/service-request", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const payload = await getOrganizationServiceRequestPayload(userId);
        return res.json(payload);
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.post("/org/quote-request", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const payload = await submitOrganizationServiceRequestWith(
          userId,
          req.body
        );
        return res.status(201).json({
          quoteRequest: payload.serviceRequest,
          quoteRequests: payload.serviceRequests,
          message: payload.message
        });
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.post("/org/service-request", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const payload = await submitOrganizationServiceRequestWith(
          userId,
          req.body
        );
        return res.status(201).json(payload);
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.get("/org/membership-id-settings", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const context = await requireOrganizationAuthorization(userId);
        if (!context.permissions.isOwner && !context.permissions.isAdmin) {
          throw new OrganizationTenantAccessError(
            "Your organization role is not allowed to manage membership ID settings.",
            403,
            "role_check"
          );
        }
        const [orgSettings] = await db.select().from(organizationMembershipIdSettingsTable).where(
          eq(
            organizationMembershipIdSettingsTable.organizationId,
            context.organization.id
          )
        ).limit(1);
        const [platformSettings] = await db.select().from(membershipIdSettingsTable).where(eq(membershipIdSettingsTable.id, 1)).limit(1);
        const fallback = {
          prefix: platformSettings?.prefix ?? "WWN",
          digits: platformSettings?.digits ?? 7
        };
        return res.json({
          settings: {
            prefix: (orgSettings?.prefix ?? fallback.prefix).toUpperCase(),
            digits: Number(orgSettings?.digits ?? fallback.digits)
          },
          isDefault: !orgSettings
        });
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.patch("/org/membership-id-settings", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const context = await requireOrganizationAuthorization(userId);
        if (!context.permissions.isOwner && !context.permissions.isAdmin) {
          throw new OrganizationTenantAccessError(
            "Your organization role is not allowed to manage membership ID settings.",
            403,
            "role_check"
          );
        }
        const parsed = updateOrganizationMembershipIdSettingsSchema.parse(
          req.body ?? {}
        );
        const now = /* @__PURE__ */ new Date();
        const [saved] = await db.insert(organizationMembershipIdSettingsTable).values({
          organizationId: context.organization.id,
          prefix: parsed.prefix,
          digits: parsed.digits,
          updatedAt: now
        }).onConflictDoUpdate({
          target: organizationMembershipIdSettingsTable.organizationId,
          set: {
            prefix: parsed.prefix,
            digits: parsed.digits,
            updatedAt: now
          }
        }).returning();
        return res.json({
          settings: {
            prefix: saved.prefix,
            digits: Number(saved.digits)
          }
        });
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.patch("/org/treasury/bank-settings", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const context = await requireOrganizationAuthorization(userId);
        if (!context.permissions.canOperateWallet && !context.permissions.canFundWallet) {
          throw new OrganizationTenantAccessError(
            "Your organization role is not allowed to manage tenant bank settings.",
            403,
            "role_check"
          );
        }
        const parsed = updateOrganizationBankSettingsSchema.parse(req.body ?? {});
        const body = "eft" in parsed ? parsed : {
          eft: {
            accountName: parsed.eftAccountName,
            institutionNumber: parsed.eftInstitutionNumber,
            transitNumber: parsed.eftTransitNumber,
            accountNumber: parsed.eftAccountNumber
          },
          interac: {
            recipientName: parsed.interacRecipientName,
            email: parsed.interacEmail
          },
          charges: typeof parsed.cashoutMinAmount === "number" && typeof parsed.cashoutFeePct === "number" && typeof parsed.cashoutFeeFixed === "number" ? {
            cashoutMinAmount: parsed.cashoutMinAmount,
            cashoutFeePct: parsed.cashoutFeePct,
            cashoutFeeFixed: parsed.cashoutFeeFixed
          } : null
        };
        const chargeSource = body.charges ?? await db.select().from(organizationBankSettingsTable).where(
          eq(
            organizationBankSettingsTable.organizationId,
            context.organization.id
          )
        ).limit(1).then((rows) => rows[0] ?? null) ?? {
          cashoutMinAmount: 0,
          cashoutFeePct: 0,
          cashoutFeeFixed: 0
        };
        const cashoutMinAmount = Number(chargeSource.cashoutMinAmount);
        const cashoutFeePct = Number(chargeSource.cashoutFeePct);
        const cashoutFeeFixed = Number(chargeSource.cashoutFeeFixed);
        if (!Number.isFinite(cashoutMinAmount) || !Number.isFinite(cashoutFeePct) || !Number.isFinite(cashoutFeeFixed)) {
          return res.status(400).json({ message: "Invalid organization bank charges configuration." });
        }
        const now = /* @__PURE__ */ new Date();
        await db.insert(organizationBankSettingsTable).values({
          organizationId: context.organization.id,
          eftAccountName: body.eft.accountName,
          eftInstitutionNumber: body.eft.institutionNumber,
          eftTransitNumber: body.eft.transitNumber,
          eftAccountNumber: body.eft.accountNumber,
          interacRecipientName: body.interac.recipientName,
          interacEmail: body.interac.email,
          cashoutMinAmount: cashoutMinAmount.toFixed(2),
          cashoutFeePct: cashoutFeePct.toFixed(3),
          cashoutFeeFixed: cashoutFeeFixed.toFixed(2),
          updatedAt: now
        }).onConflictDoUpdate({
          target: organizationBankSettingsTable.organizationId,
          set: {
            eftAccountName: body.eft.accountName,
            eftInstitutionNumber: body.eft.institutionNumber,
            eftTransitNumber: body.eft.transitNumber,
            eftAccountNumber: body.eft.accountNumber,
            interacRecipientName: body.interac.recipientName,
            interacEmail: body.interac.email,
            cashoutMinAmount: cashoutMinAmount.toFixed(2),
            cashoutFeePct: cashoutFeePct.toFixed(3),
            cashoutFeeFixed: cashoutFeeFixed.toFixed(2),
            updatedAt: now
          }
        });
        const summary = await getOrganizationTreasurySummary(context);
        return res.json({
          bankSettings: summary.treasury.bankSettings
        });
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.get("/org/treasury", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const context = await requireOrganizationAuthorization(userId);
        assertOrganizationTreasuryAccess(context);
        const summary = await getOrganizationTreasurySummary(context);
        return res.json(summary);
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.post("/org/treasury/topup-intents", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const context = await requireOrganizationAuthorization(userId, {
          capability: "org_wallet_fund",
          roleAction: "wallet_fund"
        });
        const parsed = createOrganizationTreasuryTopupIntentSchema.parse(
          req.body ?? {}
        );
        const numericAmount = Number(parsed.amount);
        if (!Number.isFinite(numericAmount) || numericAmount <= 0) {
          return res.status(400).json({ message: "Invalid amount." });
        }
        if (hasMoreThanTwoDecimalPlaces(numericAmount)) {
          return res.status(400).json({ message: "Amount can have at most 2 decimal places." });
        }
        const provider = parsed.provider ?? "MANUAL";
        const result = await db.transaction(async (tx) => {
          const wallet = await ensureWalletWith3(
            tx,
            "ORGANIZATION",
            context.organization.id
          );
          const [intent] = await tx.insert(walletPaymentIntentsTable).values({
            userId,
            walletId: wallet.id,
            provider,
            type: "TOP_UP",
            amount: parsed.amount,
            currency: wallet.currency,
            status: provider === "STRIPE" ? "CREATED" : "PENDING",
            metadata: {
              ...parsed.metadata ?? {},
              organizationId: context.organization.id,
              organizationName: context.organization.name,
              treasuryOwnerType: "ORGANIZATION",
              source: "organization_treasury"
            }
          }).returning();
          if (provider === "STRIPE") {
            const stripe = getStripeClient();
            const paymentIntent = await stripe.paymentIntents.create(
              {
                amount: Math.round(numericAmount * 100),
                currency: wallet.currency.toLowerCase(),
                automatic_payment_methods: { enabled: true },
                metadata: {
                  walletPaymentIntentId: String(intent.id),
                  userId: String(userId),
                  walletId: String(wallet.id),
                  intentType: "TOP_UP",
                  organizationId: String(context.organization.id),
                  treasuryOwnerType: "ORGANIZATION"
                },
                description: `Organization treasury top-up (${context.organization.name})`
              },
              {
                idempotencyKey: `organization_treasury_topup_intent_${intent.id}`
              }
            );
            const [updatedIntent2] = await tx.update(walletPaymentIntentsTable).set({
              status: "PENDING",
              providerReference: paymentIntent.id,
              updatedAt: /* @__PURE__ */ new Date()
            }).where(eq(walletPaymentIntentsTable.id, intent.id)).returning();
            return {
              kind: "STRIPE",
              intent: updatedIntent2,
              clientSecret: paymentIntent.client_secret
            };
          }
          const [setup] = await tx.select().from(organizationBankSettingsTable).where(
            eq(
              organizationBankSettingsTable.organizationId,
              context.organization.id
            )
          ).limit(1);
          if (!setup) {
            throw new OrganizationTenantAccessError(
              "Organization bank settings are not configured for manual treasury funding.",
              409,
              "state_check"
            );
          }
          const metadata = intent.metadata ?? {};
          const providedReference = typeof metadata["reference"] === "string" ? metadata["reference"] : "";
          const providerReference = providedReference || (provider === "INTERAC" ? `ORG-INTERAC-${intent.id}` : `ORG-EFT-${intent.id}`);
          const [updatedIntent] = await tx.update(walletPaymentIntentsTable).set({
            providerReference,
            metadata: {
              ...intent.metadata ?? {},
              ...parsed.metadata ?? {},
              organizationId: context.organization.id,
              organizationName: context.organization.name,
              treasuryOwnerType: "ORGANIZATION",
              source: "organization_treasury",
              fundingMethod: provider === "INTERAC" ? "INTERAC" : "BANK_DEPOSIT"
            },
            updatedAt: /* @__PURE__ */ new Date()
          }).where(eq(walletPaymentIntentsTable.id, intent.id)).returning();
          const nextAction = provider === "INTERAC" ? {
            title: "Interac",
            message: `Send Interac to ${setup.interacEmail} (${setup.interacRecipientName}). Use reference ${providerReference}.`,
            reference: providerReference
          } : {
            title: "EFT",
            message: `Send EFT to ${setup.eftAccountName}. Institution ${setup.eftInstitutionNumber}, Transit ${setup.eftTransitNumber}, Account ${setup.eftAccountNumber}. Use reference ${providerReference}.`,
            reference: providerReference
          };
          return {
            kind: "MANUAL_PENDING",
            intent: updatedIntent,
            nextAction
          };
        });
        if (result.kind === "STRIPE") {
          return res.status(201).json({
            intent: {
              id: result.intent.id,
              provider: result.intent.provider,
              type: result.intent.type,
              amount: Number(result.intent.amount),
              currency: result.intent.currency,
              status: result.intent.status,
              createdAt: result.intent.createdAt.toISOString(),
              providerReference: result.intent.providerReference ?? null,
              stripe: {
                clientSecret: result.clientSecret
              }
            }
          });
        }
        return res.status(201).json({
          intent: {
            id: result.intent.id,
            provider: result.intent.provider,
            type: result.intent.type,
            amount: Number(result.intent.amount),
            currency: result.intent.currency,
            status: result.intent.status,
            createdAt: result.intent.createdAt.toISOString(),
            providerReference: result.intent.providerReference ?? null,
            nextAction: result.nextAction
          }
        });
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.post(
      "/org/treasury/topup-intents/:id/confirm",
      requireAuth,
      async (req, res) => {
        const userId = req.userId;
        try {
          const context = await requireOrganizationAuthorization(userId, {
            capability: "org_wallet_fund",
            roleAction: "wallet_fund"
          });
          const intentId = Number(req.params.id);
          if (!Number.isFinite(intentId) || intentId <= 0) {
            return res.status(400).json({ message: "Invalid top-up intent id." });
          }
          const [walletIntent] = await db.select().from(walletPaymentIntentsTable).where(
            and(
              eq(walletPaymentIntentsTable.id, intentId),
              eq(walletPaymentIntentsTable.userId, userId)
            )
          ).limit(1);
          if (!walletIntent) {
            return res.status(404).json({ message: "Top-up intent not found." });
          }
          if (walletIntent.provider !== "STRIPE" || walletIntent.type !== "TOP_UP" || walletIntent.metadata?.["treasuryOwnerType"] !== "ORGANIZATION" || walletIntent.metadata?.["organizationId"] !== context.organization.id) {
            return res.status(400).json({
              message: "This intent is not an organization treasury top-up."
            });
          }
          if (walletIntent.status === "SUCCEEDED") {
            const summary = await getOrganizationTreasurySummary(context);
            return res.json({
              intent: {
                id: walletIntent.id,
                status: walletIntent.status,
                providerReference: walletIntent.providerReference ?? null
              },
              treasury: summary.treasury
            });
          }
          const paymentIntentId = walletIntent.providerReference ?? "";
          if (!paymentIntentId) {
            return res.status(400).json({ message: "Missing Stripe payment reference." });
          }
          const stripe = getStripeClient();
          const paymentIntent = await stripe.paymentIntents.retrieve(paymentIntentId);
          if (paymentIntent.status !== "succeeded") {
            const nextStatus = paymentIntent.status === "canceled" || paymentIntent.status === "requires_payment_method" ? "FAILED" : walletIntent.status;
            if (paymentIntent.status === "canceled" || paymentIntent.status === "requires_payment_method") {
              await db.update(walletPaymentIntentsTable).set({ status: "FAILED", updatedAt: /* @__PURE__ */ new Date() }).where(eq(walletPaymentIntentsTable.id, walletIntent.id));
            }
            return res.json({
              intent: {
                id: walletIntent.id,
                status: nextStatus,
                providerReference: walletIntent.providerReference ?? null,
                stripeStatus: paymentIntent.status
              },
              treasury: (await getOrganizationTreasurySummary(context)).treasury
            });
          }
          await db.transaction(async (tx) => {
            const [fresh] = await tx.select().from(walletPaymentIntentsTable).where(eq(walletPaymentIntentsTable.id, walletIntent.id)).limit(1);
            if (!fresh) {
              throw new Error("Top-up intent not found.");
            }
            if (fresh.status !== "SUCCEEDED") {
              await tx.insert(walletTransactionsTable).values({
                type: "TOP_UP",
                idempotencyKey: `wallet-topup-intent:${fresh.id}:stripe:${paymentIntent.id}`,
                toWalletId: fresh.walletId,
                amount: fresh.amount,
                metadata: {
                  intentId: fresh.id,
                  provider: "STRIPE",
                  providerReference: paymentIntent.id,
                  fundingMethod: "STRIPE",
                  organizationId: context.organization.id,
                  organizationName: context.organization.name,
                  treasuryOwnerType: "ORGANIZATION",
                  source: "organization_treasury"
                }
              }).onConflictDoNothing();
              await tx.update(walletPaymentIntentsTable).set({
                status: "SUCCEEDED",
                providerReference: paymentIntent.id,
                updatedAt: /* @__PURE__ */ new Date()
              }).where(eq(walletPaymentIntentsTable.id, fresh.id));
            }
          });
          return res.json({
            intent: {
              id: walletIntent.id,
              status: "SUCCEEDED",
              providerReference: paymentIntent.id
            },
            treasury: (await getOrganizationTreasurySummary(context)).treasury
          });
        } catch (err) {
          return handleError4(err, res);
        }
      }
    );
    router5.get(
      "/org/treasury/member-funding-intents",
      requireAuth,
      async (req, res) => {
        const userId = req.userId;
        try {
          const context = await requireOrganizationAuthorization(userId);
          assertOrganizationTreasuryAccess(context);
          return res.json({
            intents: await listOrganizationMemberFundingIntents(context)
          });
        } catch (err) {
          return handleError4(err, res);
        }
      }
    );
    router5.post(
      "/org/treasury/member-funding-intents/:id/approve",
      requireAuth,
      async (req, res) => {
        const userId = req.userId;
        try {
          const context = await requireOrganizationAuthorization(userId);
          if (!context.permissions.canFundWallet && !context.permissions.canOperateWallet) {
            throw new OrganizationTenantAccessError(
              "Your organization role is not allowed to approve wallet funding.",
              403,
              "role_check"
            );
          }
          const intentId = Number(req.params.id);
          if (!Number.isFinite(intentId) || intentId <= 0) {
            return res.status(400).json({ message: "Invalid funding intent id." });
          }
          const result = await db.transaction(async (tx) => {
            const [intent] = await tx.select().from(walletPaymentIntentsTable).where(eq(walletPaymentIntentsTable.id, intentId)).limit(1);
            if (!intent) {
              return {
                status: 404,
                body: { message: "Funding intent not found." }
              };
            }
            const metadata = intent.metadata ?? {};
            if (intent.type !== "TOP_UP" || intent.provider !== "MANUAL" && intent.provider !== "INTERAC" || metadata["source"] !== "organization_member_wallet_funding" || Number(metadata["organizationId"]) !== context.organization.id) {
              return {
                status: 400,
                body: {
                  message: "This funding intent is not organization-scoped."
                }
              };
            }
            if (intent.status !== "PENDING" && intent.status !== "CREATED") {
              return {
                status: 400,
                body: {
                  message: "This funding intent cannot be approved right now."
                }
              };
            }
            await tx.insert(walletTransactionsTable).values({
              type: "TOP_UP",
              idempotencyKey: `wallet-topup-intent:${intent.id}:organization-approve`,
              toWalletId: intent.walletId,
              amount: String(intent.amount),
              metadata: {
                intentId: intent.id,
                provider: intent.provider,
                providerReference: intent.providerReference ?? null,
                fundingMethod: intent.provider === "MANUAL" ? "BANK_DEPOSIT" : "INTERAC",
                approvedByOrganizationUserId: userId,
                organizationId: context.organization.id,
                organizationName: context.organization.name,
                source: "organization_member_wallet_funding"
              }
            }).onConflictDoNothing();
            const [updated] = await tx.update(walletPaymentIntentsTable).set({
              status: "SUCCEEDED",
              metadata: {
                ...metadata,
                approvedAt: (/* @__PURE__ */ new Date()).toISOString(),
                approvedByOrganizationUserId: userId
              },
              updatedAt: /* @__PURE__ */ new Date()
            }).where(eq(walletPaymentIntentsTable.id, intent.id)).returning();
            await notifyInAppWith(tx, {
              userId: intent.userId,
              category: "PAYMENT",
              severity: "SUCCESS",
              title: "Your wallet funding approved",
              body: `${context.organization.name} approved your funding submission.`,
              actionLabel: "Open Wallet",
              actionHref: "/dashboard/wallet"
            }).catch(() => null);
            return {
              status: 200,
              body: {
                intent: {
                  id: updated.id,
                  status: updated.status,
                  updatedAt: updated.updatedAt.toISOString(),
                  metadata: updated.metadata ?? {}
                },
                treasury: (await getOrganizationTreasurySummary(context)).treasury,
                intents: await listOrganizationMemberFundingIntents(context)
              }
            };
          });
          return res.status(result.status).json(result.body);
        } catch (err) {
          return handleError4(err, res);
        }
      }
    );
    router5.post(
      "/org/treasury/member-funding-intents/:id/cancel",
      requireAuth,
      async (req, res) => {
        const userId = req.userId;
        try {
          const context = await requireOrganizationAuthorization(userId);
          if (!context.permissions.canFundWallet && !context.permissions.canOperateWallet) {
            throw new OrganizationTenantAccessError(
              "Your organization role is not allowed to cancel wallet funding.",
              403,
              "role_check"
            );
          }
          const intentId = Number(req.params.id);
          if (!Number.isFinite(intentId) || intentId <= 0) {
            return res.status(400).json({ message: "Invalid funding intent id." });
          }
          const result = await db.transaction(async (tx) => {
            const [intent] = await tx.select().from(walletPaymentIntentsTable).where(eq(walletPaymentIntentsTable.id, intentId)).limit(1);
            if (!intent) {
              return {
                status: 404,
                body: { message: "Funding intent not found." }
              };
            }
            const metadata = intent.metadata ?? {};
            if (intent.type !== "TOP_UP" || intent.provider !== "MANUAL" && intent.provider !== "INTERAC" || metadata["source"] !== "organization_member_wallet_funding" || Number(metadata["organizationId"]) !== context.organization.id) {
              return {
                status: 400,
                body: {
                  message: "This funding intent is not organization-scoped."
                }
              };
            }
            if (intent.status !== "CREATED" && intent.status !== "PENDING" && intent.status !== "FAILED") {
              return {
                status: 400,
                body: {
                  message: "This funding intent cannot be cancelled right now."
                }
              };
            }
            const [updated] = await tx.update(walletPaymentIntentsTable).set({
              status: "CANCELLED",
              metadata: {
                ...metadata,
                cancelledAt: (/* @__PURE__ */ new Date()).toISOString(),
                cancelledByOrganizationUserId: userId
              },
              updatedAt: /* @__PURE__ */ new Date()
            }).where(eq(walletPaymentIntentsTable.id, intent.id)).returning();
            await notifyInAppWith(tx, {
              userId: intent.userId,
              category: "PAYMENT",
              severity: "INFO",
              title: "Your wallet funding rejected",
              body: `${context.organization.name} rejected your funding submission.`,
              actionLabel: "Open Wallet",
              actionHref: "/dashboard/wallet"
            }).catch(() => null);
            return {
              status: 200,
              body: {
                intent: {
                  id: updated.id,
                  status: updated.status,
                  updatedAt: updated.updatedAt.toISOString(),
                  metadata: updated.metadata ?? {}
                },
                intents: await listOrganizationMemberFundingIntents(context)
              }
            };
          });
          return res.status(result.status).json(result.body);
        } catch (err) {
          return handleError4(err, res);
        }
      }
    );
    router5.get("/org/member-contributions", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const context = await requireOrganizationAuthorization(userId, {
          roleAction: "tenant_operate"
        });
        const summary = await getOrganizationContributionSummary(context, userId);
        return res.json(summary);
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.post(
      "/org/member-contributions/obligations",
      requireAuth,
      async (req, res) => {
        const userId = req.userId;
        try {
          const context = await requireOrganizationAuthorization(userId, {
            capability: "org_member_contributions",
            roleAction: "member_contributions_manage"
          });
          assertOrganizationContributionManager(context);
          const body = createOrganizationMemberObligationSchema.parse(
            req.body ?? {}
          );
          const numericAmount = Number(body.amount);
          if (!Number.isFinite(numericAmount) || numericAmount <= 0) {
            return res.status(400).json({ message: "Invalid amount." });
          }
          if (hasMoreThanTwoDecimalPlaces(numericAmount)) {
            return res.status(400).json({ message: "Amount can have at most 2 decimal places." });
          }
          const [membership] = await db.select({
            userId: organizationMembersTable.userId
          }).from(organizationMembersTable).where(
            and(
              eq(
                organizationMembersTable.organizationId,
                context.organization.id
              ),
              eq(organizationMembersTable.userId, body.memberUserId)
            )
          ).limit(1);
          if (!membership) {
            return res.status(404).json({ message: "Organization member not found for obligation." });
          }
          const [obligation] = await db.insert(organizationMemberObligationsTable).values({
            organizationId: context.organization.id,
            memberUserId: body.memberUserId,
            assignedByUserId: userId,
            kind: "TREASURY",
            title: body.title,
            description: body.description?.trim() || null,
            amount: numericAmount.toFixed(2),
            currency: "CAD",
            dueDate: body.dueDate ? new Date(body.dueDate) : null,
            updatedAt: /* @__PURE__ */ new Date()
          }).returning();
          return res.status(201).json({
            obligation: {
              id: obligation.id,
              memberUserId: obligation.memberUserId,
              kind: obligation.kind,
              title: obligation.title,
              description: obligation.description ?? null,
              amount: Number(obligation.amount),
              currency: obligation.currency,
              status: obligation.status,
              dueDate: toIsoStringOrNull2(obligation.dueDate),
              paidAt: toIsoStringOrNull2(obligation.paidAt),
              createdAt: obligation.createdAt.toISOString()
            },
            contributions: await getOrganizationContributionSummary(
              context,
              userId
            )
          });
        } catch (err) {
          return handleError4(err, res);
        }
      }
    );
    router5.post(
      "/org/member-contributions/obligations/:id/pay",
      requireAuth,
      async (req, res) => {
        const userId = req.userId;
        try {
          const context = await requireOrganizationAuthorization(userId, {
            capability: "org_member_contributions",
            roleAction: "tenant_operate"
          });
          const obligationId = Number(req.params.id);
          if (!Number.isFinite(obligationId) || obligationId <= 0) {
            return res.status(400).json({ message: "Invalid obligation id." });
          }
          const parsedBody = organizationMemberObligationPaymentSchema.parse(
            req.body ?? {}
          );
          const submission = await db.transaction(async (tx) => {
            const [current] = await tx.select().from(organizationMemberObligationsTable).where(
              and(
                eq(organizationMemberObligationsTable.id, obligationId),
                eq(
                  organizationMemberObligationsTable.organizationId,
                  context.organization.id
                ),
                eq(organizationMemberObligationsTable.memberUserId, userId)
              )
            ).limit(1);
            if (!current) {
              throw new OrganizationTenantAccessError(
                "Assigned obligation not found.",
                404,
                "record_scope_check"
              );
            }
            if (current.status === "PAID") {
              return {
                obligation: current,
                payment: null,
                nextAction: null
              };
            }
            if (current.status !== "PENDING") {
              throw new OrganizationTenantAccessError(
                "This obligation can no longer be paid.",
                409,
                "state_check"
              );
            }
            const [bankSettings] = await tx.select().from(organizationBankSettingsTable).where(
              eq(
                organizationBankSettingsTable.organizationId,
                context.organization.id
              )
            ).limit(1);
            if (!bankSettings) {
              throw new OrganizationTenantAccessError(
                "Organization bank settings are not configured for member payments.",
                409,
                "state_check"
              );
            }
            const [existingPayment] = await tx.select().from(paymentsTable).where(
              and(
                eq(paymentsTable.userId, userId),
                inArray(paymentsTable.status, ["PENDING", "COMPLETED"]),
                sql`${paymentsTable.metadata} ->> 'source' = 'organization_member_obligation_bank_payment'`,
                sql`${paymentsTable.metadata} ->> 'organizationId' = ${String(context.organization.id)}`,
                sql`${paymentsTable.metadata} ->> 'obligationId' = ${String(current.id)}`
              )
            ).orderBy(desc(paymentsTable.createdAt)).limit(1);
            if (existingPayment) {
              throw new OrganizationTenantAccessError(
                "A bank payment has already been submitted for this obligation.",
                409,
                "state_check"
              );
            }
            const providerReference = `${parsedBody.method === "INTERAC" ? "ORG-INTERAC" : "ORG-EFT"}-${current.id}-${Date.now()}`;
            const [submittedPayment] = await tx.insert(paymentsTable).values({
              userId,
              amount: current.amount,
              currency: current.currency,
              method: parsedBody.method,
              status: "PENDING",
              reference: providerReference,
              description: `${current.title} organization obligation payment`,
              metadata: {
                source: "organization_member_obligation_bank_payment",
                organizationId: context.organization.id,
                organizationName: context.organization.name,
                obligationId: current.id,
                memberUserId: userId,
                title: current.title,
                kind: current.kind,
                dueDate: toIsoStringOrNull2(current.dueDate)
              },
              processedAt: null,
              updatedAt: /* @__PURE__ */ new Date()
            }).returning();
            const nextAction = parsedBody.method === "INTERAC" ? {
              title: "Interac",
              message: `Send Interac to ${bankSettings.interacEmail} (${bankSettings.interacRecipientName}). Use reference ${providerReference}.`,
              reference: providerReference
            } : {
              title: "EFT",
              message: `Send EFT to ${bankSettings.eftAccountName}. Institution ${bankSettings.eftInstitutionNumber}, Transit ${bankSettings.eftTransitNumber}, Account ${bankSettings.eftAccountNumber}. Use reference ${providerReference}.`,
              reference: providerReference
            };
            return {
              obligation: current,
              payment: submittedPayment,
              nextAction
            };
          });
          return res.json({
            obligation: {
              id: submission.obligation.id,
              memberUserId: submission.obligation.memberUserId,
              kind: submission.obligation.kind,
              title: submission.obligation.title,
              description: submission.obligation.description ?? null,
              amount: Number(submission.obligation.amount),
              currency: submission.obligation.currency,
              status: submission.obligation.status,
              dueDate: toIsoStringOrNull2(submission.obligation.dueDate),
              paidAt: toIsoStringOrNull2(submission.obligation.paidAt),
              createdAt: submission.obligation.createdAt.toISOString()
            },
            contributions: await getOrganizationContributionSummary(
              context,
              userId
            ),
            nextAction: submission.nextAction
          });
        } catch (err) {
          return handleError4(err, res);
        }
      }
    );
    router5.post(
      "/org/member-contributions/payments/:id/confirm",
      requireAuth,
      async (req, res) => {
        const userId = req.userId;
        try {
          const context = await requireOrganizationAuthorization(userId, {
            capability: "org_member_contributions",
            roleAction: "member_contributions_manage"
          });
          assertOrganizationContributionManager(context);
          const paymentId = Number(req.params.id);
          if (!Number.isFinite(paymentId) || paymentId <= 0) {
            return res.status(400).json({ message: "Invalid payment id." });
          }
          await db.transaction(async (tx) => {
            const [payment] = await tx.select().from(paymentsTable).where(eq(paymentsTable.id, paymentId)).limit(1);
            if (!payment) {
              throw new OrganizationTenantAccessError(
                "Submitted payment not found.",
                404,
                "record_scope_check"
              );
            }
            const metadata = payment.metadata ?? {};
            if (metadata["source"] !== "organization_member_obligation_bank_payment" || Number(metadata["organizationId"]) !== context.organization.id) {
              throw new OrganizationTenantAccessError(
                "Submitted payment not found.",
                404,
                "record_scope_check"
              );
            }
            if (payment.status !== "PENDING") {
              throw new OrganizationTenantAccessError(
                "This submitted payment has already been processed.",
                409,
                "state_check"
              );
            }
            const obligationId = Number(metadata["obligationId"]);
            const [obligation] = await tx.select().from(organizationMemberObligationsTable).where(
              and(
                eq(organizationMemberObligationsTable.id, obligationId),
                eq(
                  organizationMemberObligationsTable.organizationId,
                  context.organization.id
                )
              )
            ).limit(1);
            if (!obligation) {
              throw new OrganizationTenantAccessError(
                "Linked obligation was not found.",
                404,
                "record_scope_check"
              );
            }
            const treasuryWallet = await ensureOrganizationFinanceWalletWith(
              tx,
              context
            );
            const [walletTx] = await tx.insert(walletTransactionsTable).values({
              type: "TOP_UP",
              idempotencyKey: `org-obligation-payment:${payment.id}:confirm`,
              toWalletId: treasuryWallet.id,
              amount: payment.amount,
              metadata: {
                source: "organization_member_obligation_bank_payment",
                organizationId: context.organization.id,
                obligationId: obligation.id,
                paymentId: payment.id,
                memberUserId: obligation.memberUserId,
                method: payment.method,
                reference: payment.reference,
                confirmedByUserId: userId
              }
            }).onConflictDoNothing().returning();
            const transaction = walletTx ?? (await tx.select().from(walletTransactionsTable).where(
              eq(
                walletTransactionsTable.idempotencyKey,
                `org-obligation-payment:${payment.id}:confirm`
              )
            ).limit(1))[0];
            if (!transaction) {
              throw new Error("Unable to confirm submitted organization payment.");
            }
            await tx.update(paymentsTable).set({
              status: "COMPLETED",
              processedAt: /* @__PURE__ */ new Date(),
              updatedAt: /* @__PURE__ */ new Date()
            }).where(eq(paymentsTable.id, payment.id));
            await tx.update(organizationMemberObligationsTable).set({
              status: "PAID",
              paidAt: /* @__PURE__ */ new Date(),
              walletTransactionId: transaction.id,
              updatedAt: /* @__PURE__ */ new Date()
            }).where(eq(organizationMemberObligationsTable.id, obligation.id));
          });
          return res.json({
            contributions: await getOrganizationContributionSummary(
              context,
              userId
            ),
            treasury: (await getOrganizationTreasurySummary(context)).treasury
          });
        } catch (err) {
          return handleError4(err, res);
        }
      }
    );
    router5.post("/org/resources/:id/download", requireAuth, async (req, res) => {
      const userId = req.userId;
      const id = Number(req.params.id);
      if (!Number.isFinite(id) || id <= 0) {
        return res.status(400).json({ message: "Invalid resource id." });
      }
      try {
        await requireOrganizationAuthorization(userId, {
          productFeature: "RESOURCES"
        });
        const [resource] = await db.select({
          id: resourcesTable.id,
          resourceKind: resourcesTable.resourceKind,
          fileUrl: resourcesTable.fileUrl
        }).from(resourcesTable).where(
          and(
            eq(resourcesTable.id, id),
            eq(resourcesTable.isPublished, true),
            eq(resourcesTable.showToOrganizations, true)
          )
        );
        if (!resource) {
          return res.status(404).json({ message: "Resource not found." });
        }
        if (resource.resourceKind === "ARTICLE" || !resource.fileUrl) {
          return res.status(400).json({
            message: "Articles are opened directly and cannot be downloaded."
          });
        }
        await db.update(resourcesTable).set({
          downloads: sql`${resourcesTable.downloads} + 1`,
          updatedAt: /* @__PURE__ */ new Date()
        }).where(eq(resourcesTable.id, id));
        return res.json({ fileUrl: resource.fileUrl });
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.get("/org/susu/circles", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const context = await requireOrganizationSusuParticipantAccess(userId);
        const circles = await getOrganizationSusuCirclesSnapshot(context, userId);
        return res.json({
          organization: context.organization,
          permissions: context.permissions,
          entitlements: context.entitlements,
          circles
        });
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.post("/org/susu/circles", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const context = await requireOrganizationAuthorization(userId, {
          capability: "org_susu_operate",
          productFeature: "ORG_SUSU",
          roleAction: "tenant_operate"
        });
        assertOrganizationSusuManager(context);
        const [user] = await db.select().from(usersTable).where(eq(usersTable.id, userId)).limit(1);
        if (user) {
          const lens = getInvestorPackageLens({
            membershipType: user.membershipType ?? null,
            membershipStatus: user.membershipStatus ?? null,
            userRole: user.userRole ?? null,
            segment: user.segment ?? null,
            investorCategory: user.investorCategory ?? null
          });
          if (!lens.canRosca) {
            return res.status(403).json({
              message: "Your investor package does not include access to ROSCA Circles (Susu)."
            });
          }
        }
        const parsed = external_exports.object({
          name: external_exports.string().trim().min(1),
          description: external_exports.string().trim().optional(),
          contributionAmount: external_exports.string().trim().min(1),
          helpingHandMultiplier: external_exports.string().trim().optional(),
          frequency: external_exports.enum(["WEEKLY", "BIWEEKLY", "MONTHLY"]).default("MONTHLY"),
          orgAutoDeductEnabled: external_exports.boolean().optional(),
          isFreeToJoin: external_exports.boolean().default(false),
          maxMembers: external_exports.number().int().min(2),
          startDate: external_exports.string().optional(),
          formingTimeoutDays: external_exports.number().int().min(1).default(14)
        }).parse(req.body ?? {});
        const numericAmount = Number(parsed.contributionAmount);
        if (!Number.isFinite(numericAmount) || numericAmount <= 0) {
          return res.status(400).json({ message: "Invalid contribution amount." });
        }
        const numericHelpingHandMultiplier = parsed.helpingHandMultiplier === void 0 || parsed.helpingHandMultiplier === "" ? null : Number(parsed.helpingHandMultiplier);
        if (numericHelpingHandMultiplier !== null && (!Number.isFinite(numericHelpingHandMultiplier) || numericHelpingHandMultiplier <= 0)) {
          return res.status(400).json({ message: "Invalid Matching Fund multiplier." });
        }
        const result = await db.transaction(async (tx) => {
          const actorUserWallet = await ensureOrganizationFinanceWalletWith(
            tx,
            context
          );
          const availableBalance = await getWalletAvailableBalanceWith(
            tx,
            actorUserWallet.id
          );
          if (!parsed.isFreeToJoin && availableBalance < numericAmount) {
            return {
              status: 400,
              body: {
                message: "Fund the organization wallet before creating an organization ROSCA circle (Susu)."
              }
            };
          }
          const baseStartDate = parsed.startDate ? new Date(parsed.startDate) : null;
          const startDate = getNextCircleDueDate({
            anchorDate: baseStartDate,
            frequency: parsed.frequency
          });
          const [circle] = await tx.insert(savingsCirclesTable).values({
            name: parsed.name,
            description: parsed.description ?? null,
            contributionAmount: parsed.contributionAmount,
            helpingHandMultiplier: numericHelpingHandMultiplier !== null ? String(numericHelpingHandMultiplier) : null,
            frequency: parsed.frequency,
            maxMembers: parsed.maxMembers,
            formingTimeoutDays: parsed.formingTimeoutDays,
            isFreeToJoin: parsed.isFreeToJoin,
            status: "FORMING",
            startDate,
            endDate: null,
            organizationId: context.organization.id,
            orgAutoDeductEnabled: parsed.orgAutoDeductEnabled ?? false,
            createdByOrganizationMemberUserId: userId,
            createdByAdminId: null
          }).returning();
          await tx.insert(circleMembershipsTable).values({
            circleId: circle.id,
            userId,
            position: 1
          });
          const circleTreasuryWallet = await ensureCircleTreasuryWalletWith(
            tx,
            circle
          );
          if (!circleTreasuryWallet) {
            return {
              status: 404,
              body: {
                message: "Organization circle treasury could not be created."
              }
            };
          }
          if (!parsed.isFreeToJoin) {
            const paidAt = /* @__PURE__ */ new Date();
            const [contribution] = await tx.insert(savingsContributionsTable).values({
              circleId: circle.id,
              userId,
              dueDate: startDate,
              paidAt,
              amount: parsed.contributionAmount,
              status: "PAID",
              method: "WALLET",
              receiptRef: `wallet_tx:org-susu:create:${circle.id}:${userId}`
            }).returning();
            const [{ id: transactionId }] = await tx.insert(walletTransactionsTable).values({
              type: "CONTRIBUTION",
              idempotencyKey: `org-susu:circle-create:${circle.id}:${userId}:first_contribution`,
              fromWalletId: actorUserWallet.id,
              toWalletId: circleTreasuryWallet.id,
              amount: parsed.contributionAmount,
              metadata: {
                source: "org_susu_create_first_contribution",
                circleId: circle.id,
                organizationId: context.organization.id,
                userId,
                position: 1,
                dueDate: startDate.toISOString(),
                contributionId: contribution.id
              }
            }).returning({ id: walletTransactionsTable.id });
            await tx.update(savingsContributionsTable).set({
              receiptRef: `wallet_tx:${transactionId}`,
              updatedAt: /* @__PURE__ */ new Date()
            }).where(eq(savingsContributionsTable.id, contribution.id));
          }
          return {
            status: 201,
            body: {
              circle: {
                id: circle.id,
                name: circle.name,
                status: getCircleRuntimeStatus({
                  status: circle.status,
                  startDate: circle.startDate
                }),
                contributionAmount: Number(circle.contributionAmount),
                frequency: circle.frequency,
                maxMembers: circle.maxMembers,
                currentMembers: 1,
                startDate: toIsoStringOrNull2(circle.startDate),
                createdAt: circle.createdAt.toISOString()
              },
              workflow: "Organization circle created and the first contribution was funded from the organization wallet."
            }
          };
        });
        return res.status(result.status).json(result.body);
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.patch("/org/susu/circles/:id", requireAuth, async (req, res) => {
      const userId = req.userId;
      const circleId = Number(req.params.id);
      if (!Number.isInteger(circleId) || circleId <= 0) {
        return res.status(400).json({ message: "Invalid organization ROSCA circle (Susu) id." });
      }
      try {
        const context = await requireOrganizationAuthorization(userId, {
          capability: "org_susu_operate",
          productFeature: "ORG_SUSU",
          roleAction: "tenant_operate"
        });
        assertOrganizationSusuManager(context);
        const parsed = updateOrganizationSusuCircleSchema.parse(req.body ?? {});
        const numericAmount = Number(parsed.contributionAmount);
        if (!Number.isFinite(numericAmount) || numericAmount <= 0) {
          return res.status(400).json({ message: "Invalid contribution amount." });
        }
        if (hasMoreThanTwoDecimalPlaces(numericAmount)) {
          return res.status(400).json({ message: "Amount can have at most 2 decimal places." });
        }
        const numericHelpingHandMultiplier = parsed.helpingHandMultiplier === void 0 || parsed.helpingHandMultiplier === null || parsed.helpingHandMultiplier === "" ? null : Number(parsed.helpingHandMultiplier);
        if (numericHelpingHandMultiplier !== null && (!Number.isFinite(numericHelpingHandMultiplier) || numericHelpingHandMultiplier <= 0)) {
          return res.status(400).json({ message: "Invalid Matching Fund multiplier." });
        }
        const baseStartDate = parsed.startDate ? new Date(parsed.startDate) : null;
        if (baseStartDate && Number.isNaN(baseStartDate.getTime())) {
          return res.status(400).json({ message: "Invalid first due date." });
        }
        const result = await db.transaction(async (tx) => {
          const state = await getOrganizationSusuPreLaunchState(
            tx,
            context,
            circleId
          );
          if (parsed.maxMembers < state.memberCount) {
            return {
              status: 400,
              body: {
                message: "Max members cannot be lower than the current joined count."
              }
            };
          }
          const currentAmount = Number(state.circle.contributionAmount);
          if (Number(parsed.contributionAmount) !== currentAmount) {
            return {
              status: 409,
              body: {
                message: "Cancel and recreate this forming circle to change the contribution amount after the first wallet funding."
              }
            };
          }
          const nextStartDate = getNextCircleDueDate({
            anchorDate: baseStartDate,
            frequency: parsed.frequency
          });
          await tx.update(savingsCirclesTable).set({
            name: parsed.name,
            description: parsed.description?.trim() || null,
            helpingHandMultiplier: numericHelpingHandMultiplier !== null ? String(numericHelpingHandMultiplier) : null,
            frequency: parsed.frequency,
            orgAutoDeductEnabled: parsed.orgAutoDeductEnabled ?? state.circle.orgAutoDeductEnabled,
            maxMembers: parsed.maxMembers,
            formingTimeoutDays: parsed.formingTimeoutDays,
            isFreeToJoin: parsed.isFreeToJoin ?? state.circle.isFreeToJoin,
            startDate: nextStartDate,
            updatedAt: /* @__PURE__ */ new Date()
          }).where(eq(savingsCirclesTable.id, circleId));
          await tx.update(savingsContributionsTable).set({
            dueDate: nextStartDate,
            updatedAt: /* @__PURE__ */ new Date()
          }).where(eq(savingsContributionsTable.id, state.seedContribution.id));
          return {
            status: 200,
            body: {
              workflow: "Organization circle updated."
            }
          };
        });
        const circles = await getOrganizationSusuCirclesSnapshot(context, userId);
        const circle = circles.find((entry) => entry.id === circleId) ?? null;
        return res.status(result.status).json({
          ...result.body,
          circle
        });
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.delete("/org/susu/circles/:id", requireAuth, async (req, res) => {
      const userId = req.userId;
      const circleId = Number(req.params.id);
      if (!Number.isInteger(circleId) || circleId <= 0) {
        return res.status(400).json({ message: "Invalid organization ROSCA circle (Susu) id." });
      }
      try {
        const context = await requireOrganizationAuthorization(userId, {
          capability: "org_susu_operate",
          productFeature: "ORG_SUSU",
          roleAction: "tenant_operate"
        });
        assertOrganizationSusuManager(context);
        const scopedCircle = await getScopedOrganizationCircle(context, circleId);
        const runtimeStatus = getCircleRuntimeStatus({
          status: scopedCircle.status,
          startDate: scopedCircle.startDate
        });
        if (runtimeStatus === "CANCELLED") {
          const result2 = await db.transaction(async (tx) => {
            const [qualifyingApplication] = await tx.select({ id: helpingHandApplicationsTable.id }).from(helpingHandApplicationsTable).where(eq(helpingHandApplicationsTable.qualifyingCircleId, circleId)).limit(1);
            if (qualifyingApplication) {
              return {
                status: 409,
                body: {
                  message: "This cancelled circle is referenced by a lending record and cannot be deleted from the archive."
                }
              };
            }
            await tx.delete(circlePayoutsTable).where(eq(circlePayoutsTable.circleId, circleId));
            await tx.delete(savingsContributionsTable).where(eq(savingsContributionsTable.circleId, circleId));
            await tx.delete(circleMembershipsTable).where(eq(circleMembershipsTable.circleId, circleId));
            await tx.delete(savingsCirclesTable).where(eq(savingsCirclesTable.id, circleId));
            return {
              status: 200,
              body: {
                workflow: "Cancelled organization circle removed from the workspace archive."
              }
            };
          });
          return res.status(result2.status).json(result2.body);
        }
        const result = await db.transaction(async (tx) => {
          const state = await getOrganizationSusuPreLaunchState(
            tx,
            context,
            circleId
          );
          const refundAmount = Number(state.seedContribution.amount);
          if (!Number.isFinite(refundAmount) || refundAmount <= 0) {
            return {
              status: 409,
              body: { message: "The founding contribution is invalid." }
            };
          }
          const seedWallet = await ensureOrganizationFinanceWalletWith(
            tx,
            context
          );
          const treasuryAvailable = await getWalletAvailableBalanceWith(
            tx,
            state.circleTreasuryWallet.id
          );
          if (treasuryAvailable < refundAmount) {
            return {
              status: 409,
              body: {
                message: "This circle treasury balance is not ready for cancellation refund."
              }
            };
          }
          await tx.insert(walletTransactionsTable).values({
            type: "REFUND",
            idempotencyKey: `org-susu:circle-cancel:${circleId}:refund`,
            fromWalletId: state.circleTreasuryWallet.id,
            toWalletId: seedWallet.id,
            amount: state.seedContribution.amount,
            metadata: {
              source: "org_susu_prelaunch_cancel_refund",
              circleId,
              organizationId: context.organization.id,
              refundedUserId: state.seedMembership.userId,
              refundedContributionId: state.seedContribution.id,
              cancelledByUserId: userId
            }
          }).onConflictDoNothing();
          await tx.update(savingsCirclesTable).set({
            status: "CANCELLED",
            endDate: /* @__PURE__ */ new Date(),
            updatedAt: /* @__PURE__ */ new Date()
          }).where(eq(savingsCirclesTable.id, circleId));
          return {
            status: 200,
            body: {
              workflow: "Organization circle cancelled and the founding contribution was returned to the organization wallet."
            }
          };
        });
        return res.status(result.status).json(result.body);
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.post("/org/susu/circles/:id/join", requireAuth, async (req, res) => {
      const userId = req.userId;
      const circleId = Number(req.params.id);
      if (!Number.isInteger(circleId) || circleId <= 0) {
        return res.status(400).json({ message: "Invalid organization ROSCA circle (Susu) id." });
      }
      try {
        const [user] = await db.select().from(usersTable).where(eq(usersTable.id, userId)).limit(1);
        if (user) {
          const lens = getInvestorPackageLens({
            membershipType: user.membershipType ?? null,
            membershipStatus: user.membershipStatus ?? null,
            userRole: user.userRole ?? null,
            segment: user.segment ?? null,
            investorCategory: user.investorCategory ?? null
          });
          if (!lens.canRosca) {
            return res.status(403).json({
              message: "Your investor package does not include access to ROSCA Circles (Susu)."
            });
          }
        }
        const context = await requireOrganizationSusuParticipantAccess(userId);
        const result = await db.transaction(async (tx) => {
          const [circle] = await tx.select().from(savingsCirclesTable).where(eq(savingsCirclesTable.id, circleId));
          if (!circle || circle.organizationId !== context.organization.id) {
            return {
              status: 404,
              body: { message: "Organization ROSCA circle (Susu) not found." }
            };
          }
          const runtimeStatus = getCircleRuntimeStatus({
            status: circle.status,
            startDate: circle.startDate
          });
          if (runtimeStatus !== "FORMING") {
            return {
              status: 400,
              body: {
                message: "This organization circle is not open for joining."
              }
            };
          }
          const parsedBody = external_exports.object({
            position: external_exports.number().int().min(2)
          }).safeParse(req.body ?? {});
          if (!parsedBody.success) {
            return {
              status: 400,
              body: { message: "Invalid request payload." }
            };
          }
          const requestedPosition = parsedBody.data.position;
          const creatorSeatIssue = await getCircleCreatorSeatIssueWith(
            tx,
            circleId
          );
          if (creatorSeatIssue) {
            return {
              status: 409,
              body: { message: creatorSeatIssue }
            };
          }
          const [existingMembership] = await tx.select().from(circleMembershipsTable).where(
            and(
              eq(circleMembershipsTable.circleId, circleId),
              eq(circleMembershipsTable.userId, userId)
            )
          );
          if (existingMembership) {
            return {
              status: 400,
              body: { message: "You already belong to this organization circle." }
            };
          }
          const existingMembers = await tx.select({ position: circleMembershipsTable.position }).from(circleMembershipsTable).where(eq(circleMembershipsTable.circleId, circleId));
          const currentMembers = existingMembers.length;
          if (currentMembers >= circle.maxMembers) {
            return {
              status: 400,
              body: { message: "This organization circle is already full." }
            };
          }
          const occupiedPositions = new Set(existingMembers.map((m) => m.position));
          if (requestedPosition > circle.maxMembers) {
            return {
              status: 400,
              body: { message: "Requested spot is outside circle capacity." }
            };
          }
          if (occupiedPositions.has(requestedPosition)) {
            return {
              status: 400,
              body: { message: "Requested spot is already taken." }
            };
          }
          const assignedPosition = requestedPosition;
          const amount = String(circle.contributionAmount);
          const numericAmount = Number(circle.contributionAmount);
          if (!Number.isFinite(numericAmount) || numericAmount <= 0) {
            return {
              status: 400,
              body: { message: "Invalid contribution amount." }
            };
          }
          const membershipRole = context.membership?.role ?? null;
          const shouldFundFromOrganizationWallet = membershipRole === "OWNER" || membershipRole === "ADMIN";
          const actorUserWallet = shouldFundFromOrganizationWallet ? await ensureOrganizationFinanceWalletWith(tx, context) : await ensureWalletWith3(tx, "USER", userId);
          const circleTreasuryWallet = await ensureCircleTreasuryWalletWith(
            tx,
            circle
          );
          if (!circleTreasuryWallet) {
            return {
              status: 404,
              body: { message: "Organization circle treasury was not found." }
            };
          }
          let contributionId = null;
          let paidAt = null;
          const dueDate = getNextCircleDueDate({
            anchorDate: circle.startDate,
            frequency: circle.frequency
          });
          if (!circle.isFreeToJoin) {
            const availableBalance = await getWalletAvailableBalanceWith(
              tx,
              actorUserWallet.id
            );
            if (availableBalance < numericAmount) {
              return {
                status: 400,
                body: {
                  message: shouldFundFromOrganizationWallet ? "Insufficient available organization wallet balance to join and fund the first contribution." : "Insufficient available wallet balance to join and fund the first contribution."
                }
              };
            }
            paidAt = /* @__PURE__ */ new Date();
            const [contribution] = await tx.insert(savingsContributionsTable).values({
              circleId,
              userId,
              dueDate,
              paidAt,
              amount,
              status: "PAID",
              method: "WALLET",
              receiptRef: `wallet_tx:org-susu:join:${circleId}:${userId}`
            }).returning();
            contributionId = contribution.id;
            const [{ id: transactionId }] = await tx.insert(walletTransactionsTable).values({
              type: "CONTRIBUTION",
              idempotencyKey: `org-susu:circle-join:${circleId}:${userId}`,
              fromWalletId: actorUserWallet.id,
              toWalletId: circleTreasuryWallet.id,
              amount,
              metadata: {
                source: shouldFundFromOrganizationWallet ? "org_susu_join_first_contribution" : "org_susu_join_first_contribution_member_wallet",
                circleId,
                organizationId: context.organization.id,
                contributionId: contribution.id,
                userId,
                position: assignedPosition,
                dueDate: dueDate.toISOString()
              }
            }).returning({ id: walletTransactionsTable.id });
            await tx.update(savingsContributionsTable).set({
              receiptRef: `wallet_tx:${transactionId}`,
              updatedAt: /* @__PURE__ */ new Date()
            }).where(eq(savingsContributionsTable.id, contribution.id));
          }
          await tx.insert(circleMembershipsTable).values({
            circleId,
            userId,
            position: assignedPosition
          });
          const activation = await activateCircleIfReadyWith(tx, circleId);
          if (!activation.activated) {
            await repairCircleContributionScheduleWith(tx, circleId);
          }
          await processCircleAutomationWith(tx, circleId);
          return {
            status: 201,
            body: {
              circleId,
              position: assignedPosition,
              contribution: contributionId ? {
                id: contributionId,
                amount: numericAmount,
                paidAt: paidAt?.toISOString()
              } : null,
              activated: activation.activated,
              workflow: circle.isFreeToJoin ? "You joined the organization circle for free. You will contribute after it starts." : shouldFundFromOrganizationWallet ? "You joined the organization circle and your first contribution was paid from the organization wallet." : "You joined the organization circle and your first contribution was paid from your wallet."
            }
          };
        });
        return res.status(result.status).json(result.body);
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.post(
      "/org/susu/circles/:id/contribute",
      requireAuth,
      async (req, res) => {
        const userId = req.userId;
        const circleId = Number(req.params.id);
        if (!Number.isInteger(circleId) || circleId <= 0) {
          return res.status(400).json({ message: "Invalid organization ROSCA circle (Susu) id." });
        }
        try {
          const context = await requireOrganizationSusuParticipantAccess(userId);
          const parsedBody = external_exports.object({
            metadata: external_exports.record(external_exports.unknown()).optional()
          }).parse(req.body ?? {});
          const result = await db.transaction(async (tx) => {
            const [circle] = await tx.select().from(savingsCirclesTable).where(eq(savingsCirclesTable.id, circleId));
            if (!circle || circle.organizationId !== context.organization.id) {
              return {
                status: 404,
                body: { message: "Organization ROSCA circle (Susu) not found." }
              };
            }
            const runtimeStatus = getCircleRuntimeStatus({
              status: circle.status,
              startDate: circle.startDate
            });
            if (runtimeStatus !== "ACTIVE") {
              return {
                status: 400,
                body: { message: "This organization circle is not active." }
              };
            }
            const [membership] = await tx.select().from(circleMembershipsTable).where(
              and(
                eq(circleMembershipsTable.circleId, circleId),
                eq(circleMembershipsTable.userId, userId)
              )
            );
            if (!membership) {
              return {
                status: 400,
                body: {
                  message: "You are not a member of this organization circle."
                }
              };
            }
            await processCircleAutomationWith(tx, circleId);
            await repairCircleContributionScheduleWith(tx, circleId);
            const amount = String(circle.contributionAmount);
            const numericAmount = Number(circle.contributionAmount);
            if (!Number.isFinite(numericAmount) || numericAmount <= 0) {
              return { status: 400, body: { message: "Invalid amount." } };
            }
            const membershipRole = context.membership?.role ?? null;
            const shouldFundFromOrganizationWallet = membershipRole === "OWNER" || membershipRole === "ADMIN";
            const actorUserWallet = shouldFundFromOrganizationWallet ? await ensureOrganizationFinanceWalletWith(tx, context) : await ensureWalletWith3(tx, "USER", userId);
            const circleTreasuryWallet = await ensureCircleTreasuryWalletWith(
              tx,
              circle
            );
            if (!circleTreasuryWallet) {
              return {
                status: 404,
                body: { message: "Organization circle treasury was not found." }
              };
            }
            const [nextDue] = await tx.select().from(savingsContributionsTable).where(
              and(
                eq(savingsContributionsTable.circleId, circleId),
                eq(savingsContributionsTable.userId, userId),
                eq(savingsContributionsTable.status, "PENDING"),
                lte(savingsContributionsTable.dueDate, /* @__PURE__ */ new Date())
              )
            ).orderBy(asc(savingsContributionsTable.dueDate)).limit(1);
            if (!nextDue) {
              return {
                status: 400,
                body: { message: "No pending contribution is due right now." }
              };
            }
            const availableBalance = await getWalletAvailableBalanceWith(
              tx,
              actorUserWallet.id
            );
            if (availableBalance < numericAmount) {
              return {
                status: 400,
                body: {
                  message: shouldFundFromOrganizationWallet ? "Insufficient available organization wallet balance." : "Insufficient available wallet balance."
                }
              };
            }
            const idempotencyKey = `org-susu:contribution:${circleId}:${userId}:${nextDue.dueDate.toISOString()}`;
            const [createdTx] = await tx.insert(walletTransactionsTable).values({
              type: "CONTRIBUTION",
              idempotencyKey,
              fromWalletId: actorUserWallet.id,
              toWalletId: circleTreasuryWallet.id,
              amount,
              metadata: {
                ...parsedBody.metadata ?? {},
                source: shouldFundFromOrganizationWallet ? "org_susu_contribution" : "org_susu_contribution_member_wallet",
                circleId,
                organizationId: context.organization.id,
                contributionId: nextDue.id,
                dueDate: nextDue.dueDate.toISOString()
              }
            }).onConflictDoNothing().returning({
              id: walletTransactionsTable.id,
              type: walletTransactionsTable.type,
              amount: walletTransactionsTable.amount,
              createdAt: walletTransactionsTable.createdAt
            });
            const [transaction] = createdTx ? [createdTx] : await tx.select({
              id: walletTransactionsTable.id,
              type: walletTransactionsTable.type,
              amount: walletTransactionsTable.amount,
              createdAt: walletTransactionsTable.createdAt
            }).from(walletTransactionsTable).where(eq(walletTransactionsTable.idempotencyKey, idempotencyKey)).limit(1);
            if (!transaction) {
              return {
                status: 409,
                body: { message: "Contribution was already submitted." }
              };
            }
            const [contribution] = await tx.update(savingsContributionsTable).set({
              paidAt: /* @__PURE__ */ new Date(),
              status: "PAID",
              method: "WALLET",
              receiptRef: `wallet_tx:${transaction.id}`,
              updatedAt: /* @__PURE__ */ new Date()
            }).where(
              and(
                eq(savingsContributionsTable.id, nextDue.id),
                eq(savingsContributionsTable.status, "PENDING")
              )
            ).returning();
            if (!contribution) {
              return {
                status: 409,
                body: { message: "Contribution was already settled." }
              };
            }
            await processCircleAutomationWith(tx, circleId);
            return {
              status: 201,
              body: {
                contribution: {
                  id: contribution.id,
                  circleId: contribution.circleId,
                  amount: Number(contribution.amount),
                  paidAt: contribution.paidAt?.toISOString() ?? null,
                  receiptRef: contribution.receiptRef ?? null
                },
                transaction: {
                  id: transaction.id,
                  type: transaction.type,
                  amount: Number(transaction.amount),
                  createdAt: transaction.createdAt.toISOString()
                }
              }
            };
          });
          return res.status(result.status).json(result.body);
        } catch (err) {
          return handleError4(err, res);
        }
      }
    );
    router5.get("/org/susu/circles/:id/wallet", requireAuth, async (req, res) => {
      const userId = req.userId;
      const circleId = Number(req.params.id);
      if (!Number.isInteger(circleId) || circleId <= 0) {
        return res.status(400).json({ message: "Invalid organization ROSCA circle (Susu) id." });
      }
      try {
        const context = await requireOrganizationAuthorization(userId, {
          capability: "org_susu_operate",
          productFeature: "ORG_SUSU",
          roleAction: "tenant_operate"
        });
        assertOrganizationSusuManager(context);
        await getScopedOrganizationCircle(context, circleId);
        const [summary, transactions] = await Promise.all([
          getCircleAllocationSummaryWith(db, circleId),
          getCircleAllocationTransactionsWith(db, circleId)
        ]);
        if (!summary) {
          return res.status(404).json({ message: "Organization ROSCA circle (Susu) not found." });
        }
        return res.json({
          wallet: {
            id: summary.wallet.id,
            ownerType: summary.owner.ownerType,
            ownerId: summary.owner.ownerId,
            isDedicatedWallet: summary.owner.isDedicatedWallet,
            currency: summary.wallet.currency,
            balance: summary.allocationBalance,
            treasuryBalance: summary.treasuryBalance,
            totalIn: summary.totalIn,
            totalOut: summary.totalOut,
            transactions
          }
        });
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.get("/org/susu/circles/:id/reconcile", requireAuth, async (req, res) => {
      const userId = req.userId;
      const circleId = Number(req.params.id);
      if (!Number.isInteger(circleId) || circleId <= 0) {
        return res.status(400).json({ message: "Invalid organization ROSCA circle (Susu) id." });
      }
      try {
        const context = await requireOrganizationAuthorization(userId, {
          capability: "org_susu_operate",
          productFeature: "ORG_SUSU",
          roleAction: "tenant_operate"
        });
        assertOrganizationSusuManager(context);
        await getScopedOrganizationCircle(context, circleId);
        const [summary, contributionStats, payoutStats] = await Promise.all([
          getCircleAllocationSummaryWith(db, circleId),
          db.select({
            status: savingsContributionsTable.status,
            count: count(),
            total: sql`sum(${savingsContributionsTable.amount})`
          }).from(savingsContributionsTable).where(eq(savingsContributionsTable.circleId, circleId)).groupBy(savingsContributionsTable.status),
          db.select({
            status: circlePayoutsTable.status,
            count: count(),
            total: sql`sum(${circlePayoutsTable.amount})`
          }).from(circlePayoutsTable).where(eq(circlePayoutsTable.circleId, circleId)).groupBy(circlePayoutsTable.status)
        ]);
        if (!summary) {
          return res.status(404).json({ message: "Organization ROSCA circle (Susu) not found." });
        }
        return res.json({
          circleId,
          wallet: {
            id: summary.wallet.id,
            ownerType: summary.owner.ownerType,
            ownerId: summary.owner.ownerId,
            isDedicatedWallet: summary.owner.isDedicatedWallet,
            balance: summary.allocationBalance,
            treasuryBalance: summary.treasuryBalance,
            totalIn: summary.totalIn,
            totalOut: summary.totalOut,
            net: summary.totalIn - summary.totalOut
          },
          contributions: contributionStats.map((row) => ({
            status: row.status,
            count: Number(row.count),
            total: Number(row.total ?? 0)
          })),
          payouts: payoutStats.map((row) => ({
            status: row.status,
            count: Number(row.count),
            total: Number(row.total ?? 0)
          }))
        });
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.post("/org/members", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const context = await requireOrganizationAuthorization(userId, {
          capability: "member_management",
          roleAction: "members_manage"
        });
        const body = external_exports.object({
          email: external_exports.string().email(),
          firstName: external_exports.string().trim().min(1).max(120).optional(),
          lastName: external_exports.string().trim().max(120).optional(),
          role: external_exports.enum(ORG_ROLE_VALUES).optional().default("MEMBER")
        }).parse(req.body);
        if (body.role === "OWNER") {
          throw new OrganizationTenantAccessError(
            "The organization authority role is reserved for the organization account.",
            409,
            "role_check"
          );
        }
        const email3 = normalizeEmail(body.email);
        const token = createOrganizationInvitationToken();
        const [invitation] = await db.transaction(async (tx) => {
          await tx.execute(
            sql`select pg_advisory_xact_lock(${ORG_MEMBER_INVITE_LOCK_KEY_A}, ${context.organization.id})`
          );
          const seatUsage = await getSeatUsageWith(
            tx,
            context.organization.id
          );
          assertSeatAvailable(context.entitlements.seat_limit, seatUsage.seatsUsed);
          await tx.delete(organizationInvitationsTable).where(
            and(
              eq(
                organizationInvitationsTable.organizationId,
                context.organization.id
              ),
              eq(organizationInvitationsTable.email, email3),
              eq(organizationInvitationsTable.status, "PENDING"),
              lte(organizationInvitationsTable.expiresAt, /* @__PURE__ */ new Date())
            )
          );
          const [existingInvite, existingMemberByEmail, existingUser] = await Promise.all([
            tx.select({ id: organizationInvitationsTable.id }).from(organizationInvitationsTable).where(
              and(
                eq(
                  organizationInvitationsTable.organizationId,
                  context.organization.id
                ),
                eq(organizationInvitationsTable.email, email3),
                eq(organizationInvitationsTable.status, "PENDING"),
                gt(organizationInvitationsTable.expiresAt, /* @__PURE__ */ new Date())
              )
            ).then((rows) => rows[0] ?? null),
            tx.select({ id: organizationMembersTable.id }).from(organizationMembersTable).innerJoin(
              usersTable,
              eq(organizationMembersTable.userId, usersTable.id)
            ).where(
              and(
                eq(
                  organizationMembersTable.organizationId,
                  context.organization.id
                ),
                eq(usersTable.email, email3)
              )
            ).then((rows) => rows[0] ?? null),
            tx.select().from(usersTable).where(eq(usersTable.email, email3)).then((rows) => rows[0] ?? null)
          ]);
          if (existingInvite) {
            throw new OrganizationTenantAccessError(
              "A pending invitation already exists for this email address.",
              409
            );
          }
          if (existingMemberByEmail) {
            throw new OrganizationTenantAccessError(
              "This user is already a member of your organization.",
              409
            );
          }
          if (existingUser) {
            if (existingUser.membershipType && existingUser.membershipType !== "ORGANIZATION") {
              throw new OrganizationTenantAccessError(
                "This email belongs to a non-organization account and cannot be added to organization tenancy.",
                409
              );
            }
            if (typeof existingUser.organizationId === "number" && existingUser.organizationId !== context.organization.id) {
              throw new OrganizationTenantAccessError(
                "This user already belongs to another organization.",
                409
              );
            }
            throw new OrganizationTenantAccessError(
              "This email already belongs to a WWN account. Existing accounts cannot be auto-added to an organization without an explicit acceptance flow.",
              409
            );
          }
          try {
            return await tx.insert(organizationInvitationsTable).values({
              organizationId: context.organization.id,
              email: email3,
              firstName: body.firstName ?? null,
              lastName: body.lastName ?? null,
              role: body.role,
              invitedByUserId: userId,
              tokenHash: token.tokenHash,
              expiresAt: token.expiresAt
            }).returning({
              id: organizationInvitationsTable.id,
              email: organizationInvitationsTable.email,
              firstName: organizationInvitationsTable.firstName,
              lastName: organizationInvitationsTable.lastName,
              role: organizationInvitationsTable.role,
              status: organizationInvitationsTable.status,
              expiresAt: organizationInvitationsTable.expiresAt,
              createdAt: organizationInvitationsTable.createdAt
            });
          } catch (err) {
            if (!isUniqueViolation6(err)) {
              throw err;
            }
            throw new OrganizationTenantAccessError(
              "A pending invitation already exists for this email address.",
              409
            );
          }
        });
        const invitePath = `/join-organization?invite=${encodeURIComponent(token.token)}`;
        let delivery = { status: "sent" };
        try {
          await sendMail({
            to: email3,
            ...createOrganizationInvitationEmail({
              firstName: body.firstName ?? null,
              organizationName: context.organization.name,
              roleLabel: formatOrganizationRoleLabel(body.role),
              inviteLink: invitePath,
              expiresOnLabel: token.expiresAt.toLocaleDateString("en-CA", {
                year: "numeric",
                month: "long",
                day: "numeric"
              })
            })
          });
        } catch (err) {
          logger.error(
            { err, email: email3, invitationId: invitation.id },
            "Failed to send organization invitation email; manual sharing required"
          );
          delivery = {
            status: "manual_share_required",
            message: "Invitation created, but email delivery is unavailable right now. Share the invite link manually.",
            invitePath
          };
        }
        return res.status(201).json({
          mode: "invited",
          invitation: {
            id: invitation.id,
            email: invitation.email,
            firstName: invitation.firstName ?? null,
            lastName: invitation.lastName ?? null,
            role: invitation.role,
            roleLabel: formatOrganizationRoleLabel(invitation.role),
            status: invitation.status,
            expiresAt: invitation.expiresAt.toISOString(),
            createdAt: invitation.createdAt.toISOString()
          },
          delivery
        });
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.patch("/org/members/:memberId", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const context = await requireOrganizationAuthorization(userId, {
          capability: "member_management",
          roleAction: "members_manage"
        });
        const memberId = Number(req.params.memberId);
        if (!Number.isInteger(memberId) || memberId <= 0) {
          return res.status(400).json({ message: "Invalid organization member id." });
        }
        const body = external_exports.object({
          role: external_exports.enum(ORG_ROLE_VALUES).optional(),
          membershipStatus: external_exports.enum(ORG_MEMBER_STATUS_VALUES).optional()
        }).parse(req.body);
        const target = await requireScopedOrganizationMember(context, memberId);
        if (!body.role && !body.membershipStatus) {
          return res.status(400).json({
            message: "Provide a role or membership status change."
          });
        }
        const isRoleChangeRequested = Boolean(body.role);
        const isStatusChangeRequested = Boolean(body.membershipStatus);
        if (isRoleChangeRequested || isStatusChangeRequested) {
          assertOrganizationNotSelfTarget(
            userId,
            target.userId,
            "Use an organization-authority handoff before changing your own access."
          );
        }
        if (body.role === "OWNER") {
          throw new OrganizationTenantAccessError(
            "The organization authority role is reserved for the organization account.",
            409,
            "role_check"
          );
        }
        if (body.role) {
          assertOrganizationRoleTransition({
            actorRole: context.membership?.role,
            targetRole: target.role,
            nextRole: body.role,
            insufficientMessage: "Your organization role does not allow this membership change.",
            authorityOnlyMessage: "Only the organization authority can manage organization authority access."
          });
        }
        if (body.membershipStatus) {
          assertOrganizationOwnerAction(
            context.membership?.role,
            "Only the organization authority can change member status."
          );
        }
        if ((!body.role || target.role === body.role) && (!body.membershipStatus || target.membershipStatus === body.membershipStatus)) {
          return res.json({
            member: {
              id: target.id,
              userId: target.userId,
              email: target.email,
              firstName: target.firstName,
              lastName: target.lastName ?? null,
              role: target.role,
              roleLabel: formatOrganizationRoleLabel(target.role),
              membershipStatus: getOrganizationMemberStatus(
                target.membershipStatus
              ),
              isEmailVerified: target.isEmailVerified,
              joinedAt: target.joinedAt.toISOString(),
              createdAt: target.createdAt.toISOString()
            }
          });
        }
        const nextRole = body.role ?? target.role;
        const nextMembershipStatus = body.membershipStatus ?? target.membershipStatus;
        const isActiveOwnerLosingControl = target.role === "OWNER" && target.membershipStatus === "ACTIVE" && (nextRole !== "OWNER" || nextMembershipStatus !== "ACTIVE");
        if (isActiveOwnerLosingControl) {
          const ownerCount = await countOrganizationOwners(
            context.organization.id,
            {
              activeOnly: true
            }
          );
          assertOrganizationOwnerFloor(
            ownerCount,
            "Assign another active organization authority before changing the last active organization authority."
          );
        }
        const [updated] = await db.update(organizationMembersTable).set({
          role: nextRole,
          status: nextMembershipStatus
        }).where(eq(organizationMembersTable.id, target.id)).returning({
          id: organizationMembersTable.id,
          userId: organizationMembersTable.userId,
          role: organizationMembersTable.role,
          membershipStatus: organizationMembersTable.status,
          joinedAt: organizationMembersTable.joinedAt
        });
        return res.json({
          member: {
            id: updated.id,
            userId: updated.userId,
            email: target.email,
            firstName: target.firstName,
            lastName: target.lastName ?? null,
            role: updated.role,
            roleLabel: formatOrganizationRoleLabel(updated.role),
            membershipStatus: getOrganizationMemberStatus(updated.membershipStatus),
            isEmailVerified: target.isEmailVerified,
            joinedAt: updated.joinedAt.toISOString(),
            createdAt: target.createdAt.toISOString()
          }
        });
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.delete("/org/members/:memberId", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const context = await requireOrganizationAuthorization(userId, {
          capability: "member_management",
          roleAction: "members_manage"
        });
        const memberId = Number(req.params.memberId);
        if (!Number.isInteger(memberId) || memberId <= 0) {
          return res.status(400).json({ message: "Invalid organization member id." });
        }
        const target = await requireScopedOrganizationMember(context, memberId);
        assertOrganizationNotSelfTarget(
          userId,
          target.userId,
          "Use an organization-authority handoff before removing yourself."
        );
        assertOrganizationRoleTransition({
          actorRole: context.membership?.role,
          targetRole: target.role,
          insufficientMessage: "Your organization role does not allow this removal.",
          authorityOnlyMessage: "Only the organization authority can remove the organization authority account."
        });
        if (target.role === "OWNER" && target.membershipStatus === "ACTIVE") {
          const ownerCount = await countOrganizationOwners(
            context.organization.id,
            {
              activeOnly: true
            }
          );
          assertOrganizationOwnerFloor(
            ownerCount,
            "Assign another organization authority before removing the last organization authority."
          );
        }
        await db.transaction(async (tx) => {
          await tx.delete(organizationMembersTable).where(eq(organizationMembersTable.id, target.id));
          await tx.delete(organizationInvitationsTable).where(
            and(
              eq(
                organizationInvitationsTable.organizationId,
                context.organization.id
              ),
              eq(
                organizationInvitationsTable.email,
                normalizeEmail(target.email)
              )
            )
          );
          await tx.update(usersTable).set({
            organizationId: null,
            updatedAt: /* @__PURE__ */ new Date()
          }).where(
            and(
              eq(usersTable.id, target.userId),
              eq(usersTable.organizationId, context.organization.id)
            )
          );
        });
        return res.status(204).send();
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.delete(
      "/org/invitations/:invitationId",
      requireAuth,
      async (req, res) => {
        const userId = req.userId;
        try {
          const context = await requireOrganizationAuthorization(userId, {
            capability: "member_management",
            roleAction: "members_manage"
          });
          const invitationId = Number(req.params.invitationId);
          if (!Number.isInteger(invitationId) || invitationId <= 0) {
            return res.status(400).json({ message: "Invalid invitation id." });
          }
          const invitation = await requireScopedOrganizationInvitation(
            context,
            invitationId,
            { pendingOnly: true }
          );
          if (invitation.role === "OWNER") {
            assertOrganizationOwnerAction(
              context.membership?.role,
              "Only the organization authority can cancel an organization authority invitation."
            );
          }
          await db.delete(organizationInvitationsTable).where(eq(organizationInvitationsTable.id, invitation.id));
          return res.status(204).send();
        } catch (err) {
          return handleError4(err, res);
        }
      }
    );
    router5.get("/org/asca/groups", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const context = await requireOrganizationAscaParticipantAccess(userId);
        const groups = await db.select({
          asca: {
            id: ascasTable.id,
            name: ascasTable.name,
            description: ascasTable.description,
            termsHtml: ascasTable.termsHtml,
            organizationId: ascasTable.organizationId,
            type: ascasTable.type,
            status: ascasTable.status,
            investmentId: ascasTable.investmentId,
            escrowWalletId: ascasTable.escrowWalletId,
            targetAmount: ascasTable.targetAmount,
            currentAmount: ascasTable.currentAmount,
            fundingStartAt: ascasTable.fundingStartAt,
            fundingEndAt: ascasTable.fundingEndAt,
            constitution: ascasTable.constitution,
            createdAt: ascasTable.createdAt,
            updatedAt: ascasTable.updatedAt,
            memberCount: sql`(
            select count(*)::int from asca_members am where am.asca_id = ${ascasTable.id}
          )`,
            contributionCount: sql`(
            select count(*)::int
            from asca_members am
            where am.asca_id = ${ascasTable.id}
              and coalesce(am.contributed_amount, 0) > 0
          )`
          },
          member: ascaMembersTable
        }).from(ascasTable).leftJoin(
          ascaMembersTable,
          and(
            eq(ascaMembersTable.ascaId, ascasTable.id),
            eq(ascaMembersTable.userId, userId)
          )
        ).where(eq(ascasTable.organizationId, context.organization.id)).orderBy(desc(ascasTable.createdAt));
        return res.json({
          organization: context.organization,
          permissions: context.permissions,
          groups
        });
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.get("/org/asca/groups/:id", requireAuth, async (req, res) => {
      const userId = req.userId;
      const ascaId = Number(req.params.id);
      if (!Number.isInteger(ascaId) || ascaId <= 0) {
        return res.status(400).json({ message: "Invalid ASCA id." });
      }
      try {
        const context = await requireOrganizationAscaParticipantAccess(userId);
        const [asca] = await db.select().from(ascasTable).where(eq(ascasTable.id, ascaId));
        if (!asca || asca.organizationId !== context.organization.id) {
          return res.status(404).json({ message: "Organization ASCA not found." });
        }
        const members = await db.select({
          id: ascaMembersTable.id,
          ascaId: ascaMembersTable.ascaId,
          userId: ascaMembersTable.userId,
          targetContribution: ascaMembersTable.targetContribution,
          contributedAmount: ascaMembersTable.contributedAmount,
          status: ascaMembersTable.status,
          joinedAt: ascaMembersTable.joinedAt,
          firstName: usersTable.firstName,
          lastName: usersTable.lastName
        }).from(ascaMembersTable).innerJoin(usersTable, eq(ascaMembersTable.userId, usersTable.id)).where(eq(ascaMembersTable.ascaId, ascaId)).orderBy(desc(ascaMembersTable.contributedAmount));
        return res.json({ asca, members });
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.patch("/org/asca/groups/:id", requireAuth, async (req, res) => {
      const userId = req.userId;
      const ascaId = Number(req.params.id);
      if (!Number.isInteger(ascaId) || ascaId <= 0) {
        return res.status(400).json({ message: "Invalid ASCA id." });
      }
      try {
        const context = await requireOrganizationAscaParticipantAccess(userId);
        assertOrganizationAscaManager(context);
        const [existing] = await db.select().from(ascasTable).where(eq(ascasTable.id, ascaId));
        if (!existing || existing.organizationId !== context.organization.id) {
          return res.status(404).json({ message: "Organization ASCA not found." });
        }
        if (existing.status !== "DRAFT") {
          return res.status(400).json({ message: "Only draft ASCAs can be edited." });
        }
        const schema = external_exports.object({
          name: external_exports.string().min(3).optional(),
          description: external_exports.string().optional().nullable(),
          termsHtml: external_exports.string().optional().nullable(),
          type: external_exports.enum(["GENERAL", "INVESTMENT"]).optional(),
          investmentId: external_exports.number().int().positive().optional().nullable(),
          targetAmount: external_exports.string().optional().nullable(),
          fundingEndAt: external_exports.string().optional().nullable(),
          constitution: external_exports.object({
            allowLateJoin: external_exports.boolean().optional(),
            maxMembers: external_exports.number().int().positive().optional(),
            installmentPolicy: external_exports.enum(["INSTALLMENTS", "FULL"]).optional(),
            contributionFrequency: external_exports.enum(["WEEKLY", "MONTHLY"]).optional(),
            equalContribution: external_exports.boolean().optional(),
            contributionModel: external_exports.enum(["EQUAL", "VARIABLE"]).optional(),
            borrowingPolicy: external_exports.object({
              enabled: external_exports.boolean().optional(),
              approvalMode: external_exports.enum(["OWNER_ADMIN"]).optional(),
              maxBorrowPctOfPool: external_exports.number().min(1).max(100).optional(),
              maxBorrowPctOfOwnContribution: external_exports.number().min(1).max(100).optional(),
              liquidityReservePct: external_exports.number().min(0).max(95).optional(),
              termMonths: external_exports.number().int().min(1).max(36).optional(),
              repaymentFrequency: external_exports.enum(["WEEKLY", "BIWEEKLY", "MONTHLY"]).optional(),
              borrowerAppreciationPct: external_exports.number().min(0).max(100).optional(),
              processingFeePct: external_exports.number().min(0).max(25).optional(),
              minContributionAgeDays: external_exports.number().int().min(0).max(365).optional()
            }).partial().optional()
          }).passthrough().optional().nullable()
        }).strict();
        const parsed = schema.safeParse(req.body);
        if (!parsed.success) {
          return res.status(400).json({ errors: parsed.error.flatten() });
        }
        const data = parsed.data;
        const normalizeMoneyString2 = (input, field) => {
          const parsed2 = Number(String(input).trim());
          if (!Number.isFinite(parsed2)) {
            throw new Error(`${field} must be a valid number.`);
          }
          if (parsed2 < 0) {
            throw new Error(`${field} must be 0 or more.`);
          }
          return parsed2.toFixed(2);
        };
        const normalizeDateInput2 = (input, field) => {
          const trimmed = String(input ?? "").trim();
          const parsed2 = new Date(trimmed);
          if (!trimmed || Number.isNaN(parsed2.getTime())) {
            throw new Error(`${field} must be a valid date.`);
          }
          return parsed2;
        };
        const toContributionModel = (constitution) => {
          if (typeof constitution?.equalContribution === "boolean") {
            return constitution.equalContribution ? "EQUAL" : "VARIABLE";
          }
          return constitution?.contributionModel === "EQUAL" ? "EQUAL" : "VARIABLE";
        };
        const updatePayload = { updatedAt: /* @__PURE__ */ new Date() };
        if (typeof data.name !== "undefined") updatePayload.name = data.name;
        if (typeof data.description !== "undefined")
          updatePayload.description = data.description;
        if (typeof data.termsHtml !== "undefined") {
          const normalized = typeof data.termsHtml === "string" && data.termsHtml.trim().length > 0 ? data.termsHtml.trim() : null;
          updatePayload.termsHtml = normalized;
        }
        if (typeof data.type !== "undefined") updatePayload.type = data.type;
        if (typeof data.investmentId !== "undefined")
          updatePayload.investmentId = data.investmentId;
        if (typeof data.targetAmount !== "undefined") {
          updatePayload.targetAmount = typeof data.targetAmount === "string" && data.targetAmount.trim().length ? normalizeMoneyString2(data.targetAmount, "targetAmount") : null;
        }
        if (typeof data.fundingEndAt !== "undefined") {
          updatePayload.fundingEndAt = typeof data.fundingEndAt === "string" && data.fundingEndAt.trim().length ? normalizeDateInput2(data.fundingEndAt, "fundingEndAt") : null;
        }
        if (typeof data.constitution !== "undefined") {
          if (data.constitution === null) {
            updatePayload.constitution = {};
          } else {
            const contributionModel = toContributionModel(data.constitution);
            const {
              equalContribution: _a,
              contributionModel: _b,
              ...rest
            } = data.constitution ?? {};
            const normalized = {
              ...rest,
              equalContribution: contributionModel === "EQUAL"
            };
            if (typeof normalized.allowInstallments === "boolean" && typeof normalized.installmentPolicy !== "string") {
              normalized.installmentPolicy = normalized.allowInstallments ? "INSTALLMENTS" : "FULL";
            }
            updatePayload.constitution = normalized;
          }
        }
        const nextType = updatePayload.type ?? existing.type;
        const nextConstitution = updatePayload.constitution ?? existing.constitution;
        if (nextType !== "GENERAL" && getAscaBorrowingPolicy(nextConstitution)) {
          return res.status(400).json({
            message: "Borrowing can only be enabled for GENERAL ASCA groups."
          });
        }
        const [updated] = await db.update(ascasTable).set(updatePayload).where(eq(ascasTable.id, ascaId)).returning();
        return res.json({ asca: updated });
      } catch (err) {
        if (err instanceof Error) {
          return res.status(400).json({ message: err.message });
        }
        return handleError4(err, res);
      }
    });
    router5.post("/org/asca/groups", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const [user] = await db.select().from(usersTable).where(eq(usersTable.id, userId)).limit(1);
        if (user) {
          const lens = getInvestorPackageLens({
            membershipType: user.membershipType ?? null,
            membershipStatus: user.membershipStatus ?? null,
            userRole: user.userRole ?? null,
            segment: user.segment ?? null,
            investorCategory: user.investorCategory ?? null
          });
          if (!lens.canAsca) {
            return res.status(403).json({
              message: "Your investor package does not include access to ASCA savings groups."
            });
          }
        }
        const context = await requireOrganizationAscaParticipantAccess(userId);
        assertOrganizationAscaManager(context);
        const parsed = CreateAscaSchema.safeParse(req.body);
        if (!parsed.success) {
          return res.status(400).json({ errors: parsed.error.flatten() });
        }
        const asca = await createAsca(parsed.data, userId, {
          organizationId: context.organization.id
        });
        return res.status(201).json({ message: "ASCA created.", asca });
      } catch (err) {
        if (err instanceof Error) {
          return res.status(400).json({ message: err.message });
        }
        return handleError4(err, res);
      }
    });
    router5.delete("/org/asca/groups/:id", requireAuth, async (req, res) => {
      const userId = req.userId;
      const ascaId = Number(req.params.id);
      if (!Number.isInteger(ascaId) || ascaId <= 0) {
        return res.status(400).json({ message: "Invalid ASCA id." });
      }
      try {
        const context = await requireOrganizationAscaParticipantAccess(userId);
        assertOrganizationAscaManager(context);
        await deleteAscaGroup({
          ascaId,
          triggerUserId: userId,
          organizationId: context.organization.id
        });
        return res.json({ ok: true });
      } catch (err) {
        if (err instanceof Error) {
          return res.status(400).json({ message: err.message });
        }
        return handleError4(err, res);
      }
    });
    router5.post("/org/asca/groups/:id/cancel", requireAuth, async (req, res) => {
      const userId = req.userId;
      const ascaId = Number(req.params.id);
      if (!Number.isInteger(ascaId) || ascaId <= 0) {
        return res.status(400).json({ message: "Invalid ASCA id." });
      }
      try {
        const context = await requireOrganizationAscaParticipantAccess(userId);
        assertOrganizationAscaManager(context);
        const [asca] = await db.select({ organizationId: ascasTable.organizationId }).from(ascasTable).where(eq(ascasTable.id, ascaId));
        if (!asca || asca.organizationId !== context.organization.id) {
          return res.status(404).json({ message: "Organization ASCA not found." });
        }
        await cancelAsca(ascaId, userId);
        return res.json({ ok: true });
      } catch (err) {
        if (err instanceof Error) {
          return res.status(400).json({ message: err.message });
        }
        return handleError4(err, res);
      }
    });
    router5.post("/org/asca/groups/:id/publish", requireAuth, async (req, res) => {
      const userId = req.userId;
      const ascaId = Number(req.params.id);
      if (!Number.isInteger(ascaId) || ascaId <= 0) {
        return res.status(400).json({ message: "Invalid ASCA id." });
      }
      try {
        const context = await requireOrganizationAscaParticipantAccess(userId);
        assertOrganizationAscaManager(context);
        const [asca] = await db.select({ organizationId: ascasTable.organizationId }).from(ascasTable).where(eq(ascasTable.id, ascaId));
        if (!asca || asca.organizationId !== context.organization.id) {
          return res.status(404).json({ message: "Organization ASCA not found." });
        }
        const updated = await publishAsca(ascaId, {
          organizationId: context.organization.id
        });
        return res.json({ asca: updated });
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.post("/org/asca/groups/:id/unpublish", requireAuth, async (req, res) => {
      const userId = req.userId;
      const ascaId = Number(req.params.id);
      if (!Number.isInteger(ascaId) || ascaId <= 0) {
        return res.status(400).json({ message: "Invalid ASCA id." });
      }
      try {
        const context = await requireOrganizationAscaParticipantAccess(userId);
        assertOrganizationAscaManager(context);
        const [asca] = await db.select({ organizationId: ascasTable.organizationId }).from(ascasTable).where(eq(ascasTable.id, ascaId));
        if (!asca || asca.organizationId !== context.organization.id) {
          return res.status(404).json({ message: "Organization ASCA not found." });
        }
        const updated = await unpublishAsca(ascaId, {
          organizationId: context.organization.id
        });
        return res.json({ asca: updated });
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.post("/org/asca/groups/:id/withdraw", requireAuth, async (req, res) => {
      const userId = req.userId;
      const ascaId = Number(req.params.id);
      if (!Number.isInteger(ascaId) || ascaId <= 0) {
        return res.status(400).json({ message: "Invalid ASCA id." });
      }
      try {
        const context = await requireOrganizationAscaParticipantAccess(userId);
        assertOrganizationAscaManager(context);
        const [asca] = await db.select({ organizationId: ascasTable.organizationId }).from(ascasTable).where(eq(ascasTable.id, ascaId));
        if (!asca || asca.organizationId !== context.organization.id) {
          return res.status(404).json({ message: "Organization ASCA not found." });
        }
        await withdrawAsca(ascaId, userId);
        return res.json({ message: "ASCA withdrawn successfully" });
      } catch (err) {
        if (err instanceof Error) {
          return res.status(400).json({ message: err.message });
        }
        return handleError4(err, res);
      }
    });
    router5.post(
      "/org/asca/groups/:id/withdraw-offline",
      requireAuth,
      async (req, res) => {
        const userId = req.userId;
        const ascaId = Number(req.params.id);
        if (!Number.isInteger(ascaId) || ascaId <= 0) {
          return res.status(400).json({ message: "Invalid ASCA id." });
        }
        try {
          const context = await requireOrganizationAscaParticipantAccess(userId);
          assertOrganizationAscaManager(context);
          const [asca] = await db.select({ organizationId: ascasTable.organizationId }).from(ascasTable).where(eq(ascasTable.id, ascaId));
          if (!asca || asca.organizationId !== context.organization.id) {
            return res.status(404).json({ message: "Organization ASCA not found." });
          }
          await withdrawAscaOffline(ascaId, userId);
          return res.json({ message: "ASCA withdrawn offline successfully" });
        } catch (err) {
          if (err instanceof Error) {
            return res.status(400).json({ message: err.message });
          }
          return handleError4(err, res);
        }
      }
    );
    router5.post("/org/asca/groups/:id/invest", requireAuth, async (req, res) => {
      const userId = req.userId;
      const ascaId = Number(req.params.id);
      if (!Number.isInteger(ascaId) || ascaId <= 0) {
        return res.status(400).json({ message: "Invalid ASCA id." });
      }
      try {
        const context = await requireOrganizationAscaParticipantAccess(userId);
        assertOrganizationAscaManager(context);
        const [asca] = await db.select({
          organizationId: ascasTable.organizationId,
          investmentId: ascasTable.investmentId,
          type: ascasTable.type
        }).from(ascasTable).where(eq(ascasTable.id, ascaId));
        if (!asca || asca.organizationId !== context.organization.id) {
          return res.status(404).json({ message: "Organization ASCA not found." });
        }
        const investmentId = req.body.investmentId || asca.investmentId;
        if (!investmentId) {
          return res.status(400).json({ message: "investmentId is required" });
        }
        await convertAscaToInvestment(ascaId, Number(investmentId), userId);
        return res.json({ message: "ASCA successfully converted to investment" });
      } catch (err) {
        if (err instanceof Error) {
          return res.status(400).json({ message: err.message });
        }
        return handleError4(err, res);
      }
    });
    router5.post("/org/asca/groups/:id/join", requireAuth, async (req, res) => {
      const userId = req.userId;
      const ascaId = Number(req.params.id);
      if (!Number.isInteger(ascaId) || ascaId <= 0) {
        return res.status(400).json({ message: "Invalid ASCA id." });
      }
      const schema = external_exports.object({
        targetContribution: external_exports.string().optional(),
        catchUpAmount: external_exports.number().optional(),
        acceptedTerms: external_exports.boolean().optional()
      }).strict();
      const parsed = schema.safeParse(req.body ?? {});
      if (!parsed.success) {
        return res.status(400).json({ errors: parsed.error.flatten() });
      }
      try {
        const [user] = await db.select().from(usersTable).where(eq(usersTable.id, userId)).limit(1);
        if (user) {
          const lens = getInvestorPackageLens({
            membershipType: user.membershipType ?? null,
            membershipStatus: user.membershipStatus ?? null,
            userRole: user.userRole ?? null,
            segment: user.segment ?? null,
            investorCategory: user.investorCategory ?? null
          });
          if (!lens.canAsca) {
            return res.status(403).json({
              message: "Your investor package does not include access to ASCA savings groups."
            });
          }
        }
        const context = await requireOrganizationAscaParticipantAccess(userId);
        const [asca] = await db.select({
          organizationId: ascasTable.organizationId,
          termsHtml: ascasTable.termsHtml
        }).from(ascasTable).where(eq(ascasTable.id, ascaId));
        if (!asca || asca.organizationId !== context.organization.id) {
          return res.status(404).json({ message: "Organization ASCA not found." });
        }
        const termsRequired = Boolean(asca.termsHtml) && String(asca.termsHtml).trim().length > 0;
        if (termsRequired && parsed.data.acceptedTerms !== true) {
          return res.status(400).json({
            message: "You must accept the ASCA terms & conditions to join."
          });
        }
        const member = await joinAsca(ascaId, userId, {
          targetContribution: parsed.data.targetContribution,
          catchUpAmount: parsed.data.catchUpAmount
        });
        return res.json({ member });
      } catch (err) {
        if (err instanceof AscaCatchUpRequiredError) {
          return res.status(400).json({
            message: err.message,
            code: "ASCA_CATCH_UP_REQUIRED",
            requiredCatchUpAmount: err.requiredCatchUpAmount
          });
        }
        if (err instanceof Error) {
          return res.status(400).json({ message: err.message });
        }
        return handleError4(err, res);
      }
    });
    router5.post(
      "/org/asca/groups/:id/contribute",
      requireAuth,
      async (req, res) => {
        const userId = req.userId;
        const ascaId = Number(req.params.id);
        if (!Number.isInteger(ascaId) || ascaId <= 0) {
          return res.status(400).json({ message: "Invalid ASCA id." });
        }
        const schema = external_exports.object({ amount: external_exports.number().positive() }).strict();
        const parsed = schema.safeParse(req.body ?? {});
        if (!parsed.success) {
          return res.status(400).json({ errors: parsed.error.flatten() });
        }
        try {
          const context = await requireOrganizationAscaParticipantAccess(userId);
          const [asca] = await db.select({ organizationId: ascasTable.organizationId }).from(ascasTable).where(eq(ascasTable.id, ascaId));
          if (!asca || asca.organizationId !== context.organization.id) {
            return res.status(404).json({ message: "Organization ASCA not found." });
          }
          const contribution = await contributeToAsca(
            ascaId,
            userId,
            parsed.data.amount
          );
          return res.json({ contribution });
        } catch (err) {
          if (err instanceof Error) {
            return res.status(400).json({ message: err.message });
          }
          return handleError4(err, res);
        }
      }
    );
    router5.get(
      "/org/asca/groups/:id/borrow-summary",
      requireAuth,
      async (req, res) => {
        const userId = req.userId;
        const ascaId = Number(req.params.id);
        if (!Number.isInteger(ascaId) || ascaId <= 0) {
          return res.status(400).json({ message: "Invalid ASCA id." });
        }
        try {
          const context = await requireOrganizationAscaParticipantAccess(userId);
          const scoped = await getOrganizationAscaForBorrowing(
            context.organization.id,
            ascaId
          );
          if (!scoped) {
            return res.status(404).json({ message: "Organization ASCA not found." });
          }
          if (scoped.asca.type !== "GENERAL") {
            return res.status(400).json({
              message: "Borrowing is only available on GENERAL ASCA groups."
            });
          }
          const canManage = context.permissions.isOwner === true || context.permissions.isAdmin === true;
          const member = await getOrganizationAscaMemberRecord(ascaId, userId);
          const liquidity = scoped.borrowingPolicy && scoped.asca.escrowWalletId ? await getAscaBorrowLiquiditySnapshotWith(db, {
            ascaId,
            escrowWalletId: scoped.asca.escrowWalletId,
            liquidityReservePct: scoped.borrowingPolicy.liquidityReservePct
          }) : null;
          const applicationSelection = {
            id: loanApplicationsTable.id,
            ascaId: loanApplicationsTable.ascaId,
            borrowerId: loanApplicationsTable.borrowerId,
            requestedAmount: loanApplicationsTable.requestedAmount,
            approvedAmount: loanApplicationsTable.approvedAmount,
            disbursedAmount: loanApplicationsTable.disbursedAmount,
            borrowerAppreciationAmount: loanApplicationsTable.borrowerAppreciationAmount,
            totalRepayableAmount: loanApplicationsTable.totalRepayableAmount,
            estimatedInstallmentAmount: loanApplicationsTable.estimatedInstallmentAmount,
            repaymentFrequency: loanApplicationsTable.repaymentFrequency,
            termMonths: loanApplicationsTable.termMonths,
            purpose: loanApplicationsTable.purpose,
            notes: loanApplicationsTable.notes,
            status: loanApplicationsTable.status,
            reviewNote: loanApplicationsTable.reviewNote,
            createdAt: loanApplicationsTable.createdAt,
            reviewedAt: loanApplicationsTable.reviewedAt,
            disbursedAt: loanApplicationsTable.disbursedAt,
            borrowerFirstName: usersTable.firstName,
            borrowerLastName: usersTable.lastName
          };
          const [myApplications, manageApplications, metrics] = await Promise.all([
            db.select(applicationSelection).from(loanApplicationsTable).innerJoin(
              usersTable,
              eq(loanApplicationsTable.borrowerId, usersTable.id)
            ).where(
              and(
                eq(loanApplicationsTable.ascaId, ascaId),
                eq(loanApplicationsTable.borrowerId, userId)
              )
            ).orderBy(desc(loanApplicationsTable.createdAt)),
            canManage ? db.select(applicationSelection).from(loanApplicationsTable).innerJoin(
              usersTable,
              eq(loanApplicationsTable.borrowerId, usersTable.id)
            ).where(eq(loanApplicationsTable.ascaId, ascaId)).orderBy(desc(loanApplicationsTable.createdAt)) : Promise.resolve([]),
            getAscaBorrowMetricsWith(db, ascaId)
          ]);
          const contributedAmount = Number(member?.contributedAmount ?? 0);
          const maxBorrowAmount = scoped.borrowingPolicy && liquidity ? Math.max(
            0,
            Math.min(
              liquidity.availableToBorrow,
              liquidity.balance * (scoped.borrowingPolicy.maxBorrowPctOfPool / 100),
              contributedAmount * (scoped.borrowingPolicy.maxBorrowPctOfOwnContribution / 100)
            )
          ) : 0;
          return res.json({
            enabled: Boolean(scoped.borrowingPolicy),
            policy: scoped.borrowingPolicy,
            liquidity,
            eligibility: {
              isMember: Boolean(member),
              contributedAmount,
              joinedAt: member?.joinedAt ?? null,
              maxBorrowAmount: Number(formatMoneyAmount(maxBorrowAmount)),
              canManage
            },
            metrics,
            myApplications: myApplications.map(serializeAscaBorrowApplicationRow),
            manageApplications: manageApplications.map(
              serializeAscaBorrowApplicationRow
            )
          });
        } catch (err) {
          return handleError4(err, res);
        }
      }
    );
    router5.post(
      "/org/asca/groups/:id/borrow-applications",
      requireAuth,
      async (req, res) => {
        const userId = req.userId;
        const ascaId = Number(req.params.id);
        if (!Number.isInteger(ascaId) || ascaId <= 0) {
          return res.status(400).json({ message: "Invalid ASCA id." });
        }
        try {
          const context = await requireOrganizationAscaParticipantAccess(userId);
          const scoped = await getOrganizationAscaForBorrowing(
            context.organization.id,
            ascaId
          );
          if (!scoped) {
            return res.status(404).json({ message: "Organization ASCA not found." });
          }
          if (scoped.asca.type !== "GENERAL") {
            return res.status(400).json({
              message: "Borrowing is only available on GENERAL ASCA groups."
            });
          }
          if (!scoped.borrowingPolicy || !scoped.borrowingPolicy.enabled) {
            return res.status(400).json({
              message: "Borrowing is not enabled for this ASCA group."
            });
          }
          if (!scoped.asca.escrowWalletId) {
            return res.status(400).json({
              message: "This ASCA group does not have an escrow wallet yet."
            });
          }
          const schema = external_exports.object({
            amount: external_exports.coerce.number().positive(),
            purpose: external_exports.string().trim().min(3).max(200),
            notes: external_exports.string().trim().max(2e3).optional(),
            acceptedTerms: external_exports.boolean().optional()
          }).strict();
          const parsed = schema.safeParse(req.body ?? {});
          if (!parsed.success) {
            return res.status(400).json({ errors: parsed.error.flatten() });
          }
          if (hasMoreThanTwoDecimalPlaces(parsed.data.amount)) {
            return res.status(400).json({
              message: "Borrow amount can have at most 2 decimal places."
            });
          }
          const member = await getOrganizationAscaMemberRecord(ascaId, userId);
          if (!member) {
            return res.status(403).json({
              message: "Join this ASCA group before requesting a borrow."
            });
          }
          const termsRequired = Boolean(scoped.asca.termsHtml) && String(scoped.asca.termsHtml).trim().length > 0;
          if (termsRequired && parsed.data.acceptedTerms !== true) {
            return res.status(400).json({
              message: "Accept the ASCA terms before submitting a borrow request."
            });
          }
          const contributedAmount = Number(member.contributedAmount ?? 0);
          if (!Number.isFinite(contributedAmount) || contributedAmount <= 0) {
            return res.status(400).json({
              message: "Only contributing members can borrow from this ASCA pool."
            });
          }
          if (scoped.borrowingPolicy.minContributionAgeDays > 0 && member.joinedAt && (/* @__PURE__ */ new Date()).getTime() - new Date(member.joinedAt).getTime() < scoped.borrowingPolicy.minContributionAgeDays * 24 * 60 * 60 * 1e3) {
            return res.status(400).json({
              message: `You need at least ${scoped.borrowingPolicy.minContributionAgeDays} day(s) in this ASCA before borrowing.`
            });
          }
          const [existingActive] = await db.select({ id: loanApplicationsTable.id }).from(loanApplicationsTable).where(
            and(
              eq(loanApplicationsTable.ascaId, ascaId),
              eq(loanApplicationsTable.borrowerId, userId),
              inArray(loanApplicationsTable.status, [
                ...ACTIVE_ASCA_BORROW_APPLICATION_STATUSES
              ])
            )
          );
          if (existingActive) {
            return res.status(400).json({
              message: "You already have an active ASCA borrow request. Resolve it before opening another one."
            });
          }
          const liquidity = await getAscaBorrowLiquiditySnapshotWith(db, {
            ascaId,
            escrowWalletId: scoped.asca.escrowWalletId,
            liquidityReservePct: scoped.borrowingPolicy.liquidityReservePct
          });
          const maxBorrowAmount = Math.max(
            0,
            Math.min(
              liquidity.availableToBorrow,
              liquidity.balance * (scoped.borrowingPolicy.maxBorrowPctOfPool / 100),
              contributedAmount * (scoped.borrowingPolicy.maxBorrowPctOfOwnContribution / 100)
            )
          );
          if (maxBorrowAmount <= 0) {
            return res.status(400).json({
              message: "This ASCA pool does not have lendable cash right now."
            });
          }
          if (parsed.data.amount > maxBorrowAmount) {
            return res.status(400).json({
              message: `Borrow request exceeds your current ASCA limit of ${formatMoneyAmount(maxBorrowAmount)}.`
            });
          }
          const appreciationAmount = calculateSimpleAnnualRateAmount(
            parsed.data.amount,
            scoped.borrowingPolicy.borrowerAppreciationPct,
            scoped.borrowingPolicy.termMonths
          );
          const pricing = buildLoanPricingSnapshot({
            principalAmount: parsed.data.amount,
            appreciationAmount,
            termMonths: scoped.borrowingPolicy.termMonths,
            repaymentFrequency: scoped.borrowingPolicy.repaymentFrequency,
            processingFeePct: scoped.borrowingPolicy.processingFeePct
          });
          const now = /* @__PURE__ */ new Date();
          const [application] = await db.insert(loanApplicationsTable).values({
            ascaId,
            borrowerId: userId,
            loanType: "COMMUNITY_LENDING",
            requestedAmount: formatMoneyAmount(parsed.data.amount),
            purpose: parsed.data.purpose,
            term: pricing.termLabel,
            repaymentSchedule: pricing.repaymentScheduleLabel,
            termMonths: pricing.termMonths,
            borrowerAppreciationAmount: formatMoneyAmount(appreciationAmount),
            repaymentFrequency: pricing.repaymentFrequency,
            processingFeePct: scoped.borrowingPolicy.processingFeePct > 0 ? formatMoneyAmount(scoped.borrowingPolicy.processingFeePct) : null,
            wwnMarginPct: "0.00",
            reserveContributionPct: "0.00",
            platformAppreciationSharePct: "0.00",
            pricingLockedAt: now,
            totalRepayableAmount: formatMoneyAmount(pricing.totalRepayableAmount),
            estimatedInstallmentAmount: formatMoneyAmount(
              pricing.estimatedInstallmentAmount
            ),
            notes: parsed.data.notes?.trim() || null,
            status: "SUBMITTED",
            createdAt: now,
            updatedAt: now
          }).returning();
          return res.status(201).json({
            application: serializeAscaBorrowApplicationRow({
              ...application,
              borrowerFirstName: null,
              borrowerLastName: null
            })
          });
        } catch (err) {
          if (err instanceof Error) {
            return res.status(400).json({ message: err.message });
          }
          return handleError4(err, res);
        }
      }
    );
    router5.patch(
      "/org/asca/groups/:id/borrow-applications/:applicationId",
      requireAuth,
      async (req, res) => {
        const userId = req.userId;
        const ascaId = Number(req.params.id);
        const applicationId = Number(req.params.applicationId);
        if (!Number.isInteger(ascaId) || ascaId <= 0) {
          return res.status(400).json({ message: "Invalid ASCA id." });
        }
        if (!Number.isInteger(applicationId) || applicationId <= 0) {
          return res.status(400).json({ message: "Invalid application id." });
        }
        try {
          const context = await requireOrganizationAscaParticipantAccess(userId);
          assertOrganizationAscaManager(context);
          const scoped = await getOrganizationAscaForBorrowing(
            context.organization.id,
            ascaId
          );
          if (!scoped) {
            return res.status(404).json({ message: "Organization ASCA not found." });
          }
          if (scoped.asca.type !== "GENERAL" || !scoped.borrowingPolicy) {
            return res.status(400).json({
              message: "Borrowing is not enabled for this ASCA group."
            });
          }
          if (!scoped.asca.escrowWalletId) {
            return res.status(400).json({
              message: "This ASCA group does not have an escrow wallet yet."
            });
          }
          const schema = external_exports.object({
            action: external_exports.enum(["APPROVE", "REJECT", "FUND"]),
            approvedAmount: external_exports.coerce.number().positive().optional(),
            reviewNote: external_exports.string().trim().max(2e3).optional()
          }).strict();
          const parsed = schema.safeParse(req.body ?? {});
          if (!parsed.success) {
            return res.status(400).json({ errors: parsed.error.flatten() });
          }
          if (parsed.data.approvedAmount != null && hasMoreThanTwoDecimalPlaces(parsed.data.approvedAmount)) {
            return res.status(400).json({
              message: "Approved amount can have at most 2 decimal places."
            });
          }
          const [existing] = await db.select().from(loanApplicationsTable).where(
            and(
              eq(loanApplicationsTable.id, applicationId),
              eq(loanApplicationsTable.ascaId, ascaId)
            )
          );
          if (!existing) {
            return res.status(404).json({ message: "Borrow application not found." });
          }
          if (parsed.data.action === "REJECT") {
            if (!["SUBMITTED", "WAITLISTED", "UNDER_REVIEW", "APPROVED"].includes(
              existing.status
            )) {
              return res.status(400).json({
                message: "Only pending ASCA borrow requests can be rejected."
              });
            }
            const [updated2] = await db.update(loanApplicationsTable).set({
              status: "REJECTED",
              reviewNote: parsed.data.reviewNote?.trim() || null,
              reviewedAt: /* @__PURE__ */ new Date(),
              reviewedByAdminId: userId,
              updatedAt: /* @__PURE__ */ new Date()
            }).where(eq(loanApplicationsTable.id, applicationId)).returning();
            return res.json({
              application: serializeAscaBorrowApplicationRow({
                ...updated2,
                borrowerFirstName: null,
                borrowerLastName: null
              })
            });
          }
          const member = await getOrganizationAscaMemberRecord(
            ascaId,
            existing.borrowerId
          );
          if (!member) {
            return res.status(400).json({
              message: "Borrower is no longer an active member of this ASCA group."
            });
          }
          const contributedAmount = Number(member.contributedAmount ?? 0);
          const requestAmount = parseMoneyAmount(existing.requestedAmount);
          const nextApprovedAmount = parsed.data.approvedAmount != null ? parsed.data.approvedAmount : parseMoneyAmount(
            existing.approvedAmount ?? existing.requestedAmount
          );
          const liquidity = await getAscaBorrowLiquiditySnapshotWith(db, {
            ascaId,
            escrowWalletId: scoped.asca.escrowWalletId,
            liquidityReservePct: scoped.borrowingPolicy.liquidityReservePct
          });
          const maxAllowedAmount = Math.max(
            0,
            Math.min(
              liquidity.availableToBorrow + (existing.status === "APPROVED" ? parseMoneyAmount(existing.approvedAmount) : 0),
              liquidity.balance * (scoped.borrowingPolicy.maxBorrowPctOfPool / 100),
              contributedAmount * (scoped.borrowingPolicy.maxBorrowPctOfOwnContribution / 100)
            )
          );
          if (nextApprovedAmount > maxAllowedAmount) {
            return res.status(400).json({
              message: `Approved amount exceeds the current ASCA limit of ${formatMoneyAmount(maxAllowedAmount)} for this member.`
            });
          }
          if (parsed.data.action === "APPROVE") {
            if (!["SUBMITTED", "WAITLISTED", "UNDER_REVIEW"].includes(existing.status)) {
              return res.status(400).json({
                message: "Only new ASCA borrow requests can be approved."
              });
            }
            if (nextApprovedAmount <= 0) {
              return res.status(400).json({
                message: "Approved amount must be greater than 0."
              });
            }
            if (nextApprovedAmount > requestAmount) {
              return res.status(400).json({
                message: "Approved amount cannot exceed the requested amount."
              });
            }
            const [updated2] = await db.update(loanApplicationsTable).set({
              approvedAmount: formatMoneyAmount(nextApprovedAmount),
              status: "APPROVED",
              reviewNote: parsed.data.reviewNote?.trim() || null,
              reviewedAt: /* @__PURE__ */ new Date(),
              reviewedByAdminId: userId,
              updatedAt: /* @__PURE__ */ new Date()
            }).where(eq(loanApplicationsTable.id, applicationId)).returning();
            return res.json({
              application: serializeAscaBorrowApplicationRow({
                ...updated2,
                borrowerFirstName: null,
                borrowerLastName: null
              })
            });
          }
          if (existing.status !== "APPROVED") {
            return res.status(400).json({
              message: "Only approved ASCA borrow requests can be disbursed."
            });
          }
          const [borrowerWallet] = await Promise.all([
            ensureWalletWith3(db, "USER", existing.borrowerId)
          ]);
          const disbursementIdempotencyKey = `asca_borrow_disbursement:${existing.id}`;
          const [existingTx] = await db.select().from(walletTransactionsTable).where(
            eq(
              walletTransactionsTable.idempotencyKey,
              disbursementIdempotencyKey
            )
          );
          const transaction = existingTx ?? (await db.insert(walletTransactionsTable).values({
            type: "LOAN_DISBURSEMENT",
            idempotencyKey: disbursementIdempotencyKey,
            fromWalletId: scoped.asca.escrowWalletId,
            toWalletId: borrowerWallet.id,
            amount: formatMoneyAmount(nextApprovedAmount),
            metadata: {
              source: "ASCA_BORROW",
              ascaId,
              applicationId,
              borrowerId: existing.borrowerId
            }
          }).returning())[0];
          const firstDueDate = (() => {
            const base = /* @__PURE__ */ new Date();
            if (scoped.borrowingPolicy.repaymentFrequency === "WEEKLY") {
              base.setDate(base.getDate() + 7);
              return base;
            }
            if (scoped.borrowingPolicy.repaymentFrequency === "BIWEEKLY") {
              base.setDate(base.getDate() + 14);
              return base;
            }
            base.setMonth(base.getMonth() + 1);
            return base;
          })();
          const schedule = buildLendingRepaymentSchedule({
            totalAmount: parseMoneyAmount(existing.totalRepayableAmount),
            termMonths: existing.termMonths,
            repaymentFrequency: existing.repaymentFrequency,
            firstDueDate
          });
          const existingRepayments = await db.select({
            id: loanRepaymentsTable.id,
            dueDate: loanRepaymentsTable.dueDate,
            amount: loanRepaymentsTable.amount,
            paidAmount: loanRepaymentsTable.paidAmount,
            principalPaidAmount: loanRepaymentsTable.principalPaidAmount,
            returnPaidAmount: loanRepaymentsTable.returnPaidAmount,
            feePaidAmount: loanRepaymentsTable.feePaidAmount,
            creditedToPoolAmount: loanRepaymentsTable.creditedToPoolAmount,
            status: loanRepaymentsTable.status
          }).from(loanRepaymentsTable).where(eq(loanRepaymentsTable.loanApplicationId, applicationId)).orderBy(asc(loanRepaymentsTable.dueDate));
          const shouldReplaceSchedule = existingRepayments.length > 0 && canReplaceLoanRepaymentSchedule(existingRepayments) && !doesLoanRepaymentScheduleMatch(existingRepayments, schedule);
          if (shouldReplaceSchedule) {
            await db.delete(loanRepaymentsTable).where(eq(loanRepaymentsTable.loanApplicationId, applicationId));
          }
          if (schedule.length > 0 && (existingRepayments.length === 0 || shouldReplaceSchedule)) {
            await db.insert(loanRepaymentsTable).values(
              schedule.map((entry) => ({
                loanApplicationId: applicationId,
                dueDate: entry.dueDate,
                amount: entry.amount
              }))
            );
          }
          const [updated] = await db.update(loanApplicationsTable).set({
            approvedAmount: formatMoneyAmount(nextApprovedAmount),
            disbursedAmount: formatMoneyAmount(nextApprovedAmount),
            disbursedAt: /* @__PURE__ */ new Date(),
            disbursementTransactionId: transaction.id,
            status: "FUNDED",
            reviewNote: parsed.data.reviewNote?.trim() || existing.reviewNote,
            reviewedAt: existing.reviewedAt ?? /* @__PURE__ */ new Date(),
            reviewedByAdminId: existing.reviewedByAdminId ?? userId,
            updatedAt: /* @__PURE__ */ new Date()
          }).where(eq(loanApplicationsTable.id, applicationId)).returning();
          return res.json({
            application: serializeAscaBorrowApplicationRow({
              ...updated,
              borrowerFirstName: null,
              borrowerLastName: null
            })
          });
        } catch (err) {
          if (err instanceof Error) {
            return res.status(400).json({ message: err.message });
          }
          return handleError4(err, res);
        }
      }
    );
    router5.get(
      "/org/asca/groups/:id/borrow-applications/:applicationId/repayments",
      requireAuth,
      async (req, res) => {
        const userId = req.userId;
        const ascaId = Number(req.params.id);
        const applicationId = Number(req.params.applicationId);
        if (!Number.isInteger(ascaId) || ascaId <= 0) {
          return res.status(400).json({ message: "Invalid ASCA id." });
        }
        if (!Number.isInteger(applicationId) || applicationId <= 0) {
          return res.status(400).json({ message: "Invalid application id." });
        }
        try {
          const context = await requireOrganizationAscaParticipantAccess(userId);
          const scoped = await getOrganizationAscaForBorrowing(
            context.organization.id,
            ascaId
          );
          if (!scoped) {
            return res.status(404).json({ message: "Organization ASCA not found." });
          }
          if (scoped.asca.type !== "GENERAL") {
            return res.status(400).json({
              message: "Borrowing is only available on GENERAL ASCA groups."
            });
          }
          const canManage = context.permissions.isOwner === true || context.permissions.isAdmin === true;
          const [application] = await db.select({
            id: loanApplicationsTable.id,
            ascaId: loanApplicationsTable.ascaId,
            borrowerId: loanApplicationsTable.borrowerId,
            requestedAmount: loanApplicationsTable.requestedAmount,
            approvedAmount: loanApplicationsTable.approvedAmount,
            disbursedAmount: loanApplicationsTable.disbursedAmount,
            borrowerAppreciationAmount: loanApplicationsTable.borrowerAppreciationAmount,
            totalRepayableAmount: loanApplicationsTable.totalRepayableAmount,
            estimatedInstallmentAmount: loanApplicationsTable.estimatedInstallmentAmount,
            repaymentFrequency: loanApplicationsTable.repaymentFrequency,
            termMonths: loanApplicationsTable.termMonths,
            purpose: loanApplicationsTable.purpose,
            notes: loanApplicationsTable.notes,
            status: loanApplicationsTable.status,
            reviewNote: loanApplicationsTable.reviewNote,
            createdAt: loanApplicationsTable.createdAt,
            reviewedAt: loanApplicationsTable.reviewedAt,
            disbursedAt: loanApplicationsTable.disbursedAt,
            borrowerFirstName: usersTable.firstName,
            borrowerLastName: usersTable.lastName
          }).from(loanApplicationsTable).innerJoin(usersTable, eq(loanApplicationsTable.borrowerId, usersTable.id)).where(
            and(
              eq(loanApplicationsTable.id, applicationId),
              eq(loanApplicationsTable.ascaId, ascaId)
            )
          );
          if (!application) {
            return res.status(404).json({ message: "Borrow application not found." });
          }
          if (!canManage && application.borrowerId !== userId) {
            return res.status(403).json({
              message: "You are not authorized to view this borrow schedule."
            });
          }
          const repayments = await ensureAscaBorrowRepaymentsWith(db, application);
          const summary = summarizeAscaBorrowRepayments(repayments);
          return res.json({
            application: serializeAscaBorrowApplicationRow(application),
            repayments: repayments.map(serializeAscaBorrowRepaymentRow),
            summary: {
              ...summary,
              canPay: application.borrowerId === userId && ["FUNDED", "REPAYING"].includes(application.status)
            }
          });
        } catch (err) {
          return handleError4(err, res);
        }
      }
    );
    router5.post(
      "/org/asca/groups/:id/borrow-applications/:applicationId/payments",
      requireAuth,
      async (req, res) => {
        const userId = req.userId;
        const ascaId = Number(req.params.id);
        const applicationId = Number(req.params.applicationId);
        if (!Number.isInteger(ascaId) || ascaId <= 0) {
          return res.status(400).json({ message: "Invalid ASCA id." });
        }
        if (!Number.isInteger(applicationId) || applicationId <= 0) {
          return res.status(400).json({ message: "Invalid application id." });
        }
        try {
          const context = await requireOrganizationAscaParticipantAccess(userId);
          const scoped = await getOrganizationAscaForBorrowing(
            context.organization.id,
            ascaId
          );
          if (!scoped) {
            return res.status(404).json({ message: "Organization ASCA not found." });
          }
          if (scoped.asca.type !== "GENERAL") {
            return res.status(400).json({
              message: "Borrowing is only available on GENERAL ASCA groups."
            });
          }
          if (!scoped.asca.escrowWalletId) {
            return res.status(400).json({
              message: "This ASCA group does not have an escrow wallet yet."
            });
          }
          const parsed = external_exports.object({
            amount: external_exports.coerce.number().positive().optional(),
            payAll: external_exports.coerce.boolean().optional(),
            idempotencyKey: external_exports.string().min(1).optional()
          }).safeParse(req.body ?? {});
          if (!parsed.success) {
            return res.status(400).json({ errors: parsed.error.flatten() });
          }
          if (!parsed.data.payAll && parsed.data.amount == null) {
            return res.status(400).json({
              message: "Provide an amount or set payAll to true."
            });
          }
          if (parsed.data.amount != null && hasMoreThanTwoDecimalPlaces(parsed.data.amount)) {
            return res.status(400).json({
              message: "Payment amount can have at most 2 decimal places."
            });
          }
          const headerIdempotencyKeyRaw = req.headers["idempotency-key"] ?? req.headers["x-idempotency-key"];
          const headerIdempotencyKey = Array.isArray(headerIdempotencyKeyRaw) ? headerIdempotencyKeyRaw[0] : headerIdempotencyKeyRaw;
          const result = await db.transaction(async (tx) => {
            const [application] = await tx.select({
              id: loanApplicationsTable.id,
              ascaId: loanApplicationsTable.ascaId,
              borrowerId: loanApplicationsTable.borrowerId,
              status: loanApplicationsTable.status,
              disbursedAmount: loanApplicationsTable.disbursedAmount,
              totalRepayableAmount: loanApplicationsTable.totalRepayableAmount,
              borrowerAppreciationAmount: loanApplicationsTable.borrowerAppreciationAmount,
              processingFeePct: loanApplicationsTable.processingFeePct,
              repaymentFrequency: loanApplicationsTable.repaymentFrequency,
              termMonths: loanApplicationsTable.termMonths,
              reviewedAt: loanApplicationsTable.reviewedAt,
              disbursedAt: loanApplicationsTable.disbursedAt
            }).from(loanApplicationsTable).where(
              and(
                eq(loanApplicationsTable.id, applicationId),
                eq(loanApplicationsTable.ascaId, ascaId)
              )
            );
            if (!application) {
              return {
                status: 404,
                body: { message: "Borrow application not found." }
              };
            }
            if (application.borrowerId !== userId) {
              return {
                status: 403,
                body: { message: "You are not authorized to repay this loan." }
              };
            }
            if (!["FUNDED", "REPAYING"].includes(application.status)) {
              return {
                status: 400,
                body: {
                  message: "Loan repayments can only be made while the ASCA borrow is funded or repaying."
                }
              };
            }
            const disbursedAmount = parseMoneyAmount(application.disbursedAmount);
            const totalRepayableAmount = parseMoneyAmount(
              application.totalRepayableAmount
            );
            if (disbursedAmount <= 0 || totalRepayableAmount <= 0) {
              return {
                status: 400,
                body: {
                  message: "This ASCA borrow is not ready for repayment. Disbursement and repayment totals must be set first."
                }
              };
            }
            const repayments = await ensureAscaBorrowRepaymentsWith(
              tx,
              application
            );
            if (!repayments.length) {
              return {
                status: 400,
                body: { message: "No repayment schedule exists for this loan." }
              };
            }
            const toCents = (value) => Math.round(value * 100);
            const fromCents = (cents) => cents / 100;
            const outstandingCents = repayments.reduce((sum3, repayment) => {
              if (["PAID", "WAIVED"].includes(repayment.status)) return sum3;
              const installmentCents = toCents(parseMoneyAmount(repayment.amount));
              const paidCents = toCents(parseMoneyAmount(repayment.paidAmount));
              return sum3 + Math.max(0, installmentCents - paidCents);
            }, 0);
            if (outstandingCents <= 0) {
              return {
                status: 400,
                body: { message: "This loan has no outstanding balance." }
              };
            }
            const requestedCents = parsed.data.payAll ? outstandingCents : toCents(Number(parsed.data.amount ?? 0));
            if (requestedCents <= 0) {
              return {
                status: 400,
                body: { message: "Invalid payment amount." }
              };
            }
            if (requestedCents > outstandingCents) {
              return {
                status: 400,
                body: {
                  message: "Payment amount cannot exceed the outstanding balance."
                }
              };
            }
            const paymentAmount = fromCents(requestedCents);
            const userWallet = await ensureWalletWith3(
              tx,
              "USER",
              userId
            );
            const providedIdempotencyKey = parsed.data.idempotencyKey ?? (typeof headerIdempotencyKey === "string" ? headerIdempotencyKey : null);
            const idempotencyKey = providedIdempotencyKey ? `asca_loan_repayment:${applicationId}:${providedIdempotencyKey}` : `asca_loan_repayment:auto:${applicationId}:${userId}:${requestedCents}:${parsed.data.payAll ? 1 : 0}:${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}`;
            const [existingRepaymentTx] = await tx.select().from(walletTransactionsTable).where(eq(walletTransactionsTable.idempotencyKey, idempotencyKey));
            if (existingRepaymentTx) {
              const [latestApplication] = await tx.select({ status: loanApplicationsTable.status }).from(loanApplicationsTable).where(eq(loanApplicationsTable.id, applicationId));
              const walletBalance = await getWalletBalanceWith2(
                tx,
                userWallet.id
              );
              return {
                status: 200,
                body: {
                  appliedAmount: Number(existingRepaymentTx.amount),
                  walletBalance: Number(formatMoneyAmount(walletBalance)),
                  applicationStatus: latestApplication?.status ?? application.status,
                  walletTransactionId: existingRepaymentTx.id
                }
              };
            }
            const walletFunds = await getWalletFundsWith(
              tx,
              userWallet.id
            );
            if (walletFunds.availableBalance < paymentAmount) {
              return {
                status: 400,
                body: { message: "Insufficient available wallet balance." }
              };
            }
            await tx.execute(
              sql`select pg_advisory_xact_lock(${ORG_ASCA_BORROW_REPAYMENT_LOCK_KEY_A}, ${applicationId})`
            );
            const [walletTransaction] = await tx.insert(walletTransactionsTable).values({
              type: "LOAN_REPAYMENT",
              idempotencyKey,
              fromWalletId: userWallet.id,
              toWalletId: scoped.asca.escrowWalletId,
              amount: formatMoneyAmount(paymentAmount),
              metadata: {
                source: "ASCA_BORROW_REPAYMENT",
                ascaId,
                loanApplicationId: applicationId,
                borrowerId: userId
              }
            }).returning();
            const [paidTotals] = await tx.select({
              principalPaid: sum(loanRepaymentsTable.principalPaidAmount),
              returnPaid: sum(loanRepaymentsTable.returnPaidAmount),
              feePaid: sum(loanRepaymentsTable.feePaidAmount)
            }).from(loanRepaymentsTable).where(eq(loanRepaymentsTable.loanApplicationId, applicationId));
            let remainingPrincipalCents = Math.max(
              0,
              toCents(disbursedAmount) - toCents(parseMoneyAmount(paidTotals?.principalPaid))
            );
            let remainingReturnCents = Math.max(
              0,
              toCents(parseMoneyAmount(application.borrowerAppreciationAmount)) - toCents(parseMoneyAmount(paidTotals?.returnPaid))
            );
            let remainingFeeCents = Math.max(
              0,
              toCents(
                calculateProcessingFeeAmount(
                  disbursedAmount,
                  application.processingFeePct
                )
              ) - toCents(parseMoneyAmount(paidTotals?.feePaid))
            );
            const returnDueCents = toCents(
              parseMoneyAmount(application.borrowerAppreciationAmount)
            );
            const feeDueCents = toCents(
              calculateProcessingFeeAmount(
                disbursedAmount,
                application.processingFeePct
              )
            );
            const totalDueCents = toCents(disbursedAmount) + returnDueCents + feeDueCents;
            let remainingPaymentCents = requestedCents;
            const now = /* @__PURE__ */ new Date();
            for (const repayment of repayments) {
              if (remainingPaymentCents <= 0) break;
              if (["PAID", "WAIVED"].includes(repayment.status)) continue;
              const installmentCents = toCents(parseMoneyAmount(repayment.amount));
              const paidCents = toCents(parseMoneyAmount(repayment.paidAmount));
              const remainingInstallmentCents = Math.max(
                0,
                installmentCents - paidCents
              );
              if (remainingInstallmentCents <= 0) continue;
              const appliedCents = Math.min(
                remainingInstallmentCents,
                remainingPaymentCents
              );
              if (appliedCents <= 0) continue;
              const desiredReturnCents = totalDueCents > 0 ? Math.round(appliedCents * returnDueCents / totalDueCents) : 0;
              const desiredFeeCents = totalDueCents > 0 ? Math.round(appliedCents * feeDueCents / totalDueCents) : 0;
              let appliedReturnCents = Math.min(
                appliedCents,
                remainingReturnCents,
                Math.max(0, desiredReturnCents)
              );
              let appliedFeeCents = Math.min(
                appliedCents - appliedReturnCents,
                remainingFeeCents,
                Math.max(0, desiredFeeCents)
              );
              let appliedPrincipalCents = appliedCents - appliedReturnCents - appliedFeeCents;
              if (appliedPrincipalCents > remainingPrincipalCents) {
                const overflow = appliedPrincipalCents - remainingPrincipalCents;
                appliedPrincipalCents = remainingPrincipalCents;
                const remainingAfterPrincipal = appliedCents - appliedPrincipalCents - appliedFeeCents;
                appliedReturnCents = Math.min(
                  remainingAfterPrincipal + overflow,
                  remainingReturnCents
                );
                appliedFeeCents = Math.min(
                  appliedCents - appliedPrincipalCents - appliedReturnCents,
                  remainingFeeCents
                );
              } else if (appliedReturnCents > remainingReturnCents) {
                const overflow = appliedReturnCents - remainingReturnCents;
                appliedReturnCents = remainingReturnCents;
                appliedPrincipalCents = Math.min(
                  appliedCents - appliedReturnCents - appliedFeeCents,
                  remainingPrincipalCents,
                  appliedPrincipalCents + overflow
                );
                appliedFeeCents = Math.min(
                  appliedCents - appliedPrincipalCents - appliedReturnCents,
                  remainingFeeCents
                );
              } else if (appliedFeeCents > remainingFeeCents) {
                const overflow = appliedFeeCents - remainingFeeCents;
                appliedFeeCents = remainingFeeCents;
                appliedPrincipalCents = Math.min(
                  appliedCents - appliedReturnCents - appliedFeeCents,
                  remainingPrincipalCents,
                  appliedPrincipalCents + overflow
                );
                appliedReturnCents = Math.min(
                  appliedCents - appliedPrincipalCents - appliedFeeCents,
                  remainingReturnCents
                );
              }
              remainingPrincipalCents = Math.max(
                0,
                remainingPrincipalCents - appliedPrincipalCents
              );
              remainingReturnCents = Math.max(
                0,
                remainingReturnCents - appliedReturnCents
              );
              remainingFeeCents = Math.max(0, remainingFeeCents - appliedFeeCents);
              const nextPaidCents = paidCents + appliedCents;
              const isSettled = nextPaidCents >= installmentCents;
              const nextStatus = isSettled ? "PAID" : repayment.dueDate.getTime() < now.getTime() ? "LATE" : "PENDING";
              const nextPaidAmount = isSettled ? fromCents(installmentCents) : fromCents(nextPaidCents);
              const creditedToPoolAmount = parseMoneyAmount(repayment.creditedToPoolAmount) + fromCents(appliedCents);
              const principalPaidAmount = parseMoneyAmount(repayment.principalPaidAmount) + fromCents(appliedPrincipalCents);
              const returnPaidAmount = parseMoneyAmount(repayment.returnPaidAmount) + fromCents(appliedReturnCents);
              const feePaidAmount = parseMoneyAmount(repayment.feePaidAmount) + fromCents(appliedFeeCents);
              await tx.update(loanRepaymentsTable).set({
                paidAmount: formatMoneyAmount(nextPaidAmount),
                paidAt: isSettled ? now : null,
                status: nextStatus,
                method: "WALLET",
                creditedToPoolAmount: formatMoneyAmount(creditedToPoolAmount),
                principalPaidAmount: formatMoneyAmount(principalPaidAmount),
                returnPaidAmount: formatMoneyAmount(returnPaidAmount),
                feePaidAmount: formatMoneyAmount(feePaidAmount),
                updatedAt: now
              }).where(eq(loanRepaymentsTable.id, repayment.id));
              remainingPaymentCents -= appliedCents;
            }
            if (remainingPaymentCents !== 0) {
              return {
                status: 500,
                body: { message: "Failed to fully allocate this payment." }
              };
            }
            const outstandingAfter = await tx.select({ status: loanRepaymentsTable.status }).from(loanRepaymentsTable).where(eq(loanRepaymentsTable.loanApplicationId, applicationId));
            const hasOutstandingRepayments = outstandingAfter.some(
              (repayment) => !["PAID", "WAIVED"].includes(repayment.status)
            );
            const nextApplicationStatus = hasOutstandingRepayments ? application.status === "FUNDED" ? "REPAYING" : application.status : "CLOSED";
            if (nextApplicationStatus !== application.status) {
              await tx.update(loanApplicationsTable).set({
                status: nextApplicationStatus,
                updatedAt: now
              }).where(eq(loanApplicationsTable.id, applicationId));
            }
            const nextWalletBalance = walletFunds.balance - paymentAmount;
            return {
              status: 200,
              body: {
                appliedAmount: Number(formatMoneyAmount(paymentAmount)),
                walletBalance: Number(formatMoneyAmount(nextWalletBalance)),
                applicationStatus: nextApplicationStatus,
                walletTransactionId: walletTransaction?.id ?? null
              }
            };
          });
          if (result.status === 200) {
            await updateCreditScore(userId);
          }
          return res.status(result.status).json(result.body);
        } catch (err) {
          if (err instanceof Error) {
            return res.status(400).json({ message: err.message });
          }
          return handleError4(err, res);
        }
      }
    );
    router5.get("/org/investments/opportunities", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const context = await requireOrganizationInvestmentParticipantAccess(userId);
        const opportunities = await db.select().from(investmentOpportunitiesTable).where(
          eq(
            investmentOpportunitiesTable.organizationId,
            context.organization.id
          )
        ).orderBy(desc(investmentOpportunitiesTable.createdAt));
        return res.json({
          opportunities: opportunities.map(
            (o) => normalizeOrgInvestmentOpportunity(o, context.organization.name)
          ),
          total: opportunities.length
        });
      } catch (err) {
        if (err instanceof Error) {
          return res.status(400).json({ message: err.message });
        }
        return handleError4(err, res);
      }
    });
    router5.post("/org/investments/opportunities", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const context = await requireOrganizationInvestmentParticipantAccess(userId);
        assertOrganizationAscaManager(context);
        const schema = external_exports.object({
          title: external_exports.string().min(1),
          slug: external_exports.string().min(1),
          description: external_exports.string().min(1),
          termsHtml: external_exports.string().optional().nullable(),
          category: external_exports.enum([
            "REAL_ESTATE",
            "AGRICULTURE",
            "SMALL_BUSINESS",
            "COMMUNITY_DEVELOPMENT",
            "BONDS",
            "OTHER"
          ]),
          expectedReturnPct: external_exports.number().int().positive(),
          minInvestment: external_exports.string().min(1),
          targetAmount: external_exports.string().min(1),
          deadline: external_exports.string().refine((value) => !Number.isNaN(new Date(value).getTime()), {
            message: "Invalid deadline."
          }),
          riskLevel: external_exports.enum(["LOW", "MEDIUM", "HIGH"]).default("MEDIUM"),
          status: external_exports.enum(["DRAFT", "OPEN", "FUNDED", "CLOSED"]).default("DRAFT"),
          featured: external_exports.boolean().default(false),
          eligibleInvestorTiers: external_exports.array(external_exports.string()).default([]),
          videoUrl: external_exports.string().optional(),
          academyLink: external_exports.string().optional()
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success) {
          return res.status(400).json({ errors: parsed.error.flatten() });
        }
        const deadline = new Date(parsed.data.deadline);
        const normalizedTermsHtml = typeof parsed.data.termsHtml === "string" && parsed.data.termsHtml.trim().length > 0 ? parsed.data.termsHtml.trim() : null;
        const [opportunity] = await db.insert(investmentOpportunitiesTable).values({
          ...parsed.data,
          organizationId: context.organization.id,
          termsHtml: normalizedTermsHtml,
          deadline
        }).returning();
        return res.status(201).json({
          opportunity: normalizeOrgInvestmentOpportunity(
            opportunity,
            context.organization.name
          )
        });
      } catch (err) {
        if (err instanceof Error) {
          return res.status(400).json({ message: err.message });
        }
        return handleError4(err, res);
      }
    });
    router5.post("/org/investments/interests", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const context = await requireOrganizationAscaParticipantAccess(userId);
        const schema = external_exports.object({
          opportunityId: external_exports.coerce.number().int().positive(),
          amount: external_exports.coerce.number().positive(),
          notes: external_exports.string().max(2e3).optional(),
          acceptedTerms: external_exports.boolean().optional()
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success) {
          return res.status(400).json({ message: "Invalid request." });
        }
        const { opportunityId, amount } = parsed.data;
        const notes = parsed.data.notes?.trim() ? parsed.data.notes.trim() : null;
        const acceptedTerms = parsed.data.acceptedTerms;
        const [opp] = await db.select().from(investmentOpportunitiesTable).where(eq(investmentOpportunitiesTable.id, opportunityId));
        if (!opp || opp.organizationId !== context.organization.id) {
          return res.status(404).json({ message: "Opportunity not found." });
        }
        const termsRequired = Boolean(opp.termsHtml) && String(opp.termsHtml).trim().length > 0;
        if (termsRequired && acceptedTerms !== true) {
          return res.status(400).json({
            message: "You must accept the Investment Opportunity terms & conditions to proceed."
          });
        }
        const now = /* @__PURE__ */ new Date();
        const deadline = opp.deadline ? new Date(opp.deadline) : null;
        if (opp.status !== "OPEN" || deadline && deadline.getTime() <= now.getTime()) {
          return res.status(400).json({
            message: "This opportunity is no longer accepting interests."
          });
        }
        const minInvestment = Number(opp.minInvestment);
        if (amount < minInvestment) {
          return res.status(400).json({
            message: `Minimum investment is ${minInvestment}.`
          });
        }
        const result = await db.transaction(async (tx) => {
          const userWallet = await ensureWalletWith3(tx, "USER", userId);
          const [existing] = await tx.select().from(investmentInterestsTable).where(
            and(
              eq(investmentInterestsTable.userId, userId),
              eq(investmentInterestsTable.opportunityId, opportunityId)
            )
          );
          if (existing?.status === "CONFIRMED") {
            return {
              status: 400,
              body: {
                message: "Investment intent already approved for this opportunity."
              }
            };
          }
          const capacity = await getInvestmentOpportunityCapacityWith(tx, {
            opportunityId,
            excludePendingInterestId: existing?.id
          });
          if (!capacity) {
            return {
              status: 404,
              body: { message: "Opportunity not found." }
            };
          }
          if (Number.isFinite(capacity.targetAmount) && capacity.targetAmount > 0 && capacity.confirmedTotal + capacity.reservedPendingTotal + amount > capacity.targetAmount) {
            return {
              status: 400,
              body: {
                message: "This opportunity does not have enough remaining capacity for that amount."
              }
            };
          }
          const effectiveFunds = await getWalletFundsWith(
            tx,
            userWallet.id,
            existing?.id
          );
          if (effectiveFunds.availableBalance < amount) {
            return {
              status: 400,
              body: {
                message: `Insufficient available wallet balance. Available: ${effectiveFunds.availableBalance.toFixed(
                  2
                )}.`
              }
            };
          }
          const amountText = amount.toFixed(2);
          let interest = existing;
          if (!interest) {
            [interest] = await tx.insert(investmentInterestsTable).values({
              userId,
              opportunityId,
              amount: amountText,
              notes,
              status: "PENDING",
              confirmedAt: null,
              cancelledAt: null,
              updatedAt: now
            }).returning();
          } else {
            [interest] = await tx.update(investmentInterestsTable).set({
              amount: amountText,
              notes,
              status: "PENDING",
              confirmedAt: null,
              cancelledAt: null,
              updatedAt: now
            }).where(eq(investmentInterestsTable.id, interest.id)).returning();
          }
          const [existingReservation] = await tx.select().from(investmentIntentReservationsTable).where(eq(investmentIntentReservationsTable.interestId, interest.id));
          if (!existingReservation) {
            await tx.insert(investmentIntentReservationsTable).values({
              interestId: interest.id,
              walletId: userWallet.id,
              amount: amountText,
              status: "RESERVED",
              reservedAt: now,
              createdAt: now,
              updatedAt: now
            });
          } else {
            await tx.update(investmentIntentReservationsTable).set({
              walletId: userWallet.id,
              amount: amountText,
              status: "RESERVED",
              finalizedTransactionId: null,
              finalizedAt: null,
              releasedAt: null,
              updatedAt: now
            }).where(
              eq(investmentIntentReservationsTable.id, existingReservation.id)
            );
          }
          await tx.insert(investmentTransactionsTable).values({
            userId,
            opportunityId,
            amount: amountText,
            type: existing ? "INVESTMENT_INTENT_UPDATED" : "INVESTMENT_INTENT_SUBMITTED",
            description: existing ? "Investment intent updated and wallet funds re-reserved." : "Investment intent submitted and wallet funds reserved.",
            processedAt: now,
            createdAt: now
          });
          await notifyInAppWith(tx, {
            userId,
            category: "INVESTMENT",
            severity: "INFO",
            title: existing ? "Investment intent updated" : "Investment intent submitted",
            body: existing ? "Your investment intent has been updated." : "Your investment intent has been submitted for review.",
            actionLabel: "View Susunomics",
            actionHref: "/dashboard/investments"
          });
          const funds = await getWalletFundsWith(tx, userWallet.id);
          return {
            status: existing ? 200 : 201,
            body: {
              intent: {
                id: String(interest.id),
                status: interest.status,
                amount,
                reservedAmount: amount,
                walletBalance: funds.balance,
                reservedBalance: funds.reservedBalance,
                availableBalance: funds.availableBalance
              }
            }
          };
        });
        return res.status(result.status).json(result.body);
      } catch (err) {
        if (err instanceof Error) {
          return res.status(400).json({ message: err.message });
        }
        return handleError4(err, res);
      }
    });
    router5.patch(
      "/org/investments/opportunities/:id",
      requireAuth,
      async (req, res) => {
        const userId = req.userId;
        try {
          const context = await requireOrganizationInvestmentParticipantAccess(userId);
          assertOrganizationAscaManager(context);
          const id = Number(req.params.id);
          const schema = external_exports.object({
            title: external_exports.string().optional(),
            slug: external_exports.string().optional(),
            description: external_exports.string().optional(),
            termsHtml: external_exports.string().optional().nullable(),
            category: external_exports.enum([
              "REAL_ESTATE",
              "AGRICULTURE",
              "SMALL_BUSINESS",
              "COMMUNITY_DEVELOPMENT",
              "BONDS",
              "OTHER"
            ]).optional(),
            expectedReturnPct: external_exports.number().int().positive().optional(),
            minInvestment: external_exports.string().min(1).optional(),
            targetAmount: external_exports.string().min(1).optional(),
            deadline: external_exports.string().refine((value) => !Number.isNaN(new Date(value).getTime()), {
              message: "Invalid deadline."
            }).optional(),
            riskLevel: external_exports.enum(["LOW", "MEDIUM", "HIGH"]).optional(),
            status: external_exports.enum(["DRAFT", "OPEN", "FUNDED", "CLOSED"]).optional(),
            featured: external_exports.boolean().optional(),
            eligibleInvestorTiers: external_exports.array(external_exports.string()).optional(),
            videoUrl: external_exports.string().optional().nullable(),
            academyLink: external_exports.string().optional().nullable()
          });
          const parsed = schema.safeParse(req.body);
          if (!parsed.success) {
            return res.status(400).json({ errors: parsed.error.flatten() });
          }
          const updates = { ...parsed.data };
          if (parsed.data.deadline) {
            updates.deadline = new Date(parsed.data.deadline);
          }
          if (parsed.data.termsHtml !== void 0) {
            updates.termsHtml = typeof parsed.data.termsHtml === "string" && parsed.data.termsHtml.trim().length > 0 ? parsed.data.termsHtml.trim() : null;
          }
          if (Object.keys(updates).length > 0) {
            updates.updatedAt = /* @__PURE__ */ new Date();
            await db.update(investmentOpportunitiesTable).set(updates).where(
              and(
                eq(investmentOpportunitiesTable.id, id),
                eq(
                  investmentOpportunitiesTable.organizationId,
                  context.organization.id
                )
              )
            );
          }
          const [opportunity] = await db.select().from(investmentOpportunitiesTable).where(
            and(
              eq(investmentOpportunitiesTable.id, id),
              eq(
                investmentOpportunitiesTable.organizationId,
                context.organization.id
              )
            )
          ).limit(1);
          if (!opportunity) {
            return res.status(404).json({ message: "Opportunity not found." });
          }
          return res.json({
            opportunity: normalizeOrgInvestmentOpportunity(
              opportunity,
              context.organization.name
            )
          });
        } catch (err) {
          if (err instanceof Error) {
            return res.status(400).json({ message: err.message });
          }
          return handleError4(err, res);
        }
      }
    );
    router5.post("/org/investments/interests", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const context = await requireOrganizationInvestmentParticipantAccess(userId);
        const schema = external_exports.object({
          opportunityId: external_exports.coerce.number().int().positive(),
          amount: external_exports.coerce.number().positive(),
          notes: external_exports.string().max(2e3).optional(),
          acceptedTerms: external_exports.boolean().optional()
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success) {
          return res.status(400).json({ message: "Invalid request." });
        }
        const { opportunityId, amount } = parsed.data;
        const notes = parsed.data.notes?.trim() ? parsed.data.notes.trim() : null;
        const acceptedTerms = parsed.data.acceptedTerms;
        const [opp] = await db.select().from(investmentOpportunitiesTable).where(eq(investmentOpportunitiesTable.id, opportunityId));
        if (!opp || opp.organizationId !== context.organization.id) {
          return res.status(404).json({ message: "Opportunity not found." });
        }
        const termsRequired = Boolean(opp.termsHtml) && String(opp.termsHtml).trim().length > 0;
        if (termsRequired && acceptedTerms !== true) {
          return res.status(400).json({
            message: "You must accept the Investment Opportunity terms & conditions to proceed."
          });
        }
        const now = /* @__PURE__ */ new Date();
        const deadline = opp.deadline ? new Date(opp.deadline) : null;
        if (opp.status !== "OPEN" || deadline && deadline.getTime() <= now.getTime()) {
          return res.status(400).json({
            message: "This opportunity is no longer accepting interests."
          });
        }
        const minInvestment = Number(opp.minInvestment);
        if (amount < minInvestment) {
          return res.status(400).json({
            message: `Minimum investment is ${minInvestment}.`
          });
        }
        const result = await db.transaction(async (tx) => {
          const userWallet = await ensureWalletWith3(tx, "USER", userId);
          const [existing] = await tx.select().from(investmentInterestsTable).where(
            and(
              eq(investmentInterestsTable.userId, userId),
              eq(investmentInterestsTable.opportunityId, opportunityId)
            )
          );
          if (existing?.status === "CONFIRMED") {
            return {
              status: 400,
              body: {
                message: "Investment intent already approved for this opportunity."
              }
            };
          }
          const capacity = await getInvestmentOpportunityCapacityWith(tx, {
            opportunityId,
            excludePendingInterestId: existing?.id
          });
          if (!capacity) {
            return {
              status: 404,
              body: { message: "Opportunity not found." }
            };
          }
          if (Number.isFinite(capacity.targetAmount) && capacity.targetAmount > 0 && capacity.confirmedTotal + capacity.reservedPendingTotal + amount > capacity.targetAmount) {
            return {
              status: 400,
              body: {
                message: "This opportunity does not have enough remaining capacity for that amount."
              }
            };
          }
          const effectiveFunds = await getWalletFundsWith(
            tx,
            userWallet.id,
            existing?.id
          );
          if (effectiveFunds.availableBalance < amount) {
            return {
              status: 400,
              body: {
                message: `Insufficient available wallet balance. Available: ${effectiveFunds.availableBalance.toFixed(
                  2
                )}.`
              }
            };
          }
          const now2 = /* @__PURE__ */ new Date();
          const amountText = amount.toFixed(2);
          let interest = existing;
          if (!interest) {
            [interest] = await tx.insert(investmentInterestsTable).values({
              userId,
              opportunityId,
              amount: amountText,
              notes,
              status: "PENDING",
              confirmedAt: null,
              cancelledAt: null,
              updatedAt: now2
            }).returning();
          } else {
            [interest] = await tx.update(investmentInterestsTable).set({
              amount: amountText,
              notes,
              status: "PENDING",
              confirmedAt: null,
              cancelledAt: null,
              updatedAt: now2
            }).where(eq(investmentInterestsTable.id, interest.id)).returning();
          }
          const [existingReservation] = await tx.select().from(investmentIntentReservationsTable).where(eq(investmentIntentReservationsTable.interestId, interest.id));
          if (!existingReservation) {
            await tx.insert(investmentIntentReservationsTable).values({
              interestId: interest.id,
              walletId: userWallet.id,
              amount: amountText,
              status: "RESERVED",
              reservedAt: now2,
              createdAt: now2,
              updatedAt: now2
            });
          } else {
            await tx.update(investmentIntentReservationsTable).set({
              walletId: userWallet.id,
              amount: amountText,
              status: "RESERVED",
              finalizedTransactionId: null,
              finalizedAt: null,
              releasedAt: null,
              updatedAt: now2
            }).where(
              eq(investmentIntentReservationsTable.id, existingReservation.id)
            );
          }
          await tx.insert(investmentTransactionsTable).values({
            userId,
            opportunityId,
            amount: amountText,
            type: existing ? "INVESTMENT_INTENT_UPDATED" : "INVESTMENT_INTENT_SUBMITTED",
            description: existing ? "Investment intent updated and wallet funds re-reserved." : "Investment intent submitted and wallet funds reserved.",
            processedAt: now2,
            createdAt: now2
          });
          await notifyInAppWith(tx, {
            userId,
            category: "INVESTMENT",
            severity: "INFO",
            title: existing ? "Investment intent updated" : "Investment intent submitted",
            body: existing ? "Your investment intent has been updated." : "Your investment intent has been submitted for review.",
            actionLabel: "View Susunomics",
            actionHref: "/dashboard/investments"
          });
          const funds = await getWalletFundsWith(tx, userWallet.id);
          return {
            status: existing ? 200 : 201,
            body: {
              intent: {
                id: String(interest.id),
                status: interest.status,
                amount,
                reservedAmount: amount,
                walletBalance: funds.balance,
                reservedBalance: funds.reservedBalance,
                availableBalance: funds.availableBalance
              }
            }
          };
        });
        return res.status(result.status).json(result.body);
      } catch (err) {
        if (err instanceof Error) {
          return res.status(400).json({ message: err.message });
        }
        return handleError4(err, res);
      }
    });
    router5.get("/org/investments/intents", requireAuth, async (req, res) => {
      try {
        const authenticatedReq = req;
        const context = await requireOrganizationAuthorization(
          authenticatedReq.userId
        );
        const intents = await db.select({
          id: investmentInterestsTable.id,
          userId: investmentInterestsTable.userId,
          opportunityId: investmentInterestsTable.opportunityId,
          amount: investmentInterestsTable.amount,
          notes: investmentInterestsTable.notes,
          status: investmentInterestsTable.status,
          confirmedAt: investmentInterestsTable.confirmedAt,
          cancelledAt: investmentInterestsTable.cancelledAt,
          createdAt: investmentInterestsTable.createdAt,
          updatedAt: investmentInterestsTable.updatedAt,
          reservationStatus: investmentIntentReservationsTable.status,
          reservedAmount: investmentIntentReservationsTable.amount,
          finalizedAt: investmentIntentReservationsTable.finalizedAt,
          releasedAt: investmentIntentReservationsTable.releasedAt,
          opportunityTitle: investmentOpportunitiesTable.title,
          userEmail: usersTable.email,
          userFirstName: usersTable.firstName,
          userLastName: usersTable.lastName
        }).from(investmentInterestsTable).leftJoin(
          investmentIntentReservationsTable,
          eq(
            investmentIntentReservationsTable.interestId,
            investmentInterestsTable.id
          )
        ).leftJoin(
          investmentOpportunitiesTable,
          eq(
            investmentInterestsTable.opportunityId,
            investmentOpportunitiesTable.id
          )
        ).leftJoin(usersTable, eq(investmentInterestsTable.userId, usersTable.id)).where(
          eq(
            investmentOpportunitiesTable.organizationId,
            context.organization.id
          )
        ).orderBy(desc(investmentInterestsTable.createdAt));
        const ascaIntents = await db.select({
          ascaId: ascasTable.id,
          ascaName: ascasTable.name,
          opportunityId: investmentOpportunitiesTable.id,
          amount: ascasTable.currentAmount,
          confirmedAt: walletTransactionsTable.createdAt,
          createdAt: ascasTable.createdAt,
          updatedAt: ascasTable.updatedAt,
          opportunityTitle: investmentOpportunitiesTable.title
        }).from(ascasTable).innerJoin(
          investmentOpportunitiesTable,
          eq(ascasTable.investmentId, investmentOpportunitiesTable.id)
        ).leftJoin(
          walletTransactionsTable,
          and(
            eq(walletTransactionsTable.fromWalletId, ascasTable.escrowWalletId),
            eq(walletTransactionsTable.type, "ASCA_INVESTMENT")
          )
        ).where(
          and(
            eq(ascasTable.type, "INVESTMENT"),
            eq(ascasTable.status, "INVESTED"),
            eq(
              investmentOpportunitiesTable.organizationId,
              context.organization.id
            )
          )
        ).orderBy(
          desc(walletTransactionsTable.createdAt),
          desc(ascasTable.createdAt)
        );
        return res.json({
          intents: [
            ...intents,
            ...ascaIntents.map((asca) => {
              const confirmedAt = asca.confirmedAt ?? asca.updatedAt;
              return {
                id: -asca.ascaId,
                userId: 0,
                opportunityId: asca.opportunityId,
                amount: asca.amount,
                notes: `ASCA ${asca.ascaName} invested into this Susunomics opportunity.`,
                status: "CONFIRMED",
                confirmedAt,
                cancelledAt: null,
                createdAt: asca.createdAt,
                updatedAt: asca.updatedAt,
                reservationStatus: null,
                reservedAmount: null,
                finalizedAt: confirmedAt,
                releasedAt: null,
                opportunityTitle: asca.opportunityTitle,
                userEmail: null,
                userFirstName: "ASCA",
                userLastName: asca.ascaName
              };
            })
          ].sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())
        });
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.post(
      "/org/investments/intents/:id/approve",
      requireAuth,
      async (req, res) => {
        try {
          const authenticatedReq = req;
          const context = await requireOrganizationAuthorization(
            authenticatedReq.userId
          );
          const intentId = parseInt(req.params.id, 10);
          if (isNaN(intentId)) {
            return res.status(400).json({ message: "Invalid intent ID" });
          }
          const result = await db.transaction(async (tx) => {
            const [interest] = await tx.select().from(investmentInterestsTable).where(eq(investmentInterestsTable.id, intentId));
            if (!interest) return null;
            const [opp] = await tx.select().from(investmentOpportunitiesTable).where(eq(investmentOpportunitiesTable.id, interest.opportunityId));
            if (!opp || opp.organizationId !== context.organization.id) {
              throw new Error(
                "Opportunity not found or not owned by your organization."
              );
            }
            if (interest.status === "CONFIRMED") {
              return { interest };
            }
            if (interest.status === "CANCELLED") {
              throw new Error("This investment intent has already been cancelled.");
            }
            const [reservation] = await tx.select().from(investmentIntentReservationsTable).where(eq(investmentIntentReservationsTable.interestId, interest.id));
            const now = /* @__PURE__ */ new Date();
            if (!reservation || reservation.status !== "RESERVED") {
              throw new Error(
                "This investment intent no longer has an active wallet reservation."
              );
            }
            const [confirmedAgg] = await tx.select({ total: sum(investmentInterestsTable.amount) }).from(investmentInterestsTable).where(
              and(
                eq(
                  investmentInterestsTable.opportunityId,
                  interest.opportunityId
                ),
                eq(investmentInterestsTable.status, "CONFIRMED")
              )
            );
            const confirmedTotal = Number(confirmedAgg?.total ?? 0);
            const targetAmount = Number(opp.targetAmount ?? 0);
            const amountToConfirm = Number(reservation.amount ?? 0);
            if (Number.isFinite(targetAmount) && targetAmount > 0 && confirmedTotal + amountToConfirm > targetAmount) {
              throw new Error(
                "This opportunity does not have enough remaining capacity to approve this intent."
              );
            }
            const [confirmed] = await tx.update(investmentInterestsTable).set({
              status: "CONFIRMED",
              confirmedAt: now,
              cancelledAt: null,
              updatedAt: now
            }).where(
              and(
                eq(investmentInterestsTable.id, interest.id),
                eq(investmentInterestsTable.status, "PENDING")
              )
            ).returning();
            if (!confirmed) {
              throw new Error("This investment intent can no longer be approved.");
            }
            const userWallet = await ensureWalletWith3(
              tx,
              "USER",
              interest.userId
            );
            const orgWallet = await ensureOrganizationFinanceWalletWith(
              tx,
              context
            );
            const idempotencyKey = `org_investment_purchase:interest:${interest.id}`;
            const [existingWalletTransaction] = await tx.select().from(walletTransactionsTable).where(eq(walletTransactionsTable.idempotencyKey, idempotencyKey));
            let walletTransaction = existingWalletTransaction ?? null;
            if (!walletTransaction) {
              const authenticatedReq2 = req;
              const [created] = await tx.insert(walletTransactionsTable).values({
                type: "INVESTMENT_PURCHASE",
                idempotencyKey,
                fromWalletId: userWallet.id,
                toWalletId: orgWallet.id,
                amount: reservation.amount,
                metadata: {
                  investmentInterestId: interest.id,
                  opportunityId: interest.opportunityId,
                  investorId: interest.userId,
                  approvedByOrgAdminId: authenticatedReq2.userId
                }
              }).returning();
              walletTransaction = created;
            }
            const [existingActivity] = await tx.select({ id: investmentTransactionsTable.id }).from(investmentTransactionsTable).where(
              and(
                eq(investmentTransactionsTable.userId, interest.userId),
                eq(
                  investmentTransactionsTable.opportunityId,
                  interest.opportunityId
                ),
                eq(investmentTransactionsTable.type, "INVESTMENT_PURCHASE"),
                eq(investmentTransactionsTable.amount, reservation.amount)
              )
            );
            if (!existingActivity) {
              await tx.insert(investmentTransactionsTable).values({
                userId: interest.userId,
                opportunityId: interest.opportunityId,
                amount: reservation.amount,
                type: "INVESTMENT_PURCHASE",
                description: "Investment intent approved and funded from wallet.",
                processedAt: now,
                createdAt: now
              });
            }
            await tx.update(investmentIntentReservationsTable).set({
              status: "FINALIZED",
              finalizedTransactionId: walletTransaction.id,
              finalizedAt: now,
              releasedAt: null,
              updatedAt: now
            }).where(
              and(
                eq(investmentIntentReservationsTable.id, reservation.id),
                eq(investmentIntentReservationsTable.status, "RESERVED")
              )
            );
            await recalculateInvestmentRaisedAmount(tx, interest.opportunityId);
            await notifyInAppWith(tx, {
              userId: interest.userId,
              category: "INVESTMENT",
              severity: "SUCCESS",
              title: "Investment approved",
              body: `Your investment intent for ${opp.title} has been approved by ${context.organization.name}.`,
              actionLabel: "View Susunomics",
              actionHref: "/dashboard/investments"
            });
            return { interest: confirmed };
          });
          if (!result) {
            return res.status(404).json({ message: "Investment intent not found." });
          }
          return res.json({ intent: result.interest });
        } catch (err) {
          if (err instanceof Error) {
            return res.status(400).json({ message: err.message });
          }
          return handleError4(err, res);
        }
      }
    );
    router5.post(
      "/org/investments/intents/:id/cancel",
      requireAuth,
      async (req, res) => {
        try {
          const authenticatedReq = req;
          const context = await requireOrganizationAuthorization(
            authenticatedReq.userId
          );
          const intentId = parseInt(req.params.id, 10);
          if (isNaN(intentId)) {
            return res.status(400).json({ message: "Invalid intent ID" });
          }
          const result = await db.transaction(async (tx) => {
            const [interest] = await tx.select().from(investmentInterestsTable).where(eq(investmentInterestsTable.id, intentId));
            if (!interest) return null;
            const [opp] = await tx.select().from(investmentOpportunitiesTable).where(eq(investmentOpportunitiesTable.id, interest.opportunityId));
            if (!opp || opp.organizationId !== context.organization.id) {
              throw new Error(
                "Opportunity not found or not owned by your organization."
              );
            }
            if (interest.status === "CANCELLED") {
              return { interest };
            }
            if (interest.status === "CONFIRMED") {
              throw new Error(
                "This investment intent has already been approved and cannot be cancelled."
              );
            }
            const now = /* @__PURE__ */ new Date();
            const [cancelled] = await tx.update(investmentInterestsTable).set({
              status: "CANCELLED",
              cancelledAt: now,
              updatedAt: now
            }).where(
              and(
                eq(investmentInterestsTable.id, interest.id),
                eq(investmentInterestsTable.status, "PENDING")
              )
            ).returning();
            if (!cancelled) {
              throw new Error("This investment intent can no longer be cancelled.");
            }
            const [reservation] = await tx.select().from(investmentIntentReservationsTable).where(
              and(
                eq(investmentIntentReservationsTable.interestId, interest.id),
                eq(investmentIntentReservationsTable.status, "RESERVED")
              )
            );
            if (reservation) {
              await tx.update(investmentIntentReservationsTable).set({
                status: "RELEASED",
                releasedAt: now,
                updatedAt: now
              }).where(eq(investmentIntentReservationsTable.id, reservation.id));
            }
            await notifyInAppWith(tx, {
              userId: interest.userId,
              category: "INVESTMENT",
              severity: "WARNING",
              title: "Investment declined",
              body: `Your investment intent for ${opp.title} was declined by ${context.organization.name}. Your reserved funds have been released back to your wallet.`,
              actionLabel: "View Susunomics",
              actionHref: "/dashboard/investments"
            });
            return { interest: cancelled };
          });
          if (!result) {
            return res.status(404).json({ message: "Investment intent not found." });
          }
          return res.json({ intent: result.interest });
        } catch (err) {
          if (err instanceof Error) {
            return res.status(400).json({ message: err.message });
          }
          return handleError4(err, res);
        }
      }
    );
    router5.get(
      "/org/asca/groups/:id/lending-pool-config",
      requireAuth,
      async (req, res) => {
        const userId = req.userId;
        try {
          const context = await requireOrganizationLendingParticipantAccess(userId);
          assertOrganizationProductAccess(context, "ASCA_LENDING_POOL");
          const ascaId = Number(req.params.id);
          if (!Number.isFinite(ascaId) || ascaId <= 0) {
            return res.status(400).json({ message: "Invalid ASCA ID." });
          }
          const [asca] = await db.select().from(ascasTable).where(eq(ascasTable.id, ascaId));
          if (!asca || asca.organizationId !== context.organization.id) {
            return res.status(404).json({ message: "ASCA not found." });
          }
          if (asca.type !== "GENERAL") {
            return res.status(400).json({
              message: "Lending pool config only available for GENERAL ASCAs."
            });
          }
          const lendingPoolConfig = getAscaLendingPoolConstitution(asca.constitution);
          let walletAvailableBalance = 0;
          if (asca.escrowWalletId) {
            walletAvailableBalance = await getWalletAvailableBalanceWith(
              db,
              asca.escrowWalletId
            );
          }
          return res.json({
            ascaId: asca.id,
            ascaName: asca.name,
            ascaType: asca.type,
            currentAmount: Number(asca.currentAmount ?? 0),
            escrowWalletId: asca.escrowWalletId ?? null,
            walletAvailableBalance,
            lendingPool: lendingPoolConfig
          });
        } catch (err) {
          if (err instanceof Error) {
            return res.status(400).json({ message: err.message });
          }
          return handleError4(err, res);
        }
      }
    );
    router5.patch(
      "/org/asca/groups/:id/lending-pool-config",
      requireAuth,
      async (req, res) => {
        const userId = req.userId;
        try {
          const context = await requireOrganizationLendingParticipantAccess(userId);
          assertOrganizationProductAccess(context, "ASCA_LENDING_POOL");
          assertOrganizationAscaManager(context);
          const ascaId = Number(req.params.id);
          if (!Number.isFinite(ascaId) || ascaId <= 0) {
            return res.status(400).json({ message: "Invalid ASCA ID." });
          }
          const schema = external_exports.object({
            lendingPool: AscaLendingPoolSchema
          });
          const parsed = schema.safeParse(req.body);
          if (!parsed.success) {
            return res.status(400).json({ message: "Invalid request payload.", errors: parsed.error.flatten() });
          }
          const [asca] = await db.select().from(ascasTable).where(eq(ascasTable.id, ascaId));
          if (!asca || asca.organizationId !== context.organization.id) {
            return res.status(404).json({ message: "ASCA not found." });
          }
          if (asca.type !== "GENERAL") {
            return res.status(400).json({
              message: "Lending pool config only allowed for GENERAL ASCAs."
            });
          }
          const existingConstitution = asca.constitution ?? {};
          const existingLendingPool = existingConstitution.lendingPool ?? {};
          const incomingLendingPool = parsed.data.lendingPool ?? {};
          const borrowingPolicy = getAscaBorrowingPolicy(existingConstitution);
          const mergedLendingPool = {
            ...existingLendingPool,
            ...incomingLendingPool
          };
          if (borrowingPolicy?.liquidityReservePct !== void 0 && mergedLendingPool.maxPctOfPoolAfterReserve !== void 0 && typeof borrowingPolicy.liquidityReservePct === "number" && typeof mergedLendingPool.maxPctOfPoolAfterReserve === "number") {
            if (mergedLendingPool.maxPctOfPoolAfterReserve > 100 - borrowingPolicy.liquidityReservePct) {
              return res.status(400).json({
                message: `maxPctOfPoolAfterReserve (${mergedLendingPool.maxPctOfPoolAfterReserve}%) must be <= 100 - liquidityReservePct (${100 - borrowingPolicy.liquidityReservePct}%).`
              });
            }
          }
          const mergedConstitution = {
            ...existingConstitution,
            lendingPool: mergedLendingPool
          };
          const updatedRows = await db.update(ascasTable).set({
            constitution: mergedConstitution,
            updatedAt: /* @__PURE__ */ new Date()
          }).where(eq(ascasTable.id, ascaId)).returning();
          const normalized = getAscaLendingPoolConstitution(updatedRows[0]?.constitution);
          return res.json({ ascaId: updatedRows[0]?.id, lendingPool: normalized });
        } catch (err) {
          if (err instanceof Error) {
            return res.status(400).json({ message: err.message });
          }
          return handleError4(err, res);
        }
      }
    );
    organizationLendingPoolUpsertSchema = external_exports.object({
      name: external_exports.string().trim().min(1).max(160),
      description: external_exports.string().trim().max(2e3).optional().nullable(),
      eligibilityMode: external_exports.enum(["CONTRIBUTORS_ONLY", "ALL_ORG_MEMBERS"]),
      status: external_exports.enum(["DRAFT", "OPEN", "CLOSED"]).optional(),
      templateId: external_exports.coerce.number().int().positive().optional().nullable(),
      minRequestAmount: external_exports.coerce.number().min(0),
      maxRequestAmount: external_exports.coerce.number().min(0),
      defaultTermMonths: external_exports.coerce.number().int().min(1).max(36),
      defaultRepaymentFrequency: external_exports.enum(["WEEKLY", "BIWEEKLY", "MONTHLY"]),
      defaultBorrowerAppreciationPct: external_exports.coerce.number().min(0).max(100),
      defaultProcessingFeePct: external_exports.coerce.number().min(0).max(25),
      notes: external_exports.string().trim().max(2e3).optional().nullable()
    });
    router5.get("/org/lending/pools", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const context = await requireOrganizationLendingParticipantAccess(userId);
        assertOrganizationProductAccess(context, "ASCA_LENDING_POOL");
        assertOrganizationLendingPoolManager(context);
        const rows = await db.select().from(orgLendingPoolsTable).where(
          eq(orgLendingPoolsTable.organizationId, context.organization.id)
        ).orderBy(desc(orgLendingPoolsTable.createdAt));
        return res.json({
          pools: rows.map((row) => ({
            id: row.id,
            name: row.name,
            description: row.description,
            eligibilityMode: row.eligibilityMode,
            status: row.status,
            templateId: row.templateId,
            minRequestAmount: Number(row.minRequestAmount ?? 0),
            maxRequestAmount: Number(row.maxRequestAmount ?? 0),
            defaultTermMonths: Number(row.defaultTermMonths ?? 0),
            defaultRepaymentFrequency: row.defaultRepaymentFrequency,
            defaultBorrowerAppreciationPct: Number(
              row.defaultBorrowerAppreciationPct ?? 0
            ),
            defaultProcessingFeePct: Number(row.defaultProcessingFeePct ?? 0),
            createdAt: row.createdAt.toISOString(),
            updatedAt: row.updatedAt.toISOString()
          }))
        });
      } catch (err) {
        if (err instanceof Error) {
          return res.status(400).json({ message: err.message });
        }
        return handleError4(err, res);
      }
    });
    router5.get("/org/lending/pools/:id", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const context = await requireOrganizationLendingParticipantAccess(userId);
        assertOrganizationProductAccess(context, "ASCA_LENDING_POOL");
        assertOrganizationLendingPoolManager(context);
        const poolId = Number(req.params.id);
        if (!Number.isFinite(poolId) || poolId <= 0) {
          return res.status(400).json({ message: "Invalid pool ID." });
        }
        const [pool2] = await db.select().from(orgLendingPoolsTable).where(
          and(
            eq(orgLendingPoolsTable.id, poolId),
            eq(orgLendingPoolsTable.organizationId, context.organization.id)
          )
        ).limit(1);
        if (!pool2) {
          return res.status(404).json({ message: "Lending pool not found." });
        }
        return res.json({
          pool: {
            id: pool2.id,
            name: pool2.name,
            description: pool2.description,
            eligibilityMode: pool2.eligibilityMode,
            status: pool2.status,
            templateId: pool2.templateId,
            minRequestAmount: Number(pool2.minRequestAmount ?? 0),
            maxRequestAmount: Number(pool2.maxRequestAmount ?? 0),
            defaultTermMonths: Number(pool2.defaultTermMonths ?? 0),
            defaultRepaymentFrequency: pool2.defaultRepaymentFrequency,
            defaultBorrowerAppreciationPct: Number(
              pool2.defaultBorrowerAppreciationPct ?? 0
            ),
            defaultProcessingFeePct: Number(pool2.defaultProcessingFeePct ?? 0),
            createdAt: pool2.createdAt.toISOString(),
            updatedAt: pool2.updatedAt.toISOString()
          }
        });
      } catch (err) {
        if (err instanceof Error) {
          return res.status(400).json({ message: err.message });
        }
        return handleError4(err, res);
      }
    });
    router5.post("/org/lending/pools", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const context = await requireOrganizationLendingParticipantAccess(userId);
        assertOrganizationProductAccess(context, "ASCA_LENDING_POOL");
        assertOrganizationLendingPoolManager(context);
        const parsed = organizationLendingPoolUpsertSchema.safeParse(req.body);
        if (!parsed.success) {
          return res.status(400).json({
            message: "Invalid request payload.",
            errors: parsed.error.flatten()
          });
        }
        if (parsed.data.templateId) {
          const templateRows = await db.select().from(lendingTemplatesTable).where(eq(lendingTemplatesTable.id, parsed.data.templateId));
          const template = templateRows[0];
          if (template) {
          }
        }
        const poolRows = await db.insert(orgLendingPoolsTable).values({
          organizationId: context.organization.id,
          name: parsed.data.name,
          description: parsed.data.description,
          eligibilityMode: parsed.data.eligibilityMode,
          status: parsed.data.status ?? "DRAFT",
          templateId: parsed.data.templateId ?? null,
          minRequestAmount: parsed.data.minRequestAmount.toFixed(2),
          maxRequestAmount: parsed.data.maxRequestAmount.toFixed(2),
          defaultTermMonths: parsed.data.defaultTermMonths,
          defaultRepaymentFrequency: parsed.data.defaultRepaymentFrequency,
          defaultBorrowerAppreciationPct: parsed.data.defaultBorrowerAppreciationPct.toFixed(2),
          defaultProcessingFeePct: parsed.data.defaultProcessingFeePct.toFixed(2)
        }).returning();
        return res.status(201).json({ poolId: poolRows[0]?.id });
      } catch (err) {
        if (err instanceof Error) {
          return res.status(400).json({ message: err.message });
        }
        return handleError4(err, res);
      }
    });
    router5.patch("/org/lending/pools/:id", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const context = await requireOrganizationLendingParticipantAccess(userId);
        assertOrganizationProductAccess(context, "ASCA_LENDING_POOL");
        assertOrganizationLendingPoolManager(context);
        const poolId = Number(req.params.id);
        if (!Number.isFinite(poolId) || poolId <= 0) {
          return res.status(400).json({ message: "Invalid pool ID." });
        }
        const parsed = organizationLendingPoolUpsertSchema.partial().safeParse(req.body);
        if (!parsed.success) {
          return res.status(400).json({
            message: "Invalid request payload.",
            errors: parsed.error.flatten()
          });
        }
        const [existing] = await db.select().from(orgLendingPoolsTable).where(
          and(
            eq(orgLendingPoolsTable.id, poolId),
            eq(orgLendingPoolsTable.organizationId, context.organization.id)
          )
        );
        if (!existing) {
          return res.status(404).json({ message: "Lending pool not found." });
        }
        if (parsed.data.templateId) {
          const templateRows = await db.select().from(lendingTemplatesTable).where(eq(lendingTemplatesTable.id, parsed.data.templateId));
          const template = templateRows[0];
          if (template) {
          }
        }
        const updateValues = {
          updatedAt: /* @__PURE__ */ new Date()
        };
        if (parsed.data.name !== void 0) updateValues.name = parsed.data.name;
        if (parsed.data.description !== void 0) updateValues.description = parsed.data.description;
        if (parsed.data.eligibilityMode !== void 0) updateValues.eligibilityMode = parsed.data.eligibilityMode;
        if (parsed.data.status !== void 0) updateValues.status = parsed.data.status;
        if (parsed.data.templateId !== void 0) updateValues.templateId = parsed.data.templateId ?? null;
        if (parsed.data.minRequestAmount !== void 0) updateValues.minRequestAmount = parsed.data.minRequestAmount.toFixed(2);
        if (parsed.data.maxRequestAmount !== void 0) updateValues.maxRequestAmount = parsed.data.maxRequestAmount.toFixed(2);
        if (parsed.data.defaultTermMonths !== void 0) updateValues.defaultTermMonths = parsed.data.defaultTermMonths;
        if (parsed.data.defaultRepaymentFrequency !== void 0) updateValues.defaultRepaymentFrequency = parsed.data.defaultRepaymentFrequency;
        if (parsed.data.defaultBorrowerAppreciationPct !== void 0) updateValues.defaultBorrowerAppreciationPct = parsed.data.defaultBorrowerAppreciationPct.toFixed(2);
        if (parsed.data.defaultProcessingFeePct !== void 0) updateValues.defaultProcessingFeePct = parsed.data.defaultProcessingFeePct.toFixed(2);
        if (parsed.data.notes !== void 0) updateValues.notes = parsed.data.notes;
        const updatedRows = await db.update(orgLendingPoolsTable).set(updateValues).where(eq(orgLendingPoolsTable.id, poolId)).returning();
        return res.json({ poolId: updatedRows[0]?.id });
      } catch (err) {
        if (err instanceof Error) {
          return res.status(400).json({ message: err.message });
        }
        return handleError4(err, res);
      }
    });
    router5.delete("/org/lending/pools/:id", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const context = await requireOrganizationLendingParticipantAccess(userId);
        assertOrganizationProductAccess(context, "ASCA_LENDING_POOL");
        assertOrganizationLendingPoolManager(context);
        const poolId = Number(req.params.id);
        if (!Number.isFinite(poolId) || poolId <= 0) {
          return res.status(400).json({ message: "Invalid pool ID." });
        }
        const [existing] = await db.select().from(orgLendingPoolsTable).where(
          and(
            eq(orgLendingPoolsTable.id, poolId),
            eq(orgLendingPoolsTable.organizationId, context.organization.id)
          )
        );
        if (!existing) {
          return res.status(404).json({ message: "Lending pool not found." });
        }
        await db.delete(orgLendingPoolsTable).where(eq(orgLendingPoolsTable.id, poolId));
        return res.json({ ok: true });
      } catch (err) {
        if (err instanceof Error) {
          return res.status(400).json({ message: err.message });
        }
        return handleError4(err, res);
      }
    });
    router5.get(
      "/org/lending/pools/:id/summary",
      requireAuth,
      async (req, res) => {
        const userId = req.userId;
        try {
          const context = await requireOrganizationLendingParticipantAccess(userId);
          assertOrganizationProductAccess(context, "ASCA_LENDING_POOL");
          assertOrganizationLendingPoolManager(context);
          const poolId = Number(req.params.id);
          if (!Number.isFinite(poolId) || poolId <= 0) {
            return res.status(400).json({ message: "Invalid pool ID." });
          }
          const [pool2] = await db.select().from(orgLendingPoolsTable).where(
            and(
              eq(orgLendingPoolsTable.id, poolId),
              eq(orgLendingPoolsTable.organizationId, context.organization.id)
            )
          );
          if (!pool2) {
            return res.status(404).json({ message: "Lending pool not found." });
          }
          const poolEligibilityMode = pool2.eligibilityMode;
          const orgGeneralAscas = await db.select().from(ascasTable).where(
            and(
              eq(ascasTable.organizationId, context.organization.id),
              eq(ascasTable.type, "GENERAL")
            )
          );
          const eligibleAscas = [];
          let totalAvailable = 0;
          const poolReserved = await getPoolReservedApprovalAmountWith(db, poolId);
          const poolOutstanding = await getPoolOutstandingAmountWith(db, poolId);
          for (const asca of orgGeneralAscas) {
            const lendingPoolCfg = getAscaLendingPoolConstitution(asca.constitution);
            if (!lendingPoolCfg) continue;
            if (poolEligibilityMode === "CONTRIBUTORS_ONLY" && lendingPoolCfg.eligibilityMode !== "CONTRIBUTORS_ONLY") {
            }
            const borrowingPolicy = getAscaBorrowingPolicy(asca.constitution);
            const liquidityReservePct = borrowingPolicy?.liquidityReservePct ?? 20;
            const maxPct = lendingPoolCfg.maxPctOfPoolAfterReserve;
            let walletAvailableBalance = 0;
            if (asca.escrowWalletId) {
              const funds = await getWalletFundsWith(db, asca.escrowWalletId);
              walletAvailableBalance = funds.availableBalance;
            }
            const availableForLending = Math.max(
              0,
              walletAvailableBalance * maxPct / 100 - poolReserved - poolOutstanding
            );
            totalAvailable += availableForLending;
            eligibleAscas.push({
              id: asca.id,
              name: asca.name,
              currentAmount: Number(asca.currentAmount ?? 0),
              maxPctOfPoolAfterReserve: maxPct,
              availableForLending,
              borrowingPolicyLiquidityReserve: liquidityReservePct,
              eligibleMode: lendingPoolCfg.eligibilityMode
            });
          }
          return res.json({
            pool: {
              id: pool2.id,
              name: pool2.name,
              description: pool2.description,
              eligibilityMode: pool2.eligibilityMode,
              status: pool2.status,
              templateId: pool2.templateId,
              minRequestAmount: Number(pool2.minRequestAmount ?? 0),
              maxRequestAmount: Number(pool2.maxRequestAmount ?? 0),
              defaultTermMonths: Number(pool2.defaultTermMonths ?? 0),
              defaultRepaymentFrequency: pool2.defaultRepaymentFrequency,
              defaultBorrowerAppreciationPct: Number(
                pool2.defaultBorrowerAppreciationPct ?? 0
              ),
              defaultProcessingFeePct: Number(pool2.defaultProcessingFeePct ?? 0)
            },
            eligibleAscas,
            aggregateTotalAvailable: Number(totalAvailable.toFixed(2)),
            reservedApprovals: poolReserved,
            outstandingLoans: poolOutstanding
          });
        } catch (err) {
          if (err instanceof Error) {
            return res.status(400).json({ message: err.message });
          }
          return handleError4(err, res);
        }
      }
    );
    router5.post("/org/lending/applications", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const context = await requireOrganizationLendingParticipantAccess(userId);
        assertOrganizationProductAccess(context, "ASCA_LENDING_POOL");
        const schema = external_exports.object({
          poolId: external_exports.coerce.number().int().positive(),
          requestedAmount: external_exports.coerce.number().positive(),
          purpose: external_exports.string().trim().min(1).max(2e3),
          borrowerUserId: external_exports.coerce.number().int().positive().optional()
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success) {
          return res.status(400).json({
            message: "Invalid request payload.",
            errors: parsed.error.flatten()
          });
        }
        const borrowerUserId = parsed.data.borrowerUserId ?? userId;
        const [borrowerOrgMember] = await db.select().from(organizationMembersTable).where(
          and(
            eq(organizationMembersTable.organizationId, context.organization.id),
            eq(organizationMembersTable.userId, borrowerUserId),
            eq(organizationMembersTable.status, "ACTIVE")
          )
        );
        if (!borrowerOrgMember) {
          return res.status(403).json({
            message: "Borrower must be an active member of this organization."
          });
        }
        const individualEntitlements = await getIndividualPlanEntitlements(borrowerUserId);
        if (individualEntitlements.community_lending_access !== true) {
          return res.status(403).json({
            message: "Borrower's individual membership plan does not include community lending access."
          });
        }
        const [pool2] = await db.select().from(orgLendingPoolsTable).where(
          and(
            eq(orgLendingPoolsTable.id, parsed.data.poolId),
            eq(orgLendingPoolsTable.organizationId, context.organization.id)
          )
        );
        if (!pool2) {
          return res.status(404).json({ message: "Lending pool not found." });
        }
        if (pool2.eligibilityMode === "CONTRIBUTORS_ONLY") {
          const contributingAscas = await db.select({ id: ascasTable.id }).from(ascasTable).innerJoin(
            ascaMembersTable,
            eq(ascaMembersTable.ascaId, ascasTable.id)
          ).where(
            and(
              eq(ascasTable.organizationId, context.organization.id),
              eq(ascasTable.type, "GENERAL"),
              eq(ascaMembersTable.userId, borrowerUserId),
              eq(ascaMembersTable.status, "ACTIVE")
            )
          );
          const isContributorToEnabledPool = contributingAscas.some((a) => {
            return true;
          });
          let hasContributingAscaWithLending = false;
          for (const a of contributingAscas) {
            const [ascaFull] = await db.select({ constitution: ascasTable.constitution }).from(ascasTable).where(eq(ascasTable.id, a.id));
            const cfg = getAscaLendingPoolConstitution(ascaFull?.constitution);
            if (cfg?.enabled === true) {
              hasContributingAscaWithLending = true;
              break;
            }
          }
          if (!hasContributingAscaWithLending) {
            return res.status(403).json({
              message: "CONTRIBUTORS_ONLY eligibility requires borrower to be an active member of at least one GENERAL ASCA in this organization with community lending pool enabled."
            });
          }
        }
        const requestedAmount = parsed.data.requestedAmount;
        const minAmount = Number(pool2.minRequestAmount ?? 0);
        const maxAmount = Number(pool2.maxRequestAmount ?? 0);
        if (requestedAmount < minAmount) {
          return res.status(400).json({ message: `Requested amount below pool minimum (${minAmount}).` });
        }
        if (maxAmount > 0 && requestedAmount > maxAmount) {
          return res.status(400).json({ message: `Requested amount exceeds pool maximum (${maxAmount}).` });
        }
        let pricing;
        let borrowerAppreciationAmount = 0;
        let processingFeePct = null;
        let templateId = null;
        let termMonths = Number(pool2.defaultTermMonths ?? 12);
        let repaymentFrequency = pool2.defaultRepaymentFrequency ?? "MONTHLY";
        if (pool2.templateId) {
          const [template] = await db.select().from(lendingTemplatesTable).where(eq(lendingTemplatesTable.id, pool2.templateId));
          if (template) {
            templateId = template.id;
            termMonths = Number(template.borrowerTermMonths ?? termMonths);
            repaymentFrequency = template.repaymentFrequency ?? repaymentFrequency;
            borrowerAppreciationAmount = Number(
              template.borrowerAppreciationAmount ?? 0
            );
            processingFeePct = template.processingFeePct ? Number(template.processingFeePct) : null;
            pricing = buildLoanPricingSnapshot({
              principalAmount: requestedAmount,
              appreciationAmount: borrowerAppreciationAmount,
              termMonths,
              repaymentFrequency,
              processingFeePct
            });
          } else {
            const appreciation = requestedAmount * Number(pool2.defaultBorrowerAppreciationPct ?? 8) / 100;
            processingFeePct = Number(pool2.defaultProcessingFeePct ?? 0);
            pricing = buildLoanPricingSnapshot({
              principalAmount: requestedAmount,
              appreciationAmount: appreciation,
              termMonths,
              repaymentFrequency,
              processingFeePct
            });
            borrowerAppreciationAmount = appreciation;
          }
        } else {
          const appreciation = requestedAmount * Number(pool2.defaultBorrowerAppreciationPct ?? 8) / 100;
          processingFeePct = Number(pool2.defaultProcessingFeePct ?? 0);
          pricing = buildLoanPricingSnapshot({
            principalAmount: requestedAmount,
            appreciationAmount: appreciation,
            termMonths,
            repaymentFrequency,
            processingFeePct
          });
          borrowerAppreciationAmount = appreciation;
        }
        const appRows = await db.insert(loanApplicationsTable).values({
          borrowerId: borrowerUserId,
          templateId: templateId ?? void 0,
          opportunityId: pool2.id,
          loanType: "COMMUNITY_LENDING",
          requestedAmount: requestedAmount.toFixed(2),
          purpose: parsed.data.purpose,
          term: `${termMonths} months`,
          repaymentSchedule: repaymentFrequency,
          termMonths,
          borrowerAppreciationAmount: borrowerAppreciationAmount.toFixed(2),
          repaymentFrequency,
          processingFeePct: processingFeePct !== null ? processingFeePct.toFixed(2) : null,
          totalRepayableAmount: pricing.totalRepayableAmount.toFixed(2),
          estimatedInstallmentAmount: pricing.estimatedInstallmentAmount.toFixed(2),
          status: "SUBMITTED",
          notes: JSON.stringify({
            source: "org_community_lending",
            poolId: pool2.id
          }),
          organizationId: context.organization.id
        }).returning();
        return res.status(201).json({ applicationId: appRows[0]?.id });
      } catch (err) {
        if (err instanceof Error) {
          return res.status(400).json({ message: err.message });
        }
        return handleError4(err, res);
      }
    });
    router5.get("/org/lending/applications", requireAuth, async (req, res) => {
      const userId = req.userId;
      try {
        const context = await requireOrganizationLendingParticipantAccess(userId);
        assertOrganizationProductAccess(context, "ASCA_LENDING_POOL");
        const isManager = context.permissions.isOwner || context.permissions.isAdmin;
        const querySchema = external_exports.object({
          poolId: external_exports.coerce.number().int().positive().optional(),
          borrowerId: external_exports.coerce.number().int().positive().optional(),
          status: external_exports.string().optional()
        });
        const queryParsed = querySchema.safeParse(req.query);
        if (!queryParsed.success) {
          return res.status(400).json({ message: "Invalid query parameters." });
        }
        const filterPoolId = queryParsed.data.poolId;
        const filterBorrowerId = queryParsed.data.borrowerId;
        const filterStatus = queryParsed.data.status;
        if (!isManager) {
          if (filterBorrowerId !== void 0 && filterBorrowerId !== userId) {
            return res.status(403).json({
              message: "You can only view your own lending applications."
            });
          }
        }
        const effectiveBorrowerId = isManager ? filterBorrowerId : userId;
        const conditions = [
          eq(loanApplicationsTable.organizationId, context.organization.id)
        ];
        if (filterPoolId) {
          conditions.push(eq(loanApplicationsTable.opportunityId, filterPoolId));
        }
        if (effectiveBorrowerId) {
          conditions.push(eq(loanApplicationsTable.borrowerId, effectiveBorrowerId));
        }
        if (filterStatus) {
          conditions.push(eq(loanApplicationsTable.status, filterStatus));
        }
        const rows = await db.select({
          id: loanApplicationsTable.id,
          borrowerId: loanApplicationsTable.borrowerId,
          ascaId: loanApplicationsTable.ascaId,
          templateId: loanApplicationsTable.templateId,
          opportunityId: loanApplicationsTable.opportunityId,
          loanType: loanApplicationsTable.loanType,
          requestedAmount: loanApplicationsTable.requestedAmount,
          approvedAmount: loanApplicationsTable.approvedAmount,
          disbursedAmount: loanApplicationsTable.disbursedAmount,
          borrowerAppreciationAmount: loanApplicationsTable.borrowerAppreciationAmount,
          totalRepayableAmount: loanApplicationsTable.totalRepayableAmount,
          estimatedInstallmentAmount: loanApplicationsTable.estimatedInstallmentAmount,
          repaymentFrequency: loanApplicationsTable.repaymentFrequency,
          termMonths: loanApplicationsTable.termMonths,
          purpose: loanApplicationsTable.purpose,
          status: loanApplicationsTable.status,
          reviewNote: loanApplicationsTable.reviewNote,
          createdAt: loanApplicationsTable.createdAt,
          reviewedAt: loanApplicationsTable.reviewedAt,
          disbursedAt: loanApplicationsTable.disbursedAt,
          notes: loanApplicationsTable.notes,
          borrowerFirstName: usersTable.firstName,
          borrowerLastName: usersTable.lastName
        }).from(loanApplicationsTable).innerJoin(
          usersTable,
          eq(loanApplicationsTable.borrowerId, usersTable.id)
        ).where(and(...conditions)).orderBy(desc(loanApplicationsTable.createdAt)).limit(200);
        return res.json({
          applications: rows.map((row) => {
            let poolIdFromNotes = null;
            if (row.notes) {
              try {
                const parsedNotes = JSON.parse(row.notes);
                if (parsedNotes && typeof parsedNotes.poolId === "number") {
                  poolIdFromNotes = parsedNotes.poolId;
                }
              } catch (_) {
              }
            }
            return {
              id: row.id,
              borrowerId: row.borrowerId,
              borrowerName: [row.borrowerFirstName, row.borrowerLastName].filter(Boolean).join(" ") || `Member #${row.borrowerId}`,
              ascaId: row.ascaId,
              templateId: row.templateId,
              loanType: row.loanType,
              requestedAmount: Number(row.requestedAmount ?? 0),
              approvedAmount: row.approvedAmount ? Number(row.approvedAmount) : null,
              disbursedAmount: row.disbursedAmount ? Number(row.disbursedAmount) : null,
              borrowerAppreciationAmount: Number(
                row.borrowerAppreciationAmount ?? 0
              ),
              totalRepayableAmount: Number(row.totalRepayableAmount ?? 0),
              estimatedInstallmentAmount: Number(
                row.estimatedInstallmentAmount ?? 0
              ),
              repaymentFrequency: row.repaymentFrequency,
              termMonths: Number(row.termMonths ?? 0),
              purpose: row.purpose,
              status: row.status,
              reviewNote: row.reviewNote,
              poolId: row.opportunityId ?? poolIdFromNotes,
              createdAt: row.createdAt.toISOString(),
              reviewedAt: row.reviewedAt ? row.reviewedAt.toISOString() : null,
              disbursedAt: row.disbursedAt ? row.disbursedAt.toISOString() : null
            };
          })
        });
      } catch (err) {
        if (err instanceof Error) {
          return res.status(400).json({ message: err.message });
        }
        return handleError4(err, res);
      }
    });
    router5.patch(
      "/org/lending/applications/:id",
      requireAuth,
      async (req, res) => {
        const userId = req.userId;
        try {
          const context = await requireOrganizationLendingParticipantAccess(userId);
          assertOrganizationProductAccess(context, "ASCA_LENDING_POOL");
          assertOrganizationLendingPoolManager(context);
          const applicationId = Number(req.params.id);
          if (!Number.isFinite(applicationId) || applicationId <= 0) {
            return res.status(400).json({ message: "Invalid application ID." });
          }
          const schema = external_exports.object({
            action: external_exports.enum(["APPROVE", "REJECT", "FUND"]),
            approvedAmount: external_exports.coerce.number().positive().optional(),
            reviewNote: external_exports.string().trim().max(2e3).optional().nullable()
          });
          const parsed = schema.safeParse(req.body);
          if (!parsed.success) {
            return res.status(400).json({
              message: "Invalid request payload.",
              errors: parsed.error.flatten()
            });
          }
          const appRows = await db.select().from(loanApplicationsTable).where(eq(loanApplicationsTable.id, applicationId));
          const application = appRows[0];
          if (!application) {
            return res.status(404).json({ message: "Loan application not found." });
          }
          let poolId = null;
          if (application.opportunityId) {
            poolId = application.opportunityId;
          } else if (application.notes) {
            try {
              const parsedNotes = JSON.parse(application.notes);
              if (parsedNotes && typeof parsedNotes.poolId === "number") {
                poolId = parsedNotes.poolId;
              }
            } catch (_) {
            }
          }
          if (poolId === null) {
            return res.status(400).json({
              message: "This application is not linked to an organization lending pool."
            });
          }
          const [pool2] = await db.select().from(orgLendingPoolsTable).where(
            and(
              eq(orgLendingPoolsTable.id, poolId),
              eq(orgLendingPoolsTable.organizationId, context.organization.id)
            )
          );
          if (!pool2) {
            return res.status(404).json({ message: "Lending pool not found for this application." });
          }
          if (parsed.data.action === "APPROVE") {
            if (!["SUBMITTED", "UNDER_REVIEW", "WAITLISTED"].includes(application.status)) {
              return res.status(400).json({
                message: `Application status ${application.status} cannot be approved.`
              });
            }
            const approvedAmount = parsed.data.approvedAmount ?? Number(application.requestedAmount);
            const orgGeneralAscas = await db.select().from(ascasTable).where(
              and(
                eq(ascasTable.organizationId, context.organization.id),
                eq(ascasTable.type, "GENERAL")
              )
            );
            let totalAvailableForPool = 0;
            const poolReserved = await getPoolReservedApprovalAmountWith(db, poolId);
            const poolOutstanding = await getPoolOutstandingAmountWith(db, poolId);
            for (const asca of orgGeneralAscas) {
              const lendingPoolCfg = getAscaLendingPoolConstitution(asca.constitution);
              if (!lendingPoolCfg) continue;
              const maxPct = lendingPoolCfg.maxPctOfPoolAfterReserve;
              let walletAvailableBalance = 0;
              if (asca.escrowWalletId) {
                const funds = await getWalletFundsWith(db, asca.escrowWalletId);
                walletAvailableBalance = funds.availableBalance;
              }
              const avail = Math.max(
                0,
                walletAvailableBalance * maxPct / 100 - poolReserved - poolOutstanding
              );
              totalAvailableForPool += avail;
            }
            if (approvedAmount > totalAvailableForPool) {
              return res.status(400).json({
                message: `Approved amount (${approvedAmount}) exceeds aggregate pool availableForLending (${totalAvailableForPool.toFixed(2)}).`
              });
            }
            const updatedRows = await db.update(loanApplicationsTable).set({
              status: "APPROVED",
              approvedAmount: approvedAmount.toFixed(2),
              reviewedAt: /* @__PURE__ */ new Date(),
              reviewedByAdminId: userId,
              reviewNote: parsed.data.reviewNote ?? application.reviewNote
            }).where(eq(loanApplicationsTable.id, applicationId)).returning();
            return res.json({ applicationId: updatedRows[0]?.id });
          }
          if (parsed.data.action === "REJECT") {
            if (!["SUBMITTED", "UNDER_REVIEW", "WAITLISTED", "APPROVED"].includes(application.status)) {
              return res.status(400).json({
                message: `Application status ${application.status} cannot be rejected.`
              });
            }
            const updatedRows = await db.update(loanApplicationsTable).set({
              status: "REJECTED",
              reviewedAt: /* @__PURE__ */ new Date(),
              reviewedByAdminId: userId,
              reviewNote: parsed.data.reviewNote ?? application.reviewNote
            }).where(eq(loanApplicationsTable.id, applicationId)).returning();
            return res.json({ applicationId: updatedRows[0]?.id });
          }
          if (parsed.data.action === "FUND") {
            if (application.status !== "APPROVED") {
              return res.status(400).json({
                message: `Only APPROVED applications can be funded. Current status: ${application.status}`
              });
            }
            const approvedAmount = Number(application.approvedAmount ?? 0);
            if (approvedAmount <= 0) {
              return res.status(400).json({ message: "Approved amount is required for funding." });
            }
            const result = await db.transaction(async (tx) => {
              const poolReserved = await getPoolReservedApprovalAmountWith(tx, poolId);
              const poolOutstanding = await getPoolOutstandingAmountWith(tx, poolId);
              const orgGeneralAscas = await tx.select().from(ascasTable).where(
                and(
                  eq(ascasTable.organizationId, context.organization.id),
                  eq(ascasTable.type, "GENERAL")
                )
              );
              const ascaShares = [];
              let totalAvailableForPool = 0;
              for (const asca of orgGeneralAscas) {
                const lendingPoolCfg = getAscaLendingPoolConstitution(asca.constitution);
                if (!lendingPoolCfg) continue;
                const maxPct = lendingPoolCfg.maxPctOfPoolAfterReserve;
                let walletAvailableBalance = 0;
                if (asca.escrowWalletId) {
                  const funds = await getWalletFundsWith(tx, asca.escrowWalletId);
                  walletAvailableBalance = funds.availableBalance;
                }
                const avail = Math.max(
                  0,
                  walletAvailableBalance * maxPct / 100 - poolReserved - poolOutstanding
                );
                if (avail > 0) {
                  ascaShares.push({ asca, availableForLending: avail });
                  totalAvailableForPool += avail;
                }
              }
              if (totalAvailableForPool < approvedAmount) {
                throw new Error(
                  `Insufficient aggregate pool liquidity. Available: ${totalAvailableForPool.toFixed(2)}, Requested: ${approvedAmount}`
                );
              }
              const approvedCents = Math.round(approvedAmount * 100);
              const funderAllocations = [];
              let remainingCentsToAllocate = approvedCents;
              const totalAvailCents = Math.round(totalAvailableForPool * 100);
              for (const entry of ascaShares) {
                if (remainingCentsToAllocate <= 0) break;
                const entryAvailCents = Math.round(entry.availableForLending * 100);
                const ratio = totalAvailCents > 0 ? entryAvailCents / totalAvailCents : 0;
                const rawCents = Math.min(
                  entryAvailCents,
                  Math.round(approvedCents * ratio)
                );
                const capped = Math.min(rawCents, remainingCentsToAllocate);
                if (capped > 0 && entry.asca.escrowWalletId) {
                  funderAllocations.push({
                    ascaId: entry.asca.id,
                    ascaEscrowWalletId: entry.asca.escrowWalletId,
                    shareCents: capped
                  });
                  remainingCentsToAllocate -= capped;
                }
              }
              if (remainingCentsToAllocate > 0) {
                for (const entry of ascaShares) {
                  if (remainingCentsToAllocate <= 0) break;
                  const entryAvailCents = Math.round(entry.availableForLending * 100);
                  const already = funderAllocations.find(
                    (a) => a.ascaId === entry.asca.id
                  )?.shareCents ?? 0;
                  const canAdd = Math.min(
                    remainingCentsToAllocate,
                    entryAvailCents - already
                  );
                  if (canAdd > 0) {
                    const exist = funderAllocations.find(
                      (a) => a.ascaId === entry.asca.id
                    );
                    if (exist) {
                      exist.shareCents += canAdd;
                    } else if (entry.asca.escrowWalletId) {
                      funderAllocations.push({
                        ascaId: entry.asca.id,
                        ascaEscrowWalletId: entry.asca.escrowWalletId,
                        shareCents: canAdd
                      });
                    }
                    remainingCentsToAllocate -= canAdd;
                  }
                }
              }
              const borrowerWallet = await ensureWalletWith4(
                tx,
                "USER",
                application.borrowerId
              );
              let firstTxId = null;
              for (const alloc of funderAllocations) {
                const idempotencyKey = `org_lending_fund:${applicationId}:asca:${alloc.ascaId}`;
                const amountStr = (alloc.shareCents / 100).toFixed(2);
                const existingTxRows = await tx.select({ id: walletTransactionsTable.id }).from(walletTransactionsTable).where(eq(walletTransactionsTable.idempotencyKey, idempotencyKey));
                const existingTx = existingTxRows[0];
                if (existingTx) {
                  if (!firstTxId) firstTxId = existingTx.id;
                  continue;
                }
                const txRows = await tx.insert(walletTransactionsTable).values({
                  type: "LOAN_DISBURSEMENT",
                  idempotencyKey,
                  fromWalletId: alloc.ascaEscrowWalletId,
                  toWalletId: borrowerWallet.id,
                  amount: amountStr,
                  metadata: {
                    description: `Org community lending disbursement from ASCA #${alloc.ascaId} for loan app #${applicationId}`,
                    applicationId,
                    poolId,
                    ascaId: alloc.ascaId,
                    organizationId: context.organization.id
                  }
                }).returning();
                if (!firstTxId) firstTxId = txRows[0]?.id ?? null;
                await tx.insert(orgLendingPoolFunderUsesTable).values({
                  loanApplicationId: applicationId,
                  poolId,
                  ascaId: alloc.ascaId,
                  fundedAmount: amountStr,
                  organizationId: context.organization.id
                });
              }
              const term = Number(application.termMonths ?? 12);
              const freq = application.repaymentFrequency ?? "MONTHLY";
              const totalRepayableAmount = Number(application.totalRepayableAmount ?? 0);
              const disbursedAt = /* @__PURE__ */ new Date();
              const schedule = buildLendingRepaymentSchedule({
                totalAmount: totalRepayableAmount,
                termMonths: term,
                repaymentFrequency: freq,
                firstDueDate: (() => {
                  if (freq === "WEEKLY") return addDays5(disbursedAt, 7);
                  if (freq === "BIWEEKLY") return addDays5(disbursedAt, 14);
                  return addMonths5(disbursedAt, 1);
                })()
              });
              if (schedule.length > 0) {
                await tx.insert(loanRepaymentsTable).values(
                  schedule.map((entry) => ({
                    loanApplicationId: applicationId,
                    dueDate: entry.dueDate,
                    amount: entry.amount
                  }))
                );
              }
              const updatedAppRows = await tx.update(loanApplicationsTable).set({
                status: "REPAYING",
                disbursedAt,
                disbursedAmount: approvedAmount.toFixed(2),
                disbursementTransactionId: firstTxId,
                organizationId: context.organization.id
              }).where(eq(loanApplicationsTable.id, applicationId)).returning();
              return { applicationId: updatedAppRows[0]?.id };
            });
            return res.json({ applicationId: result.applicationId });
          }
          return res.status(400).json({ message: "Unknown action." });
        } catch (err) {
          if (err instanceof Error) {
            return res.status(400).json({ message: err.message });
          }
          return handleError4(err, res);
        }
      }
    );
    router5.get(
      "/org/lending/applications/:id/repayments",
      requireAuth,
      async (req, res) => {
        const userId = req.userId;
        try {
          const context = await requireOrganizationLendingParticipantAccess(userId);
          assertOrganizationProductAccess(context, "ASCA_LENDING_POOL");
          const applicationId = Number(req.params.id);
          if (!Number.isFinite(applicationId) || applicationId <= 0) {
            return res.status(400).json({ message: "Invalid application ID." });
          }
          const isManager = context.permissions.isOwner || context.permissions.isAdmin;
          const appRows = await db.select().from(loanApplicationsTable).where(eq(loanApplicationsTable.id, applicationId));
          const application = appRows[0];
          if (!application) {
            return res.status(404).json({ message: "Loan application not found." });
          }
          if (!isManager && application.borrowerId !== userId) {
            return res.status(403).json({ message: "You can only view your own repayment schedule." });
          }
          if (application.organizationId) {
            const orgId = application.organizationId;
            const memberRows = await db.select({ id: organizationMembersTable.id }).from(organizationMembersTable).where(
              and(
                eq(organizationMembersTable.organizationId, orgId),
                eq(organizationMembersTable.userId, userId)
              )
            );
            if (!memberRows[0]) {
              return res.status(404).json({ message: "Application not found." });
            }
          }
          const repayments = await ensureAscaBorrowRepaymentsWith(db, application);
          const summary = summarizeAscaBorrowRepayments(repayments);
          return res.json({
            application: {
              id: application.id,
              borrowerId: application.borrowerId,
              requestedAmount: Number(application.requestedAmount ?? 0),
              approvedAmount: application.approvedAmount ? Number(application.approvedAmount) : null,
              disbursedAmount: application.disbursedAmount ? Number(application.disbursedAmount) : null,
              totalRepayableAmount: Number(application.totalRepayableAmount ?? 0),
              estimatedInstallmentAmount: Number(
                application.estimatedInstallmentAmount ?? 0
              ),
              status: application.status,
              disbursedAt: application.disbursedAt ? application.disbursedAt.toISOString() : null
            },
            schedule: repayments.map(serializeAscaBorrowRepaymentRow),
            summary
          });
        } catch (err) {
          if (err instanceof Error) {
            return res.status(400).json({ message: err.message });
          }
          return handleError4(err, res);
        }
      }
    );
    router5.post(
      "/org/lending/applications/:id/payments",
      requireAuth,
      async (req, res) => {
        const userId = req.userId;
        try {
          const context = await requireOrganizationLendingParticipantAccess(userId);
          assertOrganizationProductAccess(context, "ASCA_LENDING_POOL");
          const applicationId = Number(req.params.id);
          if (!Number.isFinite(applicationId) || applicationId <= 0) {
            return res.status(400).json({ message: "Invalid application ID." });
          }
          const schema = external_exports.object({
            amount: external_exports.coerce.number().positive().optional(),
            payAll: external_exports.boolean().optional()
          });
          const parsed = schema.safeParse(req.body);
          if (!parsed.success) {
            return res.status(400).json({
              message: "Invalid request payload.",
              errors: parsed.error.flatten()
            });
          }
          if (!parsed.data.payAll && !parsed.data.amount) {
            return res.status(400).json({ message: "Either amount or payAll=true is required." });
          }
          const [application] = await db.select().from(loanApplicationsTable).where(eq(loanApplicationsTable.id, applicationId));
          if (!application) {
            return res.status(404).json({ message: "Loan application not found." });
          }
          if (application.borrowerId !== userId) {
            const isManager = context.permissions.isOwner || context.permissions.isAdmin;
            if (!isManager) {
              return res.status(403).json({ message: "Only the borrower or a manager can submit payments." });
            }
          }
          if (!["FUNDED", "REPAYING"].includes(application.status)) {
            return res.status(400).json({
              message: `Payments not allowed for status ${application.status}.`
            });
          }
          const repayments = await db.select().from(loanRepaymentsTable).where(eq(loanRepaymentsTable.loanApplicationId, applicationId)).orderBy(asc(loanRepaymentsTable.dueDate));
          const summary = summarizeAscaBorrowRepayments(repayments);
          const payAll = parsed.data.payAll === true;
          const paymentAmount = payAll ? summary.outstandingBalance : Number(parsed.data.amount ?? 0);
          if (paymentAmount <= 0) {
            return res.status(400).json({ message: "Payment amount must be greater than 0." });
          }
          let poolId = null;
          if (application.opportunityId) {
            poolId = application.opportunityId;
          } else if (application.notes) {
            try {
              const parsedNotes = JSON.parse(application.notes);
              if (parsedNotes && typeof parsedNotes.poolId === "number") {
                poolId = parsedNotes.poolId;
              }
            } catch (_) {
            }
          }
          const result = await db.transaction(async (tx) => {
            const borrowerWallet = await ensureWalletWith4(
              tx,
              "USER",
              application.borrowerId
            );
            const borrowerAvailable = await getWalletAvailableBalanceWith(
              tx,
              borrowerWallet.id
            );
            if (borrowerAvailable < paymentAmount) {
              throw new Error(
                `Insufficient borrower wallet balance. Available: ${borrowerAvailable.toFixed(2)}, Requested: ${paymentAmount.toFixed(2)}`
              );
            }
            const funderUses = poolId ? await tx.select().from(orgLendingPoolFunderUsesTable).where(
              and(
                eq(orgLendingPoolFunderUsesTable.loanApplicationId, applicationId),
                eq(orgLendingPoolFunderUsesTable.poolId, poolId)
              )
            ) : [];
            let totalFundedShare = 0;
            for (const use of funderUses) {
              totalFundedShare += Number(use.fundedAmount ?? 0);
            }
            const paymentCents = Math.round(paymentAmount * 100);
            let remainingCents = paymentCents;
            let remainingRepayments = repayments.filter(
              (r) => r.status !== "PAID" && r.status !== "WAIVED"
            );
            let now = /* @__PURE__ */ new Date();
            let principalPaidTotal = 0;
            let returnPaidTotal = 0;
            let feePaidTotal = 0;
            let creditedToPoolTotal = 0;
            for (const repayment of remainingRepayments) {
              if (remainingCents <= 0) break;
              const scheduled = parseMoneyAmount(repayment.amount);
              const paidAlready = parseMoneyAmount(repayment.paidAmount);
              const due = Math.max(0, scheduled - paidAlready);
              const dueCents = Math.round(due * 100);
              if (dueCents <= 0) continue;
              const payCents = Math.min(remainingCents, dueCents);
              const payAmount = payCents / 100;
              const disbursed = Number(application.disbursedAmount ?? 0);
              const totalRepayable = Number(application.totalRepayableAmount ?? 0);
              const principalPct = disbursed > 0 && totalRepayable > 0 ? disbursed / totalRepayable : 1;
              const returnPct = Math.max(0, 1 - principalPct);
              const principalPortion = Math.max(0, payAmount * principalPct);
              const returnPortion = Math.max(0, payAmount * returnPct);
              const feePortion = 0;
              const creditedPortion = principalPortion + returnPortion;
              principalPaidTotal += principalPortion;
              returnPaidTotal += returnPortion;
              feePaidTotal += feePortion;
              creditedToPoolTotal += creditedPortion;
              const newPaidAmount = paidAlready + payAmount;
              const newStatus = Math.round(newPaidAmount * 100) >= dueCents ? "PAID" : repayment.status;
              const isLate = repayment.dueDate < now && newStatus !== "PAID" ? "LATE" : newStatus;
              const finalStatus = newStatus === "PAID" ? "PAID" : isLate;
              await tx.update(loanRepaymentsTable).set({
                paidAmount: (parseMoneyAmount(repayment.paidAmount) + payAmount).toFixed(2),
                paidAt: now,
                status: finalStatus,
                method: "WALLET",
                principalPaidAmount: (parseMoneyAmount(repayment.principalPaidAmount) + principalPortion).toFixed(2),
                returnPaidAmount: (parseMoneyAmount(repayment.returnPaidAmount) + returnPortion).toFixed(2),
                feePaidAmount: (parseMoneyAmount(repayment.feePaidAmount) + feePortion).toFixed(2),
                creditedToPoolAmount: (parseMoneyAmount(repayment.creditedToPoolAmount) + creditedPortion).toFixed(2)
              }).where(eq(loanRepaymentsTable.id, repayment.id));
              remainingCents -= payCents;
            }
            const actualPaidCents = paymentCents - remainingCents;
            const actualPaidAmount = actualPaidCents / 100;
            if (totalFundedShare > 0 && funderUses.length > 0) {
              for (const use of funderUses) {
                const shareAmount = Number(use.fundedAmount ?? 0);
                const shareRatio = shareAmount / totalFundedShare;
                const portion = actualPaidAmount * shareRatio;
                if (portion <= 0) continue;
                const [asca] = await tx.select({ escrowWalletId: ascasTable.escrowWalletId }).from(ascasTable).where(eq(ascasTable.id, use.ascaId));
                if (asca?.escrowWalletId) {
                  const idempotencyKey = `org_lending_payment:${applicationId}:asca:${use.ascaId}:${now.getTime()}`;
                  await tx.insert(walletTransactionsTable).values({
                    type: "LOAN_REPAYMENT",
                    idempotencyKey,
                    fromWalletId: borrowerWallet.id,
                    toWalletId: asca.escrowWalletId,
                    amount: portion.toFixed(2),
                    metadata: {
                      description: `Org community lending repayment from ASCA #${use.ascaId} for loan app #${applicationId}`,
                      applicationId,
                      poolId,
                      ascaId: use.ascaId
                    }
                  });
                }
              }
            } else {
              if (application.ascaId) {
                const [asca] = await tx.select({ escrowWalletId: ascasTable.escrowWalletId }).from(ascasTable).where(eq(ascasTable.id, application.ascaId));
                if (asca?.escrowWalletId) {
                  const idempotencyKey = `org_lending_payment:${applicationId}:direct:${now.getTime()}`;
                  await tx.insert(walletTransactionsTable).values({
                    type: "LOAN_REPAYMENT",
                    idempotencyKey,
                    fromWalletId: borrowerWallet.id,
                    toWalletId: asca.escrowWalletId,
                    amount: actualPaidAmount.toFixed(2),
                    metadata: {
                      description: `Org community lending repayment for loan app #${applicationId}`,
                      applicationId,
                      poolId
                    }
                  });
                }
              }
            }
            const updatedRepaymentsAfter = await tx.select().from(loanRepaymentsTable).where(eq(loanRepaymentsTable.loanApplicationId, applicationId));
            const allSettled = updatedRepaymentsAfter.every(
              (r) => r.status === "PAID" || r.status === "WAIVED"
            );
            if (allSettled) {
              await tx.update(loanApplicationsTable).set({ status: "CLOSED" }).where(eq(loanApplicationsTable.id, applicationId));
            }
            return {
              paidAmount: actualPaidAmount,
              change: remainingCents > 0 ? remainingCents / 100 : 0,
              principalPaid: principalPaidTotal,
              returnPaid: returnPaidTotal,
              feePaid: feePaidTotal,
              creditedToPool: creditedToPoolTotal,
              status: allSettled ? "CLOSED" : "REPAYING"
            };
          });
          return res.json(result);
        } catch (err) {
          if (err instanceof Error) {
            return res.status(400).json({ message: err.message });
          }
          return handleError4(err, res);
        }
      }
    );
    router5.get("/org/susu/helping-hand", requireAuth, async (req, res) => {
      try {
        const userId = req.userId;
        const context = await requireOrganizationMatchingFundAccess(userId);
        assertOrganizationSusuMatchingFundManager(context);
        const applications = await db.select({
          id: helpingHandApplicationsTable.id,
          userId: helpingHandApplicationsTable.userId,
          requestedAmount: helpingHandApplicationsTable.requestedAmount,
          qualifyingCircleId: helpingHandApplicationsTable.qualifyingCircleId,
          qualifyingPayoutAmount: helpingHandApplicationsTable.qualifyingPayoutAmount,
          qualifyingMultiplier: helpingHandApplicationsTable.qualifyingMultiplier,
          purpose: helpingHandApplicationsTable.purpose,
          term: helpingHandApplicationsTable.term,
          repaymentSchedule: helpingHandApplicationsTable.repaymentSchedule,
          notes: helpingHandApplicationsTable.notes,
          status: helpingHandApplicationsTable.status,
          approvedAmount: helpingHandApplicationsTable.approvedAmount,
          disbursedAmount: helpingHandApplicationsTable.disbursedAmount,
          disbursedAt: helpingHandApplicationsTable.disbursedAt,
          reviewNote: helpingHandApplicationsTable.reviewNote,
          createdAt: helpingHandApplicationsTable.createdAt,
          qualifyingCircleName: savingsCirclesTable.name,
          userEmail: usersTable.email,
          userFirstName: usersTable.firstName,
          userLastName: usersTable.lastName
        }).from(helpingHandApplicationsTable).leftJoin(
          usersTable,
          eq(helpingHandApplicationsTable.userId, usersTable.id)
        ).leftJoin(
          savingsCirclesTable,
          eq(
            helpingHandApplicationsTable.qualifyingCircleId,
            savingsCirclesTable.id
          )
        ).where(
          eq(
            helpingHandApplicationsTable.organizationId,
            context.organization.id
          )
        ).orderBy(desc(helpingHandApplicationsTable.createdAt));
        return res.json({ applications, total: applications.length });
      } catch (err) {
        return handleError4(err, res);
      }
    });
    router5.patch(
      "/org/susu/helping-hand/:id",
      requireAuth,
      async (req, res) => {
        try {
          const userId = req.userId;
          const context = await requireOrganizationMatchingFundAccess(userId);
          assertOrganizationSusuMatchingFundManager(context);
          const id = Number(req.params.id);
          if (!Number.isFinite(id) || id <= 0) {
            return res.status(400).json({ message: "Invalid application id." });
          }
          const schema = external_exports.object({
            status: external_exports.enum([
              "DRAFT",
              "SUBMITTED",
              "UNDER_REVIEW",
              "APPROVED",
              "REJECTED",
              "FUNDED",
              "REPAYING",
              "CLOSED"
            ]).optional(),
            approvedAmount: external_exports.string().optional(),
            disbursedAmount: external_exports.string().optional(),
            reviewNote: external_exports.string().optional()
          });
          const parsed = schema.safeParse(req.body);
          if (!parsed.success)
            return res.status(400).json({ errors: parsed.error.flatten() });
          const updated = await db.transaction(async (tx) => {
            const [existing] = await tx.select().from(helpingHandApplicationsTable).where(eq(helpingHandApplicationsTable.id, id));
            if (!existing) {
              throw new Error("Application not found.");
            }
            if (existing.organizationId !== context.organization.id) {
              throw new OrganizationTenantAccessError(
                "Not authorized to manage this application.",
                403,
                "org_scope_check"
              );
            }
            const nextStatus = parsed.data.status ?? existing.status;
            if (parsed.data.status && parsed.data.status !== existing.status && !HELPING_HAND_APPLICATION_TRANSITIONS[existing.status]?.includes(
              parsed.data.status
            )) {
              throw new Error(
                `Invalid status transition from ${existing.status} to ${parsed.data.status}.`
              );
            }
            if (nextStatus === "CLOSED") {
              const repayments = await tx.select({
                amount: helpingHandRepaymentsTable.amount,
                paidAmount: helpingHandRepaymentsTable.paidAmount,
                status: helpingHandRepaymentsTable.status
              }).from(helpingHandRepaymentsTable).where(
                eq(
                  helpingHandRepaymentsTable.helpingHandApplicationId,
                  existing.id
                )
              );
              const hasOutstandingRepayment = repayments.some((repayment) => {
                const scheduledAmount = parseMoneyAmount(repayment.amount);
                const paidAmount = repayment.status === "PAID" ? scheduledAmount : parseMoneyAmount(repayment.paidAmount);
                return repayment.status !== "WAIVED" && paidAmount + 1e-6 < scheduledAmount;
              });
              if (hasOutstandingRepayment) {
                throw new Error(
                  "All Matching Fund repayments must be settled or waived before the case can be closed."
                );
              }
            }
            const nextApprovedAmount = parsed.data.approvedAmount !== void 0 ? parsed.data.approvedAmount || null : existing.approvedAmount;
            let disbursedAmount = existing.status === "FUNDED" && existing.disbursedAmount ? existing.disbursedAmount : parsed.data.disbursedAmount ?? existing.disbursedAmount ?? nextApprovedAmount ?? existing.requestedAmount;
            let disbursementTransactionId = existing.disbursementTransactionId ?? null;
            if (nextStatus === "FUNDED" && existing.status !== "FUNDED") {
              const numericDisbursedAmount = parseMoneyAmount(disbursedAmount);
              if (numericDisbursedAmount <= 0) {
                throw new Error("Disbursed amount must be a positive value.");
              }
              const masterWalletBalance = await getLendingMasterWalletBalanceWith2(
                tx
              );
              if (numericDisbursedAmount > masterWalletBalance) {
                throw new Error(
                  `Lending Master Wallet balance is only ${formatMoneyAmount(masterWalletBalance)}. Top up the wallet or reduce the amount before funding.`
                );
              }
              const [memberWallet, masterWallet] = await Promise.all([
                ensureWalletWith3(tx, "USER", existing.userId),
                ensureLendingMasterWalletWith2(tx)
              ]);
              const disbursementIdempotencyKey = `helping_hand_disbursement:org_fund:${existing.id}:${context.organization.id}`;
              const [existingDisbursement] = await tx.select().from(walletTransactionsTable).where(
                eq(
                  walletTransactionsTable.idempotencyKey,
                  disbursementIdempotencyKey
                )
              );
              const transaction = existingDisbursement ?? (await tx.insert(walletTransactionsTable).values({
                type: "HELPING_HAND_DISBURSEMENT",
                idempotencyKey: disbursementIdempotencyKey,
                fromWalletId: masterWallet.id,
                toWalletId: memberWallet.id,
                amount: formatMoneyAmount(numericDisbursedAmount),
                metadata: {
                  helpingHandApplicationId: existing.id,
                  userId: existing.userId,
                  organizationId: context.organization.id
                }
              }).returning())[0];
              disbursementTransactionId = transaction.id;
              disbursedAmount = formatMoneyAmount(numericDisbursedAmount);
            }
            const now = /* @__PURE__ */ new Date();
            const updates = {
              status: nextStatus,
              approvedAmount: nextApprovedAmount,
              disbursedAmount: nextStatus === "FUNDED" || existing.disbursedAmount ? disbursedAmount : existing.disbursedAmount,
              reviewNote: parsed.data.reviewNote !== void 0 ? parsed.data.reviewNote || null : existing.reviewNote,
              updatedAt: now
            };
            if (nextStatus === "FUNDED") {
              updates.disbursedAt = existing.disbursedAt ?? now;
              updates.disbursementTransactionId = disbursementTransactionId;
            }
            const [application] = await tx.update(helpingHandApplicationsTable).set(updates).where(eq(helpingHandApplicationsTable.id, id)).returning();
            return application;
          });
          return res.json({ application: updated });
        } catch (err) {
          if (err instanceof OrganizationTenantAccessError) {
            return handleError4(err, res);
          }
          if (err instanceof Error) {
            if (err.message === "Application not found.") {
              return res.status(404).json({ message: err.message });
            }
            return res.status(400).json({ message: err.message });
          }
          return handleError4(err, res);
        }
      }
    );
    router5.get(
      "/org/susu/helping-hand/:id/repayments",
      requireAuth,
      async (req, res) => {
        try {
          const userId = req.userId;
          const context = await requireOrganizationMatchingFundAccess(userId);
          const applicationId = Number(req.params.id);
          if (!Number.isFinite(applicationId) || applicationId <= 0) {
            return res.status(400).json({ message: "Invalid application id." });
          }
          const isManager = context.permissions.isOwner || context.permissions.isAdmin;
          const [app3] = await db.select({
            id: helpingHandApplicationsTable.id,
            userId: helpingHandApplicationsTable.userId,
            organizationId: helpingHandApplicationsTable.organizationId
          }).from(helpingHandApplicationsTable).where(eq(helpingHandApplicationsTable.id, applicationId));
          if (!app3) {
            return res.status(404).json({ message: "Application not found." });
          }
          if (app3.organizationId !== context.organization.id) {
            return res.status(403).json({ message: "Not authorized to access this application." });
          }
          if (!isManager && app3.userId !== userId) {
            return res.status(403).json({ message: "Not authorized to access these repayments." });
          }
          const repayments = await db.select().from(helpingHandRepaymentsTable).where(
            eq(
              helpingHandRepaymentsTable.helpingHandApplicationId,
              applicationId
            )
          ).orderBy(asc(helpingHandRepaymentsTable.dueDate));
          return res.json({
            repayments: repayments.map(serializeHelpingHandRepayment)
          });
        } catch (err) {
          return handleError4(err, res);
        }
      }
    );
    router5.post(
      "/org/susu/helping-hand/:id/repayments/generate",
      requireAuth,
      async (req, res) => {
        try {
          const userId = req.userId;
          const context = await requireOrganizationMatchingFundAccess(userId);
          assertOrganizationSusuMatchingFundManager(context);
          const applicationId = Number(req.params.id);
          if (!Number.isFinite(applicationId) || applicationId <= 0) {
            return res.status(400).json({ message: "Invalid application id." });
          }
          const parsed = external_exports.object({
            firstDueDate: external_exports.string().transform((value) => new Date(value)).optional()
          }).safeParse(req.body ?? {});
          if (!parsed.success) {
            return res.status(400).json({ errors: parsed.error.flatten() });
          }
          const [application] = await db.select().from(helpingHandApplicationsTable).where(eq(helpingHandApplicationsTable.id, applicationId));
          if (!application) {
            return res.status(404).json({ message: "Application not found." });
          }
          if (application.organizationId !== context.organization.id) {
            return res.status(403).json({ message: "Not authorized to manage this application." });
          }
          if (!HELPING_HAND_REPAYMENT_CREATEABLE_APPLICATION_STATUSES2.has(
            application.status
          )) {
            return res.status(400).json({
              message: "Repayment schedules can only be generated for funded or repaying Matching Fund cases."
            });
          }
          const existingRepayments = await db.select({ count: count() }).from(helpingHandRepaymentsTable).where(
            eq(
              helpingHandRepaymentsTable.helpingHandApplicationId,
              applicationId
            )
          );
          if (Number(existingRepayments[0]?.count ?? 0) > 0) {
            return res.status(400).json({
              message: "A repayment schedule already exists. Adjust the entries inline instead of generating a new one."
            });
          }
          const totalAmount = Number(
            application.approvedAmount ?? application.requestedAmount
          );
          if (!Number.isFinite(totalAmount) || totalAmount <= 0) {
            return res.status(400).json({
              message: "The application must have a valid approved or requested amount before a repayment schedule can be generated."
            });
          }
          const firstDueDate = parsed.data.firstDueDate ?? addPeriod3(
            application.disbursedAt ?? /* @__PURE__ */ new Date(),
            parseRepaymentFrequency(application.repaymentSchedule),
            1
          );
          const schedule = buildHelpingHandRepaymentSchedule({
            totalAmount,
            term: application.term,
            repaymentSchedule: application.repaymentSchedule,
            firstDueDate
          });
          const inserted = await db.insert(helpingHandRepaymentsTable).values(
            schedule.map((entry) => ({
              helpingHandApplicationId: applicationId,
              dueDate: entry.dueDate,
              amount: entry.amount,
              organizationId: context.organization.id
            }))
          ).returning();
          return res.status(201).json({ repayments: inserted });
        } catch (err) {
          return handleError4(err, res);
        }
      }
    );
    router5.post(
      "/org/susu/helping-hand/:id/repayments",
      requireAuth,
      async (req, res) => {
        try {
          const userId = req.userId;
          const context = await requireOrganizationMatchingFundAccess(userId);
          assertOrganizationSusuMatchingFundManager(context);
          const applicationId = Number(req.params.id);
          if (!Number.isFinite(applicationId) || applicationId <= 0) {
            return res.status(400).json({ message: "Invalid application id." });
          }
          const schema = external_exports.object({
            dueDate: external_exports.string().transform((s) => new Date(s)),
            amount: external_exports.string()
          });
          const parsed = schema.safeParse(req.body);
          if (!parsed.success)
            return res.status(400).json({ errors: parsed.error.flatten() });
          const [application] = await db.select({
            id: helpingHandApplicationsTable.id,
            status: helpingHandApplicationsTable.status,
            organizationId: helpingHandApplicationsTable.organizationId
          }).from(helpingHandApplicationsTable).where(eq(helpingHandApplicationsTable.id, applicationId));
          if (!application) {
            return res.status(404).json({ message: "Application not found." });
          }
          if (application.organizationId !== context.organization.id) {
            return res.status(403).json({ message: "Not authorized to manage this application." });
          }
          if (!HELPING_HAND_REPAYMENT_CREATEABLE_APPLICATION_STATUSES2.has(
            application.status
          )) {
            return res.status(400).json({
              message: "Repayment entries can only be created for funded or repaying Matching Fund cases."
            });
          }
          const [newRepayment] = await db.insert(helpingHandRepaymentsTable).values({
            helpingHandApplicationId: applicationId,
            dueDate: parsed.data.dueDate,
            amount: parsed.data.amount,
            organizationId: context.organization.id
          }).returning();
          return res.status(201).json({ repayment: newRepayment });
        } catch (err) {
          return handleError4(err, res);
        }
      }
    );
    router5.patch(
      "/org/susu/helping-hand/repayments/:id",
      requireAuth,
      async (req, res) => {
        try {
          const userId = req.userId;
          const context = await requireOrganizationMatchingFundAccess(userId);
          assertOrganizationSusuMatchingFundManager(context);
          const id = Number(req.params.id);
          if (!Number.isFinite(id) || id <= 0) {
            return res.status(400).json({ message: "Invalid repayment id." });
          }
          const schema = external_exports.object({
            amount: external_exports.string().optional(),
            dueDate: external_exports.string().transform((s) => new Date(s)).optional(),
            status: external_exports.enum(["PENDING", "PAID", "LATE", "WAIVED"]).optional(),
            method: external_exports.enum(["STRIPE", "EFT", "INTERAC", "WIRE", "WALLET"]).optional(),
            paidAmount: external_exports.string().optional(),
            returnPaidAmount: external_exports.string().optional()
          });
          const parsed = schema.safeParse(req.body);
          if (!parsed.success)
            return res.status(400).json({ errors: parsed.error.flatten() });
          const [existing] = await db.select().from(helpingHandRepaymentsTable).where(eq(helpingHandRepaymentsTable.id, id));
          if (!existing) {
            return res.status(404).json({ message: "Repayment not found." });
          }
          if (existing.organizationId !== context.organization.id) {
            return res.status(403).json({ message: "Not authorized to edit this repayment." });
          }
          const [application] = await db.select({
            userId: helpingHandApplicationsTable.userId,
            status: helpingHandApplicationsTable.status,
            organizationId: helpingHandApplicationsTable.organizationId
          }).from(helpingHandApplicationsTable).where(
            eq(
              helpingHandApplicationsTable.id,
              existing.helpingHandApplicationId
            )
          );
          if (!application) {
            return res.status(404).json({ message: "Application not found." });
          }
          if (application.organizationId !== context.organization.id) {
            return res.status(403).json({ message: "Not authorized to manage this application." });
          }
          if (!HELPING_HAND_REPAYMENT_SERVICEABLE_APPLICATION_STATUSES2.has(
            application.status
          )) {
            return res.status(400).json({
              message: "Repayments can only be managed for funded, repaying, or closed Matching Fund cases."
            });
          }
          const updates = {
            ...parsed.data,
            ...deriveHelpingHandRepaymentUpdate(existing, parsed.data, /* @__PURE__ */ new Date()),
            updatedAt: /* @__PURE__ */ new Date()
          };
          const [updated] = await db.update(helpingHandRepaymentsTable).set(updates).where(eq(helpingHandRepaymentsTable.id, id)).returning();
          if (!updated)
            return res.status(404).json({ message: "Repayment not found." });
          const allAppRepayments = await db.select({ status: helpingHandRepaymentsTable.status }).from(helpingHandRepaymentsTable).where(
            eq(
              helpingHandRepaymentsTable.helpingHandApplicationId,
              existing.helpingHandApplicationId
            )
          );
          const allSettled = allAppRepayments.every(
            (r) => r.status === "PAID" || r.status === "WAIVED"
          );
          if (allSettled) {
            await db.update(helpingHandApplicationsTable).set({ status: "CLOSED", updatedAt: /* @__PURE__ */ new Date() }).where(
              eq(
                helpingHandApplicationsTable.id,
                existing.helpingHandApplicationId
              )
            );
          }
          await updateCreditScore(application.userId);
          return res.json({ repayment: updated });
        } catch (err) {
          return handleError4(err, res);
        }
      }
    );
    router5.get(
      "/org/susu/helping-hand/member-eligibility",
      requireAuth,
      async (req, res) => {
        try {
          const userId = req.userId;
          const context = await requireOrganizationMatchingFundAccess(userId);
          const [eligibility, app3] = await Promise.all([
            getOrgHelpingHandEligibilitySnapshot(userId, context.organization.id),
            db.select({
              id: helpingHandApplicationsTable.id,
              requestedAmount: helpingHandApplicationsTable.requestedAmount,
              approvedAmount: helpingHandApplicationsTable.approvedAmount,
              disbursedAmount: helpingHandApplicationsTable.disbursedAmount,
              qualifyingCircleId: helpingHandApplicationsTable.qualifyingCircleId,
              qualifyingPayoutAmount: helpingHandApplicationsTable.qualifyingPayoutAmount,
              qualifyingMultiplier: helpingHandApplicationsTable.qualifyingMultiplier,
              purpose: helpingHandApplicationsTable.purpose,
              term: helpingHandApplicationsTable.term,
              repaymentSchedule: helpingHandApplicationsTable.repaymentSchedule,
              notes: helpingHandApplicationsTable.notes,
              reviewNote: helpingHandApplicationsTable.reviewNote,
              status: helpingHandApplicationsTable.status,
              disbursedAt: helpingHandApplicationsTable.disbursedAt,
              createdAt: helpingHandApplicationsTable.createdAt,
              reviewedAt: helpingHandApplicationsTable.reviewedAt,
              qualifyingCircleName: savingsCirclesTable.name
            }).from(helpingHandApplicationsTable).leftJoin(
              savingsCirclesTable,
              eq(
                helpingHandApplicationsTable.qualifyingCircleId,
                savingsCirclesTable.id
              )
            ).where(
              and(
                eq(helpingHandApplicationsTable.userId, userId),
                eq(
                  helpingHandApplicationsTable.organizationId,
                  context.organization.id
                )
              )
            ).orderBy(desc(helpingHandApplicationsTable.createdAt)).limit(1).then((rows) => rows[0] ?? null)
          ]);
          const eligibilityReason = eligibility.eligible ? "You can apply for SUSU Matching Fund." : eligibility.reasons[0] ?? "Eligibility will update with your SUSU progress.";
          return res.json({
            helpingHand: {
              id: app3?.id ?? null,
              requestedAmount: app3 ? Number(app3.requestedAmount) : null,
              approvedAmount: app3?.approvedAmount ? Number(app3.approvedAmount) : null,
              disbursedAmount: app3?.disbursedAmount ? Number(app3.disbursedAmount) : null,
              purpose: app3?.purpose ?? null,
              term: app3?.term ?? null,
              repaymentSchedule: app3?.repaymentSchedule ?? null,
              notes: app3?.notes ?? null,
              reviewNote: app3?.reviewNote ?? null,
              status: app3?.status ?? null,
              qualifyingCircleId: app3?.qualifyingCircleId ?? eligibility.inputs.qualifyingCircleId ?? null,
              qualifyingCircleName: app3?.qualifyingCircleName ?? eligibility.inputs.qualifyingCircleName ?? null,
              qualifyingPayoutAmount: app3?.qualifyingPayoutAmount ? Number(app3.qualifyingPayoutAmount) : eligibility.inputs.qualifyingPayoutAmount ?? null,
              qualifyingMultiplier: app3?.qualifyingMultiplier ? Number(app3.qualifyingMultiplier) : eligibility.inputs.qualifyingMultiplier ?? null,
              submittedAt: app3?.createdAt?.toISOString().split("T")[0] ?? null,
              reviewedAt: app3?.reviewedAt?.toISOString().split("T")[0] ?? null,
              disbursedAt: app3?.disbursedAt?.toISOString().split("T")[0] ?? null,
              eligible: eligibility.eligible,
              reasons: eligibility.reasons,
              creditScore: null,
              creditScoreTier: null,
              isEligible: eligibility.eligible,
              eligibilityScore: null,
              eligibilityReason,
              eligibilityReasons: eligibility.reasons,
              maxRequestAmount: eligibility.inputs.maxRequestAmount ?? null,
              segment: null,
              susuParticipationCount: eligibility.inputs.susuParticipationCount,
              payoutContextCount: eligibility.inputs.payoutContextCount,
              latestPayoutScheduledDate: eligibility.inputs.latestPayoutScheduledDate,
              latestPayoutPaidDate: eligibility.inputs.latestPayoutPaidDate
            }
          });
        } catch (err) {
          return handleError4(err, res);
        }
      }
    );
    router5.get(
      "/org/susu/helping-hand/applications",
      requireAuth,
      async (req, res) => {
        try {
          const userId = req.userId;
          const context = await requireOrganizationMatchingFundAccess(userId);
          const applications = await db.select({
            id: helpingHandApplicationsTable.id,
            requestedAmount: helpingHandApplicationsTable.requestedAmount,
            approvedAmount: helpingHandApplicationsTable.approvedAmount,
            disbursedAmount: helpingHandApplicationsTable.disbursedAmount,
            purpose: helpingHandApplicationsTable.purpose,
            term: helpingHandApplicationsTable.term,
            repaymentSchedule: helpingHandApplicationsTable.repaymentSchedule,
            notes: helpingHandApplicationsTable.notes,
            reviewNote: helpingHandApplicationsTable.reviewNote,
            status: helpingHandApplicationsTable.status,
            disbursedAt: helpingHandApplicationsTable.disbursedAt,
            createdAt: helpingHandApplicationsTable.createdAt,
            reviewedAt: helpingHandApplicationsTable.reviewedAt,
            qualifyingCircleName: savingsCirclesTable.name,
            qualifyingCircleId: helpingHandApplicationsTable.qualifyingCircleId,
            qualifyingPayoutAmount: helpingHandApplicationsTable.qualifyingPayoutAmount,
            qualifyingMultiplier: helpingHandApplicationsTable.qualifyingMultiplier
          }).from(helpingHandApplicationsTable).leftJoin(
            savingsCirclesTable,
            eq(
              helpingHandApplicationsTable.qualifyingCircleId,
              savingsCirclesTable.id
            )
          ).where(
            and(
              eq(helpingHandApplicationsTable.userId, userId),
              eq(
                helpingHandApplicationsTable.organizationId,
                context.organization.id
              )
            )
          ).orderBy(desc(helpingHandApplicationsTable.createdAt));
          return res.json({
            applications: applications.map((app3) => ({
              id: app3.id,
              requestedAmount: Number(app3.requestedAmount),
              approvedAmount: app3.approvedAmount ? Number(app3.approvedAmount) : null,
              disbursedAmount: app3.disbursedAmount ? Number(app3.disbursedAmount) : null,
              purpose: app3.purpose,
              term: app3.term,
              repaymentSchedule: app3.repaymentSchedule,
              notes: app3.notes ?? null,
              reviewNote: app3.reviewNote ?? null,
              status: app3.status,
              qualifyingCircleId: app3.qualifyingCircleId ?? null,
              qualifyingCircleName: app3.qualifyingCircleName ?? null,
              qualifyingPayoutAmount: app3.qualifyingPayoutAmount ? Number(app3.qualifyingPayoutAmount) : null,
              qualifyingMultiplier: app3.qualifyingMultiplier ? Number(app3.qualifyingMultiplier) : null,
              submittedAt: app3.createdAt?.toISOString().split("T")[0] ?? null,
              reviewedAt: app3.reviewedAt?.toISOString().split("T")[0] ?? null,
              disbursedAt: app3.disbursedAt?.toISOString().split("T")[0] ?? null
            }))
          });
        } catch (err) {
          return handleError4(err, res);
        }
      }
    );
    router5.post(
      "/org/susu/helping-hand/applications",
      requireAuth,
      async (req, res) => {
        try {
          const userId = req.userId;
          const context = await requireOrganizationMatchingFundAccess(userId);
          const eligibility = await getOrgHelpingHandEligibilitySnapshot(
            userId,
            context.organization.id
          );
          if (!eligibility.eligible) {
            return res.status(400).json({
              message: "You are not eligible to apply for SUSU Matching Fund at this time.",
              reasons: eligibility.reasons,
              inputs: eligibility.inputs
            });
          }
          const maxRequestAmount = eligibility.inputs.maxRequestAmount;
          const validation = validateHelpingHandApplicationInput(
            req.body,
            maxRequestAmount
          );
          if (!validation.ok) {
            return validation.errors ? res.status(400).json({ errors: validation.errors }) : res.status(400).json({ message: validation.message });
          }
          const { data } = validation;
          const [application] = await db.insert(helpingHandApplicationsTable).values({
            userId,
            organizationId: context.organization.id,
            requestedAmount: String(data.requestedAmount),
            purpose: data.purpose,
            term: data.term,
            repaymentSchedule: data.repaymentSchedule,
            notes: data.notes || null,
            status: "SUBMITTED",
            qualifyingCircleId: eligibility.inputs.qualifyingCircleId,
            qualifyingPayoutId: eligibility.inputs.qualifyingPayoutId,
            qualifyingPayoutAmount: eligibility.inputs.qualifyingPayoutAmount !== null ? String(eligibility.inputs.qualifyingPayoutAmount) : null,
            qualifyingMultiplier: eligibility.inputs.qualifyingMultiplier !== null ? String(eligibility.inputs.qualifyingMultiplier) : null
          }).returning();
          return res.status(201).json({
            application: {
              id: application.id,
              requestedAmount: Number(application.requestedAmount),
              approvedAmount: application.approvedAmount ? Number(application.approvedAmount) : null,
              purpose: application.purpose,
              term: application.term,
              repaymentSchedule: application.repaymentSchedule,
              notes: application.notes ?? "",
              status: application.status,
              reviewNote: application.reviewNote ?? null,
              submittedAt: application.createdAt.toISOString(),
              reviewedAt: application.reviewedAt?.toISOString() ?? null,
              disbursedAt: application.disbursedAt?.toISOString() ?? null
            }
          });
        } catch (err) {
          return handleError4(err, res);
        }
      }
    );
    router5.post(
      "/org/susu/helping-hand/repayments/:id/payments",
      requireAuth,
      async (req, res) => {
        const userId = req.userId;
        const repaymentId = Number(req.params.id);
        try {
          const context = await requireOrganizationMatchingFundAccess(userId);
          if (!Number.isFinite(repaymentId) || repaymentId <= 0) {
            return res.status(400).json({ message: "Invalid repayment id." });
          }
          const parsed = external_exports.object({
            amount: external_exports.coerce.number().positive()
          }).safeParse(req.body ?? {});
          if (!parsed.success) {
            return res.status(400).json({ errors: parsed.error.flatten() });
          }
          const paymentAmount = parsed.data.amount;
          if (hasMoreThanTwoDecimalPlaces(paymentAmount)) {
            return res.status(400).json({
              message: "Payment amount can have at most 2 decimal places."
            });
          }
          const result = await db.transaction(async (tx) => {
            const [repaymentRow] = await tx.select({
              id: helpingHandRepaymentsTable.id,
              helpingHandApplicationId: helpingHandRepaymentsTable.helpingHandApplicationId,
              dueDate: helpingHandRepaymentsTable.dueDate,
              amount: helpingHandRepaymentsTable.amount,
              paidAmount: helpingHandRepaymentsTable.paidAmount,
              paidAt: helpingHandRepaymentsTable.paidAt,
              status: helpingHandRepaymentsTable.status,
              method: helpingHandRepaymentsTable.method,
              createdAt: helpingHandRepaymentsTable.createdAt,
              updatedAt: helpingHandRepaymentsTable.updatedAt,
              applicationUserId: helpingHandApplicationsTable.userId,
              applicationStatus: helpingHandApplicationsTable.status,
              applicationOrganizationId: helpingHandApplicationsTable.organizationId
            }).from(helpingHandRepaymentsTable).innerJoin(
              helpingHandApplicationsTable,
              eq(
                helpingHandRepaymentsTable.helpingHandApplicationId,
                helpingHandApplicationsTable.id
              )
            ).where(eq(helpingHandRepaymentsTable.id, repaymentId));
            if (!repaymentRow) {
              return {
                status: 404,
                body: { message: "Repayment not found." }
              };
            }
            if (repaymentRow.applicationUserId !== userId) {
              return {
                status: 403,
                body: { message: "Not authorized to pay this repayment." }
              };
            }
            if (repaymentRow.applicationOrganizationId !== context.organization.id) {
              return {
                status: 403,
                body: {
                  message: "Not authorized to pay this organization's repayment."
                }
              };
            }
            if (!["FUNDED", "REPAYING"].includes(repaymentRow.applicationStatus)) {
              return {
                status: 400,
                body: {
                  message: "Repayments can only be paid while the Matching Fund case is funded or repaying."
                }
              };
            }
            if (["PAID", "WAIVED"].includes(repaymentRow.status)) {
              return {
                status: 400,
                body: {
                  message: "This repayment cannot accept additional payments."
                }
              };
            }
            const installmentAmount = Number(repaymentRow.amount);
            const currentPaidAmount = Number(repaymentRow.paidAmount ?? 0);
            const remainingAmount = Math.max(
              installmentAmount - currentPaidAmount,
              0
            );
            if (paymentAmount > remainingAmount) {
              return {
                status: 400,
                body: {
                  message: "Payment amount cannot exceed the remaining balance for this installment."
                }
              };
            }
            const userWallet = await ensureWalletWith3(
              tx,
              "USER",
              userId
            );
            const walletFunds = await getWalletFundsWith(
              tx,
              userWallet.id
            );
            if (walletFunds.availableBalance < paymentAmount) {
              return {
                status: 400,
                body: { message: "Insufficient available wallet balance." }
              };
            }
            const masterWallet = await ensureLendingMasterWalletWith2(
              tx
            );
            await tx.insert(walletTransactionsTable).values({
              type: "HELPING_HAND_REPAYMENT",
              fromWalletId: userWallet.id,
              toWalletId: masterWallet.id,
              amount: formatMoneyAmount(paymentAmount),
              metadata: {
                helpingHandApplicationId: repaymentRow.helpingHandApplicationId,
                helpingHandRepaymentId: repaymentRow.id,
                userId,
                organizationId: context.organization.id,
                source: "HELPING_HAND_REPAYMENT"
              }
            });
            const nextPaidAmount = Number(
              formatMoneyAmount(currentPaidAmount + paymentAmount)
            );
            const isSettled = nextPaidAmount >= installmentAmount;
            const nextStatus = isSettled ? "PAID" : repaymentRow.dueDate.getTime() < Date.now() ? "LATE" : "PENDING";
            const [updated] = await tx.update(helpingHandRepaymentsTable).set({
              paidAmount: isSettled ? formatMoneyAmount(installmentAmount) : formatMoneyAmount(nextPaidAmount),
              paidAt: isSettled ? /* @__PURE__ */ new Date() : null,
              status: nextStatus,
              method: "WALLET",
              updatedAt: /* @__PURE__ */ new Date()
            }).where(eq(helpingHandRepaymentsTable.id, repaymentId)).returning();
            const applicationRepayments = await tx.select({ status: helpingHandRepaymentsTable.status }).from(helpingHandRepaymentsTable).where(
              eq(
                helpingHandRepaymentsTable.helpingHandApplicationId,
                repaymentRow.helpingHandApplicationId
              )
            );
            const hasOutstandingRepayments = applicationRepayments.some(
              (repayment) => !["PAID", "WAIVED"].includes(repayment.status)
            );
            const nextApplicationStatus = hasOutstandingRepayments ? repaymentRow.applicationStatus === "FUNDED" ? "REPAYING" : repaymentRow.applicationStatus : "CLOSED";
            if (nextApplicationStatus !== repaymentRow.applicationStatus) {
              await tx.update(helpingHandApplicationsTable).set({
                status: nextApplicationStatus,
                updatedAt: /* @__PURE__ */ new Date()
              }).where(
                eq(
                  helpingHandApplicationsTable.id,
                  repaymentRow.helpingHandApplicationId
                )
              );
            }
            const nextWalletBalance = walletFunds.balance - paymentAmount;
            return {
              status: 200,
              body: {
                repayment: serializeHelpingHandRepayment(updated),
                walletBalance: Number(formatMoneyAmount(nextWalletBalance))
              }
            };
          });
          if (result.status === 200) {
            await updateCreditScore(userId);
          }
          return res.status(result.status).json(result.body);
        } catch (err) {
          return handleError4(err, res);
        }
      }
    );
    router5.post(
      "/org/susu/helping-hand/applications/:id/payments",
      requireAuth,
      async (req, res) => {
        const userId = req.userId;
        const applicationId = Number(req.params.id);
        try {
          const context = await requireOrganizationMatchingFundAccess(userId);
          if (!Number.isFinite(applicationId) || applicationId <= 0) {
            return res.status(400).json({ message: "Invalid application id." });
          }
          const parsed = external_exports.object({
            amount: external_exports.coerce.number().positive().optional(),
            payAll: external_exports.coerce.boolean().optional()
          }).safeParse(req.body ?? {});
          if (!parsed.success) {
            return res.status(400).json({ errors: parsed.error.flatten() });
          }
          if (!parsed.data.payAll && parsed.data.amount == null) {
            return res.status(400).json({
              message: "Provide an amount or set payAll to true."
            });
          }
          if (parsed.data.amount != null && hasMoreThanTwoDecimalPlaces(parsed.data.amount)) {
            return res.status(400).json({
              message: "Payment amount can have at most 2 decimal places."
            });
          }
          const result = await db.transaction(async (tx) => {
            const [application] = await tx.select({
              id: helpingHandApplicationsTable.id,
              userId: helpingHandApplicationsTable.userId,
              status: helpingHandApplicationsTable.status,
              organizationId: helpingHandApplicationsTable.organizationId
            }).from(helpingHandApplicationsTable).where(
              and(
                eq(helpingHandApplicationsTable.id, applicationId),
                eq(helpingHandApplicationsTable.userId, userId),
                eq(
                  helpingHandApplicationsTable.organizationId,
                  context.organization.id
                )
              )
            );
            if (!application) {
              return {
                status: 404,
                body: { message: "Matching Fund application not found." }
              };
            }
            if (!["FUNDED", "REPAYING"].includes(application.status)) {
              return {
                status: 400,
                body: {
                  message: "Loan repayments can only be made while the Matching Fund case is funded or repaying."
                }
              };
            }
            const repayments = await tx.select().from(helpingHandRepaymentsTable).where(
              eq(
                helpingHandRepaymentsTable.helpingHandApplicationId,
                applicationId
              )
            ).orderBy(asc(helpingHandRepaymentsTable.dueDate));
            if (!repayments.length) {
              return {
                status: 400,
                body: { message: "No repayment schedule exists for this loan." }
              };
            }
            const toCents = (value) => Math.round(value * 100);
            const fromCents = (cents) => cents / 100;
            const outstandingCents = repayments.reduce((sum3, repayment) => {
              if (["PAID", "WAIVED"].includes(repayment.status)) return sum3;
              const installmentCents = toCents(parseMoneyAmount(repayment.amount));
              const paidCents = toCents(parseMoneyAmount(repayment.paidAmount));
              return sum3 + Math.max(0, installmentCents - paidCents);
            }, 0);
            if (outstandingCents <= 0) {
              return {
                status: 400,
                body: { message: "This loan has no outstanding balance." }
              };
            }
            const requestedCents = parsed.data.payAll ? outstandingCents : toCents(Number(parsed.data.amount ?? 0));
            if (requestedCents <= 0) {
              return {
                status: 400,
                body: { message: "Invalid payment amount." }
              };
            }
            if (requestedCents > outstandingCents) {
              return {
                status: 400,
                body: {
                  message: "Payment amount cannot exceed the outstanding balance."
                }
              };
            }
            const paymentAmount = fromCents(requestedCents);
            const userWallet = await ensureWalletWith3(
              tx,
              "USER",
              userId
            );
            const walletFunds = await getWalletFundsWith(
              tx,
              userWallet.id
            );
            if (walletFunds.availableBalance < paymentAmount) {
              return {
                status: 400,
                body: { message: "Insufficient available wallet balance." }
              };
            }
            const masterWallet = await ensureLendingMasterWalletWith2(
              tx
            );
            const [walletTransaction] = await tx.insert(walletTransactionsTable).values({
              type: "HELPING_HAND_REPAYMENT",
              fromWalletId: userWallet.id,
              toWalletId: masterWallet.id,
              amount: formatMoneyAmount(paymentAmount),
              metadata: {
                helpingHandApplicationId: applicationId,
                userId,
                organizationId: context.organization.id,
                source: "HELPING_HAND_REPAYMENT"
              }
            }).returning();
            let remainingPaymentCents = requestedCents;
            const now = /* @__PURE__ */ new Date();
            for (const repayment of repayments) {
              if (remainingPaymentCents <= 0) break;
              if (["PAID", "WAIVED"].includes(repayment.status)) continue;
              const installmentCents = toCents(parseMoneyAmount(repayment.amount));
              const paidCents = toCents(parseMoneyAmount(repayment.paidAmount));
              const remainingInstallmentCents = Math.max(
                0,
                installmentCents - paidCents
              );
              if (remainingInstallmentCents <= 0) continue;
              const appliedCents = Math.min(
                remainingInstallmentCents,
                remainingPaymentCents
              );
              if (appliedCents <= 0) continue;
              const nextPaidCents = paidCents + appliedCents;
              const isSettled = nextPaidCents >= installmentCents;
              const nextStatus = isSettled ? "PAID" : repayment.dueDate.getTime() < now.getTime() ? "LATE" : "PENDING";
              const nextPaidAmount = isSettled ? fromCents(installmentCents) : fromCents(nextPaidCents);
              await tx.update(helpingHandRepaymentsTable).set({
                paidAmount: formatMoneyAmount(nextPaidAmount),
                paidAt: isSettled ? now : null,
                status: nextStatus,
                method: "WALLET",
                updatedAt: now
              }).where(eq(helpingHandRepaymentsTable.id, repayment.id));
              remainingPaymentCents -= appliedCents;
            }
            if (remainingPaymentCents !== 0) {
              return {
                status: 500,
                body: { message: "Failed to fully allocate this payment." }
              };
            }
            const outstandingAfter = await tx.select({ status: helpingHandRepaymentsTable.status }).from(helpingHandRepaymentsTable).where(
              eq(
                helpingHandRepaymentsTable.helpingHandApplicationId,
                applicationId
              )
            );
            const hasOutstandingRepayments = outstandingAfter.some(
              (repayment) => !["PAID", "WAIVED"].includes(repayment.status)
            );
            const nextApplicationStatus = hasOutstandingRepayments ? application.status === "FUNDED" ? "REPAYING" : application.status : "CLOSED";
            if (nextApplicationStatus !== application.status) {
              await tx.update(helpingHandApplicationsTable).set({
                status: nextApplicationStatus,
                updatedAt: now
              }).where(eq(helpingHandApplicationsTable.id, applicationId));
            }
            const nextWalletBalance = walletFunds.balance - paymentAmount;
            return {
              status: 200,
              body: {
                appliedAmount: Number(formatMoneyAmount(paymentAmount)),
                walletBalance: Number(formatMoneyAmount(nextWalletBalance)),
                applicationStatus: nextApplicationStatus,
                walletTransactionId: walletTransaction?.id ?? null
              }
            };
          });
          if (result.status === 200) {
            await updateCreditScore(userId);
          }
          return res.status(result.status).json(result.body);
        } catch (err) {
          return handleError4(err, res);
        }
      }
    );
    org_default = router5;
  }
});

// src/routes/plans.ts
var plans_exports = {};
__export(plans_exports, {
  default: () => plans_default
});
function optionalAuth(req, _res, next) {
  void (async () => {
    const user = await resolveAuthenticatedUser(req.cookies?.wwn_token);
    if (user) {
      req.userId = user.id;
    }
    next();
  })();
}
var import_express6, router6, plans_default;
var init_plans = __esm({
  "src/routes/plans.ts"() {
    "use strict";
    import_express6 = __toESM(require_express2(), 1);
    init_zod();
    init_src2();
    init_schema2();
    init_drizzle_orm();
    init_auth_session();
    router6 = (0, import_express6.Router)();
    router6.get("/plans", optionalAuth, async (_req, res) => {
      try {
        const plans = await db.select().from(membershipPlansTable).where(eq(membershipPlansTable.isActive, true)).orderBy(
          asc(membershipPlansTable.membershipType),
          asc(membershipPlansTable.sortOrder),
          asc(membershipPlansTable.priceAnnual)
        );
        const sanitizedPlans = plans.map((plan) => {
          const { priceMonthly: _priceMonthly, ...rest } = plan;
          return rest;
        });
        return res.json({ plans: sanitizedPlans });
      } catch (err) {
        console.error("Plans fetch error:", err);
        return res.status(500).json({ message: "Failed to fetch plans." });
      }
    });
    router6.post("/payments/webhooks/:provider", async (req, res) => {
      try {
        const secret = process.env.PAYMENT_WEBHOOK_SECRET;
        if (!secret) {
          return res.status(404).json({ message: "Not found." });
        }
        const provided = req.headers["x-webhook-secret"];
        if (typeof provided !== "string" || provided !== secret) {
          return res.status(401).json({ message: "Unauthorized." });
        }
        const provider = String(req.params.provider ?? "").toUpperCase();
        if (provider !== "STRIPE" && provider !== "INTERAC" && provider !== "MANUAL") {
          return res.status(400).json({ message: "Unsupported provider." });
        }
        const parsed = external_exports.object({
          id: external_exports.string().optional(),
          type: external_exports.string().optional()
        }).passthrough().safeParse(req.body ?? {});
        if (!parsed.success) {
          return res.status(400).json({ errors: parsed.error.flatten() });
        }
        const headerEventId = req.headers["x-event-id"];
        const eventId = parsed.data.id?.trim() || (typeof headerEventId === "string" ? headerEventId.trim() : "");
        if (!eventId) {
          return res.status(400).json({ message: "Missing event id." });
        }
        const eventType = parsed.data.type?.trim() || "unknown";
        const payload = parsed.data;
        const [inserted] = await db.insert(paymentWebhookEventsTable).values({
          provider,
          eventId,
          eventType,
          payload,
          status: "PENDING"
        }).onConflictDoNothing().returning();
        return res.status(200).json({
          received: true,
          duplicate: !inserted
        });
      } catch (err) {
        console.error("POST /payments/webhooks error:", err);
        return res.status(500).json({ message: "Failed to receive webhook." });
      }
    });
    plans_default = router6;
  }
});

// src/routes/payments.ts
var payments_exports = {};
__export(payments_exports, {
  default: () => payments_default
});
async function ensureWalletWithPayment(conn, ownerType, ownerId) {
  const existing = await conn.select().from(walletsTable).where(
    and(eq(walletsTable.ownerType, ownerType), eq(walletsTable.ownerId, ownerId))
  );
  if (existing.length) return existing[0];
  const [created] = await conn.insert(walletsTable).values({ ownerType, ownerId }).returning();
  return created;
}
function isRecord3(value) {
  return typeof value === "object" && value !== null;
}
function readString(value) {
  return typeof value === "string" ? value : null;
}
function readNumber(value) {
  if (typeof value === "number" && Number.isFinite(value)) return value;
  if (typeof value === "string" && value.trim().length > 0) {
    const parsed = Number(value);
    return Number.isFinite(parsed) ? parsed : null;
  }
  return null;
}
var import_express7, router7, payments_default;
var init_payments = __esm({
  "src/routes/payments.ts"() {
    "use strict";
    import_express7 = __toESM(require_express2(), 1);
    init_src2();
    init_schema2();
    init_drizzle_orm();
    init_notification_dispatcher();
    init_organization_context();
    init_stripe();
    init_investment_constants();
    router7 = (0, import_express7.Router)();
    router7.post("/payments/webhooks/stripe", async (req, res) => {
      try {
        const rawBody = req.body;
        if (!Buffer.isBuffer(rawBody)) {
          return res.status(400).json({ message: "Invalid webhook body." });
        }
        const signature = req.headers["stripe-signature"];
        if (typeof signature !== "string" || !signature.trim()) {
          return res.status(400).json({ message: "Missing stripe signature." });
        }
        const stripe = getStripeClient();
        const webhookSecret = getStripeWebhookSecret();
        let event;
        try {
          event = stripe.webhooks.constructEvent(rawBody, signature, webhookSecret);
        } catch (err) {
          return res.status(400).json({
            message: "Invalid signature.",
            error: err instanceof Error ? err.message : String(err)
          });
        }
        if (!isRecord3(event)) {
          return res.status(400).json({ message: "Invalid webhook payload." });
        }
        const eventId = readString(event.id) ?? "";
        const eventType = readString(event.type) ?? "unknown";
        const result = await db.transaction(async (tx) => {
          const now = /* @__PURE__ */ new Date();
          const [inserted] = await tx.insert(paymentWebhookEventsTable).values({
            provider: "STRIPE",
            eventId,
            eventType,
            payload: event,
            status: "PENDING",
            attempts: 1
          }).onConflictDoNothing().returning();
          let eventRow = inserted ?? null;
          if (!eventRow) {
            const [existingEvent] = await tx.select().from(paymentWebhookEventsTable).where(
              and(
                eq(paymentWebhookEventsTable.provider, "STRIPE"),
                eq(paymentWebhookEventsTable.eventId, eventId)
              )
            ).limit(1);
            if (!existingEvent) {
              return { duplicate: true };
            }
            if (existingEvent.status !== "FAILED") {
              return { duplicate: true };
            }
            [eventRow] = await tx.update(paymentWebhookEventsTable).set({
              status: "PENDING",
              processedAt: null,
              error: null,
              payload: event,
              attempts: sql`${paymentWebhookEventsTable.attempts} + 1`
            }).where(eq(paymentWebhookEventsTable.id, existingEvent.id)).returning();
            if (!eventRow) {
              return { duplicate: true };
            }
          }
          const finalize = async (status, error40) => {
            await tx.update(paymentWebhookEventsTable).set({
              status,
              processedAt: now,
              error: error40 ?? null
            }).where(eq(paymentWebhookEventsTable.id, eventRow.id));
          };
          try {
            const eventCreatedAtRaw = readNumber(event.created);
            const eventCreatedAt = eventCreatedAtRaw ? new Date(eventCreatedAtRaw * 1e3) : null;
            if (event.type === "payment_intent.succeeded") {
              const data = isRecord3(event.data) ? event.data : null;
              const paymentIntent = data && isRecord3(data.object) ? data.object : null;
              const metadata = paymentIntent && isRecord3(paymentIntent.metadata) ? paymentIntent.metadata : null;
              const walletPaymentIntentId = Number(
                (metadata && readString(metadata.walletPaymentIntentId)) ?? 0
              );
              const intentType = (metadata && readString(metadata.intentType)) ?? "";
              const paymentIntentId = paymentIntent ? readString(paymentIntent.id) ?? "" : "";
              if (walletPaymentIntentId > 0 && intentType === "TOP_UP") {
                const [walletIntent] = await tx.select().from(walletPaymentIntentsTable).where(eq(walletPaymentIntentsTable.id, walletPaymentIntentId)).limit(1);
                if (walletIntent && walletIntent.provider === "STRIPE" && walletIntent.type === "TOP_UP" && walletIntent.status !== "SUCCEEDED") {
                  const idempotencyKey = `wallet-topup-intent:${walletIntent.id}:stripe:${paymentIntentId}`;
                  await tx.insert(walletTransactionsTable).values({
                    type: "TOP_UP",
                    idempotencyKey,
                    toWalletId: walletIntent.walletId,
                    amount: walletIntent.amount,
                    metadata: {
                      intentId: walletIntent.id,
                      provider: "STRIPE",
                      providerReference: paymentIntentId,
                      fundingMethod: "STRIPE"
                    }
                  }).onConflictDoNothing();
                  await tx.update(walletPaymentIntentsTable).set({
                    status: "SUCCEEDED",
                    providerReference: paymentIntentId,
                    updatedAt: now
                  }).where(eq(walletPaymentIntentsTable.id, walletIntent.id));
                }
              }
              await finalize("PROCESSED");
              return { duplicate: false };
            }
            if (event.type === "payment_intent.payment_failed" || event.type === "payment_intent.canceled") {
              const data = isRecord3(event.data) ? event.data : null;
              const paymentIntent = data && isRecord3(data.object) ? data.object : null;
              const metadata = paymentIntent && isRecord3(paymentIntent.metadata) ? paymentIntent.metadata : null;
              const walletPaymentIntentId = Number(
                (metadata && readString(metadata.walletPaymentIntentId)) ?? 0
              );
              const intentType = (metadata && readString(metadata.intentType)) ?? "";
              const paymentIntentId = paymentIntent ? readString(paymentIntent.id) ?? "" : "";
              if (walletPaymentIntentId > 0 && intentType === "TOP_UP") {
                await tx.update(walletPaymentIntentsTable).set({
                  status: "FAILED",
                  providerReference: paymentIntentId,
                  updatedAt: now
                }).where(eq(walletPaymentIntentsTable.id, walletPaymentIntentId));
              }
              await finalize("PROCESSED");
              return { duplicate: false };
            }
            if (event.type === "invoice.payment_failed") {
              const data = isRecord3(event.data) ? event.data : null;
              const invoice = data && isRecord3(data.object) ? data.object : null;
              const stripeSubscriptionId = invoice ? readString(invoice.subscription) ?? "" : "";
              if (!stripeSubscriptionId) {
                await finalize("PROCESSED");
                return { duplicate: false };
              }
              const [subRow] = await tx.select({
                subscription: membershipSubscriptionsTable,
                plan: membershipPlansTable,
                user: usersTable
              }).from(membershipSubscriptionsTable).innerJoin(
                membershipPlansTable,
                eq(membershipSubscriptionsTable.planId, membershipPlansTable.id)
              ).innerJoin(
                usersTable,
                eq(membershipSubscriptionsTable.userId, usersTable.id)
              ).where(
                eq(
                  membershipSubscriptionsTable.stripeSubscriptionId,
                  stripeSubscriptionId
                )
              ).limit(1);
              if (!subRow?.subscription || !subRow.plan || !subRow.user) {
                await finalize("PROCESSED");
                return { duplicate: false };
              }
              if (eventCreatedAt && subRow.subscription.updatedAt && eventCreatedAt < subRow.subscription.updatedAt) {
                await finalize("PROCESSED");
                return { duplicate: false };
              }
              await tx.update(membershipSubscriptionsTable).set({
                status: "PENDING",
                updatedAt: now
              }).where(eq(membershipSubscriptionsTable.id, subRow.subscription.id));
              await tx.update(usersTable).set({
                membershipStatus: "PENDING",
                updatedAt: now
              }).where(eq(usersTable.id, subRow.user.id));
              await syncOrganizationSubscriptionStateWith(tx, {
                user: subRow.user,
                plan: subRow.plan,
                status: "PENDING",
                now,
                startDate: subRow.subscription.startDate,
                endDate: subRow.subscription.endDate,
                renewsAt: subRow.subscription.renewsAt,
                stripeCustomerId: subRow.subscription.stripeCustomerId,
                stripeSubscriptionId: subRow.subscription.stripeSubscriptionId
              });
              await finalize("PROCESSED");
              return { duplicate: false };
            }
            if (event.type === "invoice.payment_succeeded") {
              const data = isRecord3(event.data) ? event.data : null;
              const invoice = data && isRecord3(data.object) ? data.object : null;
              const stripeSubscriptionId = invoice ? readString(invoice.subscription) ?? "" : "";
              const stripePaymentIntentId = invoice ? readString(invoice.payment_intent) ?? "" : "";
              if (!stripeSubscriptionId) {
                await finalize("PROCESSED");
                return { duplicate: false };
              }
              const [subRow] = await tx.select({
                subscription: membershipSubscriptionsTable,
                plan: membershipPlansTable,
                user: usersTable
              }).from(membershipSubscriptionsTable).innerJoin(
                membershipPlansTable,
                eq(membershipSubscriptionsTable.planId, membershipPlansTable.id)
              ).innerJoin(
                usersTable,
                eq(membershipSubscriptionsTable.userId, usersTable.id)
              ).where(
                eq(
                  membershipSubscriptionsTable.stripeSubscriptionId,
                  stripeSubscriptionId
                )
              ).limit(1);
              if (!subRow?.subscription || !subRow.plan || !subRow.user) {
                await finalize("PROCESSED");
                return { duplicate: false };
              }
              if (eventCreatedAt && subRow.subscription.updatedAt && eventCreatedAt < subRow.subscription.updatedAt) {
                await finalize("PROCESSED");
                return { duplicate: false };
              }
              const planCycle = subRow.plan.defaultBillingCycle === "MONTHLY" ? "MONTHLY" : "ANNUAL";
              const cycleLabel = planCycle === "MONTHLY" ? "Stripe monthly" : "Stripe annual";
              const renewalDate = new Date(now);
              if (planCycle === "MONTHLY") {
                renewalDate.setMonth(renewalDate.getMonth() + 1);
              } else {
                renewalDate.setFullYear(renewalDate.getFullYear() + 1);
              }
              const [existingInvoice] = await tx.select().from(invoicesTable).where(
                and(
                  eq(invoicesTable.subscriptionId, subRow.subscription.id),
                  inArray(invoicesTable.status, ["SENT", "OVERDUE"])
                )
              ).orderBy(desc(invoicesTable.createdAt)).limit(1);
              let invoiceRow = existingInvoice ?? null;
              if (invoiceRow) {
                await tx.update(invoicesTable).set({
                  status: "PAID",
                  paidAt: now,
                  updatedAt: now
                }).where(eq(invoicesTable.id, invoiceRow.id));
              } else {
                const amountPaid = (invoice ? readNumber(invoice.amount_paid) ?? 0 : 0) / 100;
                const [createdInvoice] = await tx.insert(invoicesTable).values({
                  userId: subRow.user.id,
                  subscriptionId: subRow.subscription.id,
                  invoiceNumber: `STRIPE-${invoice ? readString(invoice.id) ?? String(Date.now()) : String(Date.now())}`,
                  amount: amountPaid.toFixed(2),
                  currency: subRow.plan.currency,
                  status: "PAID",
                  dueDate: now,
                  paidAt: now,
                  lineItems: [
                    {
                      description: `${subRow.plan.name} membership (${cycleLabel})`,
                      quantity: 1,
                      unitPrice: amountPaid,
                      total: amountPaid
                    }
                  ],
                  updatedAt: now
                }).returning();
                invoiceRow = createdInvoice;
              }
              const [existingPayment] = await tx.select().from(paymentsTable).where(
                and(
                  eq(paymentsTable.invoiceId, invoiceRow.id),
                  eq(paymentsTable.status, "PENDING")
                )
              ).orderBy(desc(paymentsTable.createdAt)).limit(1);
              if (existingPayment) {
                await tx.update(paymentsTable).set({
                  status: "COMPLETED",
                  reference: stripePaymentIntentId || existingPayment.reference,
                  processedAt: now,
                  updatedAt: now
                }).where(eq(paymentsTable.id, existingPayment.id));
              } else {
                const amountPaid = (invoice ? readNumber(invoice.amount_paid) ?? 0 : 0) / 100;
                await tx.insert(paymentsTable).values({
                  userId: subRow.user.id,
                  amount: amountPaid.toFixed(2),
                  currency: subRow.plan.currency,
                  method: "STRIPE",
                  status: "COMPLETED",
                  reference: stripePaymentIntentId || null,
                  description: `${subRow.plan.name} membership payment (Stripe)`,
                  metadata: {
                    activationType: "membership_stripe",
                    stripeInvoiceId: invoice ? readString(invoice.id) ?? "" : "",
                    stripeSubscriptionId
                  },
                  invoiceId: invoiceRow.id,
                  processedAt: now,
                  updatedAt: now
                }).returning();
              }
              await tx.update(membershipSubscriptionsTable).set({
                status: "ACTIVE",
                startDate: now,
                endDate: renewalDate,
                renewsAt: renewalDate,
                updatedAt: now
              }).where(eq(membershipSubscriptionsTable.id, subRow.subscription.id));
              await tx.update(usersTable).set({
                membershipStatus: "ACTIVE",
                updatedAt: now
              }).where(eq(usersTable.id, subRow.user.id));
              if (subRow.plan.membershipType === "INVESTOR") {
                const amountPaidForWallet = (invoice ? readNumber(invoice.amount_paid) ?? 0 : 0) / 100;
                if (amountPaidForWallet > 0) {
                  const investmentWallet = await ensureWalletWithPayment(
                    tx,
                    "INVESTMENT",
                    INVESTMENT_WALLET_OWNER_ID
                  );
                  const creditIdempotencyKey = subRow.plan.billingMode === "ONE_TIME" ? `investment_membership_onetime:${subRow.subscription.id}:invoice:${invoice ? readString(invoice.id) ?? "unknown" : "unknown"}` : `investment_membership_renewal:${subRow.subscription.id}:invoice:${invoice ? readString(invoice.id) ?? "unknown" : "unknown"}`;
                  await tx.insert(walletTransactionsTable).values({
                    type: "MEMBERSHIP_DONATION",
                    toWalletId: investmentWallet.id,
                    amount: amountPaidForWallet.toFixed(2),
                    currency: subRow.plan.currency,
                    idempotencyKey: creditIdempotencyKey,
                    metadata: {
                      source: "stripe_invoice_payment_succeeded",
                      fundingIntent: "INVESTMENT_TREASURY",
                      membershipBillingMode: subRow.plan.billingMode,
                      membershipSubscriptionId: subRow.subscription.id,
                      userId: subRow.user.id,
                      userSegment: subRow.user.segment ?? null,
                      investorCategory: subRow.user.investorCategory ?? null,
                      planTier: subRow.plan.tier,
                      planId: subRow.plan.id,
                      stripeInvoiceId: invoice ? readString(invoice.id) ?? "" : "",
                      stripeSubscriptionId
                    },
                    createdAt: now
                  }).onConflictDoNothing();
                }
              }
              await syncOrganizationSubscriptionStateWith(tx, {
                user: subRow.user,
                plan: subRow.plan,
                status: "ACTIVE",
                now,
                startDate: now,
                endDate: renewalDate,
                renewsAt: renewalDate,
                stripeCustomerId: subRow.subscription.stripeCustomerId,
                stripeSubscriptionId: subRow.subscription.stripeSubscriptionId
              });
              const amountLabel = new Intl.NumberFormat("en-CA", {
                style: "currency",
                currency: subRow.plan.currency,
                maximumFractionDigits: 2
              }).format(Number(subRow.plan.priceAnnual));
              await notifyInAppWith(tx, {
                userId: subRow.user.id,
                category: "MEMBERSHIP",
                severity: "SUCCESS",
                title: "Membership activated",
                body: `Your ${subRow.plan.name} membership is now active. We confirmed your ${amountLabel} payment.`,
                actionLabel: "Open Billing",
                actionHref: "/dashboard/billing"
              });
              await finalize("PROCESSED");
              return { duplicate: false };
            }
            if (event.type === "customer.subscription.deleted" || event.type === "customer.subscription.updated") {
              const data = isRecord3(event.data) ? event.data : null;
              const subscription = data && isRecord3(data.object) ? data.object : null;
              const stripeSubscriptionId = subscription ? readString(subscription.id) ?? "" : "";
              const stripeStatus = subscription ? readString(subscription.status) ?? "" : "";
              if (!stripeSubscriptionId) {
                await finalize("PROCESSED");
                return { duplicate: false };
              }
              const nextState = event.type === "customer.subscription.deleted" || stripeStatus === "canceled" || stripeStatus === "unpaid" || stripeStatus === "incomplete_expired" ? "CANCELLED" : stripeStatus === "past_due" ? "PENDING" : null;
              if (!nextState) {
                await finalize("PROCESSED");
                return { duplicate: false };
              }
              const [subRow] = await tx.select({
                subscription: membershipSubscriptionsTable,
                plan: membershipPlansTable,
                user: usersTable
              }).from(membershipSubscriptionsTable).innerJoin(
                membershipPlansTable,
                eq(membershipSubscriptionsTable.planId, membershipPlansTable.id)
              ).innerJoin(
                usersTable,
                eq(membershipSubscriptionsTable.userId, usersTable.id)
              ).where(
                eq(
                  membershipSubscriptionsTable.stripeSubscriptionId,
                  stripeSubscriptionId
                )
              ).limit(1);
              if (!subRow?.subscription || !subRow.plan || !subRow.user) {
                await finalize("PROCESSED");
                return { duplicate: false };
              }
              if (eventCreatedAt && subRow.subscription.updatedAt && eventCreatedAt < subRow.subscription.updatedAt) {
                await finalize("PROCESSED");
                return { duplicate: false };
              }
              await tx.update(membershipSubscriptionsTable).set({
                status: nextState,
                cancelledAt: nextState === "CANCELLED" ? now : null,
                updatedAt: now
              }).where(eq(membershipSubscriptionsTable.id, subRow.subscription.id));
              await tx.update(usersTable).set({
                membershipStatus: nextState,
                updatedAt: now
              }).where(eq(usersTable.id, subRow.user.id));
              await syncOrganizationSubscriptionStateWith(tx, {
                user: subRow.user,
                plan: subRow.plan,
                status: nextState,
                now,
                startDate: subRow.subscription.startDate,
                endDate: subRow.subscription.endDate,
                renewsAt: subRow.subscription.renewsAt,
                stripeCustomerId: subRow.subscription.stripeCustomerId,
                stripeSubscriptionId: subRow.subscription.stripeSubscriptionId
              });
              await finalize("PROCESSED");
              return { duplicate: false };
            }
            await finalize("PROCESSED");
            return { duplicate: false };
          } catch (err) {
            await finalize(
              "FAILED",
              err instanceof Error ? err.message : String(err)
            );
            throw err;
          }
        });
        return res.status(200).json({ received: true, duplicate: result.duplicate });
      } catch (err) {
        console.error("POST /payments/webhooks/stripe error:", err);
        return res.status(500).json({ message: "Failed to process webhook." });
      }
    });
    payments_default = router7;
  }
});

// src/lib/onboarding-cadence.ts
function getUtcDayNumber(date6) {
  return Math.floor(
    Date.UTC(date6.getUTCFullYear(), date6.getUTCMonth(), date6.getUTCDate()) / MS_PER_DAY
  );
}
function getOnboardingIntervalsPassed({
  enrolledAt,
  now,
  durationUnit
}) {
  if (durationUnit === "DAY") {
    return Math.max(0, getUtcDayNumber(now) - getUtcDayNumber(enrolledAt));
  }
  const intervalMs = 7 * MS_PER_DAY;
  return Math.max(0, Math.floor((now.getTime() - enrolledAt.getTime()) / intervalMs));
}
function getOnboardingUnlocksAt({
  enrolledAt,
  intervalIndex,
  durationUnit
}) {
  if (intervalIndex <= 0) return enrolledAt;
  if (durationUnit === "DAY") {
    const startDayNumber = getUtcDayNumber(enrolledAt);
    return new Date((startDayNumber + intervalIndex) * MS_PER_DAY);
  }
  return new Date(enrolledAt.getTime() + intervalIndex * 7 * MS_PER_DAY);
}
function getOnboardingCurrentWeekNumber({
  enrolledAt,
  now,
  durationUnit,
  numberOfWeeks,
  completedWeekNumbers
}) {
  const elapsedWeekNumber = Math.min(
    numberOfWeeks,
    Math.max(
      1,
      getOnboardingIntervalsPassed({
        enrolledAt,
        now,
        durationUnit
      }) + 1
    )
  );
  const completed = new Set(completedWeekNumbers);
  let currentWeekNumber = 1;
  while (currentWeekNumber < elapsedWeekNumber && completed.has(currentWeekNumber)) {
    currentWeekNumber += 1;
  }
  return currentWeekNumber;
}
var MS_PER_DAY;
var init_onboarding_cadence = __esm({
  "src/lib/onboarding-cadence.ts"() {
    "use strict";
    MS_PER_DAY = 24 * 60 * 60 * 1e3;
  }
});

// src/lib/pdf.ts
function escapePdfText(value) {
  return value.replace(/\\/g, "\\\\").replace(/\(/g, "\\(").replace(/\)/g, "\\)");
}
function toAscii(value) {
  return value.replace(/[^\x20-\x7E]/g, "");
}
function pdfRect(x, top, width, height, fillRgb) {
  const y = PAGE_HEIGHT - top - height;
  return `${fillRgb[0]} ${fillRgb[1]} ${fillRgb[2]} rg
${x} ${y} ${width} ${height} re f`;
}
function pdfStrokeRect(x, top, width, height, strokeRgb, lineWidth = 1) {
  const y = PAGE_HEIGHT - top - height;
  return `${lineWidth} w
${strokeRgb[0]} ${strokeRgb[1]} ${strokeRgb[2]} RG
${x} ${y} ${width} ${height} re S`;
}
function pdfText(x, top, text2, font, size, fillRgb) {
  const safe = escapePdfText(toAscii(text2));
  const y = PAGE_HEIGHT - top;
  return `BT
${fillRgb[0]} ${fillRgb[1]} ${fillRgb[2]} rg
/${font} ${size} Tf
1 0 0 1 ${x} ${y} Tm
(${safe}) Tj
ET`;
}
function truncatePdfText(value, maxLength) {
  const ascii = toAscii(value);
  return ascii.length <= maxLength ? ascii : `${ascii.slice(0, maxLength - 3)}...`;
}
function hexToPdfRgb(hex) {
  const normalized = hex.replace("#", "");
  const expanded = normalized.length === 3 ? normalized.split("").map((char2) => char2 + char2).join("") : normalized;
  const int2 = Number.parseInt(expanded, 16);
  return [(int2 >> 16 & 255) / 255, (int2 >> 8 & 255) / 255, (int2 & 255) / 255];
}
function buildMembershipReceiptPdf(data) {
  const commands = [];
  const brandPurple = hexToPdfRgb("#410580");
  const sunset500 = hexToPdfRgb("#c6683c");
  const sunset600 = hexToPdfRgb("#b55a30");
  const sand50 = hexToPdfRgb("#fffdfb");
  const sand100 = hexToPdfRgb("#f9eee6");
  const sand200 = hexToPdfRgb("#f1dfd3");
  const ink = hexToPdfRgb("#2c1a28");
  const muted = hexToPdfRgb("#7a5c67");
  const border = hexToPdfRgb("#efdcd1");
  const olive300 = hexToPdfRgb("#a8b83c");
  const olive500 = hexToPdfRgb("#8e9c14");
  const white = [1, 1, 1];
  commands.push(pdfRect(28, 18, 556, 96, brandPurple));
  commands.push(pdfRect(28, 114, 556, 66, sunset500));
  commands.push(pdfText(48, 58, "WWN", "F2", 30, [1, 1, 1]));
  commands.push(pdfText(48, 80, "WWN - Whole Woman Network", "F1", 12, sand100));
  commands.push(pdfText(395, 48, truncatePdfText(data.invoiceNumber, 28), "F2", 14, white));
  commands.push(pdfText(462, 78, "PAYMENT RECEIPT", "F2", 11, sand50));
  commands.push(pdfText(50, 150, "AMOUNT PAID", "F2", 12, sand100));
  commands.push(pdfText(404, 164, `${data.currency} ${data.amountPaid}`, "F2", 26, white));
  commands.push(pdfRect(28, 190, 180, 28, sand100));
  commands.push(pdfRect(218, 190, 180, 28, sand100));
  commands.push(pdfRect(408, 190, 176, 28, sand200));
  commands.push(pdfText(40, 208, `INVOICE ${data.invoiceStatus}`, "F2", 10, olive500));
  commands.push(pdfText(230, 208, `PAYMENT ${data.paymentStatus}`, "F2", 10, olive500));
  commands.push(pdfText(420, 208, data.paymentMethod, "F2", 10, brandPurple));
  commands.push(pdfStrokeRect(28, 234, 270, 164, border));
  commands.push(pdfStrokeRect(314, 234, 270, 164, border));
  commands.push(pdfRect(28, 234, 270, 2, sunset500));
  commands.push(pdfRect(314, 234, 270, 2, sunset500));
  commands.push(pdfText(42, 258, "MEMBER INFORMATION", "F2", 11, sunset500));
  commands.push(pdfText(328, 258, "PAYMENT INFORMATION", "F2", 11, sunset500));
  const memberRows = [
    ["Member Name", data.memberName],
    ["Email", data.memberEmail],
    ["Membership", data.membershipType],
    ["Plan", data.planName]
  ];
  memberRows.forEach(([label, value], index2) => {
    const top = 300 + index2 * 26;
    commands.push(pdfText(44, top, label, "F1", 11, muted));
    commands.push(pdfText(140, top, truncatePdfText(value, 28), "F2", 11, ink));
    if (index2 < memberRows.length - 1) {
      commands.push(pdfStrokeRect(42, top + 8, 226, 0.5, border, 0.5));
    }
  });
  const paymentRows = [
    ["Tier", data.planTier],
    ["Method", data.paymentMethod],
    ["Reference", data.paymentReference],
    ["Paid At", data.paidAt]
  ];
  paymentRows.forEach(([label, value], index2) => {
    const top = 300 + index2 * 26;
    commands.push(pdfText(330, top, label, "F1", 11, muted));
    commands.push(pdfText(438, top, truncatePdfText(value, 24), "F2", 11, ink));
    if (index2 < paymentRows.length - 1) {
      commands.push(pdfStrokeRect(328, top + 8, 226, 0.5, border, 0.5));
    }
  });
  commands.push(pdfText(34, 430, "LINE ITEMS", "F2", 11, sunset500));
  commands.push(pdfRect(28, 448, 556, 36, brandPurple));
  commands.push(pdfText(46, 470, "DESCRIPTION", "F2", 12, white));
  commands.push(pdfText(520, 470, "AMOUNT", "F2", 12, white));
  let rowTop = 484;
  data.lineItems.forEach((item) => {
    commands.push(pdfStrokeRect(28, rowTop, 556, 42, border, 0.7));
    commands.push(pdfText(46, rowTop + 24, truncatePdfText(item.description, 52), "F1", 12, ink));
    commands.push(pdfText(495, rowTop + 24, `${data.currency} ${item.amount}`, "F1", 12, ink));
    rowTop += 42;
  });
  commands.push(pdfStrokeRect(28, rowTop, 556, 40, border, 0.7));
  commands.push(pdfText(46, rowTop + 24, "Subtotal", "F1", 11, muted));
  commands.push(pdfText(500, rowTop + 24, `${data.currency} ${data.amountPaid}`, "F1", 11, muted));
  rowTop += 40;
  commands.push(pdfRect(28, rowTop, 556, 42, sunset600));
  commands.push(pdfText(46, rowTop + 26, "TOTAL", "F2", 14, white));
  commands.push(pdfText(488, rowTop + 26, `${data.currency} ${data.amountPaid}`, "F2", 18, white));
  rowTop += 58;
  if (data.renewsAt && data.renewsAt.trim()) {
    commands.push(pdfRect(28, rowTop, 556, 62, sand50));
    commands.push(pdfRect(42, rowTop + 16, 10, 16, olive300));
    commands.push(pdfText(74, rowTop + 24, "RENEWAL DATE", "F2", 10, olive500));
    commands.push(
      pdfText(
        74,
        rowTop + 42,
        truncatePdfText(
          `Your membership renews on ${data.renewsAt}. A reminder will be sent before your renewal date.`,
          84
        ),
        "F1",
        11,
        ink
      )
    );
  }
  commands.push(
    pdfText(
      120,
      744,
      `This is an official receipt for your records. For support, contact us at ${data.supportEmail}`,
      "F1",
      10,
      muted
    )
  );
  const content = commands.join("\n");
  const objects = [
    "<< /Type /Catalog /Pages 2 0 R >>",
    "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
    "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R /F2 6 0 R >> >> >>",
    `<< /Length ${Buffer.byteLength(content, "utf8")} >>
stream
${content}
endstream`,
    "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
    "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >>"
  ];
  let pdf = "%PDF-1.4\n";
  const offsets = [0];
  objects.forEach((object2, index2) => {
    offsets.push(Buffer.byteLength(pdf, "utf8"));
    pdf += `${index2 + 1} 0 obj
${object2}
endobj
`;
  });
  const xrefOffset = Buffer.byteLength(pdf, "utf8");
  pdf += `xref
0 ${objects.length + 1}
`;
  pdf += "0000000000 65535 f \n";
  for (let index2 = 1; index2 <= objects.length; index2 += 1) {
    pdf += `${String(offsets[index2]).padStart(10, "0")} 00000 n 
`;
  }
  pdf += `trailer
<< /Size ${objects.length + 1} /Root 1 0 R >>
startxref
${xrefOffset}
%%EOF`;
  return Buffer.from(pdf, "utf8");
}
var PAGE_HEIGHT;
var init_pdf = __esm({
  "src/lib/pdf.ts"() {
    "use strict";
    PAGE_HEIGHT = 792;
  }
});

// src/routes/member.ts
var member_exports = {};
__export(member_exports, {
  default: () => member_default
});
import { readFileSync as readFileSync3 } from "node:fs";
async function reportOrgGatingDebug2(input) {
  if (process.env.ENABLE_ORG_GATING_DEBUG !== "true") {
    return;
  }
  let debugServerUrl = "http://127.0.0.1:7777/event";
  let sessionId = "org-entitlement-gating";
  try {
    const envText = readFileSync3(".dbg/org-entitlement-gating.env", "utf8");
    debugServerUrl = envText.match(/DEBUG_SERVER_URL=(.+)/)?.[1]?.trim() ?? debugServerUrl;
    sessionId = envText.match(/DEBUG_SESSION_ID=(.+)/)?.[1]?.trim() ?? sessionId;
  } catch {
  }
  await fetch(debugServerUrl, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      sessionId,
      runId: "pre-fix",
      hypothesisId: input.hypothesisId,
      location: input.location,
      msg: `[DEBUG] ${input.msg}`,
      data: input.data ?? {},
      traceId: input.traceId,
      ts: Date.now()
    })
  }).catch(() => {
  });
}
async function getAdminNotificationActorName(userId) {
  const [user] = await db.select({
    firstName: usersTable.firstName,
    lastName: usersTable.lastName,
    email: usersTable.email
  }).from(usersTable).where(eq(usersTable.id, userId)).limit(1);
  const fullName = [user?.firstName, user?.lastName].filter(Boolean).join(" ").trim();
  return fullName || user?.email || `User #${userId}`;
}
function addDays6(date6, days) {
  const d = new Date(date6);
  d.setDate(d.getDate() + days);
  return d;
}
function addMonths6(date6, months) {
  const d = new Date(date6);
  d.setMonth(d.getMonth() + months);
  return d;
}
function addLendingRepaymentPeriod(start, frequency, index2) {
  if (frequency === "WEEKLY") return addDays6(start, 7 * index2);
  if (frequency === "BIWEEKLY") return addDays6(start, 14 * index2);
  return addMonths6(start, index2);
}
function isRecord4(value) {
  return typeof value === "object" && value !== null;
}
function readString2(value) {
  return typeof value === "string" ? value : null;
}
function requireAuth2(req, res, next) {
  void (async () => {
    const user = await resolveAuthenticatedUser(req.cookies?.wwn_token);
    if (!user) {
      res.status(401).json({ message: "Invalid or expired token." });
      return;
    }
    req.userId = user.id;
    next();
  })();
}
async function formatMemberProfileWithTenantContext(user) {
  return formatSessionUserProfile(user, {
    normalizeOrganizationTeamMemberOnboarding: false,
    useUserRowForOnboarding: false
  });
}
async function getMemberAccessContext(userId) {
  const [user] = await db.select({
    id: usersTable.id,
    userRole: usersTable.userRole,
    membershipType: usersTable.membershipType,
    membershipStatus: usersTable.membershipStatus,
    onboardingCompletedAt: usersTable.onboardingCompletedAt,
    createdAt: usersTable.createdAt
  }).from(usersTable).where(eq(usersTable.id, userId));
  if (!user) {
    throw new Error("User not found.");
  }
  if (user.membershipStatus === "ACTIVE") {
    const now = /* @__PURE__ */ new Date();
    const [subscription] = await db.select({
      id: membershipSubscriptionsTable.id,
      renewsAt: membershipSubscriptionsTable.renewsAt,
      endDate: membershipSubscriptionsTable.endDate
    }).from(membershipSubscriptionsTable).where(
      and(
        eq(membershipSubscriptionsTable.userId, userId),
        eq(membershipSubscriptionsTable.status, "ACTIVE")
      )
    ).orderBy(desc(membershipSubscriptionsTable.createdAt)).limit(1);
    const cutoff = subscription?.renewsAt ?? subscription?.endDate ?? null;
    if (cutoff && cutoff.getTime() < now.getTime()) {
      const [updated] = await db.update(usersTable).set({ membershipStatus: "EXPIRED", updatedAt: now }).where(eq(usersTable.id, userId)).returning({
        id: usersTable.id,
        userRole: usersTable.userRole,
        membershipType: usersTable.membershipType,
        membershipStatus: usersTable.membershipStatus,
        onboardingCompletedAt: usersTable.onboardingCompletedAt,
        createdAt: usersTable.createdAt
      });
      return {
        ...updated ?? user,
        planEntitlements: {}
      };
    }
  }
  return {
    ...user,
    planEntitlements: user.membershipType === "INDIVIDUAL" ? await getPreferredMemberPlanEntitlements(userId) : {}
  };
}
function getOrganizationLaneFeatureAccess(input) {
  const context = input.organizationContext;
  if (!context) {
    return {
      allowed: false,
      reason: "Organization product access is available only inside the organization workspace."
    };
  }
  if (!context.tenantAccess.allowed) {
    return {
      allowed: false,
      reason: context.tenantAccess.reasons[0] ?? "Your organization is not enabled for tenant access."
    };
  }
  switch (input.feature) {
    case "COMMUNITY":
      return { allowed: true, reason: null };
    case "SUSU":
      if (context.productAccess.ORG_SUSU.allowed) {
        return {
          allowed: false,
          reason: "Use your organization SUSU workspace instead of the personal member SUSU pages."
        };
      }
      if (context.productAccess.ORG_SUSU_EDUCATION.allowed) {
        return {
          allowed: false,
          reason: "Your organization has SUSU education access, but live SUSU activity stays in the organization workspace."
        };
      }
      return {
        allowed: false,
        reason: context.productAccess.ORG_SUSU.reason ?? context.productAccess.ORG_SUSU_EDUCATION.reason ?? "Your organization plan does not include org SUSU access."
      };
    case "INVESTMENTS":
      if (context.productAccess.INVESTMENT_CLUB.allowed || context.productAccess.P2P_CAPITAL.allowed) {
        return { allowed: true, reason: null };
      }
      return {
        allowed: false,
        reason: context.productAccess.INVESTMENT_CLUB.reason ?? context.productAccess.P2P_CAPITAL.reason ?? "Your organization plan does not include organization capital access."
      };
    case "LENDING_BORROWER":
    case "LENDING_LENDER":
      return {
        allowed: false,
        reason: "Lending Pool access is not part of the organization lane."
      };
    default:
      return {
        allowed: false,
        reason: "This feature is not available in the organization lane."
      };
  }
}
async function ensureMemberProductAccess(userId, feature) {
  const traceId = `membergate-${userId}-${feature}-${Date.now()}`;
  const user = await getMemberAccessContext(userId);
  const [userRow] = await db.select().from(usersTable).where(eq(usersTable.id, userId));
  if (!userRow) {
    throw new MemberProductAccessError("User not found.", 401);
  }
  const onboardingState = await getActiveOnboardingStateForUser(userId);
  if (user.userRole === "ADMIN" || user.userRole === "SUPER_ADMIN") {
    return user;
  }
  if (!isUserProfileComplete(userRow)) {
    throw new MemberProductAccessError(
      "Complete your profile before accessing this feature."
    );
  }
  if (onboardingState.required && !onboardingState.completed) {
    throw new MemberProductAccessError(
      "Complete onboarding before accessing this feature."
    );
  }
  const access = getMemberProductAccess({
    feature,
    membershipType: user.membershipType,
    membershipStatus: user.membershipStatus,
    onboardingRequired: onboardingState.required,
    onboardingCompleted: onboardingState.completed,
    planEntitlements: user.planEntitlements
  });
  const organizationContext = user.membershipType === "ORGANIZATION" ? await resolveOrganizationSessionContext(userId) : null;
  await reportOrgGatingDebug2({
    hypothesisId: "C",
    location: "src/routes/member.ts:ensureMemberProductAccess",
    msg: "Evaluated member product access gate",
    data: {
      userId,
      feature,
      membershipType: user.membershipType,
      membershipStatus: user.membershipStatus,
      accessAllowed: access.allowed,
      accessReason: access.reason ?? null,
      organizationTenantAllowed: organizationContext?.tenantAccess.allowed ?? null,
      organizationTenantReasons: organizationContext?.tenantAccess.reasons ?? [],
      organizationPlanId: organizationContext?.plan?.id ?? null,
      organizationPlanName: organizationContext?.plan?.name ?? null,
      organizationProductAccess: feature === "INVESTMENTS" ? {
        INVESTMENT_CLUB: organizationContext?.productAccess.INVESTMENT_CLUB ?? null,
        P2P_CAPITAL: organizationContext?.productAccess.P2P_CAPITAL ?? null
      } : feature === "SUSU" ? {
        ORG_SUSU: organizationContext?.productAccess.ORG_SUSU ?? null,
        ORG_SUSU_EDUCATION: organizationContext?.productAccess.ORG_SUSU_EDUCATION ?? null
      } : null
    },
    traceId
  });
  if (user.membershipType === "ORGANIZATION") {
    const organizationAccess = getOrganizationLaneFeatureAccess({
      feature,
      organizationContext
    });
    if (!organizationAccess.allowed) {
      throw new MemberProductAccessError(
        organizationAccess.reason ?? "Access denied."
      );
    }
    return user;
  }
  if (!access.allowed) {
    throw new MemberProductAccessError(access.reason ?? "Access denied.");
  }
  return user;
}
function isUniqueViolation7(err) {
  if (typeof err !== "object" || err === null) return false;
  const record2 = err;
  const directCode = typeof record2.code === "string" ? record2.code : null;
  const cause = record2.cause;
  const causeCode = typeof cause === "object" && cause !== null && "code" in cause && typeof cause.code === "string" ? cause.code : null;
  return directCode === "23505" || causeCode === "23505";
}
function toIsoStringOrNull3(value) {
  if (!value) return null;
  if (value instanceof Date) {
    return Number.isNaN(value.getTime()) ? null : value.toISOString();
  }
  const parsed = new Date(value);
  return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString();
}
async function ensureOrganizationBillingAuthority(input) {
  if (typeof input.organizationId !== "number") {
    return {
      allowed: false,
      message: "Organization billing requires a valid organization account."
    };
  }
  const [membership] = await db.select({
    role: organizationMembersTable.role
  }).from(organizationMembersTable).where(
    and(
      eq(organizationMembersTable.organizationId, input.organizationId),
      eq(organizationMembersTable.userId, input.userId)
    )
  ).limit(1);
  if (!membership || !canOrganizationRolePerform(membership.role, "billing_manage")) {
    return {
      allowed: false,
      message: "Only the organization authority can manage organization billing."
    };
  }
  const context = await resolveOrganizationSessionContext(input.userId);
  if (!context?.permissions.canManageBilling) {
    return {
      allowed: false,
      message: "Organization billing management is not available for this tenant context."
    };
  }
  return { allowed: true, message: null };
}
async function resolveOrganizationWalletOwnerIdWith(conn, user) {
  if (typeof user.organizationId === "number") {
    return user.organizationId;
  }
  const [membership] = await conn.select({
    organizationId: organizationMembersTable.organizationId
  }).from(organizationMembersTable).where(eq(organizationMembersTable.userId, user.id)).orderBy(
    sql`case when ${organizationMembersTable.status} = 'ACTIVE' then 0 else 1 end`,
    asc(organizationMembersTable.id)
  ).limit(1);
  return membership?.organizationId ?? null;
}
async function listOrganizationWalletApproverIdsWith(conn, organizationId) {
  const rows = await conn.select({
    userId: organizationMembersTable.userId
  }).from(organizationMembersTable).where(
    and(
      eq(organizationMembersTable.organizationId, organizationId),
      inArray(organizationMembersTable.role, ["OWNER", "ADMIN"]),
      eq(organizationMembersTable.status, "ACTIVE")
    )
  );
  return rows.map((row) => row.userId);
}
async function resolveMemberWalletScopeWith(conn, user) {
  const wallet = await ensureWalletWith6(conn, "USER", user.id);
  let organizationId = null;
  if (user.membershipType === "ORGANIZATION") {
    organizationId = await resolveOrganizationWalletOwnerIdWith(conn, user);
  } else if (typeof user.organizationId === "number") {
    organizationId = user.organizationId;
  }
  return {
    wallet,
    ownerType: "USER",
    ownerId: user.id,
    organizationId,
    usesOrganizationWallet: false
  };
}
function orderMemberCirclesForDisplay(circles, createdAtByCircleId) {
  if (circles.length <= 1) return circles;
  return [...circles].sort((left, right) => {
    const createdAtDiff = (createdAtByCircleId.get(right.id)?.getTime() ?? 0) - (createdAtByCircleId.get(left.id)?.getTime() ?? 0);
    if (createdAtDiff !== 0) return createdAtDiff;
    const joinedAtDiff = (right.joinedAt ? new Date(right.joinedAt).getTime() : 0) - (left.joinedAt ? new Date(left.joinedAt).getTime() : 0);
    if (joinedAtDiff !== 0) return joinedAtDiff;
    return right.id - left.id;
  });
}
async function getMemberCirclesSnapshot(userId) {
  const memberships = await db.select().from(circleMembershipsTable).where(eq(circleMembershipsTable.userId, userId)).orderBy(
    asc(circleMembershipsTable.joinedAt),
    asc(circleMembershipsTable.id)
  );
  if (!memberships.length) return [];
  const circleIds = Array.from(
    new Set(memberships.map((membership) => membership.circleId))
  );
  await activateReadyMemberCircles(circleIds);
  const [circles, allMemberships, payouts] = await Promise.all([
    db.select().from(savingsCirclesTable).where(inArray(savingsCirclesTable.id, circleIds)),
    db.select({ m: circleMembershipsTable, u: usersTable }).from(circleMembershipsTable).innerJoin(usersTable, eq(circleMembershipsTable.userId, usersTable.id)).where(inArray(circleMembershipsTable.circleId, circleIds)).orderBy(
      asc(circleMembershipsTable.circleId),
      asc(circleMembershipsTable.position)
    ),
    db.select().from(circlePayoutsTable).where(inArray(circlePayoutsTable.circleId, circleIds))
  ]);
  const circleById = new Map(
    circles.filter((circle) => circle.organizationId === null).map((circle) => [circle.id, circle])
  );
  const createdAtByCircleId = new Map(
    circles.filter((circle) => circle.organizationId === null).map((circle) => [circle.id, circle.createdAt])
  );
  const membershipsByCircleId = /* @__PURE__ */ new Map();
  for (const row of allMemberships) {
    const rows = membershipsByCircleId.get(row.m.circleId) ?? [];
    rows.push(row);
    membershipsByCircleId.set(row.m.circleId, rows);
  }
  const payoutsByCircleId = /* @__PURE__ */ new Map();
  for (const payout of payouts) {
    const rows = payoutsByCircleId.get(payout.circleId) ?? [];
    rows.push(payout);
    payoutsByCircleId.set(payout.circleId, rows);
  }
  const circlesInJoinOrder = [];
  for (const membership of memberships) {
    const circle = circleById.get(membership.circleId);
    if (!circle) continue;
    const runtimeStatus = getCircleRuntimeStatus({
      status: circle.status,
      startDate: circle.startDate
    });
    if (runtimeStatus !== "ACTIVE") continue;
    const circleMembershipRows = membershipsByCircleId.get(membership.circleId) ?? [];
    const circlePayoutRows = payoutsByCircleId.get(membership.circleId) ?? [];
    const payoutAmount = Number(
      calculateCirclePayoutAmount(circle.contributionAmount, circle.maxMembers)
    );
    const myPayout = circlePayoutRows.find(
      (payout) => payout.userId === userId && payout.position === membership.position
    ) ?? circlePayoutRows.find((payout) => payout.userId === userId);
    const payoutByMemberKey = new Map(
      circlePayoutRows.map(
        (payout) => [`${payout.userId}:${payout.position}`, payout]
      )
    );
    circlesInJoinOrder.push({
      id: circle.id,
      name: circle.name,
      contributionAmount: Number(circle.contributionAmount),
      frequency: circle.frequency,
      maxMembers: circle.maxMembers,
      currentMembers: circleMembershipRows.length,
      status: runtimeStatus,
      startDate: toIsoStringOrNull3(circle.startDate),
      endDate: null,
      joinedAt: toIsoStringOrNull3(membership.joinedAt),
      myPosition: membership.position,
      myPayoutReceived: myPayout?.status === "PAID",
      myPayoutDate: toIsoStringOrNull3(myPayout?.paidDate),
      myPayoutAmount: payoutAmount,
      members: circleMembershipRows.map(({ m, u }) => {
        const payout = payoutByMemberKey.get(`${m.userId}:${m.position}`);
        return {
          position: m.position,
          name: u.firstName + (u.lastName ? ` ${u.lastName[0]}.` : ""),
          month: payout?.scheduledDate ? new Date(payout.scheduledDate).toLocaleDateString("en-CA", {
            month: "short",
            year: "numeric"
          }) : `Position ${m.position}`,
          payoutAmount,
          payoutStatus: payout?.status ?? "PENDING",
          isMe: m.userId === userId
        };
      })
    });
  }
  return orderMemberCirclesForDisplay(circlesInJoinOrder, createdAtByCircleId);
}
async function activateReadyMemberCircles(circleIds) {
  if (!circleIds.length) return;
  const circles = await db.select({
    id: savingsCirclesTable.id,
    status: savingsCirclesTable.status,
    startDate: savingsCirclesTable.startDate
  }).from(savingsCirclesTable).where(inArray(savingsCirclesTable.id, circleIds));
  const readyCircleIds = circles.filter(
    (circle) => circle.status !== "ACTIVE" && getCircleRuntimeStatus({
      status: circle.status,
      startDate: circle.startDate
    }) === "ACTIVE"
  ).map((circle) => circle.id);
  for (const circleId of readyCircleIds) {
    await activateCircleIfReadyWith(db, circleId);
  }
}
async function getMembershipInvoiceHistory(userId) {
  const rows = await db.select({
    invoiceId: invoicesTable.id,
    invoiceNumber: invoicesTable.invoiceNumber,
    invoiceAmount: invoicesTable.amount,
    invoiceCurrency: invoicesTable.currency,
    invoiceStatus: invoicesTable.status,
    invoiceDueDate: invoicesTable.dueDate,
    invoicePaidAt: invoicesTable.paidAt,
    invoiceCreatedAt: invoicesTable.createdAt,
    subscriptionId: membershipSubscriptionsTable.id,
    subscriptionStatus: membershipSubscriptionsTable.status,
    subscriptionStartDate: membershipSubscriptionsTable.startDate,
    subscriptionEndDate: membershipSubscriptionsTable.endDate,
    subscriptionRenewsAt: membershipSubscriptionsTable.renewsAt,
    planId: membershipPlansTable.id,
    planName: membershipPlansTable.name,
    planMembershipType: membershipPlansTable.membershipType,
    planTier: membershipPlansTable.tier,
    planDescription: membershipPlansTable.description,
    paymentId: paymentsTable.id,
    paymentAmount: paymentsTable.amount,
    paymentCurrency: paymentsTable.currency,
    paymentStatus: paymentsTable.status,
    paymentMethod: paymentsTable.method,
    paymentReference: paymentsTable.reference,
    paymentDescription: paymentsTable.description,
    paymentProcessedAt: paymentsTable.processedAt,
    paymentMetadata: paymentsTable.metadata,
    paymentCreatedAt: paymentsTable.createdAt
  }).from(invoicesTable).leftJoin(
    membershipSubscriptionsTable,
    eq(invoicesTable.subscriptionId, membershipSubscriptionsTable.id)
  ).leftJoin(
    membershipPlansTable,
    eq(membershipSubscriptionsTable.planId, membershipPlansTable.id)
  ).leftJoin(paymentsTable, eq(paymentsTable.invoiceId, invoicesTable.id)).where(eq(invoicesTable.userId, userId)).orderBy(desc(invoicesTable.createdAt), desc(paymentsTable.createdAt));
  const historyByInvoiceId = /* @__PURE__ */ new Map();
  for (const row of rows) {
    if (historyByInvoiceId.has(row.invoiceId)) {
      continue;
    }
    historyByInvoiceId.set(row.invoiceId, {
      invoiceId: row.invoiceId,
      invoiceNumber: row.invoiceNumber,
      amount: Number(row.invoiceAmount),
      currency: row.invoiceCurrency,
      status: row.invoiceStatus,
      dueDate: toIsoStringOrNull3(row.invoiceDueDate),
      paidAt: toIsoStringOrNull3(row.invoicePaidAt),
      createdAt: toIsoStringOrNull3(row.invoiceCreatedAt),
      receiptUrl: `/api/member/membership/receipts/${row.invoiceId}.pdf`,
      billingCycle: row.paymentId ? "annual" : null,
      subscription: typeof row.subscriptionId === "number" ? {
        id: row.subscriptionId,
        status: row.subscriptionStatus ?? "PENDING",
        startDate: toIsoStringOrNull3(row.subscriptionStartDate),
        endDate: toIsoStringOrNull3(row.subscriptionEndDate),
        renewsAt: toIsoStringOrNull3(row.subscriptionRenewsAt)
      } : null,
      plan: typeof row.planId === "number" ? {
        id: row.planId,
        name: row.planName ?? "",
        membershipType: row.planMembershipType ?? "INDIVIDUAL",
        tier: row.planTier ?? "STARTER",
        description: row.planDescription ?? null
      } : null,
      payment: typeof row.paymentId === "number" ? {
        id: row.paymentId,
        amount: Number(row.paymentAmount),
        currency: row.paymentCurrency ?? "CAD",
        status: row.paymentStatus ?? "PENDING",
        method: row.paymentMethod,
        reference: row.paymentReference ?? null,
        description: row.paymentDescription ?? null,
        processedAt: toIsoStringOrNull3(row.paymentProcessedAt),
        createdAt: toIsoStringOrNull3(row.paymentCreatedAt),
        metadata: row.paymentMetadata ?? null
      } : null
    });
  }
  return Array.from(historyByInvoiceId.values());
}
function resolveMembershipCheckoutReturnPath(value) {
  if (typeof value === "string" && value.startsWith("/dashboard") && !value.startsWith("//")) {
    return value;
  }
  return "/dashboard/billing";
}
function roundMoneyAmount(value) {
  return Math.round((value + Number.EPSILON) * 100) / 100;
}
function getMembershipPlanPriceCents(plan) {
  const annualPrice = Number(plan.priceAnnual ?? 0);
  return Number.isFinite(annualPrice) ? Math.round(annualPrice * 100) : 0;
}
function compareMembershipPlansByPrice(left, right) {
  const priceDifference = getMembershipPlanPriceCents(left) - getMembershipPlanPriceCents(right);
  if (priceDifference !== 0) return priceDifference;
  const sortDifference = (left.sortOrder ?? 0) - (right.sortOrder ?? 0);
  if (sortDifference !== 0) return sortDifference;
  return left.id - right.id;
}
function getMembershipChangeKind(currentPlan, targetPlan) {
  if (currentPlan.id === targetPlan.id) return "NONE";
  const priceDifference = compareMembershipPlansByPrice(
    targetPlan,
    currentPlan
  );
  if (priceDifference > 0) return "UPGRADE";
  if (priceDifference < 0) return "DOWNGRADE";
  return "NONE";
}
function calculateMembershipProration(input) {
  const currentPrice = Number(input.currentPlan.priceAnnual);
  const targetPrice = Number(input.targetPlan.priceAnnual);
  const renewsAt = input.subscription.renewsAt ?? input.subscription.endDate;
  const startDate = input.subscription.startDate;
  if (!startDate || !renewsAt || Number.isNaN(startDate.getTime()) || Number.isNaN(renewsAt.getTime()) || renewsAt <= input.now || renewsAt <= startDate) {
    const amountDue2 = Math.max(0, roundMoneyAmount(targetPrice - currentPrice));
    return {
      ratioRemaining: amountDue2 > 0 ? 1 : 0,
      unusedCredit: amountDue2 > 0 ? roundMoneyAmount(currentPrice) : 0,
      targetProratedAmount: amountDue2 > 0 ? roundMoneyAmount(targetPrice) : 0,
      amountDue: amountDue2
    };
  }
  const totalMs = renewsAt.getTime() - startDate.getTime();
  const remainingMs = Math.max(0, renewsAt.getTime() - input.now.getTime());
  const ratioRemaining = Math.max(0, Math.min(1, remainingMs / totalMs));
  const unusedCredit = roundMoneyAmount(currentPrice * ratioRemaining);
  const targetProratedAmount = roundMoneyAmount(targetPrice * ratioRemaining);
  const amountDue = Math.max(
    0,
    roundMoneyAmount(targetProratedAmount - unusedCredit)
  );
  return {
    ratioRemaining,
    unusedCredit,
    targetProratedAmount,
    amountDue
  };
}
async function ensureStripeMembershipPrice(stripe, plan) {
  const isRecurring = plan.billingMode === "RECURRING";
  const billingCycle = plan.defaultBillingCycle ?? "ANNUAL";
  const rawAmount = billingCycle === "MONTHLY" ? Number(plan.priceMonthly ?? plan.priceAnnual) : Number(plan.priceAnnual);
  const amountCents = Math.round(rawAmount * 100);
  const targetCurrency = plan.currency.toLowerCase();
  const targetInterval = isRecurring ? billingCycle === "MONTHLY" ? "month" : "year" : null;
  const existingProducts = await stripe.products.list({ limit: 100 });
  let membershipProduct = existingProducts.data.find(
    (product) => product.metadata?.membershipPlanId === String(plan.id) && product.active
  ) ?? null;
  if (!membershipProduct) {
    membershipProduct = await stripe.products.create({
      name: `${plan.name} Membership`,
      metadata: {
        membershipPlanId: String(plan.id)
      }
    });
  }
  const existingPrices = await stripe.prices.list({
    product: membershipProduct.id,
    active: true,
    limit: 100
  });
  let membershipPrice = existingPrices.data.find((price) => {
    if (price.currency !== targetCurrency) return false;
    if (price.unit_amount !== amountCents) return false;
    if (isRecurring) {
      return price.recurring?.interval === targetInterval;
    }
    return !price.recurring;
  }) ?? null;
  if (!membershipPrice) {
    membershipPrice = await stripe.prices.create({
      currency: targetCurrency,
      unit_amount: amountCents,
      ...isRecurring ? { recurring: { interval: targetInterval } } : {},
      product: membershipProduct.id
    });
  }
  return membershipPrice;
}
async function ensureWalletWith6(conn, ownerType, ownerId) {
  const existing = await conn.select().from(walletsTable).where(
    and(
      eq(walletsTable.ownerType, ownerType),
      eq(walletsTable.ownerId, ownerId)
    )
  );
  if (existing.length) return existing[0];
  const [created] = await conn.insert(walletsTable).values({ ownerType, ownerId }).returning();
  return created;
}
async function ensureInvestmentWalletWith2(conn) {
  return ensureWalletWith6(conn, "INVESTMENT", INVESTMENT_WALLET_OWNER_ID);
}
async function getWalletBalanceWith4(conn, walletId) {
  const [[credits], [debits]] = await Promise.all([
    conn.select({ total: sum(walletTransactionsTable.amount) }).from(walletTransactionsTable).where(eq(walletTransactionsTable.toWalletId, walletId)),
    conn.select({ total: sum(walletTransactionsTable.amount) }).from(walletTransactionsTable).where(eq(walletTransactionsTable.fromWalletId, walletId))
  ]);
  return Number(credits.total ?? 0) - Number(debits.total ?? 0);
}
async function getWalletReservedBalanceWith3(conn, walletId, excludeInterestId) {
  const whereClause = excludeInterestId ? and(
    eq(investmentIntentReservationsTable.walletId, walletId),
    eq(investmentIntentReservationsTable.status, "RESERVED"),
    eq(investmentInterestsTable.status, "PENDING"),
    ne(investmentIntentReservationsTable.interestId, excludeInterestId)
  ) : and(
    eq(investmentIntentReservationsTable.walletId, walletId),
    eq(investmentIntentReservationsTable.status, "RESERVED"),
    eq(investmentInterestsTable.status, "PENDING")
  );
  const [row] = await conn.select({ total: sum(investmentIntentReservationsTable.amount) }).from(investmentIntentReservationsTable).innerJoin(
    investmentInterestsTable,
    eq(
      investmentIntentReservationsTable.interestId,
      investmentInterestsTable.id
    )
  ).where(whereClause);
  return Number(row?.total ?? 0);
}
async function getWalletCashoutReservedBalanceWith2(conn, walletId, excludeIntentId) {
  const whereClause = excludeIntentId ? and(
    eq(walletPaymentIntentsTable.walletId, walletId),
    eq(walletPaymentIntentsTable.type, "CASH_OUT"),
    inArray(walletPaymentIntentsTable.status, [
      "CREATED",
      "PENDING"
    ]),
    ne(walletPaymentIntentsTable.id, excludeIntentId)
  ) : and(
    eq(walletPaymentIntentsTable.walletId, walletId),
    eq(walletPaymentIntentsTable.type, "CASH_OUT"),
    inArray(walletPaymentIntentsTable.status, [
      "CREATED",
      "PENDING"
    ])
  );
  const [row] = await conn.select({ total: sum(walletPaymentIntentsTable.amount) }).from(walletPaymentIntentsTable).where(whereClause);
  return Number(row?.total ?? 0);
}
async function getWalletFundsWith2(conn, walletId, excludeInterestId) {
  const [balance, reservedBalance, cashoutReservedBalance] = await Promise.all([
    getWalletBalanceWith4(conn, walletId),
    getWalletReservedBalanceWith3(conn, walletId, excludeInterestId),
    getWalletCashoutReservedBalanceWith2(conn, walletId)
  ]);
  const totalReservedBalance = reservedBalance + cashoutReservedBalance;
  return {
    balance,
    reservedBalance: totalReservedBalance,
    availableBalance: Math.max(0, balance - totalReservedBalance)
  };
}
function formatWalletPartyName(input) {
  if (input.ownerType === "USER" && input.user) {
    return `${input.user.firstName} ${input.user.lastName ?? ""}`.trim();
  }
  if (input.ownerType === "ORGANIZATION" && input.organization) {
    return input.organization.name;
  }
  if (input.ownerType === "CIRCLE" && input.circle) {
    return input.circle.name;
  }
  switch (input.ownerType) {
    case "PLATFORM":
      return "WWN Platform";
    case "SUSU":
      return "WWN Susu";
    case "INVESTMENT":
      return "WWN Investments";
    case "LENDING_POOL":
      return "WWN Lending Pool";
    case "LENDING_MASTER":
      return "WWN Lending Master";
    default:
      return input.ownerType.replaceAll("_", " ");
  }
}
function parseMetadataNumber(metadata, key) {
  const value = metadata[key];
  if (typeof value === "number" && Number.isFinite(value)) {
    return value;
  }
  if (typeof value === "string" && value.trim().length) {
    const parsed = Number(value);
    return Number.isFinite(parsed) ? parsed : null;
  }
  return null;
}
async function getWalletTransactionsWith(conn, walletId) {
  const txs = await conn.select().from(walletTransactionsTable).where(
    or(
      eq(walletTransactionsTable.fromWalletId, walletId),
      eq(walletTransactionsTable.toWalletId, walletId)
    )
  ).orderBy(desc(walletTransactionsTable.createdAt)).limit(50);
  const relatedWalletIds = /* @__PURE__ */ new Set();
  const relatedCircleIds = /* @__PURE__ */ new Set();
  for (const tx of txs) {
    if (tx.fromWalletId != null) relatedWalletIds.add(tx.fromWalletId);
    if (tx.toWalletId != null) relatedWalletIds.add(tx.toWalletId);
    const metadata = tx.metadata ?? {};
    const circleId = parseMetadataNumber(metadata, "circleId");
    if (circleId != null) relatedCircleIds.add(circleId);
  }
  const walletRows = relatedWalletIds.size ? await conn.select({
    id: walletsTable.id,
    ownerType: walletsTable.ownerType,
    ownerId: walletsTable.ownerId
  }).from(walletsTable).where(inArray(walletsTable.id, Array.from(relatedWalletIds))) : [];
  const userIds = /* @__PURE__ */ new Set();
  const organizationIds = /* @__PURE__ */ new Set();
  for (const wallet of walletRows) {
    if (wallet.ownerType === "USER") {
      userIds.add(wallet.ownerId);
    } else if (wallet.ownerType === "ORGANIZATION") {
      organizationIds.add(wallet.ownerId);
    } else if (wallet.ownerType === "CIRCLE") {
      relatedCircleIds.add(wallet.ownerId);
    }
  }
  const [userRows, organizationRows, circleRows] = await Promise.all([
    userIds.size ? conn.select({
      id: usersTable.id,
      firstName: usersTable.firstName,
      lastName: usersTable.lastName
    }).from(usersTable).where(inArray(usersTable.id, Array.from(userIds))) : Promise.resolve([]),
    organizationIds.size ? conn.select({
      id: organizationsTable.id,
      name: organizationsTable.name
    }).from(organizationsTable).where(inArray(organizationsTable.id, Array.from(organizationIds))) : Promise.resolve([]),
    relatedCircleIds.size ? conn.select({
      id: savingsCirclesTable.id,
      name: savingsCirclesTable.name
    }).from(savingsCirclesTable).where(inArray(savingsCirclesTable.id, Array.from(relatedCircleIds))) : Promise.resolve([])
  ]);
  const usersById = new Map(userRows.map((row) => [row.id, row]));
  const organizationsById = new Map(
    organizationRows.map((row) => [row.id, row])
  );
  const circlesById = new Map(circleRows.map((row) => [row.id, row]));
  const walletsById = new Map(walletRows.map((row) => [row.id, row]));
  const buildWalletParty = (relatedWalletId) => {
    if (relatedWalletId == null) return null;
    const wallet = walletsById.get(relatedWalletId);
    if (!wallet) return null;
    const circle = wallet.ownerType === "CIRCLE" ? circlesById.get(wallet.ownerId) ?? null : null;
    return {
      ownerType: wallet.ownerType,
      name: formatWalletPartyName({
        ownerType: wallet.ownerType,
        user: wallet.ownerType === "USER" ? usersById.get(wallet.ownerId) ?? null : null,
        organization: wallet.ownerType === "ORGANIZATION" ? organizationsById.get(wallet.ownerId) ?? null : null,
        circle
      })
    };
  };
  return txs.map((t) => ({
    ...t.toWalletId === walletId ? {
      from: buildWalletParty(t.fromWalletId),
      to: buildWalletParty(t.toWalletId)
    } : {
      from: buildWalletParty(t.fromWalletId),
      to: buildWalletParty(t.toWalletId)
    },
    id: t.id,
    type: t.type,
    amount: Number(t.amount),
    direction: t.toWalletId === walletId ? "IN" : "OUT",
    createdAt: t.createdAt.toISOString(),
    metadata: t.metadata ?? {},
    circle: circlesById.get(
      parseMetadataNumber(
        t.metadata ?? {},
        "circleId"
      ) ?? (walletsById.get(t.fromWalletId ?? -1)?.ownerType === "CIRCLE" ? walletsById.get(t.fromWalletId ?? -1)?.ownerId ?? -1 : walletsById.get(t.toWalletId ?? -1)?.ownerType === "CIRCLE" ? walletsById.get(t.toWalletId ?? -1)?.ownerId ?? -1 : -1)
    ) ?? null
  }));
}
async function getInvestmentOpportunityCapacityWith2(conn, input) {
  const [opp] = await conn.select({
    id: investmentOpportunitiesTable.id,
    targetAmount: investmentOpportunitiesTable.targetAmount
  }).from(investmentOpportunitiesTable).where(eq(investmentOpportunitiesTable.id, input.opportunityId));
  if (!opp) return null;
  const [confirmedRows, reservedRows] = await Promise.all([
    conn.select({ total: sum(investmentInterestsTable.amount) }).from(investmentInterestsTable).where(
      and(
        eq(investmentInterestsTable.opportunityId, input.opportunityId),
        eq(investmentInterestsTable.status, "CONFIRMED")
      )
    ),
    conn.select({ total: sum(investmentIntentReservationsTable.amount) }).from(investmentIntentReservationsTable).innerJoin(
      investmentInterestsTable,
      eq(
        investmentIntentReservationsTable.interestId,
        investmentInterestsTable.id
      )
    ).where(
      and(
        eq(investmentInterestsTable.opportunityId, input.opportunityId),
        eq(investmentIntentReservationsTable.status, "RESERVED"),
        eq(investmentInterestsTable.status, "PENDING"),
        input.excludePendingInterestId ? ne(investmentInterestsTable.id, input.excludePendingInterestId) : void 0
      )
    )
  ]);
  const confirmedRow = confirmedRows[0];
  const reservedRow = reservedRows[0];
  return {
    targetAmount: Number(opp.targetAmount ?? 0),
    confirmedTotal: Number(confirmedRow?.total ?? 0),
    reservedPendingTotal: Number(reservedRow?.total ?? 0)
  };
}
async function ensurePlatformWalletWith(conn) {
  return ensureWalletWith6(conn, "PLATFORM", PLATFORM_WALLET_OWNER_ID2);
}
async function getConfirmedPoolCommitmentTotalWith(conn, opportunityId) {
  const [row] = await conn.select({ total: sum(lendingCommitmentsTable.amount) }).from(lendingCommitmentsTable).where(
    and(
      eq(lendingCommitmentsTable.opportunityId, opportunityId),
      eq(lendingCommitmentsTable.status, "CONFIRMED")
    )
  );
  return row?.total ?? "0";
}
async function getConfirmedPoolCommitmentsWith2(conn, opportunityId) {
  return conn.select({
    id: lendingCommitmentsTable.id,
    userId: lendingCommitmentsTable.userId,
    amount: lendingCommitmentsTable.amount,
    confirmedAt: lendingCommitmentsTable.confirmedAt
  }).from(lendingCommitmentsTable).where(
    and(
      eq(lendingCommitmentsTable.opportunityId, opportunityId),
      eq(lendingCommitmentsTable.status, "CONFIRMED")
    )
  ).orderBy(
    asc(lendingCommitmentsTable.confirmedAt),
    asc(lendingCommitmentsTable.id)
  );
}
async function reconcileLendingPoolCommittedAmountWith(conn, opportunityId) {
  const committedAmount = await getConfirmedPoolCommitmentTotalWith(
    conn,
    opportunityId
  );
  const [pool2] = await conn.update(lendingOpportunitiesTable).set({
    committedAmount,
    updatedAt: /* @__PURE__ */ new Date()
  }).where(eq(lendingOpportunitiesTable.id, opportunityId)).returning();
  return pool2;
}
async function ensureLendingMasterWalletWith3(conn) {
  return ensureWalletWith6(
    conn,
    "LENDING_MASTER",
    LENDING_MASTER_WALLET_OWNER_ID3
  );
}
async function createLendingReturnAllocationEvent2(params) {
  const {
    conn,
    opportunityId,
    applicationId,
    repaymentId,
    walletTransactionId
  } = params;
  const returnAmount = Math.max(0, params.returnAmount);
  const grossAmount = Math.max(0, params.grossAmount);
  const principalAmount = Math.max(0, params.principalAmount);
  if (walletTransactionId != null) {
    const [existingEvent] = await conn.select().from(lendingOpportunityReturnEventsTable).where(
      and(
        eq(lendingOpportunityReturnEventsTable.repaymentId, repaymentId),
        eq(
          lendingOpportunityReturnEventsTable.walletTransactionId,
          walletTransactionId
        )
      )
    );
    if (existingEvent) return existingEvent;
  }
  const [event] = await conn.insert(lendingOpportunityReturnEventsTable).values({
    opportunityId,
    repaymentId,
    loanApplicationId: applicationId,
    walletTransactionId,
    grossAmount: formatMoneyAmount(grossAmount),
    principalAmount: formatMoneyAmount(principalAmount),
    returnAmount: formatMoneyAmount(returnAmount),
    allocatedReturnAmount: formatMoneyAmount(0),
    occurredAt: params.occurredAt ?? /* @__PURE__ */ new Date()
  }).returning();
  const commitments = await getConfirmedPoolCommitmentsWith2(
    conn,
    opportunityId
  );
  if (!commitments.length) {
    return event;
  }
  const principalAllocations = allocateProRataReturnAmount(
    principalAmount,
    commitments
  );
  const returnAllocations = allocateProRataReturnAmount(
    returnAmount,
    commitments
  );
  if (returnAmount > 0) {
    const returnAllocationRows = returnAllocations.filter(
      (allocation) => allocation.allocatedReturnAmount > 0
    );
    if (returnAllocationRows.length > 0) {
      await conn.insert(lendingOpportunityReturnAllocationsTable).values(
        returnAllocationRows.map((allocation) => ({
          returnEventId: event.id,
          commitmentId: allocation.id,
          opportunityId,
          userId: allocation.userId,
          commitmentAmountSnapshot: formatMoneyAmount(
            parseMoneyAmount(allocation.amount)
          ),
          ownershipPctSnapshot: String(allocation.ownershipPct.toFixed(6)),
          allocatedReturnAmount: formatMoneyAmount(
            allocation.allocatedReturnAmount
          ),
          occurredAt: params.occurredAt ?? /* @__PURE__ */ new Date()
        }))
      );
    }
  }
  const allocatedPrincipalAmount = principalAllocations.reduce(
    (sum3, allocation) => sum3 + allocation.allocatedReturnAmount,
    0
  );
  const allocatedReturnAmount = returnAllocations.reduce(
    (sum3, allocation) => sum3 + allocation.allocatedReturnAmount,
    0
  );
  const totalInvestorPayoutAmount = allocatedPrincipalAmount + allocatedReturnAmount;
  if (totalInvestorPayoutAmount <= 0) {
    return event;
  }
  const masterWallet = await ensureLendingMasterWalletWith3(conn);
  const masterWalletBalance = await getWalletBalanceWith4(conn, masterWallet.id);
  if (masterWalletBalance < totalInvestorPayoutAmount) {
    throw new Error(
      "Lending wallet does not have enough balance to pay out investor principal and returns."
    );
  }
  for (const allocation of commitments) {
    const investorWallet = await ensureWalletWith6(
      conn,
      "USER",
      allocation.userId
    );
    const principalAllocation = principalAllocations.find((item) => item.id === allocation.id)?.allocatedReturnAmount ?? 0;
    const returnAllocation = returnAllocations.find((item) => item.id === allocation.id)?.allocatedReturnAmount ?? 0;
    if (principalAllocation > 0) {
      const principalPayoutIdempotencyKey = `lending_principal_payout:${event.id}:${allocation.id}`;
      const [existingPrincipalPayoutTx] = await conn.select({ id: walletTransactionsTable.id }).from(walletTransactionsTable).where(
        eq(
          walletTransactionsTable.idempotencyKey,
          principalPayoutIdempotencyKey
        )
      );
      if (!existingPrincipalPayoutTx) {
        await conn.insert(walletTransactionsTable).values({
          type: "LENDING_PRINCIPAL_PAYOUT",
          idempotencyKey: principalPayoutIdempotencyKey,
          fromWalletId: masterWallet.id,
          toWalletId: investorWallet.id,
          amount: formatMoneyAmount(principalAllocation),
          metadata: {
            source: "lending_principal_payout",
            opportunityId,
            repaymentId,
            applicationId,
            returnEventId: event.id,
            commitmentId: allocation.id,
            investorId: allocation.userId
          }
        });
      }
    }
    if (returnAllocation > 0) {
      const payoutIdempotencyKey = `lending_return_payout:${event.id}:${allocation.id}`;
      const [existingPayoutTx] = await conn.select({ id: walletTransactionsTable.id }).from(walletTransactionsTable).where(
        eq(walletTransactionsTable.idempotencyKey, payoutIdempotencyKey)
      );
      if (!existingPayoutTx) {
        await conn.insert(walletTransactionsTable).values({
          type: "LENDING_RETURN_PAYOUT",
          idempotencyKey: payoutIdempotencyKey,
          fromWalletId: masterWallet.id,
          toWalletId: investorWallet.id,
          amount: formatMoneyAmount(returnAllocation),
          metadata: {
            source: "lending_return_payout",
            opportunityId,
            repaymentId,
            applicationId,
            returnEventId: event.id,
            commitmentId: allocation.id,
            investorId: allocation.userId
          }
        });
      }
    }
  }
  const [updatedEvent] = await conn.update(lendingOpportunityReturnEventsTable).set({
    allocatedReturnAmount: formatMoneyAmount(allocatedReturnAmount)
  }).where(eq(lendingOpportunityReturnEventsTable.id, event.id)).returning();
  return updatedEvent ?? event;
}
async function getLendingCommitmentReturnSummaryMapWith(conn, commitmentIds) {
  const uniqueCommitmentIds = Array.from(new Set(commitmentIds));
  const summaryByCommitmentId = /* @__PURE__ */ new Map();
  if (!uniqueCommitmentIds.length) {
    return summaryByCommitmentId;
  }
  const allocations = await conn.select({
    commitmentId: lendingOpportunityReturnAllocationsTable.commitmentId,
    allocatedReturnAmount: lendingOpportunityReturnAllocationsTable.allocatedReturnAmount
  }).from(lendingOpportunityReturnAllocationsTable).where(
    inArray(
      lendingOpportunityReturnAllocationsTable.commitmentId,
      uniqueCommitmentIds
    )
  );
  for (const commitmentId of uniqueCommitmentIds) {
    summaryByCommitmentId.set(commitmentId, { realizedReturn: 0 });
  }
  for (const allocation of allocations) {
    const current = summaryByCommitmentId.get(allocation.commitmentId) ?? {
      realizedReturn: 0
    };
    current.realizedReturn += parseMoneyAmount(
      allocation.allocatedReturnAmount
    );
    summaryByCommitmentId.set(allocation.commitmentId, current);
  }
  return summaryByCommitmentId;
}
async function getLendingPoolEligibilitySnapshot(userId) {
  const [user, userRow] = await Promise.all([
    getMemberAccessContext(userId),
    db.select().from(usersTable).where(eq(usersTable.id, userId)).then((rows) => rows[0] ?? null)
  ]);
  const [scoreRow] = await db.select({
    score: wwnCreditScoresTable.score,
    computedAt: wwnCreditScoresTable.computedAt
  }).from(wwnCreditScoresTable).where(eq(wwnCreditScoresTable.userId, userId));
  const [
    circleMembershipCounts,
    contributionAggRows,
    activeLoanAggRows,
    lateLoanRepaymentAggRows,
    lateHelpingHandRepaymentAggRows
  ] = await Promise.all([
    db.select({ count: count() }).from(circleMembershipsTable).where(eq(circleMembershipsTable.userId, userId)),
    db.select({
      total: count(),
      missed: sql`count(*) filter (where ${savingsContributionsTable.status} = 'MISSED')`
    }).from(savingsContributionsTable).where(eq(savingsContributionsTable.userId, userId)),
    db.select({ count: count() }).from(loanApplicationsTable).where(
      and(
        eq(loanApplicationsTable.borrowerId, userId),
        inArray(loanApplicationsTable.status, [
          ...ACTIVE_LENDING_POOL_STATUSES
        ])
      )
    ),
    db.select({ count: count() }).from(loanRepaymentsTable).innerJoin(
      loanApplicationsTable,
      eq(loanRepaymentsTable.loanApplicationId, loanApplicationsTable.id)
    ).where(
      and(
        eq(loanApplicationsTable.borrowerId, userId),
        eq(loanRepaymentsTable.status, "LATE")
      )
    ),
    db.select({ count: count() }).from(helpingHandRepaymentsTable).innerJoin(
      helpingHandApplicationsTable,
      eq(
        helpingHandRepaymentsTable.helpingHandApplicationId,
        helpingHandApplicationsTable.id
      )
    ).where(
      and(
        eq(helpingHandApplicationsTable.userId, userId),
        eq(helpingHandRepaymentsTable.status, "LATE")
      )
    )
  ]);
  const now = /* @__PURE__ */ new Date();
  const membershipMonths = Math.max(
    1,
    Math.floor(
      (now.getTime() - user.createdAt.getTime()) / (1e3 * 60 * 60 * 24 * 30)
    )
  );
  const susuScore = scoreRow?.score ?? null;
  const participationCount = Number(circleMembershipCounts[0]?.count ?? 0);
  const missedContributionCount = Number(contributionAggRows[0]?.missed ?? 0);
  const totalContributionCount = Number(contributionAggRows[0]?.total ?? 0);
  const activeLoanApplicationCount = Number(activeLoanAggRows[0]?.count ?? 0);
  const delinquentLoanRepaymentCount = Number(
    lateLoanRepaymentAggRows[0]?.count ?? 0
  );
  const delinquentHelpingHandRepaymentCount = Number(
    lateHelpingHandRepaymentAggRows[0]?.count ?? 0
  );
  const delinquentObligationCount = delinquentLoanRepaymentCount + delinquentHelpingHandRepaymentCount;
  const reasons = [];
  if (!userRow || !isUserProfileComplete(userRow)) {
    reasons.push("Complete your profile before applying for member lending.");
  }
  const onboardingState = await getActiveOnboardingStateForUser(userId);
  const productAccess = getMemberProductAccess({
    feature: "LENDING_BORROWER",
    membershipType: user.membershipType,
    membershipStatus: user.membershipStatus,
    onboardingRequired: onboardingState.required,
    onboardingCompleted: onboardingState.completed,
    planEntitlements: user.planEntitlements
  });
  if (!productAccess.allowed && productAccess.reason) {
    reasons.push(productAccess.reason);
  }
  if (typeof susuScore !== "number") {
    reasons.push("Your Susu Score is not available yet.");
  } else if (susuScore < 65) {
    reasons.push(
      "Your Susu Score must be at least 65% to apply for P2P lending."
    );
  }
  if (activeLoanApplicationCount > 0) {
    reasons.push(
      "You already have an active Lending Pool application or loan in progress."
    );
  }
  if (delinquentObligationCount > 0) {
    reasons.push(
      "Outstanding late repayment obligations must be resolved before applying."
    );
  }
  return {
    eligible: reasons.length === 0,
    reasons,
    inputs: {
      membershipStatus: user.membershipStatus,
      membershipMonths,
      maxRequestAmount: LENDING_POOL_MAX_REQUEST_AMOUNT,
      susuScore,
      susuScoreTier: typeof susuScore === "number" ? getLendingPoolTier(susuScore) : null,
      lastSusuScoreUpdate: toIsoStringOrNull3(scoreRow?.computedAt),
      participationCount,
      totalContributionCount,
      missedContributionCount,
      activeLoanApplicationCount,
      delinquentLoanRepaymentCount,
      delinquentHelpingHandRepaymentCount,
      delinquentObligationCount
    }
  };
}
function serializeLoanApplication(app3) {
  return {
    id: String(app3.id),
    loanType: normalizeLendingLoanType(app3.loanType),
    templateId: app3.templateId ? String(app3.templateId) : null,
    opportunityId: app3.opportunityId ? String(app3.opportunityId) : null,
    templateTitle: app3.templateTitle ?? null,
    templateBorrowerType: app3.templateBorrowerType ?? null,
    requestedAmount: Number(app3.requestedAmount),
    approvedAmount: app3.approvedAmount ? Number(app3.approvedAmount) : null,
    disbursedAmount: app3.disbursedAmount ? Number(app3.disbursedAmount) : null,
    purpose: app3.purpose,
    term: app3.term,
    repaymentSchedule: app3.repaymentSchedule,
    termMonths: app3.termMonths,
    borrowerAppreciationAmount: Number(app3.borrowerAppreciationAmount),
    repaymentFrequency: app3.repaymentFrequency,
    processingFeePct: app3.processingFeePct !== null ? Number(app3.processingFeePct) : null,
    wwnMarginPct: Number(app3.wwnMarginPct ?? 0),
    reserveContributionPct: Number(app3.reserveContributionPct ?? 0),
    totalRepayableAmount: Number(app3.totalRepayableAmount),
    estimatedInstallmentAmount: Number(app3.estimatedInstallmentAmount),
    notes: app3.notes ?? "",
    status: app3.status,
    reviewNote: app3.reviewNote ?? null,
    submittedAt: app3.createdAt.toISOString(),
    reviewedAt: app3.reviewedAt?.toISOString() ?? null,
    reservedAt: app3.reservedAt?.toISOString() ?? null,
    disbursedAt: app3.disbursedAt?.toISOString() ?? null,
    createdAt: app3.createdAt.toISOString(),
    updatedAt: app3.updatedAt.toISOString()
  };
}
function serializeLoanRepayment(repayment) {
  return {
    id: repayment.id,
    dueDate: repayment.dueDate.toISOString(),
    amount: Number(repayment.amount),
    paidAmount: repayment.paidAmount ? Number(repayment.paidAmount) : null,
    paidAt: repayment.paidAt?.toISOString() ?? null,
    status: repayment.status,
    method: repayment.method ?? null,
    createdAt: repayment.createdAt.toISOString()
  };
}
function serializeHelpingHandRepayment2(repayment) {
  const amount = Number(repayment.amount);
  const rawPaidAmount = repayment.paidAmount !== null ? Number(repayment.paidAmount) : null;
  const normalizedPaidAmount = repayment.status === "PAID" && (rawPaidAmount === null || !Number.isFinite(rawPaidAmount) || rawPaidAmount <= 0) ? amount : rawPaidAmount;
  return {
    id: repayment.id,
    dueDate: repayment.dueDate.toISOString(),
    amount: String(repayment.amount),
    paidAmount: normalizedPaidAmount !== null ? String(normalizedPaidAmount) : null,
    paidAt: repayment.paidAt?.toISOString() ?? null,
    status: repayment.status,
    method: repayment.method ?? null,
    createdAt: repayment.createdAt.toISOString(),
    updatedAt: repayment.updatedAt.toISOString()
  };
}
async function getHelpingHandEligibilitySnapshot(userId) {
  const user = await getMemberAccessContext(userId);
  const [
    circleRows,
    contributionRows,
    payoutRows,
    activeHelpingHandRows,
    outstandingRepaymentRows
  ] = await Promise.all([
    db.select({
      circleId: savingsCirclesTable.id,
      circleName: savingsCirclesTable.name,
      helpingHandMultiplier: savingsCirclesTable.helpingHandMultiplier
    }).from(circleMembershipsTable).innerJoin(
      savingsCirclesTable,
      eq(circleMembershipsTable.circleId, savingsCirclesTable.id)
    ).where(eq(circleMembershipsTable.userId, userId)),
    db.select({
      circleId: savingsContributionsTable.circleId,
      total: count(),
      missed: sql`count(*) filter (where ${savingsContributionsTable.status} = 'MISSED')`
    }).from(savingsContributionsTable).where(eq(savingsContributionsTable.userId, userId)).groupBy(savingsContributionsTable.circleId),
    db.select({
      circleId: circlePayoutsTable.circleId,
      payoutId: circlePayoutsTable.id,
      scheduledDate: circlePayoutsTable.scheduledDate,
      paidDate: circlePayoutsTable.paidDate,
      amount: circlePayoutsTable.amount
    }).from(circlePayoutsTable).where(
      and(
        eq(circlePayoutsTable.userId, userId),
        eq(circlePayoutsTable.status, "PAID")
      )
    ).orderBy(desc(circlePayoutsTable.paidDate), desc(circlePayoutsTable.id)),
    db.select({ count: count() }).from(helpingHandApplicationsTable).where(
      and(
        eq(helpingHandApplicationsTable.userId, userId),
        inArray(helpingHandApplicationsTable.status, [
          ...BLOCKING_HELPING_HAND_DEBT_STATUSES2
        ])
      )
    ),
    db.select({
      count: count()
    }).from(helpingHandRepaymentsTable).innerJoin(
      helpingHandApplicationsTable,
      eq(
        helpingHandRepaymentsTable.helpingHandApplicationId,
        helpingHandApplicationsTable.id
      )
    ).where(
      and(
        eq(helpingHandApplicationsTable.userId, userId),
        inArray(helpingHandRepaymentsTable.status, ["PENDING", "LATE"])
      )
    )
  ]);
  const susuParticipationCount = circleRows.length;
  const payoutContextCount = payoutRows.length;
  const contributionByCircleId = new Map(
    contributionRows.map((row) => [
      row.circleId,
      {
        total: Number(row.total ?? 0),
        missed: Number(row.missed ?? 0)
      }
    ])
  );
  const payoutByCircleId = new Map(
    payoutRows.map((row) => [
      row.circleId,
      {
        payoutId: row.payoutId,
        amount: Number(row.amount),
        scheduledDate: row.scheduledDate,
        paidDate: row.paidDate
      }
    ])
  );
  const totalContributionCount = contributionRows.reduce(
    (sum3, row) => sum3 + Number(row.total ?? 0),
    0
  );
  const missedContributionCount = contributionRows.reduce(
    (sum3, row) => sum3 + Number(row.missed ?? 0),
    0
  );
  const activeHelpingHandDebtCount = Number(
    activeHelpingHandRows[0]?.count ?? 0
  );
  const outstandingHelpingHandRepaymentCount = Number(
    outstandingRepaymentRows[0]?.count ?? 0
  );
  const payoutContextOptions = circleRows.map((circle) => {
    const contributionStats = contributionByCircleId.get(circle.circleId) ?? {
      total: 0,
      missed: 0
    };
    const payout = payoutByCircleId.get(circle.circleId) ?? null;
    const multiplier = circle.helpingHandMultiplier !== null ? Number(circle.helpingHandMultiplier) : null;
    const maxRequestAmount = payout && multiplier !== null && Number.isFinite(multiplier) && multiplier > 0 ? Number((payout.amount * multiplier).toFixed(2)) : null;
    return {
      circleId: circle.circleId,
      circleName: circle.circleName,
      payoutId: payout?.payoutId ?? null,
      payoutAmount: payout?.amount ?? null,
      payoutPaidDate: payout?.paidDate ?? null,
      payoutScheduledDate: payout?.scheduledDate ?? null,
      contributionCount: contributionStats.total,
      missedContributionCount: contributionStats.missed,
      multiplier,
      maxRequestAmount
    };
  }).filter((option) => option.payoutId !== null).sort(
    (a, b) => new Date(b.payoutPaidDate ?? 0).getTime() - new Date(a.payoutPaidDate ?? 0).getTime()
  );
  const qualifyingOptions = payoutContextOptions.filter(
    (option) => option.missedContributionCount === 0 && option.maxRequestAmount !== null
  ).sort((a, b) => {
    if ((b.maxRequestAmount ?? 0) !== (a.maxRequestAmount ?? 0)) {
      return (b.maxRequestAmount ?? 0) - (a.maxRequestAmount ?? 0);
    }
    return new Date(b.payoutPaidDate ?? 0).getTime() - new Date(a.payoutPaidDate ?? 0).getTime();
  });
  const qualifyingOption = qualifyingOptions[0] ?? null;
  const payoutContextOption = payoutContextOptions[0] ?? null;
  const reasons = [];
  const onboardingState = await getActiveOnboardingStateForUser(userId);
  const susuAccess = getMemberProductAccess({
    feature: "SUSU",
    membershipType: user.membershipType,
    membershipStatus: user.membershipStatus,
    onboardingRequired: onboardingState.required,
    onboardingCompleted: onboardingState.completed,
    planEntitlements: user.planEntitlements
  });
  if (!susuAccess.allowed && susuAccess.reason) {
    reasons.push(susuAccess.reason);
  }
  if (activeHelpingHandDebtCount > 0) {
    reasons.push(
      "Finish repaying your current SUSU Matching Fund balance first."
    );
  }
  if (outstandingHelpingHandRepaymentCount > 0) {
    reasons.push("Clear your outstanding SUSU Matching Fund repayments first.");
  }
  if (susuParticipationCount === 0) {
    reasons.push("Join a ROSCA circle (Susu) first.");
  }
  if (susuParticipationCount > 0 && payoutContextCount === 0) {
    reasons.push("Receive your SUSU payout first.");
  }
  if (susuParticipationCount > 0 && qualifyingOption === null) {
    const hasMissedCirclePayments = circleRows.some(
      (circle) => (contributionByCircleId.get(circle.circleId)?.missed ?? 0) > 0
    );
    const hasPaidPayoutWithoutMultiplier = circleRows.some((circle) => {
      const payout = payoutByCircleId.get(circle.circleId);
      const multiplier = circle.helpingHandMultiplier !== null ? Number(circle.helpingHandMultiplier) : null;
      return payout && (multiplier === null || !Number.isFinite(multiplier) || multiplier <= 0);
    });
    if (hasMissedCirclePayments) {
      reasons.push("Complete your qualifying circle with no missed payments.");
    }
    if (hasPaidPayoutWithoutMultiplier) {
      reasons.push(
        "Matching Fund is not configured for your payout circle yet."
      );
    }
  }
  if (qualifyingOption === null && reasons.length === 0) {
    reasons.push("You do not have a qualifying SUSU payout yet.");
  }
  return {
    eligible: reasons.length === 0,
    reasons,
    inputs: {
      susuParticipationCount,
      payoutContextCount,
      maxRequestAmount: qualifyingOption?.maxRequestAmount ?? null,
      qualifyingCircleId: qualifyingOption?.circleId ?? payoutContextOption?.circleId ?? null,
      qualifyingCircleName: qualifyingOption?.circleName ?? payoutContextOption?.circleName ?? null,
      qualifyingPayoutId: qualifyingOption?.payoutId ?? payoutContextOption?.payoutId ?? null,
      qualifyingPayoutAmount: qualifyingOption?.payoutAmount ?? payoutContextOption?.payoutAmount ?? null,
      qualifyingMultiplier: qualifyingOption?.multiplier ?? null,
      latestPayoutScheduledDate: toIsoStringOrNull3(
        qualifyingOption?.payoutScheduledDate ?? payoutContextOption?.payoutScheduledDate ?? null
      ),
      latestPayoutPaidDate: toIsoStringOrNull3(
        qualifyingOption?.payoutPaidDate ?? payoutContextOption?.payoutPaidDate ?? null
      ),
      totalContributionCount,
      missedContributionCount,
      activeHelpingHandCount: activeHelpingHandDebtCount,
      outstandingHelpingHandRepaymentCount
    }
  };
}
async function getMemberOnboardingSnapshot(userId) {
  const now = /* @__PURE__ */ new Date();
  const enrollment = await ensureActiveOnboardingEnrollmentForUser(userId);
  if (!enrollment) {
    return {
      enrollment: null,
      program: null,
      weeks: []
    };
  }
  const [program] = await db.select().from(onboardingProgramsTable).where(eq(onboardingProgramsTable.id, enrollment.programId));
  if (!program) {
    return {
      enrollment: null,
      program: null,
      weeks: []
    };
  }
  const weeks = await db.select().from(onboardingProgramWeeksTable).where(eq(onboardingProgramWeeksTable.programId, program.id)).orderBy(asc(onboardingProgramWeeksTable.sortOrder));
  const weekIds = weeks.map((w) => w.id);
  const activities = weekIds.length ? await db.select().from(onboardingWeekActivitiesTable).where(inArray(onboardingWeekActivitiesTable.weekId, weekIds)).orderBy(asc(onboardingWeekActivitiesTable.sortOrder)) : [];
  const activityIds = activities.map((a) => a.id);
  const progressRows = activityIds.length ? await db.select().from(onboardingActivityProgressTable).where(
    and(
      eq(onboardingActivityProgressTable.enrollmentId, enrollment.id),
      inArray(onboardingActivityProgressTable.activityId, activityIds)
    )
  ) : [];
  const progressByActivityId = new Map(
    progressRows.map((row) => [row.activityId, row])
  );
  const activitiesByWeekId = /* @__PURE__ */ new Map();
  for (const activity of activities) {
    const list = activitiesByWeekId.get(activity.weekId) ?? [];
    list.push(activity);
    activitiesByWeekId.set(activity.weekId, list);
  }
  const enrolledAt = enrollment.enrolledAt;
  const intervalsPassed = getOnboardingIntervalsPassed({
    enrolledAt,
    now,
    durationUnit: program.durationUnit
  });
  const elapsedWeekNumber = Math.min(
    program.numberOfWeeks,
    Math.max(1, intervalsPassed + 1)
  );
  const completedWeekNumbersForUnlock = new Set(
    weeks.filter((week) => {
      const activitiesForWeek = activitiesByWeekId.get(week.id) ?? [];
      return activitiesForWeek.every((activity) => {
        const row = progressByActivityId.get(activity.id);
        return row?.status === "COMPLETED";
      });
    }).map((week) => week.weekNumber)
  );
  const currentWeekNumber = getOnboardingCurrentWeekNumber({
    enrolledAt,
    now,
    durationUnit: program.durationUnit,
    numberOfWeeks: program.numberOfWeeks,
    completedWeekNumbers: completedWeekNumbersForUnlock
  });
  if (enrollment.completedAt && currentWeekNumber < program.numberOfWeeks) {
    await db.transaction(async (tx) => {
      await tx.update(onboardingEnrollmentsTable).set({ completedAt: null, updatedAt: now }).where(eq(onboardingEnrollmentsTable.id, enrollment.id));
      await tx.update(usersTable).set({ onboardingCompletedAt: null, updatedAt: now }).where(eq(usersTable.id, userId));
    });
    enrollment.completedAt = null;
    updateCreditScore(userId).catch(() => {
    });
  }
  const trackedActivityIds = activities.map((a) => a.id);
  const completedCount = trackedActivityIds.filter((id) => {
    const row = progressByActivityId.get(id);
    return row?.status === "COMPLETED";
  }).length;
  const totalCount = trackedActivityIds.length;
  const progressPct = totalCount === 0 ? 0 : Math.round(completedCount / totalCount * 100);
  const weekSummaries = weeks.map((week) => {
    const unlocksAt = getOnboardingUnlocksAt({
      enrolledAt,
      intervalIndex: week.weekNumber - 1,
      durationUnit: program.durationUnit
    });
    const locked = week.weekNumber > currentWeekNumber;
    const lockReason = locked ? week.weekNumber <= elapsedWeekNumber ? "PREVIOUS_INCOMPLETE" : "SCHEDULE" : null;
    const activitiesForWeek = activitiesByWeekId.get(week.id) ?? [];
    const completedForWeek = activitiesForWeek.filter((a) => {
      const row = progressByActivityId.get(a.id);
      return row?.status === "COMPLETED";
    });
    const weekCompleted = activitiesForWeek.length > 0 && completedForWeek.length === activitiesForWeek.length;
    const unlocksInDays = lockReason === "SCHEDULE" ? Math.max(
      0,
      Math.ceil(
        (unlocksAt.getTime() - now.getTime()) / (24 * 60 * 60 * 1e3)
      )
    ) : null;
    return {
      id: week.id,
      weekNumber: week.weekNumber,
      title: week.title,
      description: week.description ?? null,
      locked,
      lockReason,
      unlocksAt: unlocksAt.toISOString(),
      unlocksInDays,
      completed: weekCompleted,
      activities: locked ? [] : activitiesForWeek.map((activity) => {
        const progress = progressByActivityId.get(activity.id) ?? null;
        return {
          id: activity.id,
          title: activity.title,
          description: activity.description ?? null,
          durationMinutes: activity.durationMinutes ?? null,
          type: activity.type,
          content: activity.content ?? null,
          isRequired: activity.isRequired,
          status: progress?.status ?? "NOT_STARTED"
        };
      })
    };
  });
  return {
    enrollment: {
      id: enrollment.id,
      enrolledAt: enrollment.enrolledAt.toISOString(),
      completedAt: enrollment.completedAt?.toISOString() ?? null,
      currentWeekNumber,
      progressPct
    },
    program: {
      id: program.id,
      title: program.title,
      description: program.description ?? null,
      durationUnit: program.durationUnit,
      numberOfWeeks: program.numberOfWeeks,
      status: program.status
    },
    weeks: weekSummaries
  };
}
async function finalizeOnboardingIfCompleted(userId) {
  const now = /* @__PURE__ */ new Date();
  const enrollment = await ensureActiveOnboardingEnrollmentForUser(userId);
  if (!enrollment) {
    const [user2] = await db.select().from(usersTable).where(eq(usersTable.id, userId));
    return { completed: false, user: user2 ?? null };
  }
  const [program] = await db.select().from(onboardingProgramsTable).where(eq(onboardingProgramsTable.id, enrollment.programId));
  if (!program) return { completed: false, user: null };
  const intervalsPassed = getOnboardingIntervalsPassed({
    enrolledAt: enrollment.enrolledAt,
    now,
    durationUnit: program.durationUnit
  });
  const activityRows = await db.select({
    id: onboardingWeekActivitiesTable.id,
    weekId: onboardingWeekActivitiesTable.weekId,
    weekNumber: onboardingProgramWeeksTable.weekNumber
  }).from(onboardingWeekActivitiesTable).innerJoin(
    onboardingProgramWeeksTable,
    eq(onboardingWeekActivitiesTable.weekId, onboardingProgramWeeksTable.id)
  ).where(and(eq(onboardingProgramWeeksTable.programId, program.id))).orderBy(asc(onboardingProgramWeeksTable.weekNumber));
  const activityIds = activityRows.map((row) => row.id);
  if (!activityIds.length) return { completed: false, user: null };
  const progressRows = await db.select().from(onboardingActivityProgressTable).where(
    and(
      eq(onboardingActivityProgressTable.enrollmentId, enrollment.id),
      inArray(onboardingActivityProgressTable.activityId, activityIds)
    )
  );
  const progressByActivityId = new Map(
    progressRows.map((row) => [row.activityId, row])
  );
  const completedWeekNumbersForUnlock = new Set(
    Array.from(new Set(activityRows.map((row) => row.weekNumber))).filter(
      (weekNumber) => {
        const activitiesForWeek = activityRows.filter(
          (activity) => activity.weekNumber === weekNumber
        );
        return activitiesForWeek.every((activity) => {
          const progress = progressByActivityId.get(activity.id);
          return progress?.status === "COMPLETED";
        });
      }
    )
  );
  const currentWeekNumber = getOnboardingCurrentWeekNumber({
    enrolledAt: enrollment.enrolledAt,
    now,
    durationUnit: program.durationUnit,
    numberOfWeeks: program.numberOfWeeks,
    completedWeekNumbers: completedWeekNumbersForUnlock
  });
  const completedCount = activityIds.filter((activityId) => {
    const progress = progressByActivityId.get(activityId);
    return progress?.status === "COMPLETED";
  }).length;
  if (enrollment.completedAt && (currentWeekNumber < program.numberOfWeeks || completedCount !== activityIds.length)) {
    await db.transaction(async (tx) => {
      await tx.update(onboardingEnrollmentsTable).set({ completedAt: null, updatedAt: now }).where(eq(onboardingEnrollmentsTable.id, enrollment.id));
      await tx.update(usersTable).set({ onboardingCompletedAt: null, updatedAt: now }).where(eq(usersTable.id, userId));
    });
    updateCreditScore(userId).catch(() => {
    });
    return { completed: false, user: null };
  }
  if (currentWeekNumber < program.numberOfWeeks) {
    return { completed: false, user: null };
  }
  if (completedCount !== activityIds.length) {
    return { completed: false, user: null };
  }
  if (enrollment.completedAt) {
    const [user2] = await db.select().from(usersTable).where(eq(usersTable.id, userId));
    return { completed: true, user: user2 ?? null };
  }
  await db.transaction(async (tx) => {
    await tx.update(onboardingEnrollmentsTable).set({ completedAt: now, updatedAt: now }).where(eq(onboardingEnrollmentsTable.id, enrollment.id));
    const [updatedUser] = await tx.update(usersTable).set({ onboardingCompletedAt: now, updatedAt: now }).where(eq(usersTable.id, userId)).returning();
    if (updatedUser) {
      updateCreditScore(userId).catch(() => {
      });
    }
  });
  const [user] = await db.select().from(usersTable).where(eq(usersTable.id, userId));
  return { completed: true, user: user ?? null };
}
function getMembershipPlanTierRank(tier) {
  switch ((tier ?? "").toUpperCase()) {
    case "ENTREPRENEUR":
      return 4;
    case "IMPACT":
    case "ELITE":
    case "GRASSROOT":
      return 3;
    case "SPONSOR":
    case "PROFESSIONAL":
    case "EDUCATION":
      return 2;
    case "YOUTH":
    case "WORKER":
    case "COMMUNITY":
    case "STARTER":
      return 1;
    default:
      return 0;
  }
}
function isMembershipPlanTierAtLeast(params) {
  return getMembershipPlanTierRank(params.memberTier) >= getMembershipPlanTierRank(params.minTier);
}
async function getMemberMembershipPlanTier(userId) {
  const [row] = await db.select({
    planTier: membershipPlansTable.tier
  }).from(membershipSubscriptionsTable).leftJoin(
    membershipPlansTable,
    eq(membershipSubscriptionsTable.planId, membershipPlansTable.id)
  ).where(
    and(
      eq(membershipSubscriptionsTable.userId, userId),
      inArray(membershipSubscriptionsTable.status, ["ACTIVE", "PENDING"])
    )
  ).orderBy(desc(membershipSubscriptionsTable.createdAt)).limit(1);
  return row?.planTier ?? "STARTER";
}
function normalizeInvestmentOpportunityEligibleInvestorTiers(value) {
  if (!Array.isArray(value)) return [];
  return value.map((tier) => typeof tier === "string" ? tier.toUpperCase() : null).filter((tier) => Boolean(tier));
}
function isInvestmentOpportunityAllowedForMember(params) {
  if ((params.membershipType ?? "").toUpperCase() !== "INVESTOR") {
    return true;
  }
  const eligibleTiers = normalizeInvestmentOpportunityEligibleInvestorTiers(
    params.eligibleInvestorTiers
  );
  if (eligibleTiers.length === 0) {
    return true;
  }
  const normalizedTier = (params.memberTier ?? "").toUpperCase();
  return normalizedTier.length > 0 && eligibleTiers.includes(normalizedTier);
}
async function resolveInvestmentScopeForUser(userId) {
  const [user] = await db.select({
    membershipType: usersTable.membershipType,
    userOrganizationId: usersTable.organizationId
  }).from(usersTable).where(eq(usersTable.id, userId)).limit(1);
  if (user?.membershipType === "ORGANIZATION") {
    if (typeof user.userOrganizationId === "number") {
      return {
        kind: "ORG_SCOPED",
        organizationId: user.userOrganizationId
      };
    }
    const [orgMembership] = await db.select({
      organizationId: organizationMembersTable.organizationId,
      status: organizationMembersTable.status
    }).from(organizationMembersTable).where(
      and(
        eq(organizationMembersTable.userId, userId),
        eq(organizationMembersTable.status, "ACTIVE")
      )
    ).orderBy(desc(organizationMembersTable.id)).limit(1);
    if (orgMembership) {
      return {
        kind: "ORG_SCOPED",
        organizationId: orgMembership.organizationId
      };
    }
    return { kind: "GLOBAL" };
  }
  if (user?.membershipType === "INDIVIDUAL" || user?.membershipType === "INVESTOR") {
    const [orgMembership] = await db.select({
      organizationId: organizationMembersTable.organizationId,
      status: organizationMembersTable.status
    }).from(organizationMembersTable).where(
      and(
        eq(organizationMembersTable.userId, userId),
        eq(organizationMembersTable.status, "ACTIVE")
      )
    ).orderBy(desc(organizationMembersTable.id)).limit(1);
    if (orgMembership) {
      return {
        kind: "ORG_SCOPED",
        organizationId: orgMembership.organizationId
      };
    }
  }
  return { kind: "GLOBAL" };
}
function applyInvestmentScopeFilter(filters, scope) {
  if (scope.kind === "ORG_SCOPED") {
    filters.push(
      eq(investmentOpportunitiesTable.organizationId, scope.organizationId)
    );
  } else {
    filters.push(sql`${investmentOpportunitiesTable.organizationId} IS NULL`);
  }
}
async function getAscaBackedInvestmentPortfolioWith(conn, userId, scope, asOf = /* @__PURE__ */ new Date()) {
  const filters = [
    eq(ascaMembersTable.userId, userId),
    eq(ascasTable.type, "INVESTMENT"),
    eq(ascasTable.status, "INVESTED")
  ];
  applyInvestmentScopeFilter(filters, scope);
  const rows = await conn.select({
    ascaId: ascasTable.id,
    ascaName: ascasTable.name,
    ascaCreatedAt: ascasTable.createdAt,
    ascaUpdatedAt: ascasTable.updatedAt,
    opportunityId: investmentOpportunitiesTable.id,
    opportunityTitle: investmentOpportunitiesTable.title,
    category: investmentOpportunitiesTable.category,
    deadline: investmentOpportunitiesTable.deadline,
    expectedReturnPct: investmentOpportunitiesTable.expectedReturnPct,
    contributedAmount: ascaMembersTable.contributedAmount,
    investedAt: walletTransactionsTable.createdAt
  }).from(ascaMembersTable).innerJoin(ascasTable, eq(ascaMembersTable.ascaId, ascasTable.id)).innerJoin(
    investmentOpportunitiesTable,
    eq(ascasTable.investmentId, investmentOpportunitiesTable.id)
  ).leftJoin(
    walletTransactionsTable,
    and(
      eq(walletTransactionsTable.fromWalletId, ascasTable.escrowWalletId),
      eq(walletTransactionsTable.type, "ASCA_INVESTMENT")
    )
  ).where(and(...filters)).orderBy(desc(walletTransactionsTable.createdAt), desc(ascasTable.id));
  return rows.map((row) => {
    const amount = Number(row.contributedAmount ?? 0);
    if (!Number.isFinite(amount) || amount <= 0) return null;
    const confirmedAt = row.investedAt ?? row.ascaUpdatedAt ?? row.ascaCreatedAt;
    const confirmedAtIso = confirmedAt.toISOString().split("T")[0];
    const matured = row.deadline.getTime() <= asOf.getTime();
    const annualRatePct = row.expectedReturnPct ?? null;
    const returnEarned = annualRatePct !== null ? Number(
      calculateAccruedInterest({
        principal: amount,
        annualRatePct,
        startAt: confirmedAt,
        asOf,
        stopAt: row.deadline
      }).toFixed(2)
    ) : null;
    return {
      id: `asca_${row.ascaId}`,
      opportunityId: String(row.opportunityId),
      title: `${row.opportunityTitle} via ${row.ascaName}`,
      category: row.category,
      amount,
      status: matured ? "MATURED" : "CONFIRMED",
      returnEarned,
      submittedAt: confirmedAtIso,
      confirmedAt: confirmedAtIso,
      maturedAt: row.deadline.toISOString().split("T")[0]
    };
  }).filter(Boolean);
}
async function getAscaBackedInvestmentActivityWith(conn, userId, scope) {
  const filters = [
    eq(ascaMembersTable.userId, userId),
    eq(ascasTable.type, "INVESTMENT"),
    eq(walletTransactionsTable.type, "ASCA_INVESTMENT")
  ];
  applyInvestmentScopeFilter(filters, scope);
  const rows = await conn.select({
    walletTxId: walletTransactionsTable.id,
    occurredAt: walletTransactionsTable.createdAt,
    opportunityId: investmentOpportunitiesTable.id,
    opportunityTitle: investmentOpportunitiesTable.title,
    ascaName: ascasTable.name,
    contributedAmount: ascaMembersTable.contributedAmount
  }).from(ascaMembersTable).innerJoin(ascasTable, eq(ascaMembersTable.ascaId, ascasTable.id)).innerJoin(
    investmentOpportunitiesTable,
    eq(ascasTable.investmentId, investmentOpportunitiesTable.id)
  ).innerJoin(
    walletTransactionsTable,
    and(
      eq(walletTransactionsTable.fromWalletId, ascasTable.escrowWalletId),
      eq(walletTransactionsTable.type, "ASCA_INVESTMENT")
    )
  ).where(and(...filters)).orderBy(desc(walletTransactionsTable.createdAt));
  return rows.map((row) => {
    const amount = Number(row.contributedAmount ?? 0);
    if (!Number.isFinite(amount) || amount <= 0) return null;
    return {
      id: `asca_tx_${row.walletTxId}_${row.opportunityId}`,
      opportunityId: String(row.opportunityId),
      title: `${row.opportunityTitle} funded via ${row.ascaName}`,
      amount,
      direction: "OUT",
      occurredAt: row.occurredAt.toISOString()
    };
  }).filter(Boolean);
}
async function validateInvestmentOpportunityScope(userId, opportunity) {
  const scope = await resolveInvestmentScopeForUser(userId);
  if (scope.kind === "GLOBAL") {
    if (opportunity.organizationId !== null) {
      return {
        allowed: false,
        reason: "This opportunity is not available in your scope."
      };
    }
  } else {
    if (opportunity.organizationId !== scope.organizationId) {
      return {
        allowed: false,
        reason: "This opportunity is not available for your organization."
      };
    }
  }
  return { allowed: true };
}
async function requireTreasuryAccess(req, res) {
  const userId = req.userId;
  const [user] = await db.select().from(usersTable).where(eq(usersTable.id, userId)).limit(1);
  if (!user) {
    void res.status(404).json({ message: "User not found." });
    return null;
  }
  const lens = getInvestorPackageLens({
    membershipType: user.membershipType ?? null,
    membershipStatus: user.membershipStatus ?? null,
    userRole: user.userRole ?? null,
    segment: user.segment ?? null,
    investorCategory: user.investorCategory ?? null
  });
  if (!lens.canDoTreasuryTransfer) {
    void res.status(403).json({
      message: "Treasury access requires Worker Owner or Admin privileges."
    });
    return null;
  }
  return { userId, user };
}
var import_express8, router8, MemberProductAccessError, optionalProfileString, optionalInvestorCategory, optionalProfileUrl, memberProfileUpdateSchema, memberCredentialsUpdateSchema, membershipActivationSchema, membershipStripeSubscribeSchema, membershipStripeCheckoutConfirmSchema, membershipPlanChangeSchema, ACTIVE_LENDING_POOL_STATUSES, BLOCKING_HELPING_HAND_DEBT_STATUSES2, LENDING_MASTER_WALLET_OWNER_ID3, LOAN_APPLICATION_LOCK_KEY_A, LOAN_REPAYMENT_LOCK_KEY_A, MEMBERSHIP_ACTIVATION_LOCK_KEY_A, PLATFORM_WALLET_OWNER_ID2, registerPushTokenSchema, updateNotificationPreferenceSchema, member_default;
var init_member = __esm({
  "src/routes/member.ts"() {
    "use strict";
    init_bcryptjs();
    import_express8 = __toESM(require_express2(), 1);
    init_zod();
    init_src2();
    init_investment_funding();
    init_schema2();
    init_drizzle_orm();
    init_credit_score();
    init_onboarding_cadence();
    init_config();
    init_auth_session();
    init_investments();
    init_stripe();
    init_member_onboarding_program();
    init_lending();
    init_helping_hand();
    init_susu();
    init_member_access();
    init_member_plan_entitlements();
    init_organization_context();
    init_organization_authorization();
    init_organization_tenancy();
    init_pdf();
    init_profile();
    init_membership_registration_id();
    init_session_profile();
    init_investment_constants();
    init_admin_metrics();
    init_member_access();
    init_notifications();
    init_notification_dispatcher();
    init_admin_notifications();
    init_notification_deliveries();
    init_push();
    init_notification_preferences();
    init_live_events();
    router8 = (0, import_express8.Router)();
    router8.get("/member/events/stream", requireAuth2, (req, res) => {
      const userId = req.userId;
      res.status(200);
      res.setHeader("Content-Type", "text/event-stream");
      res.setHeader("Cache-Control", "no-cache, no-transform");
      res.setHeader("Connection", "keep-alive");
      res.setHeader("X-Accel-Buffering", "no");
      res.flushHeaders?.();
      const unsubscribe = subscribeUserToLiveEvents(userId, res);
      writePing(res);
      const pingInterval = setInterval(() => {
        writePing(res);
      }, 25e3);
      req.on("close", () => {
        clearInterval(pingInterval);
        unsubscribe();
      });
    });
    router8.get("/org/context", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        const context = await resolveOrganizationSessionContext(userId);
        if (!context) {
          return res.status(403).json({
            message: "Organization tenant context is available only to organization members."
          });
        }
        return res.json({ organization: context });
      } catch (err) {
        const maybeTenantError = err;
        return res.status(500).json({
          message: maybeTenantError?.message ?? "Failed to resolve organization tenant context."
        });
      }
    });
    MemberProductAccessError = class extends Error {
      statusCode;
      constructor(message, statusCode = 403) {
        super(message);
        this.name = "MemberProductAccessError";
        this.statusCode = statusCode;
      }
    };
    optionalProfileString = external_exports.string().trim().max(280).optional().or(external_exports.literal("")).transform(
      (value) => value === void 0 ? void 0 : value && value.length ? value : null
    );
    optionalInvestorCategory = external_exports.enum(["WORKER_OWNER", "COMMUNITY_SPONSOR", "IMPACT_INVESTOR"]).optional().or(external_exports.literal("")).transform(
      (value) => value === void 0 ? void 0 : value && value.length ? value : null
    );
    optionalProfileUrl = external_exports.string().trim().optional().or(external_exports.literal("")).transform(
      (value) => value === void 0 ? void 0 : value && value.length ? value : null
    ).refine((value) => {
      if (!value) return true;
      try {
        const url2 = new URL(value);
        return url2.protocol === "http:" || url2.protocol === "https:";
      } catch {
        return false;
      }
    });
    memberProfileUpdateSchema = external_exports.object({
      firstName: external_exports.string().trim().min(1).max(191).optional(),
      lastName: optionalProfileString,
      phone: optionalProfileString,
      username: external_exports.string().trim().min(3).max(30).regex(/^[a-zA-Z0-9_]+$/).optional().or(external_exports.literal("")).transform(
        (value) => value === void 0 ? void 0 : value && value.length ? value : null
      ),
      bio: optionalProfileString,
      contactAddress: optionalProfileString,
      contactStreet: optionalProfileString,
      contactPostalCode: optionalProfileString,
      contactCountryIso2: optionalProfileString,
      city: optionalProfileString,
      province: optionalProfileString,
      ageRange: optionalProfileString,
      occupation: optionalProfileString,
      employmentEmployed: external_exports.boolean().optional().nullable(),
      employmentStatus: optionalProfileString,
      employerName: optionalProfileString,
      employerAddress: optionalProfileString,
      employmentPosition: optionalProfileString,
      businessName: optionalProfileString,
      businessType: optionalProfileString,
      yearsInBusiness: optionalProfileString,
      annualRevenue: optionalProfileString,
      howHeard: optionalProfileString,
      referrerName: optionalProfileString,
      referrerPhone: optionalProfileString,
      referrerWwnId: optionalProfileString,
      referrerAddress: optionalProfileString,
      referrerStreet: optionalProfileString,
      referrerCity: optionalProfileString,
      referrerPostalCode: optionalProfileString,
      goals: optionalProfileString,
      consentAccepted: external_exports.boolean().optional(),
      nextOfKinFirstName: optionalProfileString,
      nextOfKinLastName: optionalProfileString,
      nextOfKinOtherNames: optionalProfileString,
      nextOfKinGender: optionalProfileString,
      nextOfKinResidentialAddress: optionalProfileString,
      nextOfKinStreet: optionalProfileString,
      nextOfKinCity: optionalProfileString,
      nextOfKinPostalCode: optionalProfileString,
      nextOfKinEmail: optionalProfileString,
      nextOfKinPhone: optionalProfileString,
      nextOfKinRelationship: optionalProfileString,
      nextOfKinOccupation: optionalProfileString,
      kycIdFrontUrl: optionalProfileUrl,
      kycIdBackUrl: optionalProfileUrl,
      kycSelfieUrl: optionalProfileUrl,
      investorCategory: optionalInvestorCategory
    });
    memberCredentialsUpdateSchema = external_exports.object({
      currentPassword: external_exports.string().min(1),
      newPassword: external_exports.string().min(8)
    });
    membershipActivationSchema = external_exports.object({
      planId: external_exports.coerce.number().int().positive(),
      paymentMethod: external_exports.enum(["INTERAC", "EFT", "WALLET"]),
      paymentReference: external_exports.string().trim().min(3).max(191).optional().nullable(),
      proofUrl: external_exports.string().trim().optional().nullable().refine((value) => {
        if (!value) return true;
        try {
          const url2 = new URL(value);
          return url2.protocol === "http:" || url2.protocol === "https:";
        } catch {
          return false;
        }
      }),
      note: external_exports.string().trim().max(2e3).optional().nullable()
    });
    membershipStripeSubscribeSchema = external_exports.object({
      planId: external_exports.coerce.number().int().positive(),
      returnPath: external_exports.string().trim().max(200).optional()
    });
    membershipStripeCheckoutConfirmSchema = external_exports.object({
      sessionId: external_exports.string().trim().min(3)
    });
    membershipPlanChangeSchema = external_exports.object({
      planId: external_exports.coerce.number().int().positive()
    });
    ACTIVE_LENDING_POOL_STATUSES = [...ACTIVE_LENDING_APPLICATION_STATUSES];
    BLOCKING_HELPING_HAND_DEBT_STATUSES2 = ["FUNDED", "REPAYING"];
    LENDING_MASTER_WALLET_OWNER_ID3 = 1;
    LOAN_APPLICATION_LOCK_KEY_A = 88101;
    LOAN_REPAYMENT_LOCK_KEY_A = 88102;
    MEMBERSHIP_ACTIVATION_LOCK_KEY_A = 88103;
    PLATFORM_WALLET_OWNER_ID2 = 1;
    router8.get("/member/wallet", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        const [user] = await db.select({
          id: usersTable.id,
          membershipType: usersTable.membershipType,
          organizationId: usersTable.organizationId
        }).from(usersTable).where(eq(usersTable.id, userId)).limit(1);
        if (!user) {
          return res.status(404).json({ message: "User not found." });
        }
        const walletScope = await resolveMemberWalletScopeWith(db, user);
        const [funds, transactions] = await Promise.all([
          getWalletFundsWith2(db, walletScope.wallet.id),
          getWalletTransactionsWith(db, walletScope.wallet.id)
        ]);
        return res.json({
          wallet: {
            id: walletScope.wallet.id,
            currency: walletScope.wallet.currency,
            balance: funds.balance,
            reservedBalance: funds.reservedBalance,
            availableBalance: funds.availableBalance,
            transactions,
            ownerType: walletScope.ownerType,
            ownerId: walletScope.ownerId,
            usesOrganizationWallet: walletScope.usesOrganizationWallet
          }
        });
      } catch (err) {
        console.error("GET /member/wallet error:", err);
        return res.status(500).json({ message: "Failed to fetch wallet." });
      }
    });
    router8.post("/member/wallet/topup-intents", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        const parsed = external_exports.object({
          amount: external_exports.string().min(1),
          provider: external_exports.enum(["STRIPE", "INTERAC", "MANUAL"]).optional(),
          metadata: external_exports.record(external_exports.unknown()).optional()
        }).safeParse(req.body ?? {});
        if (!parsed.success)
          return res.status(400).json({ errors: parsed.error.flatten() });
        const numericAmount = Number(parsed.data.amount);
        if (!Number.isFinite(numericAmount) || numericAmount <= 0) {
          return res.status(400).json({ message: "Invalid amount." });
        }
        if (hasMoreThanTwoDecimalPlaces(numericAmount)) {
          return res.status(400).json({ message: "Amount can have at most 2 decimal places." });
        }
        const provider = parsed.data.provider ?? "MANUAL";
        const organizationContext = await resolveOrganizationSessionContext(userId);
        const isOrganizationWorkspaceMemberFunding = organizationContext?.membership?.role === "MEMBER";
        if (isOrganizationWorkspaceMemberFunding && provider === "STRIPE") {
          return res.status(403).json({
            message: "Organization workspace members must use the organization's payment methods."
          });
        }
        const result = await db.transaction(async (tx) => {
          const [user] = await tx.select({
            id: usersTable.id,
            membershipType: usersTable.membershipType,
            organizationId: usersTable.organizationId
          }).from(usersTable).where(eq(usersTable.id, userId)).limit(1);
          if (!user) {
            throw new Error("User not found.");
          }
          const walletScope = await resolveMemberWalletScopeWith(tx, user);
          const wallet = walletScope.wallet;
          const isOrganizationMemberFundingIntent = isOrganizationWorkspaceMemberFunding && walletScope.organizationId !== null;
          const [intent] = await tx.insert(walletPaymentIntentsTable).values({
            userId,
            walletId: wallet.id,
            provider,
            type: "TOP_UP",
            amount: parsed.data.amount,
            currency: wallet.currency,
            status: provider === "STRIPE" ? "CREATED" : "PENDING",
            metadata: {
              ...parsed.data.metadata ?? {},
              fundingIntent: isOrganizationMemberFundingIntent ? "ORGANIZATION_MEMBER_WALLET" : "USER_WALLET",
              source: isOrganizationMemberFundingIntent ? "organization_member_wallet_funding" : "member_wallet_topup",
              walletOwnerType: walletScope.ownerType,
              walletOwnerId: walletScope.ownerId,
              organizationId: walletScope.organizationId
            }
          }).returning();
          if (provider === "STRIPE") {
            const stripe = getStripeClient();
            const amountCents = Math.round(numericAmount * 100);
            const paymentIntent = await stripe.paymentIntents.create(
              {
                amount: amountCents,
                currency: wallet.currency.toLowerCase(),
                automatic_payment_methods: { enabled: true },
                metadata: {
                  walletPaymentIntentId: String(intent.id),
                  userId: String(userId),
                  walletId: String(wallet.id),
                  intentType: "TOP_UP",
                  walletOwnerType: walletScope.ownerType,
                  walletOwnerId: String(walletScope.ownerId),
                  organizationId: walletScope.organizationId !== null ? String(walletScope.organizationId) : ""
                },
                description: isOrganizationMemberFundingIntent ? `Member wallet top-up (${wallet.currency} ${numericAmount.toFixed(2)})` : `WWN wallet top-up (${wallet.currency} ${numericAmount.toFixed(2)})`
              },
              {
                idempotencyKey: `wallet_topup_intent_${intent.id}`
              }
            );
            const [updatedIntent2] = await tx.update(walletPaymentIntentsTable).set({
              status: "PENDING",
              providerReference: paymentIntent.id,
              updatedAt: /* @__PURE__ */ new Date()
            }).where(eq(walletPaymentIntentsTable.id, intent.id)).returning();
            const walletBalance2 = await getWalletBalanceWith4(tx, wallet.id);
            return {
              kind: "STRIPE",
              intent: updatedIntent2,
              walletBalance: walletBalance2,
              clientSecret: paymentIntent.client_secret
            };
          }
          const [platformSetup] = await tx.select().from(bankSetupTable).limit(1);
          const [organizationSetup] = isOrganizationMemberFundingIntent && walletScope.organizationId !== null ? await tx.select().from(organizationBankSettingsTable).where(
            eq(
              organizationBankSettingsTable.organizationId,
              walletScope.organizationId
            )
          ).limit(1) : [];
          const setup = isOrganizationMemberFundingIntent ? organizationSetup : platformSetup;
          if (!setup) {
            throw new Error(
              isOrganizationMemberFundingIntent ? "Organization payment methods are not configured." : "Bank setup is not configured."
            );
          }
          const metadata = intent.metadata ?? {};
          const providedReference = typeof metadata["reference"] === "string" ? metadata["reference"] : "";
          const providerReference = providedReference || (provider === "INTERAC" ? `INTERAC-${intent.id}` : `EFT-${intent.id}`);
          const [updatedIntent] = await tx.update(walletPaymentIntentsTable).set({
            providerReference,
            metadata: {
              ...intent.metadata ?? {},
              ...parsed.data.metadata ?? {},
              fundingMethod: provider === "MANUAL" ? "BANK_DEPOSIT" : "INTERAC",
              source: isOrganizationMemberFundingIntent ? "organization_member_wallet_funding" : "member_wallet_topup",
              walletOwnerType: walletScope.ownerType,
              walletOwnerId: walletScope.ownerId,
              organizationId: walletScope.organizationId
            },
            updatedAt: /* @__PURE__ */ new Date()
          }).where(eq(walletPaymentIntentsTable.id, intent.id)).returning();
          const walletBalance = await getWalletBalanceWith4(tx, wallet.id);
          const nextAction = provider === "INTERAC" ? {
            title: "Interac",
            message: `Send Interac to ${setup.interacEmail} (${setup.interacRecipientName}). Use reference ${providerReference}.`,
            reference: providerReference
          } : {
            title: "EFT",
            message: `Send EFT to ${setup.eftAccountName}. Institution ${setup.eftInstitutionNumber}, Transit ${setup.eftTransitNumber}, Account ${setup.eftAccountNumber}. Use reference ${providerReference}.`,
            reference: providerReference
          };
          return {
            kind: "MANUAL_PENDING",
            intent: updatedIntent,
            walletBalance,
            nextAction
          };
        });
        try {
          publishLiveEventToUser(userId, {
            kind: "DATA_CHANGED",
            scopes: ["wallet"],
            payload: { action: "wallet_topup_intent_created" }
          });
        } catch {
        }
        try {
          if (isOrganizationWorkspaceMemberFunding && result.intent.metadata && typeof result.intent.metadata === "object" && Number(
            result.intent.metadata["organizationId"]
          ) > 0) {
            const organizationId = Number(
              result.intent.metadata["organizationId"]
            );
            const approverIds = await listOrganizationWalletApproverIdsWith(
              db,
              organizationId
            );
            const [sender] = await db.select({
              firstName: usersTable.firstName,
              lastName: usersTable.lastName
            }).from(usersTable).where(eq(usersTable.id, userId)).limit(1);
            const senderName = [sender?.firstName, sender?.lastName].filter(Boolean).join(" ") || "A member";
            await Promise.all(
              approverIds.filter((approverId) => approverId !== userId).map(
                (approverId) => notifyInAppWith(db, {
                  userId: approverId,
                  category: "PAYMENT",
                  severity: "INFO",
                  title: "Member wallet funding submitted",
                  body: `${senderName} submitted ${numericAmount.toFixed(2)} for member wallet funding.`,
                  actionLabel: "Open Wallet",
                  actionHref: "/dashboard/wallet"
                }).catch(() => null)
              )
            );
          } else {
            const actorName = await getAdminNotificationActorName(userId);
            void notifyAdminsWith(db, {
              category: "PAYMENT",
              severity: "INFO",
              title: "Wallet top-up initiated",
              body: `${actorName} created a ${provider} top-up intent for ${numericAmount.toFixed(2)}.`,
              actionLabel: "Open Wallets",
              actionHref: "/admin/wallets"
            });
          }
        } catch {
        }
        if (result.kind === "STRIPE") {
          return res.status(201).json({
            intent: {
              id: result.intent.id,
              provider: result.intent.provider,
              type: result.intent.type,
              amount: Number(result.intent.amount),
              currency: result.intent.currency,
              status: result.intent.status,
              createdAt: result.intent.createdAt.toISOString(),
              providerReference: result.intent.providerReference ?? null,
              devStub: false,
              stripe: {
                clientSecret: result.clientSecret
              }
            },
            transaction: null,
            walletBalance: result.walletBalance
          });
        }
        return res.status(201).json({
          intent: {
            id: result.intent.id,
            provider: result.intent.provider,
            type: result.intent.type,
            amount: Number(result.intent.amount),
            currency: result.intent.currency,
            status: result.intent.status,
            createdAt: result.intent.createdAt.toISOString(),
            providerReference: result.intent.providerReference ?? null,
            devStub: false,
            nextAction: result.nextAction
          },
          transaction: null,
          walletBalance: result.walletBalance
        });
      } catch (err) {
        console.error("POST /member/wallet/topup-intents error:", err);
        return res.status(500).json({ message: "Failed to create top-up intent." });
      }
    });
    router8.post(
      "/member/wallet/topup-intents/:id/confirm",
      requireAuth2,
      async (req, res) => {
        const userId = req.userId;
        try {
          const intentId = Number(req.params.id);
          if (!Number.isFinite(intentId) || intentId <= 0) {
            return res.status(400).json({ message: "Invalid top-up intent id." });
          }
          const [walletIntent] = await db.select().from(walletPaymentIntentsTable).where(
            and(
              eq(walletPaymentIntentsTable.id, intentId),
              eq(walletPaymentIntentsTable.userId, userId)
            )
          ).limit(1);
          if (!walletIntent) {
            return res.status(404).json({ message: "Top-up intent not found." });
          }
          if (walletIntent.provider !== "STRIPE" || walletIntent.type !== "TOP_UP") {
            return res.status(400).json({ message: "This intent is not a Stripe top-up." });
          }
          if (walletIntent.status === "SUCCEEDED") {
            const walletBalance = await getWalletBalanceWith4(
              db,
              walletIntent.walletId
            );
            return res.json({
              intent: {
                id: walletIntent.id,
                status: walletIntent.status,
                providerReference: walletIntent.providerReference ?? null
              },
              walletBalance
            });
          }
          const paymentIntentId = walletIntent.providerReference ?? "";
          if (!paymentIntentId) {
            return res.status(400).json({ message: "Missing Stripe payment reference." });
          }
          const stripe = getStripeClient();
          const paymentIntent = await stripe.paymentIntents.retrieve(paymentIntentId);
          const status = paymentIntent.status;
          if (status !== "succeeded") {
            const nextStatus = status === "canceled" || status === "requires_payment_method" ? "FAILED" : walletIntent.status;
            if (status === "canceled" || status === "requires_payment_method") {
              await db.update(walletPaymentIntentsTable).set({ status: "FAILED", updatedAt: /* @__PURE__ */ new Date() }).where(eq(walletPaymentIntentsTable.id, walletIntent.id));
            }
            return res.json({
              intent: {
                id: walletIntent.id,
                status: nextStatus,
                providerReference: walletIntent.providerReference ?? null,
                stripeStatus: status
              },
              walletBalance: await getWalletBalanceWith4(db, walletIntent.walletId)
            });
          }
          const settled = await db.transaction(async (tx) => {
            const now = /* @__PURE__ */ new Date();
            const [fresh] = await tx.select().from(walletPaymentIntentsTable).where(eq(walletPaymentIntentsTable.id, walletIntent.id)).limit(1);
            if (!fresh) throw new Error("Top-up intent not found.");
            if (fresh.status !== "SUCCEEDED") {
              const idempotencyKey = `wallet-topup-intent:${fresh.id}:stripe:${paymentIntent.id}`;
              await tx.insert(walletTransactionsTable).values({
                type: "TOP_UP",
                idempotencyKey,
                toWalletId: fresh.walletId,
                amount: fresh.amount,
                metadata: {
                  intentId: fresh.id,
                  provider: "STRIPE",
                  providerReference: paymentIntent.id,
                  fundingMethod: "STRIPE"
                }
              }).onConflictDoNothing();
              await tx.update(walletPaymentIntentsTable).set({
                status: "SUCCEEDED",
                providerReference: paymentIntent.id,
                updatedAt: now
              }).where(eq(walletPaymentIntentsTable.id, fresh.id));
            }
            const walletBalance = await getWalletBalanceWith4(tx, fresh.walletId);
            return { walletBalance };
          });
          publishLiveEventToUser(userId, {
            kind: "DATA_CHANGED",
            scopes: ["wallet"],
            payload: { action: "wallet_topup_succeeded" }
          });
          const actorName = await getAdminNotificationActorName(userId);
          void notifyAdminsWith(db, {
            category: "PAYMENT",
            severity: "SUCCESS",
            title: "Wallet funded",
            body: `${actorName} wallet top-up succeeded.`,
            actionLabel: "Open Wallets",
            actionHref: "/admin/wallets"
          });
          return res.json({
            intent: {
              id: walletIntent.id,
              status: "SUCCEEDED",
              providerReference: paymentIntent.id
            },
            walletBalance: settled.walletBalance
          });
        } catch (err) {
          console.error(
            "POST /member/wallet/topup-intents/:id/confirm error:",
            err
          );
          return res.status(500).json({ message: "Failed to confirm top-up." });
        }
      }
    );
    router8.get("/member/bank-setup", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        const [user] = await db.select({
          id: usersTable.id,
          membershipType: usersTable.membershipType,
          organizationId: usersTable.organizationId
        }).from(usersTable).where(eq(usersTable.id, userId)).limit(1);
        if (!user) {
          return res.status(404).json({ message: "User not found." });
        }
        const walletScope = await resolveMemberWalletScopeWith(db, user);
        if (walletScope.usesOrganizationWallet && walletScope.organizationId) {
          const [setup2] = await db.select().from(organizationBankSettingsTable).where(
            eq(
              organizationBankSettingsTable.organizationId,
              walletScope.organizationId
            )
          ).limit(1);
          if (!setup2) {
            return res.status(409).json({
              message: "Organization payment methods are not configured. Update Payment Methods."
            });
          }
          return res.json({
            bankSetup: {
              eft: {
                accountName: setup2.eftAccountName,
                institutionNumber: setup2.eftInstitutionNumber,
                transitNumber: setup2.eftTransitNumber,
                accountNumber: setup2.eftAccountNumber
              },
              interac: {
                recipientName: setup2.interacRecipientName,
                email: setup2.interacEmail
              },
              charges: {
                cashoutMinAmount: Number(setup2.cashoutMinAmount),
                cashoutFeePct: Number(setup2.cashoutFeePct),
                cashoutFeeFixed: Number(setup2.cashoutFeeFixed)
              }
            }
          });
        }
        const [setup] = await db.select().from(bankSetupTable).limit(1);
        if (!setup) {
          return res.status(500).json({ message: "Bank setup is not configured." });
        }
        return res.json({
          bankSetup: {
            eft: {
              accountName: setup.eftAccountName,
              institutionNumber: setup.eftInstitutionNumber,
              transitNumber: setup.eftTransitNumber,
              accountNumber: setup.eftAccountNumber
            },
            interac: {
              recipientName: setup.interacRecipientName,
              email: setup.interacEmail
            },
            charges: {
              cashoutMinAmount: Number(setup.cashoutMinAmount),
              cashoutFeePct: Number(setup.cashoutFeePct),
              cashoutFeeFixed: Number(setup.cashoutFeeFixed)
            }
          }
        });
      } catch (err) {
        console.error("GET /member/bank-setup error:", err);
        return res.status(500).json({ message: "Failed to load bank setup." });
      }
    });
    router8.get("/member/wallet/topup-intents", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        const [user] = await db.select({
          id: usersTable.id,
          membershipType: usersTable.membershipType,
          organizationId: usersTable.organizationId
        }).from(usersTable).where(eq(usersTable.id, userId)).limit(1);
        if (!user) {
          return res.status(404).json({ message: "User not found." });
        }
        const walletScope = await resolveMemberWalletScopeWith(db, user);
        const rows = await db.select().from(walletPaymentIntentsTable).where(
          and(
            eq(walletPaymentIntentsTable.walletId, walletScope.wallet.id),
            eq(walletPaymentIntentsTable.type, "TOP_UP")
          )
        ).orderBy(desc(walletPaymentIntentsTable.createdAt)).limit(25);
        return res.json({
          intents: rows.map((i) => ({
            id: i.id,
            provider: i.provider,
            type: i.type,
            amount: Number(i.amount),
            currency: i.currency,
            status: i.status,
            providerReference: i.providerReference ?? null,
            metadata: i.metadata ?? {},
            createdAt: i.createdAt.toISOString(),
            updatedAt: i.updatedAt.toISOString()
          }))
        });
      } catch (err) {
        console.error("GET /member/wallet/topup-intents error:", err);
        return res.status(500).json({ message: "Failed to fetch top-ups." });
      }
    });
    router8.get("/member/wallet/cashout-intents", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        const [user] = await db.select({
          id: usersTable.id,
          membershipType: usersTable.membershipType,
          organizationId: usersTable.organizationId
        }).from(usersTable).where(eq(usersTable.id, userId)).limit(1);
        if (!user) {
          return res.status(404).json({ message: "User not found." });
        }
        const walletScope = await resolveMemberWalletScopeWith(db, user);
        const rows = await db.select().from(walletPaymentIntentsTable).where(
          and(
            eq(walletPaymentIntentsTable.walletId, walletScope.wallet.id),
            eq(walletPaymentIntentsTable.type, "CASH_OUT")
          )
        ).orderBy(desc(walletPaymentIntentsTable.createdAt)).limit(25);
        return res.json({
          intents: rows.map((i) => ({
            id: i.id,
            provider: i.provider,
            type: i.type,
            amount: Number(i.amount),
            currency: i.currency,
            status: i.status,
            providerReference: i.providerReference ?? null,
            metadata: i.metadata ?? {},
            createdAt: i.createdAt.toISOString(),
            updatedAt: i.updatedAt.toISOString()
          }))
        });
      } catch (err) {
        console.error("GET /member/wallet/cashout-intents error:", err);
        return res.status(500).json({ message: "Failed to fetch withdrawals." });
      }
    });
    router8.post("/member/wallet/cashout-intents", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        const parsed = external_exports.object({
          amount: external_exports.string().min(1),
          method: external_exports.enum(["EFT", "INTERAC"]),
          destination: external_exports.record(external_exports.unknown()).optional(),
          note: external_exports.string().max(500).optional()
        }).safeParse(req.body ?? {});
        if (!parsed.success)
          return res.status(400).json({ errors: parsed.error.flatten() });
        const numericAmount = Number(parsed.data.amount);
        if (!Number.isFinite(numericAmount) || numericAmount <= 0) {
          return res.status(400).json({ message: "Invalid amount." });
        }
        if (hasMoreThanTwoDecimalPlaces(numericAmount)) {
          return res.status(400).json({ message: "Amount can have at most 2 decimal places." });
        }
        const result = await db.transaction(async (tx) => {
          const [user] = await tx.select({
            id: usersTable.id,
            membershipType: usersTable.membershipType,
            organizationId: usersTable.organizationId
          }).from(usersTable).where(eq(usersTable.id, userId)).limit(1);
          if (!user) {
            throw new Error("User not found.");
          }
          const walletScope = await resolveMemberWalletScopeWith(tx, user);
          const wallet = walletScope.wallet;
          const feeSource = walletScope.usesOrganizationWallet && walletScope.organizationId ? "ORGANIZATION" : "PLATFORM";
          let minAmount = 0;
          let feePct = 0;
          let feeFixed = 0;
          if (feeSource === "ORGANIZATION" && walletScope.organizationId) {
            const [orgSetup] = await tx.select().from(organizationBankSettingsTable).where(
              eq(
                organizationBankSettingsTable.organizationId,
                walletScope.organizationId
              )
            ).limit(1);
            if (!orgSetup) {
              return {
                status: 409,
                body: {
                  message: "Organization bank charges are not configured. Update Payment Methods."
                }
              };
            }
            minAmount = Number(orgSetup.cashoutMinAmount);
            feePct = Number(orgSetup.cashoutFeePct);
            feeFixed = Number(orgSetup.cashoutFeeFixed);
          } else {
            const [bankSetup] = await tx.select().from(bankSetupTable).limit(1);
            if (!bankSetup) {
              return {
                status: 500,
                body: { message: "Bank setup is not configured." }
              };
            }
            minAmount = Number(bankSetup.cashoutMinAmount);
            feePct = Number(bankSetup.cashoutFeePct);
            feeFixed = Number(bankSetup.cashoutFeeFixed);
          }
          if (!Number.isFinite(minAmount) || !Number.isFinite(feePct) || !Number.isFinite(feeFixed) || minAmount < 0 || feePct < 0 || feeFixed < 0) {
            return {
              status: 500,
              body: { message: "Bank charges are misconfigured." }
            };
          }
          if (numericAmount < minAmount) {
            return {
              status: 400,
              body: {
                message: `Minimum withdrawal amount is ${minAmount.toFixed(2)}.`
              }
            };
          }
          const feeAmount = Number(
            (numericAmount * feePct / 100 + feeFixed).toFixed(2)
          );
          const netAmount = Number((numericAmount - feeAmount).toFixed(2));
          if (netAmount <= 0) {
            return {
              status: 400,
              body: { message: "Withdrawal amount is too low." }
            };
          }
          const funds = await getWalletFundsWith2(tx, wallet.id);
          if (funds.availableBalance < numericAmount) {
            return {
              status: 400,
              body: { message: "Insufficient available wallet balance." }
            };
          }
          const [intent] = await tx.insert(walletPaymentIntentsTable).values({
            userId,
            walletId: wallet.id,
            provider: "MANUAL",
            type: "CASH_OUT",
            amount: numericAmount.toFixed(2),
            currency: wallet.currency,
            status: "CREATED",
            metadata: {
              method: parsed.data.method,
              destination: parsed.data.destination ?? {},
              note: parsed.data.note ?? null,
              feePct,
              feeFixed,
              feeAmount,
              netAmount,
              feeSource,
              walletOwnerType: walletScope.ownerType,
              walletOwnerId: walletScope.ownerId,
              organizationId: walletScope.organizationId
            }
          }).returning();
          const nextFunds = await getWalletFundsWith2(tx, wallet.id);
          return {
            status: 201,
            body: {
              intent: {
                id: intent.id,
                provider: intent.provider,
                type: intent.type,
                amount: Number(intent.amount),
                currency: intent.currency,
                status: intent.status,
                createdAt: intent.createdAt.toISOString(),
                providerReference: intent.providerReference ?? null,
                metadata: intent.metadata ?? {}
              },
              wallet: {
                balance: nextFunds.balance,
                reservedBalance: nextFunds.reservedBalance,
                availableBalance: nextFunds.availableBalance
              }
            }
          };
        });
        if (result.status === 201) {
          publishLiveEventToUser(userId, {
            kind: "DATA_CHANGED",
            scopes: ["wallet"],
            payload: { action: "wallet_cashout_intent_created" }
          });
          const actorName = await getAdminNotificationActorName(userId);
          void notifyAdminsWith(db, {
            category: "PAYMENT",
            severity: "WARNING",
            title: "Withdrawal requested",
            body: `${actorName} requested a withdrawal of ${numericAmount.toFixed(2)}.`,
            actionLabel: "Open Wallets",
            actionHref: "/admin/wallets"
          });
        }
        return res.status(result.status).json(result.body);
      } catch (err) {
        console.error("POST /member/wallet/cashout-intents error:", err);
        return res.status(500).json({ message: "Failed to create withdrawal." });
      }
    });
    router8.post(
      "/member/wallet/cashout-intents/:id/cancel",
      requireAuth2,
      async (req, res) => {
        const userId = req.userId;
        try {
          const intentId = Number(req.params.id);
          if (!Number.isFinite(intentId) || intentId <= 0) {
            return res.status(400).json({ message: "Invalid withdrawal id." });
          }
          const result = await db.transaction(async (tx) => {
            const [intent] = await tx.select().from(walletPaymentIntentsTable).where(
              and(
                eq(walletPaymentIntentsTable.id, intentId),
                eq(walletPaymentIntentsTable.userId, userId),
                eq(walletPaymentIntentsTable.type, "CASH_OUT")
              )
            ).limit(1);
            if (!intent)
              return { status: 404, body: { message: "Not found." } };
            if (intent.status !== "CREATED") {
              return {
                status: 400,
                body: { message: "This withdrawal can no longer be cancelled." }
              };
            }
            const [updated] = await tx.update(walletPaymentIntentsTable).set({ status: "CANCELLED", updatedAt: /* @__PURE__ */ new Date() }).where(eq(walletPaymentIntentsTable.id, intent.id)).returning();
            const funds = await getWalletFundsWith2(tx, updated.walletId);
            return {
              status: 200,
              body: {
                intent: {
                  id: updated.id,
                  status: updated.status,
                  updatedAt: updated.updatedAt.toISOString()
                },
                wallet: {
                  balance: funds.balance,
                  reservedBalance: funds.reservedBalance,
                  availableBalance: funds.availableBalance
                }
              }
            };
          });
          if (result.status === 200) {
            publishLiveEventToUser(userId, {
              kind: "DATA_CHANGED",
              scopes: ["wallet"],
              payload: { action: "wallet_cashout_intent_cancelled" }
            });
            const actorName = await getAdminNotificationActorName(userId);
            void notifyAdminsWith(db, {
              category: "PAYMENT",
              severity: "INFO",
              title: "Withdrawal cancelled",
              body: `${actorName} cancelled a withdrawal request.`,
              actionLabel: "Open Wallets",
              actionHref: "/admin/wallets"
            });
          }
          return res.status(result.status).json(result.body);
        } catch (err) {
          console.error(
            "POST /member/wallet/cashout-intents/:id/cancel error:",
            err
          );
          return res.status(500).json({ message: "Failed to cancel withdrawal." });
        }
      }
    );
    router8.get("/member/profile", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        let [user] = await db.select().from(usersTable).where(eq(usersTable.id, userId));
        if (!user) {
          return res.status(404).json({ message: "User not found." });
        }
        if (!user.membershipRegistrationId) {
          await assignMembershipRegistrationId(db, {
            userId,
            organizationId: user.organizationId ?? null
          });
          [user] = await db.select().from(usersTable).where(eq(usersTable.id, userId));
        }
        return res.json({
          profile: await formatMemberProfileWithTenantContext(user)
        });
      } catch (err) {
        console.error("GET /member/profile error:", err);
        return res.status(500).json({ message: "Failed to fetch profile." });
      }
    });
    router8.patch("/member/profile", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        const parsed = memberProfileUpdateSchema.safeParse(req.body ?? {});
        if (!parsed.success) {
          return res.status(400).json({ errors: parsed.error.flatten() });
        }
        const updates = Object.fromEntries(
          Object.entries(parsed.data).filter(([, value]) => value !== void 0)
        );
        if (Object.keys(updates).length === 0) {
          const [user] = await db.select().from(usersTable).where(eq(usersTable.id, userId));
          return res.json({
            profile: await formatMemberProfileWithTenantContext(user)
          });
        }
        if (updates.consentAccepted === true) {
          updates.consentAcceptedAt = /* @__PURE__ */ new Date();
        } else if (updates.consentAccepted === false) {
          updates.consentAcceptedAt = null;
        }
        const hasKycUpdates = "kycIdFrontUrl" in updates || "kycIdBackUrl" in updates || "kycSelfieUrl" in updates;
        if (hasKycUpdates) {
          const front = updates.kycIdFrontUrl ?? null;
          const back = updates.kycIdBackUrl ?? null;
          const selfie = updates.kycSelfieUrl ?? null;
          if (!front || !back || !selfie) {
            return res.status(400).json({
              message: "KYC submission requires ID front, ID back, and photo."
            });
          }
          updates.kycStatus = "PENDING";
          updates.kycSubmittedAt = /* @__PURE__ */ new Date();
          updates.kycReviewedAt = null;
          updates.kycReviewedByUserId = null;
          updates.kycRejectionReason = null;
        }
        if (typeof updates.username === "string" && updates.username.length > 0) {
          const existingUsername = await db.select({ id: usersTable.id }).from(usersTable).where(eq(usersTable.username, updates.username));
          if (existingUsername.some((row) => row.id !== userId)) {
            return res.status(409).json({ message: "Username already taken." });
          }
        }
        const [updatedUser] = await db.update(usersTable).set({
          ...updates,
          updatedAt: /* @__PURE__ */ new Date()
        }).where(eq(usersTable.id, userId)).returning();
        ensureActiveOnboardingEnrollmentForUser(userId).catch(() => {
        });
        publishLiveEventToUser(userId, {
          kind: "DATA_CHANGED",
          scopes: ["profile"],
          payload: { action: "profile_updated" }
        });
        return res.json({
          profile: await formatMemberProfileWithTenantContext(updatedUser)
        });
      } catch (err) {
        console.error("PATCH /member/profile error:", err);
        return res.status(500).json({ message: "Failed to update profile." });
      }
    });
    router8.patch("/member/profile/credentials", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        const parsed = memberCredentialsUpdateSchema.safeParse(req.body ?? {});
        if (!parsed.success) {
          return res.status(400).json({ errors: parsed.error.flatten() });
        }
        const [existingUser] = await db.select().from(usersTable).where(eq(usersTable.id, userId));
        if (!existingUser) {
          return res.status(404).json({ message: "User not found." });
        }
        const currentPasswordValid = await bcryptjs_default.compare(
          parsed.data.currentPassword,
          existingUser.passwordHash
        );
        if (!currentPasswordValid) {
          return res.status(401).json({ message: "Current password is incorrect." });
        }
        const [updatedUser] = await db.update(usersTable).set({
          passwordHash: await bcryptjs_default.hash(parsed.data.newPassword, 12),
          updatedAt: /* @__PURE__ */ new Date()
        }).where(eq(usersTable.id, userId)).returning();
        publishLiveEventToUser(userId, {
          kind: "DATA_CHANGED",
          scopes: ["profile"],
          payload: { action: "member_credentials_updated" }
        });
        return res.json({
          profile: await formatMemberProfileWithTenantContext(updatedUser),
          message: "Password updated."
        });
      } catch (err) {
        console.error("PATCH /member/profile/credentials error:", err);
        return res.status(500).json({ message: "Failed to update password." });
      }
    });
    router8.post("/member/account/delete", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        const [updatedUser] = await db.update(usersTable).set({
          deletedAt: /* @__PURE__ */ new Date(),
          membershipStatus: "CANCELLED",
          authTokenVersion: sql`${usersTable.authTokenVersion} + 1`,
          updatedAt: /* @__PURE__ */ new Date()
        }).where(eq(usersTable.id, userId)).returning();
        if (!updatedUser) {
          return res.status(404).json({ message: "User not found." });
        }
        publishLiveEventToUser(userId, {
          kind: "DATA_CHANGED",
          scopes: ["profile"],
          payload: { action: "account_deleted" }
        });
        return res.json({
          message: "Account deleted.",
          profile: await formatMemberProfileWithTenantContext(updatedUser)
        });
      } catch (err) {
        console.error("POST /member/account/delete error:", err);
        return res.status(500).json({ message: "Failed to delete account." });
      }
    });
    router8.get("/member/onboarding", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        const snapshot = await getMemberOnboardingSnapshot(userId);
        return res.json(snapshot);
      } catch (err) {
        console.error("GET /member/onboarding error:", err);
        return res.status(500).json({ message: "Failed to fetch onboarding programme." });
      }
    });
    router8.patch(
      "/member/onboarding/activities/:id",
      requireAuth2,
      async (req, res) => {
        const userId = req.userId;
        const activityId = Number(req.params.id);
        try {
          const parsed = external_exports.object({
            status: external_exports.enum(["NOT_STARTED", "IN_PROGRESS", "COMPLETED"])
          }).strict().safeParse(req.body ?? {});
          if (!parsed.success) {
            return res.status(400).json({ errors: parsed.error.flatten() });
          }
          const enrollment = await ensureActiveOnboardingEnrollmentForUser(userId);
          if (!enrollment) {
            return res.status(400).json({ message: "Onboarding is not active for this account." });
          }
          const row = await db.select({
            activityId: onboardingWeekActivitiesTable.id,
            weekId: onboardingWeekActivitiesTable.weekId,
            weekNumber: onboardingProgramWeeksTable.weekNumber,
            programId: onboardingProgramWeeksTable.programId
          }).from(onboardingWeekActivitiesTable).innerJoin(
            onboardingProgramWeeksTable,
            eq(
              onboardingWeekActivitiesTable.weekId,
              onboardingProgramWeeksTable.id
            )
          ).where(eq(onboardingWeekActivitiesTable.id, activityId)).then((rows) => rows[0] ?? null);
          if (!row || row.programId !== enrollment.programId) {
            return res.status(404).json({ message: "Activity not found." });
          }
          const [program] = await db.select().from(onboardingProgramsTable).where(eq(onboardingProgramsTable.id, enrollment.programId));
          if (!program) {
            return res.status(404).json({ message: "Onboarding programme not found." });
          }
          const now = /* @__PURE__ */ new Date();
          const intervalsPassed = getOnboardingIntervalsPassed({
            enrolledAt: enrollment.enrolledAt,
            now,
            durationUnit: program.durationUnit
          });
          const elapsedWeekNumber = Math.min(
            program.numberOfWeeks,
            Math.max(1, intervalsPassed + 1)
          );
          const programActivityRows = await db.select({
            id: onboardingWeekActivitiesTable.id,
            weekNumber: onboardingProgramWeeksTable.weekNumber
          }).from(onboardingWeekActivitiesTable).innerJoin(
            onboardingProgramWeeksTable,
            eq(
              onboardingWeekActivitiesTable.weekId,
              onboardingProgramWeeksTable.id
            )
          ).where(eq(onboardingProgramWeeksTable.programId, program.id));
          const progressRows = programActivityRows.length ? await db.select().from(onboardingActivityProgressTable).where(
            and(
              eq(onboardingActivityProgressTable.enrollmentId, enrollment.id),
              inArray(
                onboardingActivityProgressTable.activityId,
                programActivityRows.map((activity) => activity.id)
              )
            )
          ) : [];
          const progressByActivityId = new Map(
            progressRows.map((progress) => [progress.activityId, progress])
          );
          const completedWeekNumbersForUnlock = new Set(
            Array.from(
              new Set(programActivityRows.map((activity) => activity.weekNumber))
            ).filter((weekNumber) => {
              const activitiesForWeek = programActivityRows.filter(
                (activity) => activity.weekNumber === weekNumber
              );
              return activitiesForWeek.every((activity) => {
                const progress = progressByActivityId.get(activity.id);
                return progress?.status === "COMPLETED";
              });
            })
          );
          const currentWeekNumber = getOnboardingCurrentWeekNumber({
            enrolledAt: enrollment.enrolledAt,
            now,
            durationUnit: program.durationUnit,
            numberOfWeeks: program.numberOfWeeks,
            completedWeekNumbers: completedWeekNumbersForUnlock
          });
          if (row.weekNumber > currentWeekNumber) {
            return res.status(403).json({
              message: row.weekNumber <= elapsedWeekNumber ? "Complete the previous week's activities to unlock this week." : "This week is locked. You cannot complete future activities yet."
            });
          }
          const existing = await db.select().from(onboardingActivityProgressTable).where(
            and(
              eq(onboardingActivityProgressTable.enrollmentId, enrollment.id),
              eq(onboardingActivityProgressTable.activityId, activityId)
            )
          ).then((rows) => rows[0] ?? null);
          if (existing?.status === "COMPLETED") {
            const snapshot2 = await getMemberOnboardingSnapshot(userId);
            return res.json({ snapshot: snapshot2, milestone: null });
          }
          const nextStatus = parsed.data.status;
          const startedAt = existing?.startedAt ?? (nextStatus !== "NOT_STARTED" ? now : null);
          const completedAt = nextStatus === "COMPLETED" ? now : null;
          await db.transaction(async (tx) => {
            if (!existing) {
              await tx.insert(onboardingActivityProgressTable).values({
                enrollmentId: enrollment.id,
                activityId,
                status: nextStatus,
                startedAt,
                completedAt,
                updatedAt: now
              });
            } else {
              await tx.update(onboardingActivityProgressTable).set({
                status: nextStatus,
                startedAt,
                completedAt,
                updatedAt: now
              }).where(eq(onboardingActivityProgressTable.id, existing.id));
            }
            await tx.update(onboardingEnrollmentsTable).set({ lastActivityAt: now, updatedAt: now }).where(eq(onboardingEnrollmentsTable.id, enrollment.id));
          });
          const completion = await finalizeOnboardingIfCompleted(userId);
          let milestone = null;
          if (nextStatus === "COMPLETED") {
            const weekActivityIds = await db.select({ id: onboardingWeekActivitiesTable.id }).from(onboardingWeekActivitiesTable).where(and(eq(onboardingWeekActivitiesTable.weekId, row.weekId))).then((rows) => rows.map((r) => r.id));
            if (weekActivityIds.length) {
              const weekCompletedCount = await db.select({ count: count() }).from(onboardingActivityProgressTable).where(
                and(
                  eq(onboardingActivityProgressTable.enrollmentId, enrollment.id),
                  eq(onboardingActivityProgressTable.status, "COMPLETED"),
                  inArray(
                    onboardingActivityProgressTable.activityId,
                    weekActivityIds
                  )
                )
              ).then((rows) => Number(rows[0]?.count ?? 0));
              if (weekCompletedCount === weekActivityIds.length) {
                milestone = { kind: "WEEK_COMPLETED", weekNumber: row.weekNumber };
              }
            }
          }
          if (completion.completed) {
            milestone = { kind: "PROGRAM_COMPLETED" };
          }
          const snapshot = await getMemberOnboardingSnapshot(userId);
          return res.json({ snapshot, milestone });
        } catch (err) {
          console.error("PATCH /member/onboarding/activities/:id error:", err);
          return res.status(500).json({ message: "Failed to update onboarding activity." });
        }
      }
    );
    router8.post("/member/onboarding/complete", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        const [user] = await db.select().from(usersTable).where(eq(usersTable.id, userId));
        if (!user) {
          return res.status(404).json({ message: "User not found." });
        }
        if (user.membershipStatus !== "ACTIVE") {
          return res.status(400).json({ message: "Activate your membership to complete onboarding." });
        }
        if (!isUserProfileComplete(user)) {
          return res.status(400).json({ message: "Complete your profile to start onboarding." });
        }
        const completion = await finalizeOnboardingIfCompleted(userId);
        if (!completion.completed) {
          return res.status(400).json({
            message: "Complete all onboarding weeks and activities to finish the programme."
          });
        }
        if (!completion.user) {
          return res.status(500).json({ message: "Failed to complete onboarding." });
        }
        return res.json({
          profile: await formatMemberProfileWithTenantContext(completion.user)
        });
      } catch (err) {
        console.error("POST /member/onboarding/complete error:", err);
        return res.status(500).json({ message: "Failed to complete onboarding." });
      }
    });
    router8.get("/member/membership", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        const [user, subscriptionRow, history] = await Promise.all([
          db.select().from(usersTable).where(eq(usersTable.id, userId)).then((rows) => rows[0] ?? null),
          db.select({
            subscriptionId: membershipSubscriptionsTable.id,
            subscriptionStatus: membershipSubscriptionsTable.status,
            subscriptionStartDate: membershipSubscriptionsTable.startDate,
            subscriptionEndDate: membershipSubscriptionsTable.endDate,
            subscriptionRenewsAt: membershipSubscriptionsTable.renewsAt,
            subscriptionCreatedAt: membershipSubscriptionsTable.createdAt,
            planId: membershipPlansTable.id,
            planMembershipType: membershipPlansTable.membershipType,
            planTier: membershipPlansTable.tier,
            planName: membershipPlansTable.name,
            planDescription: membershipPlansTable.description,
            planPriceAnnual: membershipPlansTable.priceAnnual,
            planCurrency: membershipPlansTable.currency
          }).from(membershipSubscriptionsTable).leftJoin(
            membershipPlansTable,
            eq(membershipSubscriptionsTable.planId, membershipPlansTable.id)
          ).where(
            and(
              eq(membershipSubscriptionsTable.userId, userId),
              inArray(membershipSubscriptionsTable.status, ["ACTIVE", "PENDING"])
            )
          ).orderBy(desc(membershipSubscriptionsTable.createdAt)).limit(1).then((rows) => rows[0] ?? null),
          getMembershipInvoiceHistory(userId)
        ]);
        if (!user) {
          return res.status(404).json({ message: "User not found." });
        }
        const latestHistoryEntry = history[0] ?? null;
        return res.json({
          membership: {
            status: user.membershipStatus ?? "PENDING",
            subscription: subscriptionRow ? {
              id: subscriptionRow.subscriptionId,
              status: subscriptionRow.subscriptionStatus,
              startDate: toIsoStringOrNull3(
                subscriptionRow.subscriptionStartDate
              ),
              endDate: toIsoStringOrNull3(subscriptionRow.subscriptionEndDate),
              renewsAt: toIsoStringOrNull3(subscriptionRow.subscriptionRenewsAt),
              createdAt: toIsoStringOrNull3(
                subscriptionRow.subscriptionCreatedAt
              )
            } : null,
            plan: subscriptionRow && typeof subscriptionRow.planId === "number" ? {
              id: subscriptionRow.planId,
              membershipType: subscriptionRow.planMembershipType,
              tier: subscriptionRow.planTier,
              name: subscriptionRow.planName,
              description: subscriptionRow.planDescription ?? null,
              priceAnnual: Number(subscriptionRow.planPriceAnnual),
              currency: subscriptionRow.planCurrency
            } : null,
            invoice: latestHistoryEntry ? {
              id: latestHistoryEntry.invoiceId,
              invoiceNumber: latestHistoryEntry.invoiceNumber,
              amount: latestHistoryEntry.amount,
              currency: latestHistoryEntry.currency,
              status: latestHistoryEntry.status,
              dueDate: latestHistoryEntry.dueDate,
              paidAt: latestHistoryEntry.paidAt,
              createdAt: latestHistoryEntry.createdAt
            } : null,
            payment: latestHistoryEntry?.payment ? {
              id: latestHistoryEntry.payment.id,
              amount: latestHistoryEntry.payment.amount,
              currency: latestHistoryEntry.payment.currency,
              status: latestHistoryEntry.payment.status,
              method: latestHistoryEntry.payment.method,
              reference: latestHistoryEntry.payment.reference ?? null,
              description: latestHistoryEntry.payment.description ?? null,
              processedAt: latestHistoryEntry.payment.processedAt,
              createdAt: latestHistoryEntry.payment.createdAt,
              metadata: latestHistoryEntry.payment.metadata ?? null
            } : null,
            history
          }
        });
      } catch (err) {
        console.error("GET /member/membership error:", err);
        return res.status(500).json({ message: "Failed to fetch membership payment state." });
      }
    });
    router8.get("/member/academy/courses", requireAuth2, async (_req, res) => {
      try {
        const courses = await db.select({
          id: academyCoursesTable.id,
          title: academyCoursesTable.title,
          slug: academyCoursesTable.slug,
          description: academyCoursesTable.description,
          thumbnailUrl: academyCoursesTable.thumbnailUrl,
          categoryId: academyCoursesTable.categoryId,
          categoryName: academyCategoriesTable.name,
          categorySlug: academyCategoriesTable.slug,
          instructor: academyCoursesTable.instructor,
          duration: academyCoursesTable.duration,
          level: academyCoursesTable.level,
          enrolledCount: academyCoursesTable.enrolledCount,
          externalUrl: academyCoursesTable.externalUrl,
          tags: academyCoursesTable.tags,
          sortOrder: academyCoursesTable.sortOrder,
          createdAt: academyCoursesTable.createdAt
        }).from(academyCoursesTable).leftJoin(
          academyCategoriesTable,
          eq(academyCoursesTable.categoryId, academyCategoriesTable.id)
        ).where(eq(academyCoursesTable.isPublished, true)).orderBy(
          asc(academyCoursesTable.sortOrder),
          desc(academyCoursesTable.createdAt)
        );
        return res.json({
          courses: courses.map((course) => ({
            id: course.id,
            title: course.title,
            slug: course.slug,
            description: course.description,
            thumbnailUrl: typeof course.thumbnailUrl === "string" && course.thumbnailUrl.trim().length > 0 ? course.thumbnailUrl : null,
            category: course.categoryName ? {
              id: course.categoryId,
              name: course.categoryName,
              slug: course.categorySlug ?? null
            } : null,
            instructor: course.instructor,
            duration: course.duration,
            level: course.level,
            enrolledCount: course.enrolledCount,
            externalUrl: course.externalUrl,
            tags: Array.isArray(course.tags) ? course.tags.filter((tag) => typeof tag === "string") : [],
            sortOrder: course.sortOrder,
            createdAt: toIsoStringOrNull3(course.createdAt)
          }))
        });
      } catch (err) {
        console.error("GET /member/academy/courses error:", err);
        return res.status(500).json({ message: "Failed to load academy courses." });
      }
    });
    router8.get("/member/community/announcements", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        await ensureMemberProductAccess(userId, "COMMUNITY");
        const announcements = await db.select({
          id: announcementsTable.id,
          title: announcementsTable.title,
          body: announcementsTable.body,
          category: announcementsTable.category,
          pinned: announcementsTable.pinned,
          publishedAt: announcementsTable.publishedAt,
          createdAt: announcementsTable.createdAt
        }).from(announcementsTable).orderBy(
          desc(announcementsTable.pinned),
          desc(announcementsTable.publishedAt)
        );
        return res.json({
          announcements: announcements.map((item) => ({
            id: item.id,
            title: item.title,
            body: item.body,
            category: item.category,
            pinned: item.pinned,
            publishedAt: toIsoStringOrNull3(item.publishedAt),
            createdAt: toIsoStringOrNull3(item.createdAt)
          }))
        });
      } catch (err) {
        if (err instanceof MemberProductAccessError) {
          return res.status(err.statusCode).json({ message: err.message });
        }
        console.error("GET /member/community/announcements error:", err);
        return res.status(500).json({ message: "Failed to load community announcements." });
      }
    });
    router8.get("/member/community/events", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        await ensureMemberProductAccess(userId, "COMMUNITY");
        const [events, rsvpCounts, myRsvps] = await Promise.all([
          db.select({
            id: communityEventsTable.id,
            title: communityEventsTable.title,
            description: communityEventsTable.description,
            date: communityEventsTable.date,
            startTime: communityEventsTable.startTime,
            endTime: communityEventsTable.endTime,
            location: communityEventsTable.location,
            type: communityEventsTable.type,
            maxAttendees: communityEventsTable.maxAttendees,
            coverImageUrl: communityEventsTable.coverImageUrl,
            createdAt: communityEventsTable.createdAt,
            updatedAt: communityEventsTable.updatedAt
          }).from(communityEventsTable).orderBy(asc(communityEventsTable.date)),
          db.select({
            eventId: eventRsvpsTable.eventId,
            goingCount: count(eventRsvpsTable.id)
          }).from(eventRsvpsTable).where(eq(eventRsvpsTable.status, "GOING")).groupBy(eventRsvpsTable.eventId),
          db.select({
            eventId: eventRsvpsTable.eventId,
            status: eventRsvpsTable.status
          }).from(eventRsvpsTable).where(eq(eventRsvpsTable.userId, userId))
        ]);
        const goingCountByEventId = new Map(
          rsvpCounts.map((row) => [row.eventId, Number(row.goingCount ?? 0)])
        );
        const myStatusByEventId = new Map(
          myRsvps.map((row) => [row.eventId, String(row.status)])
        );
        return res.json({
          events: events.map((event) => ({
            id: event.id,
            title: event.title,
            description: event.description,
            date: toIsoStringOrNull3(event.date),
            startTime: event.startTime,
            endTime: event.endTime ?? null,
            location: event.location,
            type: String(event.type),
            maxAttendees: event.maxAttendees ?? null,
            coverImageUrl: event.coverImageUrl ?? null,
            goingCount: goingCountByEventId.get(event.id) ?? 0,
            myRsvpStatus: myStatusByEventId.get(event.id) ?? null,
            createdAt: toIsoStringOrNull3(event.createdAt),
            updatedAt: toIsoStringOrNull3(event.updatedAt)
          }))
        });
      } catch (err) {
        if (err instanceof MemberProductAccessError) {
          return res.status(err.statusCode).json({ message: err.message });
        }
        console.error("GET /member/community/events error:", err);
        return res.status(500).json({ message: "Failed to load community events." });
      }
    });
    router8.get("/member/community/events/:id", requireAuth2, async (req, res) => {
      const userId = req.userId;
      const id = Number(req.params.id);
      if (!Number.isFinite(id) || id <= 0) {
        return res.status(400).json({ message: "Invalid event id." });
      }
      try {
        await ensureMemberProductAccess(userId, "COMMUNITY");
        const [event] = await db.select().from(communityEventsTable).where(eq(communityEventsTable.id, id));
        if (!event) return res.status(404).json({ message: "Event not found." });
        const [[goingRow], [myRow]] = await Promise.all([
          db.select({ goingCount: count(eventRsvpsTable.id) }).from(eventRsvpsTable).where(
            and(
              eq(eventRsvpsTable.eventId, id),
              eq(eventRsvpsTable.status, "GOING")
            )
          ),
          db.select({ status: eventRsvpsTable.status }).from(eventRsvpsTable).where(
            and(
              eq(eventRsvpsTable.eventId, id),
              eq(eventRsvpsTable.userId, userId)
            )
          )
        ]);
        return res.json({
          event: {
            id: event.id,
            title: event.title,
            description: event.description,
            date: toIsoStringOrNull3(event.date),
            startTime: event.startTime,
            endTime: event.endTime ?? null,
            location: event.location,
            type: String(event.type),
            maxAttendees: event.maxAttendees ?? null,
            coverImageUrl: event.coverImageUrl ?? null,
            goingCount: Number(goingRow?.goingCount ?? 0),
            myRsvpStatus: myRow?.status ? String(myRow.status) : null,
            createdAt: toIsoStringOrNull3(event.createdAt),
            updatedAt: toIsoStringOrNull3(event.updatedAt)
          }
        });
      } catch (err) {
        if (err instanceof MemberProductAccessError) {
          return res.status(err.statusCode).json({ message: err.message });
        }
        console.error("GET /member/community/events/:id error:", err);
        return res.status(500).json({ message: "Failed to load community event." });
      }
    });
    router8.post(
      "/member/community/events/:id/rsvp",
      requireAuth2,
      async (req, res) => {
        const userId = req.userId;
        const eventId = Number(req.params.id);
        if (!Number.isFinite(eventId) || eventId <= 0) {
          return res.status(400).json({ message: "Invalid event id." });
        }
        try {
          await ensureMemberProductAccess(userId, "COMMUNITY");
          const schema = external_exports.object({
            status: external_exports.enum(["GOING", "CANCELLED"])
          });
          const parsed = schema.safeParse(req.body);
          if (!parsed.success) {
            return res.status(400).json({ errors: parsed.error.flatten() });
          }
          const [event] = await db.select({
            id: communityEventsTable.id,
            maxAttendees: communityEventsTable.maxAttendees
          }).from(communityEventsTable).where(eq(communityEventsTable.id, eventId));
          if (!event) return res.status(404).json({ message: "Event not found." });
          let finalStatus = parsed.data.status;
          if (parsed.data.status === "GOING" && event.maxAttendees != null) {
            const [countRow] = await db.select({ goingCount: count(eventRsvpsTable.id) }).from(eventRsvpsTable).where(
              and(
                eq(eventRsvpsTable.eventId, eventId),
                eq(eventRsvpsTable.status, "GOING")
              )
            );
            const goingCount = Number(countRow?.goingCount ?? 0);
            if (goingCount >= event.maxAttendees) {
              finalStatus = "WAITLISTED";
            }
          }
          try {
            const [created] = await db.insert(eventRsvpsTable).values({
              userId,
              eventId,
              status: finalStatus
            }).returning({
              id: eventRsvpsTable.id,
              status: eventRsvpsTable.status,
              createdAt: eventRsvpsTable.createdAt
            });
            return res.json({
              rsvp: {
                id: created.id,
                eventId,
                status: String(created.status),
                createdAt: toIsoStringOrNull3(created.createdAt)
              }
            });
          } catch (err) {
            if (!isUniqueViolation7(err)) throw err;
          }
          const [updated] = await db.update(eventRsvpsTable).set({ status: finalStatus }).where(
            and(
              eq(eventRsvpsTable.userId, userId),
              eq(eventRsvpsTable.eventId, eventId)
            )
          ).returning({
            id: eventRsvpsTable.id,
            status: eventRsvpsTable.status,
            createdAt: eventRsvpsTable.createdAt
          });
          return res.json({
            rsvp: {
              id: updated.id,
              eventId,
              status: String(updated.status),
              createdAt: toIsoStringOrNull3(updated.createdAt)
            }
          });
        } catch (err) {
          if (err instanceof MemberProductAccessError) {
            return res.status(err.statusCode).json({ message: err.message });
          }
          console.error("POST /member/community/events/:id/rsvp error:", err);
          return res.status(500).json({ message: "Failed to update RSVP." });
        }
      }
    );
    router8.get("/member/resources", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        let user;
        let userRow = null;
        try {
          user = await getMemberAccessContext(userId);
          userRow = (await db.select().from(usersTable).where(eq(usersTable.id, userId)).limit(1))[0] ?? null;
        } catch {
          return res.status(401).json({ message: "User not found." });
        }
        if (user.membershipType === "ORGANIZATION") {
          try {
            await requireOrganizationAuthorization(userId, {
              productFeature: "RESOURCES"
            });
          } catch (error40) {
            if (error40 instanceof OrganizationTenantAccessError) {
              return res.status(error40.statusCode).json({
                message: error40.message
              });
            }
            throw error40;
          }
        } else {
          if (user.membershipType !== "INVESTOR" && user.membershipType !== "INDIVIDUAL") {
            return res.status(403).json({
              message: "Resources are only available to active member accounts."
            });
          }
          if (user.membershipStatus !== "ACTIVE") {
            return res.status(403).json({
              message: "Activate your membership plan to unlock Resources."
            });
          }
          if (!userRow || !isUserProfileComplete(userRow)) {
            return res.status(403).json({
              message: "Complete your profile before accessing Resources."
            });
          }
          const onboardingState = await getActiveOnboardingStateForUser(userId);
          if (onboardingState.required && !onboardingState.completed) {
            return res.status(403).json({
              message: "Complete onboarding before accessing Resources."
            });
          }
        }
        const audienceFilter = user.membershipType === "ORGANIZATION" ? eq(resourcesTable.showToOrganizations, true) : user.membershipType === "INVESTOR" ? eq(resourcesTable.showToInvestors, true) : eq(resourcesTable.showToIndividuals, true);
        const [categories, resources] = await Promise.all([
          db.select({
            id: resourceCategoriesTable.id,
            name: resourceCategoriesTable.name,
            slug: resourceCategoriesTable.slug,
            sortOrder: resourceCategoriesTable.sortOrder
          }).from(resourceCategoriesTable).orderBy(asc(resourceCategoriesTable.sortOrder)),
          db.select({
            id: resourcesTable.id,
            title: resourcesTable.title,
            slug: resourcesTable.slug,
            description: resourcesTable.description,
            resourceKind: resourcesTable.resourceKind,
            categoryId: resourcesTable.categoryId,
            categoryName: resourceCategoriesTable.name,
            categorySlug: resourceCategoriesTable.slug,
            fileUrl: resourcesTable.fileUrl,
            fileType: resourcesTable.fileType,
            fileSize: resourcesTable.fileSize,
            coverImageUrl: resourcesTable.coverImageUrl,
            authorName: resourcesTable.authorName,
            contentHtml: resourcesTable.contentHtml,
            downloads: resourcesTable.downloads,
            publishedAt: resourcesTable.publishedAt,
            createdAt: resourcesTable.createdAt
          }).from(resourcesTable).leftJoin(
            resourceCategoriesTable,
            eq(resourcesTable.categoryId, resourceCategoriesTable.id)
          ).where(and(eq(resourcesTable.isPublished, true), audienceFilter)).orderBy(
            desc(resourcesTable.publishedAt),
            desc(resourcesTable.createdAt)
          )
        ]);
        return res.json({
          categories,
          resources: resources.map((resource) => ({
            id: resource.id,
            title: resource.title,
            slug: resource.slug,
            description: resource.description ?? null,
            resourceKind: resource.resourceKind,
            category: resource.categoryName ? {
              id: resource.categoryId,
              name: resource.categoryName,
              slug: resource.categorySlug ?? null
            } : null,
            fileUrl: resource.fileUrl ?? null,
            fileType: resource.fileType,
            fileSize: resource.fileSize ?? null,
            coverImageUrl: resource.coverImageUrl ?? null,
            authorName: resource.authorName ?? null,
            contentHtml: resource.contentHtml ?? null,
            downloads: resource.downloads,
            publishedAt: toIsoStringOrNull3(resource.publishedAt),
            createdAt: toIsoStringOrNull3(resource.createdAt)
          }))
        });
      } catch (err) {
        console.error("GET /member/resources error:", err);
        return res.status(500).json({ message: "Failed to load resources." });
      }
    });
    router8.post("/member/resources/:id/download", requireAuth2, async (req, res) => {
      const userId = req.userId;
      const id = Number(req.params.id);
      if (!Number.isFinite(id) || id <= 0) {
        return res.status(400).json({ message: "Invalid resource id." });
      }
      try {
        let user;
        let userRow = null;
        try {
          user = await getMemberAccessContext(userId);
          userRow = (await db.select().from(usersTable).where(eq(usersTable.id, userId)).limit(1))[0] ?? null;
        } catch {
          return res.status(401).json({ message: "User not found." });
        }
        if (user.membershipType === "ORGANIZATION") {
          try {
            await requireOrganizationAuthorization(userId, {
              productFeature: "RESOURCES"
            });
          } catch (error40) {
            if (error40 instanceof OrganizationTenantAccessError) {
              return res.status(error40.statusCode).json({
                message: error40.message
              });
            }
            throw error40;
          }
        } else {
          if (user.membershipType !== "INVESTOR" && user.membershipType !== "INDIVIDUAL") {
            return res.status(403).json({
              message: "Resources are only available to active member accounts."
            });
          }
          if (user.membershipStatus !== "ACTIVE") {
            return res.status(403).json({
              message: "Activate your membership plan to unlock Resources."
            });
          }
          if (!userRow || !isUserProfileComplete(userRow)) {
            return res.status(403).json({
              message: "Complete your profile before accessing Resources."
            });
          }
          const onboardingState = await getActiveOnboardingStateForUser(userId);
          if (onboardingState.required && !onboardingState.completed) {
            return res.status(403).json({
              message: "Complete onboarding before accessing Resources."
            });
          }
        }
        const audienceFilter = user.membershipType === "ORGANIZATION" ? eq(resourcesTable.showToOrganizations, true) : user.membershipType === "INVESTOR" ? eq(resourcesTable.showToInvestors, true) : eq(resourcesTable.showToIndividuals, true);
        const [resource] = await db.select({
          id: resourcesTable.id,
          resourceKind: resourcesTable.resourceKind,
          fileUrl: resourcesTable.fileUrl
        }).from(resourcesTable).where(
          and(
            eq(resourcesTable.id, id),
            eq(resourcesTable.isPublished, true),
            audienceFilter
          )
        );
        if (!resource) {
          return res.status(404).json({ message: "Resource not found." });
        }
        if (resource.resourceKind === "ARTICLE" || !resource.fileUrl) {
          return res.status(400).json({
            message: "Articles are opened directly and cannot be downloaded."
          });
        }
        await db.update(resourcesTable).set({
          downloads: sql`${resourcesTable.downloads} + 1`,
          updatedAt: /* @__PURE__ */ new Date()
        }).where(eq(resourcesTable.id, id));
        return res.json({ fileUrl: resource.fileUrl });
      } catch (err) {
        console.error("POST /member/resources/:id/download error:", err);
        return res.status(500).json({ message: "Failed to download resource." });
      }
    });
    router8.post("/member/membership/change", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        const parsed = membershipPlanChangeSchema.safeParse(req.body ?? {});
        if (!parsed.success) {
          return res.status(400).json({ errors: parsed.error.flatten() });
        }
        const [user] = await db.select().from(usersTable).where(eq(usersTable.id, userId));
        if (!user) {
          return res.status(404).json({ message: "User not found." });
        }
        const [targetPlan] = await db.select().from(membershipPlansTable).where(eq(membershipPlansTable.id, parsed.data.planId));
        if (!targetPlan || !targetPlan.isActive) {
          return res.status(404).json({ message: "Membership plan not found." });
        }
        if (user.membershipType && targetPlan.membershipType !== user.membershipType) {
          return res.status(400).json({
            message: "This plan does not match your selected membership type."
          });
        }
        if (user.membershipType === "ORGANIZATION" && targetPlan.membershipType === "ORGANIZATION") {
          const billingAccess = await ensureOrganizationBillingAuthority({
            userId,
            organizationId: user.organizationId
          });
          if (!billingAccess.allowed) {
            return res.status(403).json({ message: billingAccess.message });
          }
        }
        let stripe = null;
        const now = /* @__PURE__ */ new Date();
        const result = await db.transaction(async (tx) => {
          await tx.execute(
            sql`select pg_advisory_xact_lock(${MEMBERSHIP_ACTIVATION_LOCK_KEY_A}, ${userId})`
          );
          const [currentRow] = await tx.select({
            subscription: membershipSubscriptionsTable,
            plan: membershipPlansTable
          }).from(membershipSubscriptionsTable).innerJoin(
            membershipPlansTable,
            eq(membershipSubscriptionsTable.planId, membershipPlansTable.id)
          ).where(
            and(
              eq(membershipSubscriptionsTable.userId, userId),
              eq(membershipSubscriptionsTable.status, "ACTIVE")
            )
          ).limit(1);
          if (!currentRow?.subscription || !currentRow.plan) {
            return { kind: "NOT_FOUND" };
          }
          const changeKind = getMembershipChangeKind(currentRow.plan, targetPlan);
          if (changeKind === "NONE") {
            return { kind: "ALREADY_ACTIVE" };
          }
          if (changeKind !== "DOWNGRADE") {
            return { kind: "REQUIRES_PAYMENT" };
          }
          if (currentRow.subscription.stripeSubscriptionId) {
            stripe = stripe ?? getStripeClient();
            const stripeSubscription = await stripe.subscriptions.retrieve(
              currentRow.subscription.stripeSubscriptionId
            );
            const subscriptionItemId = Array.isArray(
              stripeSubscription.items?.data
            ) ? stripeSubscription.items.data[0]?.id ?? null : null;
            if (!subscriptionItemId) {
              throw new Error("Stripe subscription item is missing.");
            }
            const nextPrice = await ensureStripeMembershipPrice(stripe, targetPlan);
            await stripe.subscriptions.update(
              currentRow.subscription.stripeSubscriptionId,
              {
                items: [{ id: subscriptionItemId, price: nextPrice.id }],
                proration_behavior: "none",
                billing_cycle_anchor: "unchanged"
              }
            );
          }
          const [updatedSubscription] = await tx.update(membershipSubscriptionsTable).set({
            planId: targetPlan.id,
            updatedAt: now
          }).where(eq(membershipSubscriptionsTable.id, currentRow.subscription.id)).returning();
          const [updatedUser] = await tx.update(usersTable).set({
            membershipStatus: "ACTIVE",
            updatedAt: now
          }).where(eq(usersTable.id, userId)).returning();
          await syncOrganizationSubscriptionStateWith(tx, {
            user: updatedUser,
            plan: targetPlan,
            status: "ACTIVE",
            now,
            startDate: updatedSubscription?.startDate ?? currentRow.subscription.startDate,
            endDate: updatedSubscription?.endDate ?? currentRow.subscription.endDate,
            renewsAt: updatedSubscription?.renewsAt ?? currentRow.subscription.renewsAt,
            stripeCustomerId: currentRow.subscription.stripeCustomerId,
            stripeSubscriptionId: currentRow.subscription.stripeSubscriptionId
          });
          await notifyInAppWith(tx, {
            userId,
            category: "MEMBERSHIP",
            severity: "SUCCESS",
            title: "Membership updated",
            body: `Your membership has moved from ${currentRow.plan.name} to ${targetPlan.name}.`,
            actionLabel: "Open Billing",
            actionHref: "/dashboard/billing"
          });
          return {
            kind: "OK",
            user: updatedUser,
            subscription: updatedSubscription ?? currentRow.subscription,
            previousPlan: currentRow.plan
          };
        });
        if (result.kind === "NOT_FOUND") {
          return res.status(404).json({ message: "Active membership not found." });
        }
        if (result.kind === "ALREADY_ACTIVE") {
          return res.status(409).json({ message: "This is already your current plan." });
        }
        if (result.kind === "REQUIRES_PAYMENT") {
          return res.status(409).json({
            message: "This plan change requires payment. Start the upgrade flow instead."
          });
        }
        return res.json({
          user: await formatMemberProfileWithTenantContext(result.user),
          subscription: {
            id: result.subscription.id,
            status: result.subscription.status,
            startDate: toIsoStringOrNull3(result.subscription.startDate),
            endDate: toIsoStringOrNull3(result.subscription.endDate),
            renewsAt: toIsoStringOrNull3(result.subscription.renewsAt)
          },
          previousPlan: {
            id: result.previousPlan.id,
            name: result.previousPlan.name,
            tier: result.previousPlan.tier
          },
          plan: {
            id: targetPlan.id,
            name: targetPlan.name,
            membershipType: targetPlan.membershipType,
            tier: targetPlan.tier,
            currency: targetPlan.currency,
            priceAnnual: Number(targetPlan.priceAnnual)
          }
        });
      } catch (err) {
        console.error("POST /member/membership/change error:", err);
        return res.status(500).json({ message: "Failed to change membership plan." });
      }
    });
    router8.get(
      "/member/membership/receipts/:invoiceId.pdf",
      requireAuth2,
      async (req, res) => {
        const userId = req.userId;
        const invoiceId = Number(req.params.invoiceId);
        if (!Number.isFinite(invoiceId) || invoiceId <= 0) {
          return res.status(400).json({ message: "Invalid invoice id." });
        }
        try {
          const [user] = await db.select().from(usersTable).where(eq(usersTable.id, userId));
          if (!user) {
            return res.status(404).json({ message: "User not found." });
          }
          if (!isUserProfileComplete(user)) {
            return res.status(400).json({
              message: "Complete your profile details before starting membership payment."
            });
          }
          const [invoice] = await db.select().from(invoicesTable).where(
            and(
              eq(invoicesTable.id, invoiceId),
              eq(invoicesTable.userId, userId)
            )
          );
          if (!invoice) {
            return res.status(404).json({ message: "Receipt not found." });
          }
          const [subscription] = typeof invoice.subscriptionId === "number" ? await db.select().from(membershipSubscriptionsTable).where(
            eq(membershipSubscriptionsTable.id, invoice.subscriptionId)
          ) : [null];
          const [plan] = subscription ? await db.select().from(membershipPlansTable).where(eq(membershipPlansTable.id, subscription.planId)) : [null];
          const [payment] = await db.select().from(paymentsTable).where(eq(paymentsTable.invoiceId, invoice.id)).orderBy(desc(paymentsTable.createdAt)).limit(1);
          const fullName = [user.firstName, user.lastName].filter(Boolean).join(" ") || user.email;
          const lineItems = Array.isArray(invoice.lineItems) ? invoice.lineItems : [];
          const paidAtDate = payment?.processedAt ?? invoice.paidAt ?? null;
          const renewsAtDate = subscription?.renewsAt ?? null;
          const receiptLineItems = lineItems.length ? lineItems.map((item, index2) => {
            const description = typeof item.description === "string" ? item.description : `Item ${index2 + 1}`;
            const total = typeof item.total === "number" ? item.total.toFixed(2) : typeof item.total === "string" ? item.total : Number(invoice.amount).toFixed(2);
            return { description, amount: total };
          }) : [
            {
              description: "Membership fee",
              amount: Number(invoice.amount).toFixed(2)
            }
          ];
          const pdfBuffer = buildMembershipReceiptPdf({
            invoiceNumber: invoice.invoiceNumber,
            amountPaid: Number(invoice.amount).toFixed(2),
            currency: invoice.currency,
            paymentStatus: payment?.status ?? (invoice.status === "PAID" ? "COMPLETED" : "PENDING"),
            invoiceStatus: invoice.status,
            paymentMethod: payment?.method ?? "N/A",
            memberName: fullName,
            memberEmail: user.email,
            membershipType: user.membershipType ?? "Not set",
            planName: plan?.name ?? "WWN Membership",
            planTier: plan?.tier ?? "N/A",
            paymentReference: payment?.reference ?? "N/A",
            paidAt: paidAtDate ? new Date(paidAtDate).toUTCString().replace("GMT", "UTC") : "N/A",
            renewsAt: renewsAtDate ? new Date(renewsAtDate).toLocaleDateString("en-CA", {
              year: "numeric",
              month: "long",
              day: "numeric"
            }) : "N/A",
            lineItems: receiptLineItems,
            supportEmail: "support@wwncoop.com"
          });
          const filename = `WWN-Receipt-${invoice.invoiceNumber}.pdf`;
          res.setHeader("Content-Type", "application/pdf");
          res.setHeader(
            "Content-Disposition",
            `attachment; filename="${filename}"`
          );
          return res.status(200).send(pdfBuffer);
        } catch (err) {
          console.error(
            "GET /member/membership/receipts/:invoiceId.pdf error:",
            err
          );
          return res.status(500).json({ message: "Failed to generate receipt." });
        }
      }
    );
    router8.post(
      "/member/membership/stripe/subscribe",
      requireAuth2,
      async (req, res) => {
        const userId = req.userId;
        try {
          const parsed = membershipStripeSubscribeSchema.safeParse(req.body ?? {});
          if (!parsed.success) {
            return res.status(400).json({ errors: parsed.error.flatten() });
          }
          let stripe;
          try {
            stripe = getStripeClient();
          } catch (err) {
            return res.status(503).json({
              message: err instanceof Error ? err.message : "Stripe is not configured."
            });
          }
          const [user] = await db.select().from(usersTable).where(eq(usersTable.id, userId));
          if (!user) {
            return res.status(404).json({ message: "User not found." });
          }
          const [plan] = await db.select().from(membershipPlansTable).where(eq(membershipPlansTable.id, parsed.data.planId));
          if (!plan || !plan.isActive) {
            return res.status(404).json({ message: "Membership plan not found." });
          }
          if (user.membershipType && plan.membershipType !== user.membershipType) {
            return res.status(400).json({
              message: "This plan does not match your selected membership type."
            });
          }
          if (user.membershipType === "ORGANIZATION" && plan.membershipType === "ORGANIZATION") {
            const billingAccess = await ensureOrganizationBillingAuthority({
              userId,
              organizationId: user.organizationId
            });
            if (!billingAccess.allowed) {
              return res.status(403).json({ message: billingAccess.message });
            }
          }
          const now = /* @__PURE__ */ new Date();
          const dueDate = new Date(now);
          dueDate.setDate(dueDate.getDate() + 1);
          const result = await db.transaction(async (tx) => {
            await tx.execute(
              sql`select pg_advisory_xact_lock(${MEMBERSHIP_ACTIVATION_LOCK_KEY_A}, ${userId})`
            );
            const [existingActive] = await tx.select({
              subscription: membershipSubscriptionsTable,
              plan: membershipPlansTable
            }).from(membershipSubscriptionsTable).innerJoin(
              membershipPlansTable,
              eq(membershipSubscriptionsTable.planId, membershipPlansTable.id)
            ).where(
              and(
                eq(membershipSubscriptionsTable.userId, userId),
                eq(membershipSubscriptionsTable.status, "ACTIVE")
              )
            ).limit(1);
            if (existingActive?.subscription && existingActive.plan) {
              const changeKind = getMembershipChangeKind(existingActive.plan, plan);
              if (changeKind === "NONE") {
                return { kind: "ALREADY_ACTIVE" };
              }
              if (changeKind === "DOWNGRADE") {
                return { kind: "REQUIRES_DIRECT_CHANGE" };
              }
              const proration = calculateMembershipProration({
                currentPlan: existingActive.plan,
                targetPlan: plan,
                subscription: existingActive.subscription,
                now
              });
              let stripeCustomerId2 = existingActive.subscription.stripeCustomerId ?? null;
              if (!stripeCustomerId2) {
                const [previous] = await tx.select({
                  stripeCustomerId: membershipSubscriptionsTable.stripeCustomerId
                }).from(membershipSubscriptionsTable).where(
                  and(
                    eq(membershipSubscriptionsTable.userId, userId),
                    sql`${membershipSubscriptionsTable.stripeCustomerId} is not null`
                  )
                ).orderBy(desc(membershipSubscriptionsTable.createdAt)).limit(1);
                stripeCustomerId2 = previous?.stripeCustomerId ?? null;
              }
              if (!stripeCustomerId2) {
                const customer = await stripe.customers.create({
                  email: user.email,
                  name: [user.firstName, user.lastName].filter(Boolean).join(" ") || void 0,
                  metadata: { userId: String(userId) }
                });
                stripeCustomerId2 = customer.id;
              }
              await tx.update(membershipSubscriptionsTable).set({
                stripeCustomerId: stripeCustomerId2,
                updatedAt: now
              }).where(
                eq(
                  membershipSubscriptionsTable.id,
                  existingActive.subscription.id
                )
              );
              const invoiceNumber = `INV-${now.getFullYear()}-${userId}-${Date.now()}`;
              const [invoice2] = await tx.insert(invoicesTable).values({
                userId,
                subscriptionId: existingActive.subscription.id,
                invoiceNumber,
                amount: proration.amountDue.toFixed(2),
                currency: plan.currency,
                status: "SENT",
                dueDate,
                paidAt: null,
                lineItems: [
                  {
                    description: `${plan.name} prorated upgrade charge`,
                    quantity: 1,
                    unitPrice: proration.targetProratedAmount,
                    total: proration.targetProratedAmount
                  },
                  {
                    description: `${existingActive.plan.name} unused time credit`,
                    quantity: 1,
                    unitPrice: -proration.unusedCredit,
                    total: -proration.unusedCredit
                  }
                ],
                updatedAt: now
              }).returning();
              const [payment2] = await tx.insert(paymentsTable).values({
                userId,
                amount: proration.amountDue.toFixed(2),
                currency: plan.currency,
                method: "STRIPE",
                status: "PENDING",
                reference: null,
                description: `${plan.name} membership upgrade payment (Stripe)`,
                metadata: {
                  activationType: "membership_stripe_plan_change",
                  planId: plan.id,
                  fromPlanId: existingActive.plan.id,
                  toPlanId: plan.id,
                  changeKind: "UPGRADE",
                  unusedCredit: proration.unusedCredit,
                  targetProratedAmount: proration.targetProratedAmount,
                  amountDue: proration.amountDue,
                  stripeCustomerId: stripeCustomerId2
                },
                invoiceId: invoice2.id,
                processedAt: null,
                updatedAt: now
              }).returning();
              return {
                kind: "UPGRADE_PENDING",
                subscription: existingActive.subscription,
                invoice: invoice2,
                payment: payment2,
                updatedUser: user,
                stripeCustomerId: stripeCustomerId2,
                proration
              };
            }
            const [existingPending] = await tx.select().from(membershipSubscriptionsTable).where(
              and(
                eq(membershipSubscriptionsTable.userId, userId),
                eq(membershipSubscriptionsTable.status, "PENDING")
              )
            ).orderBy(desc(membershipSubscriptionsTable.createdAt)).limit(1);
            let subscription = existingPending ?? null;
            if (subscription && subscription.planId !== plan.id) {
              await tx.update(membershipSubscriptionsTable).set({
                status: "CANCELLED",
                cancelledAt: now,
                updatedAt: now
              }).where(eq(membershipSubscriptionsTable.id, subscription.id));
              subscription = null;
            }
            if (!subscription) {
              try {
                [subscription] = await tx.insert(membershipSubscriptionsTable).values({
                  userId,
                  planId: plan.id,
                  status: "PENDING",
                  startDate: null,
                  endDate: null,
                  renewsAt: null,
                  updatedAt: now
                }).returning();
              } catch (err) {
                if (!isUniqueViolation7(err)) throw err;
                const existing = await tx.select().from(membershipSubscriptionsTable).where(
                  and(
                    eq(membershipSubscriptionsTable.userId, userId),
                    inArray(membershipSubscriptionsTable.status, [
                      "PENDING",
                      "ACTIVE"
                    ])
                  )
                ).orderBy(desc(membershipSubscriptionsTable.createdAt)).limit(1);
                subscription = existing[0] ?? null;
              }
            }
            if (!subscription) {
              throw new Error("Failed to create subscription.");
            }
            if (subscription.status === "ACTIVE") {
              return { kind: "ALREADY_ACTIVE" };
            }
            const planBillingCycle2 = plan.defaultBillingCycle ?? "ANNUAL";
            const planIsRecurring = plan.billingMode === "RECURRING";
            const cycleAmount2 = Number(
              planBillingCycle2 === "MONTHLY" ? plan.priceMonthly ?? plan.priceAnnual : plan.priceAnnual
            );
            if (!Number.isFinite(cycleAmount2) || cycleAmount2 <= 0) {
              throw new Error("Invalid plan amount.");
            }
            const cycleDescription = planBillingCycle2 === "MONTHLY" ? "Monthly" : "Yearly (billed annually)";
            const purchaseDescription = planIsRecurring ? cycleDescription : `One-time purchase (${planBillingCycle2 === "MONTHLY" ? "monthly" : "annual"} term)`;
            let stripeCustomerId = subscription.stripeCustomerId ?? null;
            if (!stripeCustomerId) {
              const [previous] = await tx.select({
                stripeCustomerId: membershipSubscriptionsTable.stripeCustomerId
              }).from(membershipSubscriptionsTable).where(
                and(
                  eq(membershipSubscriptionsTable.userId, userId),
                  sql`${membershipSubscriptionsTable.stripeCustomerId} is not null`
                )
              ).orderBy(desc(membershipSubscriptionsTable.createdAt)).limit(1);
              stripeCustomerId = previous?.stripeCustomerId ?? null;
            }
            if (!stripeCustomerId) {
              const customer = await stripe.customers.create({
                email: user.email,
                name: [user.firstName, user.lastName].filter(Boolean).join(" ") || void 0,
                metadata: { userId: String(userId) }
              });
              stripeCustomerId = customer.id;
            }
            const membershipPrice = await ensureStripeMembershipPrice(stripe, plan);
            const stripePriceId = membershipPrice.id;
            await tx.update(membershipSubscriptionsTable).set({
              stripeCustomerId,
              updatedAt: now
            }).where(eq(membershipSubscriptionsTable.id, subscription.id));
            const [existingInvoice] = await tx.select().from(invoicesTable).where(
              and(
                eq(invoicesTable.subscriptionId, subscription.id),
                inArray(invoicesTable.status, ["SENT", "OVERDUE"])
              )
            ).orderBy(desc(invoicesTable.createdAt)).limit(1);
            let invoice = existingInvoice ?? null;
            if (!invoice) {
              const invoiceNumber = `INV-${now.getFullYear()}-${userId}-${Date.now()}`;
              [invoice] = await tx.insert(invoicesTable).values({
                userId,
                subscriptionId: subscription.id,
                invoiceNumber,
                amount: String(cycleAmount2),
                currency: plan.currency,
                status: "SENT",
                dueDate,
                paidAt: null,
                lineItems: [
                  {
                    description: `${plan.name} membership (${purchaseDescription})`,
                    quantity: 1,
                    unitPrice: cycleAmount2,
                    total: cycleAmount2
                  }
                ],
                updatedAt: now
              }).returning();
            }
            const [existingPayment] = await tx.select().from(paymentsTable).where(
              and(
                eq(paymentsTable.invoiceId, invoice.id),
                eq(paymentsTable.status, "PENDING")
              )
            ).orderBy(desc(paymentsTable.createdAt)).limit(1);
            let payment = existingPayment ?? null;
            const nextMetadata = {
              planId: plan.id,
              activationType: "membership_stripe_checkout",
              stripeCustomerId,
              stripePriceId
            };
            if (payment) {
              const [updatedPayment] = await tx.update(paymentsTable).set({
                amount: String(cycleAmount2),
                currency: plan.currency,
                method: "STRIPE",
                reference: null,
                metadata: nextMetadata,
                updatedAt: now
              }).where(eq(paymentsTable.id, payment.id)).returning();
              payment = updatedPayment ?? payment;
            } else {
              [payment] = await tx.insert(paymentsTable).values({
                userId,
                amount: String(cycleAmount2),
                currency: plan.currency,
                method: "STRIPE",
                status: "PENDING",
                reference: null,
                description: `${plan.name} membership payment (Stripe)`,
                metadata: nextMetadata,
                invoiceId: invoice.id,
                processedAt: null,
                updatedAt: now
              }).returning();
            }
            const [updatedUser] = await tx.update(usersTable).set({
              membershipStatus: "PENDING",
              updatedAt: now
            }).where(eq(usersTable.id, userId)).returning();
            await syncOrganizationSubscriptionStateWith(tx, {
              user,
              plan,
              status: "PENDING",
              now,
              stripeCustomerId
            });
            return {
              kind: "PENDING",
              subscription,
              invoice,
              payment,
              updatedUser,
              stripeCustomerId,
              stripePriceId
            };
          });
          if (result.kind === "ALREADY_ACTIVE") {
            return res.status(409).json({ message: "Membership is already active." });
          }
          if (result.kind === "REQUIRES_DIRECT_CHANGE") {
            return res.status(409).json({
              message: "This change lowers your plan. Use the downgrade flow instead."
            });
          }
          const rawWebBase = process.env.PUBLIC_WEB_URL?.trim() ?? process.env.WEB_BASE_URL?.trim() ?? (Array.isArray(CORS_ORIGIN) ? CORS_ORIGIN[0] : CORS_ORIGIN);
          const webBase = typeof rawWebBase === "string" && /^https?:\/\//i.test(rawWebBase) ? rawWebBase.replace(/\/+$/, "") : "http://localhost:5173";
          const planBillingCycle = plan.defaultBillingCycle ?? "ANNUAL";
          const cycleAmount = Number(
            planBillingCycle === "MONTHLY" ? plan.priceMonthly ?? plan.priceAnnual : plan.priceAnnual
          );
          const returnPath = resolveMembershipCheckoutReturnPath(
            parsed.data.returnPath
          );
          const checkoutSession = result.kind === "UPGRADE_PENDING" ? await stripe.checkout.sessions.create({
            mode: "payment",
            customer: result.stripeCustomerId,
            line_items: [
              {
                price_data: {
                  currency: plan.currency.toLowerCase(),
                  unit_amount: Math.round(result.proration.amountDue * 100),
                  product_data: {
                    name: `${plan.name} membership upgrade`
                  }
                },
                quantity: 1
              }
            ],
            success_url: `${webBase}${returnPath}?stripeMembership=success&session_id={CHECKOUT_SESSION_ID}`,
            cancel_url: `${webBase}${returnPath}?stripeMembership=cancel`,
            metadata: {
              membershipSubscriptionId: String(result.subscription.id),
              userId: String(userId),
              planId: String(plan.id),
              membershipChangeKind: "UPGRADE"
            }
          }) : plan.billingMode === "ONE_TIME" ? await stripe.checkout.sessions.create({
            mode: "payment",
            customer: result.stripeCustomerId,
            line_items: [
              {
                price_data: {
                  currency: plan.currency.toLowerCase(),
                  unit_amount: Math.round(cycleAmount * 100),
                  product_data: {
                    name: `${plan.name} membership`
                  }
                },
                quantity: 1
              }
            ],
            success_url: `${webBase}${returnPath}?stripeMembership=success&session_id={CHECKOUT_SESSION_ID}`,
            cancel_url: `${webBase}${returnPath}?stripeMembership=cancel`,
            metadata: {
              membershipSubscriptionId: String(result.subscription.id),
              userId: String(userId),
              planId: String(plan.id),
              membershipBillingMode: "ONE_TIME",
              membershipBillingCycle: plan.defaultBillingCycle ?? "ANNUAL"
            },
            payment_intent_data: {
              metadata: {
                activationType: "membership_stripe_checkout",
                membershipSubscriptionId: String(result.subscription.id),
                userId: String(userId),
                planId: String(plan.id),
                membershipBillingMode: "ONE_TIME",
                membershipBillingCycle: plan.defaultBillingCycle ?? "ANNUAL"
              }
            }
          }) : await stripe.checkout.sessions.create({
            mode: "subscription",
            customer: result.stripeCustomerId,
            line_items: [{ price: result.stripePriceId, quantity: 1 }],
            success_url: `${webBase}${returnPath}?stripeMembership=success&session_id={CHECKOUT_SESSION_ID}`,
            cancel_url: `${webBase}${returnPath}?stripeMembership=cancel`,
            metadata: {
              membershipSubscriptionId: String(result.subscription.id),
              userId: String(userId),
              planId: String(plan.id),
              membershipBillingMode: "RECURRING",
              membershipBillingCycle: plan.defaultBillingCycle ?? "ANNUAL"
            },
            subscription_data: {
              metadata: {
                membershipSubscriptionId: String(result.subscription.id),
                userId: String(userId),
                planId: String(plan.id)
              }
            }
          });
          if (!checkoutSession.url) {
            throw new Error("Unable to start Stripe checkout.");
          }
          await db.update(paymentsTable).set({
            reference: checkoutSession.id,
            updatedAt: /* @__PURE__ */ new Date()
          }).where(eq(paymentsTable.id, result.payment.id));
          return res.status(201).json({
            user: await formatMemberProfileWithTenantContext(result.updatedUser),
            subscription: {
              id: result.subscription.id,
              status: result.subscription.status,
              startDate: toIsoStringOrNull3(result.subscription.startDate),
              endDate: toIsoStringOrNull3(result.subscription.endDate),
              renewsAt: toIsoStringOrNull3(result.subscription.renewsAt),
              stripeSubscriptionId: result.subscription.stripeSubscriptionId ?? null
            },
            invoice: {
              id: result.invoice.id,
              invoiceNumber: result.invoice.invoiceNumber,
              amount: Number(result.invoice.amount),
              status: result.invoice.status
            },
            payment: {
              id: result.payment.id,
              amount: Number(result.payment.amount),
              status: result.payment.status,
              method: result.payment.method,
              reference: result.payment.reference ?? null
            },
            plan: {
              id: plan.id,
              name: plan.name,
              membershipType: plan.membershipType,
              tier: plan.tier,
              currency: plan.currency,
              priceAnnual: Number(plan.priceAnnual)
            },
            stripe: {
              checkoutUrl: checkoutSession.url,
              sessionId: checkoutSession.id
            }
          });
        } catch (err) {
          console.error("POST /member/membership/stripe/subscribe error:", err);
          return res.status(500).json({ message: "Failed to start Stripe membership payment." });
        }
      }
    );
    router8.post(
      "/member/membership/stripe/confirm",
      requireAuth2,
      async (req, res) => {
        const userId = req.userId;
        try {
          const parsed = membershipStripeCheckoutConfirmSchema.safeParse(
            req.body ?? {}
          );
          if (!parsed.success) {
            return res.status(400).json({ errors: parsed.error.flatten() });
          }
          const [user] = await db.select().from(usersTable).where(eq(usersTable.id, userId));
          if (!user) {
            return res.status(404).json({ message: "User not found." });
          }
          if (user.membershipType === "ORGANIZATION") {
            const billingAccess = await ensureOrganizationBillingAuthority({
              userId,
              organizationId: user.organizationId
            });
            if (!billingAccess.allowed) {
              return res.status(403).json({ message: billingAccess.message });
            }
          }
          const stripe = getStripeClient();
          const session = await stripe.checkout.sessions.retrieve(
            parsed.data.sessionId,
            {
              expand: ["subscription"]
            }
          );
          if (!isRecord4(session)) {
            return res.status(500).json({ message: "Unable to verify Stripe session." });
          }
          const paymentStatus = readString2(session.payment_status);
          if (paymentStatus !== "paid") {
            return res.status(402).json({ message: "Stripe payment is not complete." });
          }
          const sessionMetadata = isRecord4(session.metadata) ? session.metadata : null;
          const membershipSubscriptionIdRaw = sessionMetadata ? readString2(sessionMetadata.membershipSubscriptionId) : null;
          const membershipSubscriptionId = membershipSubscriptionIdRaw ? Number(membershipSubscriptionIdRaw) : NaN;
          if (!Number.isFinite(membershipSubscriptionId) || membershipSubscriptionId <= 0) {
            return res.status(400).json({ message: "Stripe session is missing membership context." });
          }
          const now = /* @__PURE__ */ new Date();
          const changeKind = sessionMetadata ? readString2(sessionMetadata.membershipChangeKind) : null;
          const result = await db.transaction(async (tx) => {
            await tx.execute(
              sql`select pg_advisory_xact_lock(${MEMBERSHIP_ACTIVATION_LOCK_KEY_A}, ${userId})`
            );
            const [subscription] = await tx.select().from(membershipSubscriptionsTable).where(
              and(
                eq(membershipSubscriptionsTable.id, membershipSubscriptionId),
                eq(membershipSubscriptionsTable.userId, userId)
              )
            );
            if (!subscription) {
              return { kind: "NOT_FOUND" };
            }
            const [invoice] = await tx.select().from(invoicesTable).where(
              and(
                eq(invoicesTable.subscriptionId, subscription.id),
                inArray(invoicesTable.status, ["SENT", "OVERDUE"])
              )
            ).orderBy(desc(invoicesTable.createdAt)).limit(1);
            const [payment] = invoice ? await tx.select().from(paymentsTable).where(eq(paymentsTable.invoiceId, invoice.id)).orderBy(desc(paymentsTable.createdAt)).limit(1) : [];
            if (changeKind === "UPGRADE") {
              const planIdRaw = sessionMetadata ? readString2(sessionMetadata.planId) : null;
              const planId = planIdRaw ? Number(planIdRaw) : NaN;
              if (!Number.isFinite(planId) || planId <= 0) {
                throw new Error("Stripe upgrade session is missing target plan.");
              }
              const [plan2] = await tx.select().from(membershipPlansTable).where(eq(membershipPlansTable.id, planId));
              if (!plan2) {
                throw new Error("Membership plan not found.");
              }
              if (subscription.stripeSubscriptionId) {
                const existingStripeSubscription = await stripe.subscriptions.retrieve(
                  subscription.stripeSubscriptionId
                );
                const subscriptionItemId = Array.isArray(
                  existingStripeSubscription.items?.data
                ) ? existingStripeSubscription.items.data[0]?.id ?? null : null;
                if (!subscriptionItemId) {
                  throw new Error("Stripe subscription item is missing.");
                }
                const nextPrice = await ensureStripeMembershipPrice(stripe, plan2);
                await stripe.subscriptions.update(
                  subscription.stripeSubscriptionId,
                  {
                    items: [{ id: subscriptionItemId, price: nextPrice.id }],
                    proration_behavior: "none",
                    billing_cycle_anchor: "unchanged"
                  }
                );
              }
              const [updatedSubscription2] = await tx.update(membershipSubscriptionsTable).set({
                planId: plan2.id,
                status: "ACTIVE",
                updatedAt: now
              }).where(eq(membershipSubscriptionsTable.id, subscription.id)).returning();
              const updatedInvoice2 = invoice ? (await tx.update(invoicesTable).set({
                status: "PAID",
                paidAt: now,
                updatedAt: now
              }).where(eq(invoicesTable.id, invoice.id)).returning())[0] : null;
              const updatedPayment2 = payment ? (await tx.update(paymentsTable).set({
                status: "COMPLETED",
                processedAt: now,
                reference: parsed.data.sessionId,
                updatedAt: now
              }).where(eq(paymentsTable.id, payment.id)).returning())[0] : null;
              const [updatedUser2] = await tx.update(usersTable).set({
                membershipStatus: "ACTIVE",
                membershipType: plan2.membershipType,
                updatedAt: now
              }).where(eq(usersTable.id, userId)).returning();
              await syncOrganizationSubscriptionStateWith(tx, {
                user: updatedUser2,
                plan: plan2,
                status: "ACTIVE",
                now,
                startDate: updatedSubscription2?.startDate ?? subscription.startDate,
                endDate: updatedSubscription2?.endDate ?? subscription.endDate,
                renewsAt: updatedSubscription2?.renewsAt ?? subscription.renewsAt,
                stripeCustomerId: subscription.stripeCustomerId ?? readString2(session.customer),
                stripeSubscriptionId: subscription.stripeSubscriptionId
              });
              await notifyInAppWith(tx, {
                userId,
                category: "MEMBERSHIP",
                severity: "SUCCESS",
                title: "Membership updated",
                body: "Your Stripe payment was successful and your membership plan has been updated.",
                actionLabel: "Open Membership",
                actionHref: "/dashboard/membership"
              });
              return {
                kind: "OK",
                updatedUser: updatedUser2,
                subscription: updatedSubscription2 ?? subscription,
                plan: plan2,
                invoice: updatedInvoice2 ?? invoice ?? null,
                payment: updatedPayment2 ?? payment ?? null
              };
            }
            if (subscription.status === "ACTIVE") {
              return { kind: "ALREADY_ACTIVE", subscription };
            }
            const [plan] = await tx.select().from(membershipPlansTable).where(eq(membershipPlansTable.id, subscription.planId));
            if (!plan) {
              throw new Error("Membership plan not found.");
            }
            const sessionBillingMode = sessionMetadata ? readString2(sessionMetadata.membershipBillingMode) : null;
            const sessionBillingCycle = sessionMetadata ? readString2(sessionMetadata.membershipBillingCycle) : null;
            const isOneTime = plan.billingMode === "ONE_TIME" || sessionBillingMode === "ONE_TIME";
            const effectiveCycle = sessionBillingCycle === "MONTHLY" || sessionBillingCycle === "ANNUAL" ? sessionBillingCycle : plan.defaultBillingCycle === "MONTHLY" ? "MONTHLY" : "ANNUAL";
            let stripeSubscriptionId = null;
            let startDate;
            let endDate;
            let renewsAt;
            if (isOneTime) {
              startDate = now;
              const termEnd = new Date(now);
              if (effectiveCycle === "MONTHLY") {
                termEnd.setMonth(termEnd.getMonth() + 1);
              } else {
                termEnd.setFullYear(termEnd.getFullYear() + 1);
              }
              endDate = termEnd;
              renewsAt = null;
              stripeSubscriptionId = null;
            } else {
              stripeSubscriptionId = typeof session.subscription === "string" ? session.subscription : isRecord4(session.subscription) ? readString2(session.subscription.id) : null;
              if (!stripeSubscriptionId) {
                throw new Error("Stripe session is missing subscription id.");
              }
              const stripeSubscription = await stripe.subscriptions.retrieve(stripeSubscriptionId);
              const currentPeriodStart = isRecord4(stripeSubscription) && typeof stripeSubscription.current_period_start === "number" ? stripeSubscription.current_period_start : null;
              const currentPeriodEnd = isRecord4(stripeSubscription) && typeof stripeSubscription.current_period_end === "number" ? stripeSubscription.current_period_end : null;
              startDate = currentPeriodStart ? new Date(currentPeriodStart * 1e3) : now;
              renewsAt = currentPeriodEnd ? new Date(currentPeriodEnd * 1e3) : null;
              endDate = null;
            }
            const [updatedSubscription] = await tx.update(membershipSubscriptionsTable).set({
              status: "ACTIVE",
              stripeSubscriptionId,
              startDate,
              endDate,
              renewsAt,
              updatedAt: now
            }).where(eq(membershipSubscriptionsTable.id, subscription.id)).returning();
            const updatedInvoice = invoice ? (await tx.update(invoicesTable).set({
              status: "PAID",
              paidAt: now,
              updatedAt: now
            }).where(eq(invoicesTable.id, invoice.id)).returning())[0] : null;
            const updatedPayment = payment ? (await tx.update(paymentsTable).set({
              status: "COMPLETED",
              processedAt: now,
              reference: parsed.data.sessionId,
              updatedAt: now
            }).where(eq(paymentsTable.id, payment.id)).returning())[0] : null;
            const [updatedUser] = await tx.update(usersTable).set({
              membershipStatus: "ACTIVE",
              membershipType: plan.membershipType,
              updatedAt: now
            }).where(eq(usersTable.id, userId)).returning();
            if (plan.membershipType === "INVESTOR" && updatedInvoice && updatedInvoice.status === "PAID") {
              const creditAmount = Number(updatedInvoice.amount);
              if (creditAmount > 0) {
                const investmentWallet = await ensureInvestmentWalletWith2(tx);
                const creditIdempotencyKey = isOneTime ? `investment_membership_onetime:${updatedSubscription?.id ?? subscription.id}:invoice:${updatedInvoice.id}` : `investment_membership_renewal:${updatedSubscription?.id ?? subscription.id}:invoice:${updatedInvoice.id}`;
                await tx.insert(walletTransactionsTable).values({
                  type: "MEMBERSHIP_DONATION",
                  toWalletId: investmentWallet.id,
                  amount: creditAmount.toFixed(2),
                  currency: plan.currency,
                  idempotencyKey: creditIdempotencyKey,
                  metadata: {
                    source: "stripe_checkout_confirm",
                    fundingIntent: "INVESTMENT_TREASURY",
                    membershipBillingMode: isOneTime ? "ONE_TIME" : plan.billingMode ?? "RECURRING",
                    membershipSubscriptionId: updatedSubscription?.id ?? subscription.id,
                    userId,
                    userSegment: user.segment ?? null,
                    investorCategory: user.investorCategory ?? null,
                    planTier: plan.tier,
                    planId: plan.id,
                    invoiceId: updatedInvoice.id,
                    sessionId: parsed.data.sessionId
                  },
                  createdAt: now
                }).onConflictDoNothing();
              }
            }
            await syncOrganizationSubscriptionStateWith(tx, {
              user: updatedUser,
              plan,
              status: "ACTIVE",
              now,
              startDate,
              endDate,
              renewsAt,
              stripeCustomerId: subscription.stripeCustomerId ?? readString2(session.customer),
              stripeSubscriptionId
            });
            await notifyInAppWith(tx, {
              userId,
              category: "MEMBERSHIP",
              severity: "SUCCESS",
              title: "Membership active",
              body: "Your Stripe payment was successful and your membership is now active.",
              actionLabel: "Open Membership",
              actionHref: "/dashboard/membership"
            });
            return {
              kind: "OK",
              updatedUser,
              subscription: updatedSubscription ?? subscription,
              plan,
              invoice: updatedInvoice ?? invoice ?? null,
              payment: updatedPayment ?? payment ?? null
            };
          });
          if (result.kind === "NOT_FOUND") {
            return res.status(404).json({ message: "Membership subscription not found." });
          }
          if (result.kind === "ALREADY_ACTIVE") {
            return res.status(200).json({ message: "Membership is already active." });
          }
          if (!result.plan || !result.invoice || !result.payment) {
            return res.status(500).json({ message: "Membership activation is incomplete." });
          }
          return res.status(200).json({
            user: await formatMemberProfileWithTenantContext(result.updatedUser),
            subscription: {
              id: result.subscription.id,
              status: result.subscription.status,
              startDate: toIsoStringOrNull3(result.subscription.startDate),
              endDate: toIsoStringOrNull3(result.subscription.endDate),
              renewsAt: toIsoStringOrNull3(result.subscription.renewsAt)
            },
            invoice: {
              id: result.invoice.id,
              invoiceNumber: result.invoice.invoiceNumber,
              amount: Number(result.invoice.amount),
              status: result.invoice.status
            },
            payment: {
              id: result.payment.id,
              amount: Number(result.payment.amount),
              status: result.payment.status,
              method: result.payment.method,
              reference: result.payment.reference ?? null
            },
            plan: {
              id: result.plan.id,
              name: result.plan.name,
              membershipType: result.plan.membershipType,
              tier: result.plan.tier,
              currency: result.plan.currency,
              priceAnnual: Number(result.plan.priceAnnual)
            }
          });
        } catch (err) {
          console.error("POST /member/membership/stripe/confirm error:", err);
          return res.status(500).json({ message: "Failed to confirm Stripe payment." });
        }
      }
    );
    router8.post("/member/membership/activate", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        const parsed = membershipActivationSchema.safeParse(req.body ?? {});
        if (!parsed.success) {
          return res.status(400).json({ errors: parsed.error.flatten() });
        }
        const [user] = await db.select().from(usersTable).where(eq(usersTable.id, userId));
        if (!user) {
          return res.status(404).json({ message: "User not found." });
        }
        if (!isUserProfileComplete(user)) {
          return res.status(400).json({
            message: "Complete your profile details before activating membership."
          });
        }
        const [plan] = await db.select().from(membershipPlansTable).where(eq(membershipPlansTable.id, parsed.data.planId));
        if (!plan || !plan.isActive) {
          return res.status(404).json({ message: "Membership plan not found." });
        }
        if (user.membershipType && plan.membershipType !== user.membershipType) {
          return res.status(400).json({
            message: "This plan does not match your selected membership type."
          });
        }
        if (user.membershipType === "ORGANIZATION" && plan.membershipType === "ORGANIZATION") {
          const billingAccess = await ensureOrganizationBillingAuthority({
            userId,
            organizationId: user.organizationId
          });
          if (!billingAccess.allowed) {
            return res.status(403).json({ message: billingAccess.message });
          }
        }
        const now = /* @__PURE__ */ new Date();
        const amount = plan.priceAnnual;
        const dueDate = new Date(now);
        dueDate.setDate(dueDate.getDate() + 7);
        const result = await db.transaction(async (tx) => {
          await tx.execute(
            sql`select pg_advisory_xact_lock(${MEMBERSHIP_ACTIVATION_LOCK_KEY_A}, ${userId})`
          );
          const [existingActive] = await tx.select({
            subscription: membershipSubscriptionsTable,
            plan: membershipPlansTable
          }).from(membershipSubscriptionsTable).innerJoin(
            membershipPlansTable,
            eq(membershipSubscriptionsTable.planId, membershipPlansTable.id)
          ).where(
            and(
              eq(membershipSubscriptionsTable.userId, userId),
              eq(membershipSubscriptionsTable.status, "ACTIVE")
            )
          ).limit(1);
          if (existingActive?.subscription && existingActive.plan) {
            const changeKind = getMembershipChangeKind(existingActive.plan, plan);
            if (changeKind === "NONE") {
              return { kind: "ALREADY_ACTIVE" };
            }
            if (changeKind === "DOWNGRADE") {
              return { kind: "REQUIRES_DIRECT_CHANGE" };
            }
            const proration = calculateMembershipProration({
              currentPlan: existingActive.plan,
              targetPlan: plan,
              subscription: existingActive.subscription,
              now
            });
            const invoiceNumber = `INV-${now.getFullYear()}-${userId}-${Date.now()}`;
            const [invoice2] = await tx.insert(invoicesTable).values({
              userId,
              subscriptionId: existingActive.subscription.id,
              invoiceNumber,
              amount: proration.amountDue.toFixed(2),
              currency: plan.currency,
              status: "SENT",
              dueDate,
              paidAt: null,
              lineItems: [
                {
                  description: `${plan.name} prorated upgrade charge`,
                  quantity: 1,
                  unitPrice: proration.targetProratedAmount,
                  total: proration.targetProratedAmount
                },
                {
                  description: `${existingActive.plan.name} unused time credit`,
                  quantity: 1,
                  unitPrice: -proration.unusedCredit,
                  total: -proration.unusedCredit
                }
              ],
              updatedAt: now
            }).returning();
            const isWalletActivation2 = parsed.data.paymentMethod === "WALLET";
            const walletScope2 = isWalletActivation2 ? await resolveMemberWalletScopeWith(tx, user) : null;
            const [payment2] = await tx.insert(paymentsTable).values({
              userId,
              amount: proration.amountDue.toFixed(2),
              currency: plan.currency,
              method: parsed.data.paymentMethod,
              status: isWalletActivation2 ? "COMPLETED" : "PENDING",
              reference: isWalletActivation2 ? null : parsed.data.paymentReference?.trim() || null,
              description: isWalletActivation2 ? `${plan.name} membership upgrade payment (wallet)` : `${plan.name} membership upgrade payment (manual review)`,
              metadata: {
                activationType: isWalletActivation2 ? "membership_wallet_plan_change" : "membership_manual_plan_change",
                planId: plan.id,
                fromPlanId: existingActive.plan.id,
                toPlanId: plan.id,
                changeKind: "UPGRADE",
                proofUrl: parsed.data.proofUrl?.trim() || null,
                note: parsed.data.note?.trim() || null,
                unusedCredit: proration.unusedCredit,
                targetProratedAmount: proration.targetProratedAmount,
                amountDue: proration.amountDue,
                walletOwnerType: walletScope2?.ownerType ?? null,
                walletOwnerId: walletScope2?.ownerId ?? null,
                organizationId: walletScope2?.organizationId ?? null
              },
              invoiceId: invoice2.id,
              processedAt: isWalletActivation2 ? now : null,
              updatedAt: now
            }).returning();
            if (isWalletActivation2) {
              const availableBalance = (await getWalletFundsWith2(tx, walletScope2.wallet.id)).availableBalance;
              if (availableBalance < proration.amountDue) {
                return {
                  kind: "INSUFFICIENT_FUNDS",
                  availableBalance
                };
              }
              const targetWallet = plan.membershipType === "INVESTOR" ? await ensureInvestmentWalletWith2(tx) : await ensurePlatformWalletWith(tx);
              await tx.insert(walletTransactionsTable).values({
                type: plan.membershipType === "INVESTOR" ? "MEMBERSHIP_DONATION" : "ADJUSTMENT",
                idempotencyKey: `membership-wallet-upgrade:${existingActive.subscription.id}:${payment2.id}`,
                fromWalletId: walletScope2.wallet.id,
                toWalletId: targetWallet.id,
                amount: proration.amountDue.toFixed(2),
                metadata: {
                  source: "membership_wallet_upgrade",
                  fundingIntent: plan.membershipType === "INVESTOR" ? "INVESTMENT_TREASURY" : "PLATFORM_MEMBERSHIP",
                  membershipBillingMode: plan.billingMode ?? "RECURRING",
                  userId,
                  organizationId: walletScope2.organizationId,
                  membershipSubscriptionId: existingActive.subscription.id,
                  invoiceId: invoice2.id,
                  paymentId: payment2.id,
                  fromPlanId: existingActive.plan.id,
                  planId: plan.id,
                  planTier: plan.tier,
                  walletOwnerType: walletScope2.ownerType,
                  walletOwnerId: walletScope2.ownerId,
                  userSegment: user.segment ?? null,
                  investorCategory: user.investorCategory ?? null
                }
              }).onConflictDoNothing();
              const [updatedInvoice] = await tx.update(invoicesTable).set({
                status: "PAID",
                paidAt: now,
                updatedAt: now
              }).where(eq(invoicesTable.id, invoice2.id)).returning();
              const [updatedSubscription] = await tx.update(membershipSubscriptionsTable).set({
                planId: plan.id,
                status: "ACTIVE",
                updatedAt: now
              }).where(
                eq(
                  membershipSubscriptionsTable.id,
                  existingActive.subscription.id
                )
              ).returning();
              const [updatedUser2] = await tx.update(usersTable).set({
                membershipStatus: "ACTIVE",
                membershipType: plan.membershipType,
                updatedAt: now
              }).where(eq(usersTable.id, userId)).returning();
              await syncOrganizationSubscriptionStateWith(tx, {
                user: updatedUser2,
                plan,
                status: "ACTIVE",
                now,
                startDate: updatedSubscription?.startDate ?? existingActive.subscription.startDate,
                endDate: updatedSubscription?.endDate ?? existingActive.subscription.endDate,
                renewsAt: updatedSubscription?.renewsAt ?? existingActive.subscription.renewsAt,
                stripeCustomerId: existingActive.subscription.stripeCustomerId,
                stripeSubscriptionId: existingActive.subscription.stripeSubscriptionId
              });
              await notifyInAppWith(tx, {
                userId,
                category: "MEMBERSHIP",
                severity: "SUCCESS",
                title: "Membership updated",
                body: "Your wallet payment succeeded and your membership plan has been updated.",
                actionLabel: "Open Membership",
                actionHref: "/dashboard/membership"
              });
              return {
                kind: "ACTIVE_PLAN_CHANGE",
                subscription: updatedSubscription ?? existingActive.subscription,
                invoice: updatedInvoice ?? invoice2,
                payment: payment2,
                updatedUser: updatedUser2
              };
            }
            await notifyInAppWith(tx, {
              userId,
              category: "MEMBERSHIP",
              severity: "INFO",
              title: "Upgrade payment submitted",
              body: "Your membership upgrade payment has been submitted for review.",
              actionLabel: "Open Membership",
              actionHref: "/dashboard/membership"
            });
            return {
              kind: "PENDING_PLAN_CHANGE",
              subscription: existingActive.subscription,
              invoice: invoice2,
              payment: payment2,
              updatedUser: user
            };
          }
          const [existingPending] = await tx.select().from(membershipSubscriptionsTable).where(
            and(
              eq(membershipSubscriptionsTable.userId, userId),
              eq(membershipSubscriptionsTable.status, "PENDING")
            )
          ).orderBy(desc(membershipSubscriptionsTable.createdAt)).limit(1);
          let subscription = existingPending ?? null;
          if (subscription && subscription.planId !== plan.id) {
            await tx.update(membershipSubscriptionsTable).set({
              status: "CANCELLED",
              cancelledAt: now,
              updatedAt: now
            }).where(eq(membershipSubscriptionsTable.id, subscription.id));
            subscription = null;
          }
          if (!subscription) {
            try {
              [subscription] = await tx.insert(membershipSubscriptionsTable).values({
                userId,
                planId: plan.id,
                status: "PENDING",
                startDate: null,
                endDate: null,
                renewsAt: null,
                updatedAt: now
              }).returning();
            } catch (err) {
              if (!isUniqueViolation7(err)) throw err;
              const existing = await tx.select().from(membershipSubscriptionsTable).where(
                and(
                  eq(membershipSubscriptionsTable.userId, userId),
                  inArray(membershipSubscriptionsTable.status, [
                    "PENDING",
                    "ACTIVE"
                  ])
                )
              ).orderBy(desc(membershipSubscriptionsTable.createdAt)).limit(1);
              subscription = existing[0] ?? null;
            }
          }
          if (!subscription) {
            throw new Error("Failed to create subscription.");
          }
          if (subscription.status === "ACTIVE") {
            return { kind: "ALREADY_ACTIVE" };
          }
          let didCreate = false;
          const [existingInvoice] = await tx.select().from(invoicesTable).where(
            and(
              eq(invoicesTable.subscriptionId, subscription.id),
              inArray(invoicesTable.status, ["SENT", "OVERDUE"])
            )
          ).orderBy(desc(invoicesTable.createdAt)).limit(1);
          let invoice = existingInvoice ?? null;
          if (invoice && Number(invoice.amount) !== Number(amount)) {
            await tx.update(invoicesTable).set({
              status: "CANCELLED",
              updatedAt: now
            }).where(eq(invoicesTable.id, invoice.id));
            invoice = null;
          }
          if (!invoice) {
            const invoiceNumber = `INV-${now.getFullYear()}-${userId}-${Date.now()}`;
            [invoice] = await tx.insert(invoicesTable).values({
              userId,
              subscriptionId: subscription.id,
              invoiceNumber,
              amount,
              currency: plan.currency,
              status: "SENT",
              dueDate,
              paidAt: null,
              lineItems: [
                {
                  description: `${plan.name} membership (Yearly (billed annually))`,
                  quantity: 1,
                  unitPrice: Number(amount),
                  total: Number(amount)
                }
              ],
              updatedAt: now
            }).returning();
            didCreate = true;
          }
          const [existingPayment] = await tx.select().from(paymentsTable).where(
            and(
              eq(paymentsTable.invoiceId, invoice.id),
              eq(paymentsTable.status, "PENDING")
            )
          ).orderBy(desc(paymentsTable.createdAt)).limit(1);
          let payment = existingPayment ?? null;
          const walletScope = await resolveMemberWalletScopeWith(tx, user);
          const isWalletActivation = parsed.data.paymentMethod === "WALLET";
          const nextMetadata = isWalletActivation ? {
            planId: plan.id,
            activationType: "membership_wallet",
            fundingIntent: "PLATFORM_MEMBERSHIP",
            walletOwnerType: walletScope.ownerType,
            walletOwnerId: walletScope.ownerId,
            organizationId: walletScope.organizationId,
            proofUrl: null,
            note: parsed.data.note?.trim() || null
          } : {
            planId: plan.id,
            activationType: "membership_manual",
            proofUrl: parsed.data.proofUrl?.trim() || null,
            note: parsed.data.note?.trim() || null
          };
          if (payment) {
            const [updatedPayment] = await tx.update(paymentsTable).set({
              amount,
              currency: plan.currency,
              method: parsed.data.paymentMethod,
              reference: isWalletActivation ? null : parsed.data.paymentReference?.trim() || null,
              metadata: nextMetadata,
              status: isWalletActivation ? "COMPLETED" : "PENDING",
              processedAt: isWalletActivation ? now : null,
              updatedAt: now
            }).where(eq(paymentsTable.id, payment.id)).returning();
            payment = updatedPayment ?? payment;
          } else {
            [payment] = await tx.insert(paymentsTable).values({
              userId,
              amount,
              currency: plan.currency,
              method: parsed.data.paymentMethod,
              status: isWalletActivation ? "COMPLETED" : "PENDING",
              reference: isWalletActivation ? null : parsed.data.paymentReference?.trim() || null,
              description: isWalletActivation ? `${plan.name} membership payment (wallet)` : `${plan.name} membership payment (manual review)`,
              metadata: nextMetadata,
              invoiceId: invoice.id,
              processedAt: isWalletActivation ? now : null,
              updatedAt: now
            }).returning();
            didCreate = true;
          }
          if (isWalletActivation) {
            const availableBalance = (await getWalletFundsWith2(tx, walletScope.wallet.id)).availableBalance;
            const numericAmount = Number(amount);
            if (availableBalance < numericAmount) {
              return {
                kind: "INSUFFICIENT_FUNDS",
                availableBalance
              };
            }
            const targetWallet = plan.membershipType === "INVESTOR" ? await ensureInvestmentWalletWith2(tx) : await ensurePlatformWalletWith(tx);
            await tx.insert(walletTransactionsTable).values({
              type: plan.membershipType === "INVESTOR" ? "MEMBERSHIP_DONATION" : "ADJUSTMENT",
              idempotencyKey: `membership-wallet:${subscription.id}:${payment.id}`,
              fromWalletId: walletScope.wallet.id,
              toWalletId: targetWallet.id,
              amount,
              metadata: {
                source: "membership_wallet_activation",
                fundingIntent: plan.membershipType === "INVESTOR" ? "INVESTMENT_TREASURY" : "PLATFORM_MEMBERSHIP",
                membershipBillingMode: plan.billingMode ?? "RECURRING",
                userId,
                organizationId: walletScope.organizationId,
                membershipSubscriptionId: subscription.id,
                invoiceId: invoice.id,
                paymentId: payment.id,
                planId: plan.id,
                planTier: plan.tier,
                walletOwnerType: walletScope.ownerType,
                walletOwnerId: walletScope.ownerId,
                userSegment: user.segment ?? null,
                investorCategory: user.investorCategory ?? null
              }
            }).onConflictDoNothing();
            const renewalDate = new Date(now);
            renewalDate.setFullYear(renewalDate.getFullYear() + 1);
            const [updatedInvoice] = await tx.update(invoicesTable).set({
              status: "PAID",
              paidAt: now,
              updatedAt: now
            }).where(eq(invoicesTable.id, invoice.id)).returning();
            const [updatedSubscription] = await tx.update(membershipSubscriptionsTable).set({
              status: "ACTIVE",
              startDate: now,
              endDate: renewalDate,
              renewsAt: renewalDate,
              updatedAt: now
            }).where(eq(membershipSubscriptionsTable.id, subscription.id)).returning();
            const [updatedUser2] = await tx.update(usersTable).set({
              membershipStatus: "ACTIVE",
              membershipType: plan.membershipType,
              updatedAt: now
            }).where(eq(usersTable.id, userId)).returning();
            await syncOrganizationSubscriptionStateWith(tx, {
              user: updatedUser2,
              plan,
              status: "ACTIVE",
              now,
              startDate: now,
              endDate: renewalDate,
              renewsAt: renewalDate
            });
            await notifyInAppWith(tx, {
              userId,
              category: "MEMBERSHIP",
              severity: "SUCCESS",
              title: "Membership active",
              body: "Your wallet payment succeeded and your membership is now active.",
              actionLabel: "Open Membership",
              actionHref: "/dashboard/membership"
            });
            return {
              kind: "ACTIVE",
              subscription: updatedSubscription ?? subscription,
              invoice: updatedInvoice ?? invoice,
              payment,
              updatedUser: updatedUser2
            };
          }
          const [updatedUser] = await tx.update(usersTable).set({
            membershipStatus: "PENDING",
            updatedAt: now
          }).where(eq(usersTable.id, userId)).returning();
          await syncOrganizationSubscriptionStateWith(tx, {
            user,
            plan,
            status: "PENDING",
            now
          });
          let inAppNotificationId = null;
          if (didCreate) {
            const inApp = await notifyInAppWith(tx, {
              userId,
              category: "MEMBERSHIP",
              severity: "INFO",
              title: "Payment submitted",
              body: "Your membership payment has been submitted for review. We'll activate your membership once it is confirmed.",
              actionLabel: "Open Membership",
              actionHref: "/dashboard/membership"
            });
            inAppNotificationId = inApp.id;
          }
          return {
            kind: "PENDING",
            subscription,
            invoice,
            payment,
            updatedUser,
            inAppNotificationId
          };
        });
        if (result.kind === "ALREADY_ACTIVE") {
          return res.status(409).json({ message: "Membership is already active." });
        }
        if (result.kind === "REQUIRES_DIRECT_CHANGE") {
          return res.status(409).json({
            message: "This change lowers your plan. Use the downgrade flow instead."
          });
        }
        if (result.kind === "INSUFFICIENT_FUNDS") {
          return res.status(409).json({
            message: `Insufficient available wallet balance. Current available balance is ${result.availableBalance.toFixed(2)}.`
          });
        }
        return res.status(201).json({
          user: await formatMemberProfileWithTenantContext(result.updatedUser),
          subscription: {
            id: result.subscription.id,
            status: result.subscription.status,
            startDate: toIsoStringOrNull3(result.subscription.startDate),
            endDate: toIsoStringOrNull3(result.subscription.endDate),
            renewsAt: toIsoStringOrNull3(result.subscription.renewsAt)
          },
          invoice: {
            id: result.invoice.id,
            invoiceNumber: result.invoice.invoiceNumber,
            amount: Number(result.invoice.amount),
            status: result.invoice.status
          },
          payment: {
            id: result.payment.id,
            amount: Number(result.payment.amount),
            status: result.payment.status,
            method: result.payment.method
          },
          plan: {
            id: plan.id,
            name: plan.name,
            membershipType: plan.membershipType,
            tier: plan.tier,
            currency: plan.currency,
            priceAnnual: Number(plan.priceAnnual)
          }
        });
      } catch (err) {
        console.error("POST /member/membership/activate error:", err);
        return res.status(500).json({ message: "Failed to activate membership." });
      }
    });
    router8.get("/member/notifications", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        const limit = Math.min(
          100,
          Math.max(1, Number(req.query.limit ?? 50) || 50)
        );
        const offset = Math.max(0, Number(req.query.offset ?? 0) || 0);
        const includeReadRaw = String(
          req.query.includeRead ?? "true"
        ).toLowerCase();
        const includeRead = includeReadRaw !== "false" && includeReadRaw !== "0";
        const notifications = await listNotificationsWith(db, {
          userId,
          limit,
          offset,
          includeRead
        });
        return res.json({
          notifications: notifications.map((n) => ({
            id: String(n.id),
            category: n.category,
            severity: n.severity,
            title: n.title,
            body: n.body,
            read: n.read,
            readAt: n.readAt ? n.readAt.toISOString() : null,
            createdAt: n.createdAt.toISOString(),
            actionLabel: n.actionLabel ?? null,
            actionHref: n.actionHref ?? null
          }))
        });
      } catch (err) {
        console.error("GET /member/notifications error:", err);
        return res.status(500).json({ message: "Failed to fetch notifications." });
      }
    });
    router8.get(
      "/member/notifications/unread-count",
      requireAuth2,
      async (req, res) => {
        const userId = req.userId;
        try {
          const unreadCount = await getUnreadCountWith(db, userId);
          return res.json({ unreadCount });
        } catch (err) {
          console.error("GET /member/notifications/unread-count error:", err);
          return res.status(500).json({ message: "Failed to fetch unread count." });
        }
      }
    );
    router8.post("/member/notifications/read-all", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        const updatedCount = await markAllNotificationsReadWith(db, userId);
        return res.json({ updatedCount });
      } catch (err) {
        console.error("POST /member/notifications/read-all error:", err);
        return res.status(500).json({ message: "Failed to mark notifications read." });
      }
    });
    router8.post("/member/notifications/:id/read", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        const notificationId = Number.parseInt(req.params.id, 10);
        if (!Number.isFinite(notificationId)) {
          return res.status(400).json({ message: "Invalid notification id." });
        }
        const notification = await markNotificationReadWith(db, {
          userId,
          id: notificationId
        });
        if (!notification) {
          return res.status(404).json({ message: "Notification not found." });
        }
        return res.json({
          notification: {
            id: String(notification.id),
            category: notification.category,
            severity: notification.severity,
            title: notification.title,
            body: notification.body,
            read: notification.read,
            readAt: notification.readAt ? notification.readAt.toISOString() : null,
            createdAt: notification.createdAt.toISOString(),
            actionLabel: notification.actionLabel ?? null,
            actionHref: notification.actionHref ?? null
          }
        });
      } catch (err) {
        console.error("POST /member/notifications/:id/read error:", err);
        return res.status(500).json({ message: "Failed to mark notification read." });
      }
    });
    registerPushTokenSchema = external_exports.object({
      token: external_exports.string().trim().min(10).refine(
        (value) => /^(Expo(nent)?PushToken)\[[A-Za-z0-9\-_:]+]$/.test(value) || value.startsWith("ExponentPushToken[") || value.startsWith("ExpoPushToken["),
        "Invalid Expo push token."
      ),
      deviceName: external_exports.string().trim().min(1).max(200).optional(),
      deviceId: external_exports.string().trim().min(1).max(200).optional()
    });
    router8.post("/member/push-tokens/register", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        const parsed = registerPushTokenSchema.safeParse(req.body ?? {});
        if (!parsed.success) {
          return res.status(400).json({ errors: parsed.error.flatten() });
        }
        const row = await upsertExpoPushTokenWith(db, {
          userId,
          token: parsed.data.token,
          deviceName: parsed.data.deviceName ?? null,
          deviceId: parsed.data.deviceId ?? null
        });
        return res.json({
          token: row.token,
          isEnabled: row.isEnabled,
          lastSeenAt: row.lastSeenAt.toISOString()
        });
      } catch (err) {
        console.error("POST /member/push-tokens/register error:", err);
        return res.status(500).json({ message: "Failed to register push token." });
      }
    });
    router8.post("/member/push-tokens/unregister", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        const token = typeof req.body?.token === "string" ? req.body.token.trim() : "";
        if (!token) {
          return res.status(400).json({ message: "token is required." });
        }
        const row = await disableExpoPushTokenWith(db, { userId, token });
        if (!row) {
          return res.status(404).json({ message: "Push token not found." });
        }
        return res.json({ token: row.token, isEnabled: row.isEnabled });
      } catch (err) {
        console.error("POST /member/push-tokens/unregister error:", err);
        return res.status(500).json({ message: "Failed to unregister push token." });
      }
    });
    router8.get(
      "/member/notification-preferences",
      requireAuth2,
      async (req, res) => {
        const userId = req.userId;
        try {
          const result = await listNotificationPreferencesWith(db, userId);
          return res.json(result);
        } catch (err) {
          console.error("GET /member/notification-preferences error:", err);
          return res.status(500).json({ message: "Failed to fetch notification preferences." });
        }
      }
    );
    updateNotificationPreferenceSchema = external_exports.object({
      channel: external_exports.enum(["PUSH", "EMAIL"]),
      category: external_exports.enum([
        "SYSTEM",
        "MEMBERSHIP",
        "SAVINGS",
        "LENDING",
        "INVESTMENT",
        "ACADEMY",
        "PAYMENT",
        "COMMUNITY"
      ]),
      enabled: external_exports.boolean()
    });
    router8.post(
      "/member/notification-preferences",
      requireAuth2,
      async (req, res) => {
        const userId = req.userId;
        try {
          const parsed = updateNotificationPreferenceSchema.safeParse(
            req.body ?? {}
          );
          if (!parsed.success) {
            return res.status(400).json({ errors: parsed.error.flatten() });
          }
          const row = await upsertNotificationPreferenceWith(db, {
            userId,
            channel: parsed.data.channel,
            category: parsed.data.category,
            enabled: parsed.data.enabled
          });
          return res.json({
            channel: row.channel,
            category: row.category,
            enabled: row.enabled,
            updatedAt: row.updatedAt.toISOString()
          });
        } catch (err) {
          console.error("POST /member/notification-preferences error:", err);
          return res.status(500).json({ message: "Failed to update notification preferences." });
        }
      }
    );
    router8.get("/member/circles", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        await ensureMemberProductAccess(userId, "SUSU");
        const circles = await getMemberCirclesSnapshot(userId);
        return res.json({ circles });
      } catch (err) {
        if (err instanceof MemberProductAccessError) {
          return res.status(err.statusCode).json({ message: err.message });
        }
        console.error("GET /member/circles error:", err);
        return res.status(500).json({ message: "Failed to fetch circles." });
      }
    });
    router8.get("/member/circle", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        await ensureMemberProductAccess(userId, "SUSU");
        const circles = await getMemberCirclesSnapshot(userId);
        return res.json({ circle: circles[0] ?? null });
      } catch (err) {
        if (err instanceof MemberProductAccessError) {
          return res.status(err.statusCode).json({ message: err.message });
        }
        console.error("GET /member/circle error:", err);
        return res.status(500).json({ message: "Failed to fetch circle." });
      }
    });
    router8.get("/member/contributions", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        await ensureMemberProductAccess(userId, "SUSU");
        const circleMemberships = await db.select({ circleId: circleMembershipsTable.circleId }).from(circleMembershipsTable).where(eq(circleMembershipsTable.userId, userId));
        await activateReadyMemberCircles(
          circleMemberships.map((membership) => membership.circleId)
        );
        await Promise.all(
          circleMemberships.map(
            (membership) => repairCircleContributionScheduleWith(db, membership.circleId)
          )
        );
        const contributions = await db.select().from(savingsContributionsTable).where(eq(savingsContributionsTable.userId, userId)).orderBy(asc(savingsContributionsTable.dueDate));
        return res.json({
          contributions: contributions.map((c) => ({
            id: c.id,
            circleId: c.circleId,
            dueDate: c.dueDate.toISOString(),
            month: new Date(c.dueDate).toLocaleDateString("en-CA", {
              month: "short",
              year: "numeric"
            }),
            amount: Number(c.amount),
            status: c.status,
            method: c.method ?? null,
            paidAt: c.paidAt?.toISOString() ?? null
          }))
        });
      } catch (err) {
        if (err instanceof MemberProductAccessError) {
          return res.status(err.statusCode).json({ message: err.message });
        }
        console.error("GET /member/contributions error:", err);
        return res.status(500).json({ message: "Failed to fetch contributions." });
      }
    });
    router8.get("/member/credit-score", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        const scores = await db.select().from(wwnCreditScoresTable).where(eq(wwnCreditScoresTable.userId, userId));
        if (!scores.length) return res.json({ susuScore: null });
        const scoreRow = scores[0];
        const factors = await db.select().from(creditScoreFactorsTable).where(eq(creditScoreFactorsTable.creditScoreId, scoreRow.id));
        const tier = scoreRow.score >= 80 ? "Excellent" : scoreRow.score >= 65 ? "Good" : scoreRow.score >= 50 ? "Fair" : "Needs Improvement";
        return res.json({
          susuScore: {
            score: scoreRow.score,
            tier,
            lastUpdated: scoreRow.computedAt.toISOString().split("T")[0],
            factors: factors.map((f) => ({ label: f.factorName, score: f.score }))
          }
        });
      } catch (err) {
        console.error("GET /member/credit-score error:", err);
        return res.status(500).json({ message: "Failed to fetch Susu Score." });
      }
    });
    router8.get("/member/helping-hand", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        await ensureMemberProductAccess(userId, "SUSU");
        const [eligibility, app3] = await Promise.all([
          getHelpingHandEligibilitySnapshot(userId),
          db.select({
            id: helpingHandApplicationsTable.id,
            requestedAmount: helpingHandApplicationsTable.requestedAmount,
            approvedAmount: helpingHandApplicationsTable.approvedAmount,
            disbursedAmount: helpingHandApplicationsTable.disbursedAmount,
            qualifyingCircleId: helpingHandApplicationsTable.qualifyingCircleId,
            qualifyingPayoutAmount: helpingHandApplicationsTable.qualifyingPayoutAmount,
            qualifyingMultiplier: helpingHandApplicationsTable.qualifyingMultiplier,
            purpose: helpingHandApplicationsTable.purpose,
            term: helpingHandApplicationsTable.term,
            repaymentSchedule: helpingHandApplicationsTable.repaymentSchedule,
            notes: helpingHandApplicationsTable.notes,
            reviewNote: helpingHandApplicationsTable.reviewNote,
            status: helpingHandApplicationsTable.status,
            disbursedAt: helpingHandApplicationsTable.disbursedAt,
            createdAt: helpingHandApplicationsTable.createdAt,
            reviewedAt: helpingHandApplicationsTable.reviewedAt,
            qualifyingCircleName: savingsCirclesTable.name
          }).from(helpingHandApplicationsTable).leftJoin(
            savingsCirclesTable,
            eq(
              helpingHandApplicationsTable.qualifyingCircleId,
              savingsCirclesTable.id
            )
          ).where(eq(helpingHandApplicationsTable.userId, userId)).orderBy(desc(helpingHandApplicationsTable.createdAt)).limit(1).then((rows) => rows[0] ?? null)
        ]);
        const eligibilityReason = eligibility.eligible ? "You can apply for SUSU Matching Fund." : eligibility.reasons[0] ?? "Eligibility will update with your SUSU progress.";
        return res.json({
          helpingHand: {
            id: app3?.id ?? null,
            requestedAmount: app3 ? Number(app3.requestedAmount) : null,
            approvedAmount: app3?.approvedAmount ? Number(app3.approvedAmount) : null,
            disbursedAmount: app3?.disbursedAmount ? Number(app3.disbursedAmount) : null,
            purpose: app3?.purpose ?? null,
            term: app3?.term ?? null,
            repaymentSchedule: app3?.repaymentSchedule ?? null,
            notes: app3?.notes ?? null,
            reviewNote: app3?.reviewNote ?? null,
            status: app3?.status ?? null,
            qualifyingCircleId: app3?.qualifyingCircleId ?? eligibility.inputs.qualifyingCircleId ?? null,
            qualifyingCircleName: app3?.qualifyingCircleName ?? eligibility.inputs.qualifyingCircleName ?? null,
            qualifyingPayoutAmount: app3?.qualifyingPayoutAmount ? Number(app3.qualifyingPayoutAmount) : eligibility.inputs.qualifyingPayoutAmount ?? null,
            qualifyingMultiplier: app3?.qualifyingMultiplier ? Number(app3.qualifyingMultiplier) : eligibility.inputs.qualifyingMultiplier ?? null,
            submittedAt: app3?.createdAt?.toISOString().split("T")[0] ?? null,
            reviewedAt: app3?.reviewedAt?.toISOString().split("T")[0] ?? null,
            disbursedAt: app3?.disbursedAt?.toISOString().split("T")[0] ?? null,
            eligible: eligibility.eligible,
            reasons: eligibility.reasons,
            creditScore: null,
            creditScoreTier: null,
            isEligible: eligibility.eligible,
            eligibilityScore: null,
            eligibilityReason,
            eligibilityReasons: eligibility.reasons,
            maxRequestAmount: eligibility.inputs.maxRequestAmount ?? null,
            segment: null,
            susuParticipationCount: eligibility.inputs.susuParticipationCount,
            payoutContextCount: eligibility.inputs.payoutContextCount,
            latestPayoutScheduledDate: eligibility.inputs.latestPayoutScheduledDate,
            latestPayoutPaidDate: eligibility.inputs.latestPayoutPaidDate
          }
        });
      } catch (err) {
        if (err instanceof MemberProductAccessError) {
          return res.status(err.statusCode).json({ message: err.message });
        }
        console.error("GET /member/helping-hand error:", err);
        return res.status(500).json({ message: "Failed to fetch matching fund." });
      }
    });
    router8.get(
      "/member/helping-hand/applications",
      requireAuth2,
      async (req, res) => {
        const userId = req.userId;
        try {
          await ensureMemberProductAccess(userId, "SUSU");
          const applications = await db.select({
            id: helpingHandApplicationsTable.id,
            requestedAmount: helpingHandApplicationsTable.requestedAmount,
            approvedAmount: helpingHandApplicationsTable.approvedAmount,
            disbursedAmount: helpingHandApplicationsTable.disbursedAmount,
            purpose: helpingHandApplicationsTable.purpose,
            term: helpingHandApplicationsTable.term,
            repaymentSchedule: helpingHandApplicationsTable.repaymentSchedule,
            notes: helpingHandApplicationsTable.notes,
            reviewNote: helpingHandApplicationsTable.reviewNote,
            status: helpingHandApplicationsTable.status,
            disbursedAt: helpingHandApplicationsTable.disbursedAt,
            createdAt: helpingHandApplicationsTable.createdAt,
            reviewedAt: helpingHandApplicationsTable.reviewedAt,
            qualifyingCircleName: savingsCirclesTable.name,
            qualifyingCircleId: helpingHandApplicationsTable.qualifyingCircleId,
            qualifyingPayoutAmount: helpingHandApplicationsTable.qualifyingPayoutAmount,
            qualifyingMultiplier: helpingHandApplicationsTable.qualifyingMultiplier
          }).from(helpingHandApplicationsTable).leftJoin(
            savingsCirclesTable,
            eq(
              helpingHandApplicationsTable.qualifyingCircleId,
              savingsCirclesTable.id
            )
          ).where(eq(helpingHandApplicationsTable.userId, userId)).orderBy(desc(helpingHandApplicationsTable.createdAt));
          return res.json({
            applications: applications.map((app3) => ({
              id: app3.id,
              requestedAmount: Number(app3.requestedAmount),
              approvedAmount: app3.approvedAmount ? Number(app3.approvedAmount) : null,
              disbursedAmount: app3.disbursedAmount ? Number(app3.disbursedAmount) : null,
              purpose: app3.purpose,
              term: app3.term,
              repaymentSchedule: app3.repaymentSchedule,
              notes: app3.notes ?? null,
              reviewNote: app3.reviewNote ?? null,
              status: app3.status,
              qualifyingCircleId: app3.qualifyingCircleId ?? null,
              qualifyingCircleName: app3.qualifyingCircleName ?? null,
              qualifyingPayoutAmount: app3.qualifyingPayoutAmount ? Number(app3.qualifyingPayoutAmount) : null,
              qualifyingMultiplier: app3.qualifyingMultiplier ? Number(app3.qualifyingMultiplier) : null,
              submittedAt: app3.createdAt?.toISOString().split("T")[0] ?? null,
              reviewedAt: app3.reviewedAt?.toISOString().split("T")[0] ?? null,
              disbursedAt: app3.disbursedAt?.toISOString().split("T")[0] ?? null
            }))
          });
        } catch (err) {
          if (err instanceof MemberProductAccessError) {
            return res.status(err.statusCode).json({ message: err.message });
          }
          console.error("GET /member/helping-hand/applications error:", err);
          return res.status(500).json({
            message: "Failed to fetch matching fund applications."
          });
        }
      }
    );
    router8.post(
      "/member/helping-hand/applications",
      requireAuth2,
      async (req, res) => {
        const userId = req.userId;
        try {
          await ensureMemberProductAccess(userId, "SUSU");
          const eligibility = await getHelpingHandEligibilitySnapshot(userId);
          if (!eligibility.eligible) {
            return res.status(400).json({
              message: "You are not eligible to apply for SUSU Matching Fund at this time.",
              reasons: eligibility.reasons,
              inputs: eligibility.inputs
            });
          }
          const maxRequestAmount = eligibility.inputs.maxRequestAmount;
          const validation = validateHelpingHandApplicationInput(
            req.body,
            maxRequestAmount
          );
          if (!validation.ok) {
            return validation.errors ? res.status(400).json({ errors: validation.errors }) : res.status(400).json({ message: validation.message });
          }
          const { data } = validation;
          const [application] = await db.insert(helpingHandApplicationsTable).values({
            userId,
            requestedAmount: String(data.requestedAmount),
            purpose: data.purpose,
            term: data.term,
            repaymentSchedule: data.repaymentSchedule,
            notes: data.notes || null,
            status: "SUBMITTED",
            qualifyingCircleId: eligibility.inputs.qualifyingCircleId,
            qualifyingPayoutId: eligibility.inputs.qualifyingPayoutId,
            qualifyingPayoutAmount: eligibility.inputs.qualifyingPayoutAmount !== null ? String(eligibility.inputs.qualifyingPayoutAmount) : null,
            qualifyingMultiplier: eligibility.inputs.qualifyingMultiplier !== null ? String(eligibility.inputs.qualifyingMultiplier) : null
          }).returning();
          return res.status(201).json({
            application: {
              id: application.id,
              requestedAmount: Number(application.requestedAmount),
              approvedAmount: application.approvedAmount ? Number(application.approvedAmount) : null,
              purpose: application.purpose,
              term: application.term,
              repaymentSchedule: application.repaymentSchedule,
              notes: application.notes ?? "",
              status: application.status,
              reviewNote: application.reviewNote ?? null,
              submittedAt: application.createdAt.toISOString(),
              reviewedAt: application.reviewedAt?.toISOString() ?? null,
              disbursedAt: application.disbursedAt?.toISOString() ?? null
            }
          });
        } catch (err) {
          if (err instanceof MemberProductAccessError) {
            return res.status(err.statusCode).json({ message: err.message });
          }
          console.error("POST /member/helping-hand/applications error:", err);
          return res.status(500).json({ message: "Failed to create SUSU Matching Fund application." });
        }
      }
    );
    router8.get(
      "/member/helping-hand/:id/repayments",
      requireAuth2,
      async (req, res) => {
        const userId = req.userId;
        const applicationId = Number(req.params.id);
        if (!Number.isFinite(applicationId) || applicationId <= 0) {
          return res.status(400).json({ message: "Invalid application id." });
        }
        try {
          await ensureMemberProductAccess(userId, "SUSU");
          const apps = await db.select({ id: helpingHandApplicationsTable.id }).from(helpingHandApplicationsTable).where(
            and(
              eq(helpingHandApplicationsTable.id, applicationId),
              eq(helpingHandApplicationsTable.userId, userId)
            )
          );
          if (!apps.length) {
            return res.status(403).json({ message: "Not authorized to access this application." });
          }
          const repayments = await db.select().from(helpingHandRepaymentsTable).where(
            eq(
              helpingHandRepaymentsTable.helpingHandApplicationId,
              applicationId
            )
          ).orderBy(asc(helpingHandRepaymentsTable.dueDate));
          return res.json({
            repayments: repayments.map(serializeHelpingHandRepayment2)
          });
        } catch (err) {
          if (err instanceof MemberProductAccessError) {
            return res.status(err.statusCode).json({ message: err.message });
          }
          console.error("GET /member/helping-hand/:id/repayments error:", err);
          return res.status(500).json({ message: "Failed to fetch repayments." });
        }
      }
    );
    router8.post(
      "/member/helping-hand/repayments/:id/payments",
      requireAuth2,
      async (req, res) => {
        const userId = req.userId;
        const repaymentId = Number(req.params.id);
        try {
          await ensureMemberProductAccess(userId, "SUSU");
          if (!Number.isFinite(repaymentId) || repaymentId <= 0) {
            return res.status(400).json({ message: "Invalid repayment id." });
          }
          const parsed = external_exports.object({
            amount: external_exports.coerce.number().positive()
          }).safeParse(req.body ?? {});
          if (!parsed.success) {
            return res.status(400).json({ errors: parsed.error.flatten() });
          }
          const paymentAmount = parsed.data.amount;
          if (hasMoreThanTwoDecimalPlaces(paymentAmount)) {
            return res.status(400).json({
              message: "Payment amount can have at most 2 decimal places."
            });
          }
          const result = await db.transaction(async (tx) => {
            const [repaymentRow] = await tx.select({
              id: helpingHandRepaymentsTable.id,
              helpingHandApplicationId: helpingHandRepaymentsTable.helpingHandApplicationId,
              dueDate: helpingHandRepaymentsTable.dueDate,
              amount: helpingHandRepaymentsTable.amount,
              paidAmount: helpingHandRepaymentsTable.paidAmount,
              paidAt: helpingHandRepaymentsTable.paidAt,
              status: helpingHandRepaymentsTable.status,
              method: helpingHandRepaymentsTable.method,
              createdAt: helpingHandRepaymentsTable.createdAt,
              updatedAt: helpingHandRepaymentsTable.updatedAt,
              applicationUserId: helpingHandApplicationsTable.userId,
              applicationStatus: helpingHandApplicationsTable.status
            }).from(helpingHandRepaymentsTable).innerJoin(
              helpingHandApplicationsTable,
              eq(
                helpingHandRepaymentsTable.helpingHandApplicationId,
                helpingHandApplicationsTable.id
              )
            ).where(eq(helpingHandRepaymentsTable.id, repaymentId));
            if (!repaymentRow) {
              return {
                status: 404,
                body: { message: "Repayment not found." }
              };
            }
            if (repaymentRow.applicationUserId !== userId) {
              return {
                status: 403,
                body: { message: "Not authorized to pay this repayment." }
              };
            }
            if (!["FUNDED", "REPAYING"].includes(repaymentRow.applicationStatus)) {
              return {
                status: 400,
                body: {
                  message: "Repayments can only be paid while the Matching Fund case is funded or repaying."
                }
              };
            }
            if (["PAID", "WAIVED"].includes(repaymentRow.status)) {
              return {
                status: 400,
                body: {
                  message: "This repayment cannot accept additional payments."
                }
              };
            }
            const installmentAmount = Number(repaymentRow.amount);
            const currentPaidAmount = Number(repaymentRow.paidAmount ?? 0);
            const remainingAmount = Math.max(
              installmentAmount - currentPaidAmount,
              0
            );
            if (paymentAmount > remainingAmount) {
              return {
                status: 400,
                body: {
                  message: "Payment amount cannot exceed the remaining balance for this installment."
                }
              };
            }
            const userWallet = await ensureWalletWith6(
              tx,
              "USER",
              userId
            );
            const walletFunds = await getWalletFundsWith2(
              tx,
              userWallet.id
            );
            if (walletFunds.availableBalance < paymentAmount) {
              return {
                status: 400,
                body: { message: "Insufficient available wallet balance." }
              };
            }
            const masterWallet = await ensureLendingMasterWalletWith3(
              tx
            );
            await tx.insert(walletTransactionsTable).values({
              type: "HELPING_HAND_REPAYMENT",
              fromWalletId: userWallet.id,
              toWalletId: masterWallet.id,
              amount: formatMoneyAmount(paymentAmount),
              metadata: {
                helpingHandApplicationId: repaymentRow.helpingHandApplicationId,
                helpingHandRepaymentId: repaymentRow.id,
                userId,
                source: "HELPING_HAND_REPAYMENT"
              }
            });
            const nextPaidAmount = Number(
              formatMoneyAmount(currentPaidAmount + paymentAmount)
            );
            const isSettled = nextPaidAmount >= installmentAmount;
            const nextStatus = isSettled ? "PAID" : repaymentRow.dueDate.getTime() < Date.now() ? "LATE" : "PENDING";
            const [updated] = await tx.update(helpingHandRepaymentsTable).set({
              paidAmount: isSettled ? formatMoneyAmount(installmentAmount) : formatMoneyAmount(nextPaidAmount),
              paidAt: isSettled ? /* @__PURE__ */ new Date() : null,
              status: nextStatus,
              method: "WALLET",
              updatedAt: /* @__PURE__ */ new Date()
            }).where(eq(helpingHandRepaymentsTable.id, repaymentId)).returning();
            const applicationRepayments = await tx.select({ status: helpingHandRepaymentsTable.status }).from(helpingHandRepaymentsTable).where(
              eq(
                helpingHandRepaymentsTable.helpingHandApplicationId,
                repaymentRow.helpingHandApplicationId
              )
            );
            const hasOutstandingRepayments = applicationRepayments.some(
              (repayment) => !["PAID", "WAIVED"].includes(repayment.status)
            );
            const nextApplicationStatus = hasOutstandingRepayments ? repaymentRow.applicationStatus === "FUNDED" ? "REPAYING" : repaymentRow.applicationStatus : "CLOSED";
            if (nextApplicationStatus !== repaymentRow.applicationStatus) {
              await tx.update(helpingHandApplicationsTable).set({
                status: nextApplicationStatus,
                updatedAt: /* @__PURE__ */ new Date()
              }).where(
                eq(
                  helpingHandApplicationsTable.id,
                  repaymentRow.helpingHandApplicationId
                )
              );
            }
            const nextWalletBalance = walletFunds.balance - paymentAmount;
            return {
              status: 200,
              body: {
                repayment: serializeHelpingHandRepayment2(updated),
                walletBalance: Number(formatMoneyAmount(nextWalletBalance))
              }
            };
          });
          if (result.status === 200) {
            await updateCreditScore(userId);
          }
          return res.status(result.status).json(result.body);
        } catch (err) {
          if (err instanceof MemberProductAccessError) {
            return res.status(err.statusCode).json({ message: err.message });
          }
          console.error(
            "POST /member/helping-hand/repayments/:id/payments error:",
            err
          );
          return res.status(500).json({ message: "Failed to apply repayment payment." });
        }
      }
    );
    router8.post(
      "/member/helping-hand/applications/:id/payments",
      requireAuth2,
      async (req, res) => {
        const userId = req.userId;
        const applicationId = Number(req.params.id);
        try {
          await ensureMemberProductAccess(userId, "SUSU");
          if (!Number.isFinite(applicationId) || applicationId <= 0) {
            return res.status(400).json({ message: "Invalid application id." });
          }
          const parsed = external_exports.object({
            amount: external_exports.coerce.number().positive().optional(),
            payAll: external_exports.coerce.boolean().optional()
          }).safeParse(req.body ?? {});
          if (!parsed.success) {
            return res.status(400).json({ errors: parsed.error.flatten() });
          }
          if (!parsed.data.payAll && parsed.data.amount == null) {
            return res.status(400).json({
              message: "Provide an amount or set payAll to true."
            });
          }
          if (parsed.data.amount != null && hasMoreThanTwoDecimalPlaces(parsed.data.amount)) {
            return res.status(400).json({
              message: "Payment amount can have at most 2 decimal places."
            });
          }
          const result = await db.transaction(async (tx) => {
            const [application] = await tx.select({
              id: helpingHandApplicationsTable.id,
              userId: helpingHandApplicationsTable.userId,
              status: helpingHandApplicationsTable.status
            }).from(helpingHandApplicationsTable).where(
              and(
                eq(helpingHandApplicationsTable.id, applicationId),
                eq(helpingHandApplicationsTable.userId, userId)
              )
            );
            if (!application) {
              return {
                status: 404,
                body: { message: "Matching Fund application not found." }
              };
            }
            if (!["FUNDED", "REPAYING"].includes(application.status)) {
              return {
                status: 400,
                body: {
                  message: "Loan repayments can only be made while the Matching Fund case is funded or repaying."
                }
              };
            }
            const repayments = await tx.select().from(helpingHandRepaymentsTable).where(
              eq(
                helpingHandRepaymentsTable.helpingHandApplicationId,
                applicationId
              )
            ).orderBy(asc(helpingHandRepaymentsTable.dueDate));
            if (!repayments.length) {
              return {
                status: 400,
                body: { message: "No repayment schedule exists for this loan." }
              };
            }
            const toCents = (value) => Math.round(value * 100);
            const fromCents = (cents) => cents / 100;
            const outstandingCents = repayments.reduce((sum3, repayment) => {
              if (["PAID", "WAIVED"].includes(repayment.status)) return sum3;
              const installmentCents = toCents(parseMoneyAmount(repayment.amount));
              const paidCents = toCents(parseMoneyAmount(repayment.paidAmount));
              return sum3 + Math.max(0, installmentCents - paidCents);
            }, 0);
            if (outstandingCents <= 0) {
              return {
                status: 400,
                body: { message: "This loan has no outstanding balance." }
              };
            }
            const requestedCents = parsed.data.payAll ? outstandingCents : toCents(Number(parsed.data.amount ?? 0));
            if (requestedCents <= 0) {
              return {
                status: 400,
                body: { message: "Invalid payment amount." }
              };
            }
            if (requestedCents > outstandingCents) {
              return {
                status: 400,
                body: {
                  message: "Payment amount cannot exceed the outstanding balance."
                }
              };
            }
            const paymentAmount = fromCents(requestedCents);
            const userWallet = await ensureWalletWith6(
              tx,
              "USER",
              userId
            );
            const walletFunds = await getWalletFundsWith2(
              tx,
              userWallet.id
            );
            if (walletFunds.availableBalance < paymentAmount) {
              return {
                status: 400,
                body: { message: "Insufficient available wallet balance." }
              };
            }
            const masterWallet = await ensureLendingMasterWalletWith3(
              tx
            );
            const [walletTransaction] = await tx.insert(walletTransactionsTable).values({
              type: "HELPING_HAND_REPAYMENT",
              fromWalletId: userWallet.id,
              toWalletId: masterWallet.id,
              amount: formatMoneyAmount(paymentAmount),
              metadata: {
                helpingHandApplicationId: applicationId,
                userId,
                source: "HELPING_HAND_REPAYMENT"
              }
            }).returning();
            let remainingPaymentCents = requestedCents;
            const now = /* @__PURE__ */ new Date();
            for (const repayment of repayments) {
              if (remainingPaymentCents <= 0) break;
              if (["PAID", "WAIVED"].includes(repayment.status)) continue;
              const installmentCents = toCents(parseMoneyAmount(repayment.amount));
              const paidCents = toCents(parseMoneyAmount(repayment.paidAmount));
              const remainingInstallmentCents = Math.max(
                0,
                installmentCents - paidCents
              );
              if (remainingInstallmentCents <= 0) continue;
              const appliedCents = Math.min(
                remainingInstallmentCents,
                remainingPaymentCents
              );
              if (appliedCents <= 0) continue;
              const nextPaidCents = paidCents + appliedCents;
              const isSettled = nextPaidCents >= installmentCents;
              const nextStatus = isSettled ? "PAID" : repayment.dueDate.getTime() < now.getTime() ? "LATE" : "PENDING";
              const nextPaidAmount = isSettled ? fromCents(installmentCents) : fromCents(nextPaidCents);
              await tx.update(helpingHandRepaymentsTable).set({
                paidAmount: formatMoneyAmount(nextPaidAmount),
                paidAt: isSettled ? now : null,
                status: nextStatus,
                method: "WALLET",
                updatedAt: now
              }).where(eq(helpingHandRepaymentsTable.id, repayment.id));
              remainingPaymentCents -= appliedCents;
            }
            if (remainingPaymentCents !== 0) {
              return {
                status: 500,
                body: { message: "Failed to fully allocate this payment." }
              };
            }
            const outstandingAfter = await tx.select({ status: helpingHandRepaymentsTable.status }).from(helpingHandRepaymentsTable).where(
              eq(
                helpingHandRepaymentsTable.helpingHandApplicationId,
                applicationId
              )
            );
            const hasOutstandingRepayments = outstandingAfter.some(
              (repayment) => !["PAID", "WAIVED"].includes(repayment.status)
            );
            const nextApplicationStatus = hasOutstandingRepayments ? application.status === "FUNDED" ? "REPAYING" : application.status : "CLOSED";
            if (nextApplicationStatus !== application.status) {
              await tx.update(helpingHandApplicationsTable).set({
                status: nextApplicationStatus,
                updatedAt: now
              }).where(eq(helpingHandApplicationsTable.id, applicationId));
            }
            const nextWalletBalance = walletFunds.balance - paymentAmount;
            await notifyInAppWith(tx, {
              userId,
              category: "LENDING",
              severity: "SUCCESS",
              title: "Loan repayment received",
              body: `We recorded your repayment of ${Number(formatMoneyAmount(paymentAmount)).toLocaleString("en-CA", { style: "currency", currency: "CAD" })}.`,
              actionLabel: "View Lending",
              actionHref: "/dashboard/lending"
            });
            return {
              status: 200,
              body: {
                appliedAmount: Number(formatMoneyAmount(paymentAmount)),
                walletBalance: Number(formatMoneyAmount(nextWalletBalance)),
                applicationStatus: nextApplicationStatus,
                walletTransactionId: walletTransaction?.id ?? null
              }
            };
          });
          if (result.status === 200) {
            await updateCreditScore(userId);
            void (async () => {
              const walletTransactionId = typeof result.body?.walletTransactionId === "number" ? result.body.walletTransactionId : null;
              if (!walletTransactionId) return;
              const key = `helping_hand_repayment_received:${walletTransactionId}:push`;
              const reserved = await reserveNotificationDeliveryWith(db, {
                userId,
                channel: "PUSH",
                category: "LENDING",
                idempotencyKey: key,
                status: "SKIPPED",
                provider: null,
                metadata: {
                  kind: "helping_hand_repayment_received",
                  walletTransactionId
                }
              });
              if (!reserved.reserved) return;
              try {
                const pushResult = await deliverPushIfEnabled({
                  userId,
                  category: "LENDING",
                  title: "Loan repayment received",
                  body: `Your repayment has been recorded.`,
                  data: { actionHref: "/dashboard/lending" }
                });
                await finalizeNotificationDeliveryWith(db, {
                  idempotencyKey: key,
                  status: pushResult.status,
                  provider: pushResult.status === "SENT" ? "EXPO" : null,
                  errorMessage: pushResult.reason ?? null,
                  notificationId: null,
                  metadata: {
                    kind: "helping_hand_repayment_received",
                    reason: pushResult.reason ?? null,
                    walletTransactionId
                  }
                });
              } catch (err) {
                await finalizeNotificationDeliveryWith(db, {
                  idempotencyKey: key,
                  status: "FAILED",
                  provider: "EXPO",
                  errorMessage: err instanceof Error ? err.message : String(err),
                  notificationId: null,
                  metadata: {
                    kind: "helping_hand_repayment_received",
                    walletTransactionId
                  }
                });
              }
            })();
          }
          return res.status(result.status).json(result.body);
        } catch (err) {
          if (err instanceof MemberProductAccessError) {
            return res.status(err.statusCode).json({ message: err.message });
          }
          console.error(
            "POST /member/helping-hand/applications/:id/payments error:",
            err
          );
          return res.status(500).json({ message: "Failed to apply loan repayment." });
        }
      }
    );
    router8.get("/lending/borrower/eligibility", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        const snapshot = await getLendingPoolEligibilitySnapshot(userId);
        return res.json(snapshot);
      } catch (err) {
        console.error("GET /lending/borrower/eligibility error:", err);
        return res.status(500).json({ message: "Failed to evaluate Lending Pool eligibility." });
      }
    });
    router8.get("/lending/borrower/pools", requireAuth2, async (_req, res) => {
      try {
        const userId = _req.userId;
        await ensureMemberProductAccess(userId, "LENDING_BORROWER");
        const memberPlanTier = await getMemberMembershipPlanTier(userId);
        const requestedLoanTypeRaw = _req.query.loanType;
        const requestedLoanType = requestedLoanTypeRaw === "P2P_LENDING" || requestedLoanTypeRaw === "COMMUNITY_LENDING" ? requestedLoanTypeRaw : null;
        const baseWhere = requestedLoanType ? and(
          eq(lendingTemplatesTable.status, "OPEN"),
          eq(lendingTemplatesTable.loanType, requestedLoanType)
        ) : eq(lendingTemplatesTable.status, "OPEN");
        const pools = await db.select({
          id: lendingTemplatesTable.id,
          loanType: lendingTemplatesTable.loanType,
          title: lendingTemplatesTable.title,
          description: lendingTemplatesTable.description,
          termsHtml: lendingTemplatesTable.termsHtml,
          term: lendingTemplatesTable.term,
          status: lendingTemplatesTable.status,
          borrowerType: lendingTemplatesTable.borrowerType,
          minRequestAmount: lendingTemplatesTable.minRequestAmount,
          maxRequestAmount: lendingTemplatesTable.maxRequestAmount,
          minBorrowerPlanTier: lendingTemplatesTable.minBorrowerPlanTier,
          borrowerAppreciationAmount: lendingTemplatesTable.borrowerAppreciationAmount,
          borrowerTermMonths: lendingTemplatesTable.borrowerTermMonths,
          repaymentFrequency: lendingTemplatesTable.repaymentFrequency,
          processingFeePct: lendingTemplatesTable.processingFeePct,
          expectedReturnPct: lendingTemplatesTable.expectedReturnPct,
          wwnMarginPct: lendingTemplatesTable.wwnMarginPct,
          reserveContributionPct: lendingTemplatesTable.reserveContributionPct,
          minAppreciationType: lendingTemplatesTable.minAppreciationType,
          minAppreciationValue: lendingTemplatesTable.minAppreciationValue,
          minAppreciationTiers: lendingTemplatesTable.minAppreciationTiers
        }).from(lendingTemplatesTable).where(baseWhere).orderBy(desc(lendingTemplatesTable.createdAt));
        const browsablePools = pools.filter(
          (pool2) => canMembersBrowseLendingPool(pool2.status) && isMembershipPlanTierAtLeast({
            memberTier: memberPlanTier,
            minTier: pool2.minBorrowerPlanTier
          })
        );
        const serializedPools = browsablePools.map((pool2) => {
          const minRequestAmount = parseMoneyAmount(pool2.minRequestAmount);
          const maxRequestAmount = parseMoneyAmount(pool2.maxRequestAmount);
          const borrowerType = pool2.borrowerType ?? (pool2.minBorrowerPlanTier === "ENTREPRENEUR" ? "Entrepreneur" : pool2.minBorrowerPlanTier === "ELITE" ? "Elite" : pool2.minBorrowerPlanTier === "PROFESSIONAL" ? "Professional" : "Starter");
          return {
            id: pool2.id,
            loanType: normalizeLendingLoanType(pool2.loanType),
            title: pool2.title,
            description: pool2.description,
            termsHtml: pool2.termsHtml ?? null,
            term: formatTermMonthsLabel(pool2.borrowerTermMonths),
            status: pool2.status,
            borrowerType,
            minRequestAmount,
            maxRequestAmount,
            minBorrowerPlanTier: pool2.minBorrowerPlanTier,
            borrowerAppreciationAmount: Number(pool2.borrowerAppreciationAmount),
            borrowerTermMonths: pool2.borrowerTermMonths,
            repaymentFrequency: pool2.repaymentFrequency,
            processingFeePct: pool2.processingFeePct !== null ? Number(pool2.processingFeePct) : null,
            expectedReturnPct: Number(pool2.expectedReturnPct ?? 0),
            wwnMarginPct: Number(pool2.wwnMarginPct ?? 0),
            reserveContributionPct: Number(pool2.reserveContributionPct ?? 0),
            minAppreciationType: pool2.minAppreciationType,
            minAppreciationValue: Number(pool2.minAppreciationValue),
            minAppreciationTiers: pool2.minAppreciationTiers ?? null,
            applicationState: "APPLY",
            applicationStateLabel: "Submit request"
          };
        });
        return res.json({ pools: serializedPools, total: serializedPools.length });
      } catch (err) {
        if (err instanceof MemberProductAccessError) {
          return res.status(err.statusCode).json({ message: err.message });
        }
        console.error("GET /lending/borrower/pools error:", err);
        return res.status(500).json({ message: "Failed to fetch Lending Pool options." });
      }
    });
    router8.get("/lending/borrower/applications", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        const applications = await db.select({
          id: loanApplicationsTable.id,
          loanType: loanApplicationsTable.loanType,
          borrowerId: loanApplicationsTable.borrowerId,
          templateId: loanApplicationsTable.templateId,
          opportunityId: loanApplicationsTable.opportunityId,
          requestedAmount: loanApplicationsTable.requestedAmount,
          purpose: loanApplicationsTable.purpose,
          term: loanApplicationsTable.term,
          repaymentSchedule: loanApplicationsTable.repaymentSchedule,
          termMonths: loanApplicationsTable.termMonths,
          borrowerAppreciationAmount: loanApplicationsTable.borrowerAppreciationAmount,
          repaymentFrequency: loanApplicationsTable.repaymentFrequency,
          processingFeePct: loanApplicationsTable.processingFeePct,
          wwnMarginPct: loanApplicationsTable.wwnMarginPct,
          reserveContributionPct: loanApplicationsTable.reserveContributionPct,
          totalRepayableAmount: loanApplicationsTable.totalRepayableAmount,
          estimatedInstallmentAmount: loanApplicationsTable.estimatedInstallmentAmount,
          notes: loanApplicationsTable.notes,
          status: loanApplicationsTable.status,
          poolAssignedAt: loanApplicationsTable.poolAssignedAt,
          poolAssignedByAdminId: loanApplicationsTable.poolAssignedByAdminId,
          poolReassignedAt: loanApplicationsTable.poolReassignedAt,
          poolReassignedByAdminId: loanApplicationsTable.poolReassignedByAdminId,
          poolReassignmentNote: loanApplicationsTable.poolReassignmentNote,
          reviewedByAdminId: loanApplicationsTable.reviewedByAdminId,
          reviewedAt: loanApplicationsTable.reviewedAt,
          reviewNote: loanApplicationsTable.reviewNote,
          approvedAmount: loanApplicationsTable.approvedAmount,
          reservedAt: loanApplicationsTable.reservedAt,
          reservedByAdminId: loanApplicationsTable.reservedByAdminId,
          disbursedAt: loanApplicationsTable.disbursedAt,
          disbursedAmount: loanApplicationsTable.disbursedAmount,
          disbursementTransactionId: loanApplicationsTable.disbursementTransactionId,
          createdAt: loanApplicationsTable.createdAt,
          updatedAt: loanApplicationsTable.updatedAt,
          templateTitle: lendingTemplatesTable.title,
          templateBorrowerType: lendingTemplatesTable.borrowerType
        }).from(loanApplicationsTable).leftJoin(
          lendingTemplatesTable,
          eq(loanApplicationsTable.templateId, lendingTemplatesTable.id)
        ).where(eq(loanApplicationsTable.borrowerId, userId)).orderBy(desc(loanApplicationsTable.createdAt));
        return res.json({
          applications: applications.map(serializeLoanApplication)
        });
      } catch (err) {
        console.error("GET /lending/borrower/applications error:", err);
        return res.status(500).json({ message: "Failed to fetch Lending Pool applications." });
      }
    });
    router8.post("/lending/borrower/applications", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        await ensureMemberProductAccess(userId, "LENDING_BORROWER");
        const validation = validateLendingBorrowerApplicationInput(req.body);
        if (!validation.ok) {
          return validation.errors ? res.status(400).json({ errors: validation.errors }) : res.status(400).json({ message: validation.message });
        }
        const { data } = validation;
        if (!data.templateId) {
          return res.status(400).json({
            message: "Select a lending template before submitting a Community Lending or P2P Lending request."
          });
        }
        let templatePool = null;
        if (data.templateId) {
          const [pool2] = await db.select({
            id: lendingTemplatesTable.id,
            loanType: lendingTemplatesTable.loanType,
            title: lendingTemplatesTable.title,
            status: lendingTemplatesTable.status,
            termsHtml: lendingTemplatesTable.termsHtml,
            minRequestAmount: lendingTemplatesTable.minRequestAmount,
            maxRequestAmount: lendingTemplatesTable.maxRequestAmount,
            minCommitment: lendingTemplatesTable.minCommitment,
            borrowerTermMonths: lendingTemplatesTable.borrowerTermMonths,
            repaymentFrequency: lendingTemplatesTable.repaymentFrequency,
            processingFeePct: lendingTemplatesTable.processingFeePct,
            wwnMarginPct: lendingTemplatesTable.wwnMarginPct,
            reserveContributionPct: lendingTemplatesTable.reserveContributionPct,
            platformAppreciationSharePct: lendingTemplatesTable.platformAppreciationSharePct,
            minAppreciationType: lendingTemplatesTable.minAppreciationType,
            minAppreciationValue: lendingTemplatesTable.minAppreciationValue,
            minAppreciationTiers: lendingTemplatesTable.minAppreciationTiers,
            expectedReturnPct: lendingTemplatesTable.expectedReturnPct,
            termMonths: lendingTemplatesTable.termMonths,
            returnModel: lendingTemplatesTable.returnModel,
            borrowerType: lendingTemplatesTable.borrowerType,
            minBorrowerPlanTier: lendingTemplatesTable.minBorrowerPlanTier
          }).from(lendingTemplatesTable).where(eq(lendingTemplatesTable.id, data.templateId));
          templatePool = pool2 ?? null;
          if (!templatePool || !canMembersBrowseLendingPool(templatePool.status)) {
            return res.status(404).json({ message: "Selected Lending Pool is unavailable." });
          }
          const memberPlanTier = await getMemberMembershipPlanTier(userId);
          if (!isMembershipPlanTierAtLeast({
            memberTier: memberPlanTier,
            minTier: templatePool.minBorrowerPlanTier
          })) {
            return res.status(403).json({
              message: "Your membership plan does not include access to this Lending Pool option."
            });
          }
          const termsRequiredForApply = Boolean(templatePool.termsHtml) && String(templatePool.termsHtml).trim().length > 0;
          if (termsRequiredForApply && data.acceptedTerms !== true) {
            return res.status(400).json({
              message: "You must accept the Lending Pool terms & conditions to submit a request."
            });
          }
          const maxRequestAmount = parseMoneyAmount(templatePool.maxRequestAmount);
          if (maxRequestAmount > 0 && data.amount > maxRequestAmount) {
            return res.status(400).json({
              message: `Maximum request amount for this pool is ${formatMoneyAmount(maxRequestAmount)}.`
            });
          }
        }
        const eligibility = await getLendingPoolEligibilitySnapshot(userId);
        if (!eligibility.eligible) {
          return res.status(400).json({
            message: "You are not eligible to apply for the Lending Pool at this time.",
            reasons: eligibility.reasons,
            inputs: eligibility.inputs
          });
        }
        if (templatePool && data.amount < parseMoneyAmount(templatePool.minRequestAmount)) {
          return res.status(400).json({
            message: `Minimum request amount for this pool is ${formatMoneyAmount(parseMoneyAmount(templatePool.minRequestAmount))}.`
          });
        }
        const selectedTermMonths = Math.max(
          1,
          Math.min(
            24,
            Math.round(
              Number(data.termMonths ?? templatePool?.borrowerTermMonths ?? 12)
            )
          )
        );
        if (!templatePool) {
          return res.status(400).json({
            message: "Select a lending template before submitting this request."
          });
        }
        const loanType = normalizeLendingLoanType(templatePool.loanType);
        const minimumAppreciationAmount = templatePool ? calculateMinAppreciationAmount({
          principalAmount: data.amount,
          termMonths: selectedTermMonths,
          minAppreciationType: templatePool.minAppreciationType,
          minAppreciationValue: templatePool.minAppreciationValue,
          minAppreciationTiers: templatePool.minAppreciationTiers
        }) : 0;
        const requestedSupportAmount = Math.max(
          0,
          parseMoneyAmount(data.appreciationAmount)
        );
        if (templatePool && !isP2PLendingLoanType(loanType) && requestedSupportAmount < minimumAppreciationAmount) {
          return res.status(400).json({
            message: `Minimum token of appreciation amount for this request is ${formatMoneyAmount(minimumAppreciationAmount)}.`
          });
        }
        const p2pPricing = isP2PLendingLoanType(loanType) && templatePool ? buildP2PRatePricingSnapshot({
          principalAmount: data.amount,
          termMonths: selectedTermMonths,
          investorRatePct: templatePool.expectedReturnPct,
          wwnMarginPct: templatePool.wwnMarginPct,
          reserveContributionPct: templatePool.reserveContributionPct
        }) : null;
        const effectiveSupportAmount = isP2PLendingLoanType(loanType) ? p2pPricing?.borrowerRateAmount ?? 0 : Math.max(requestedSupportAmount, minimumAppreciationAmount);
        const existingActiveApplications = await db.select({
          id: loanApplicationsTable.id,
          status: loanApplicationsTable.status
        }).from(loanApplicationsTable).where(
          and(
            eq(loanApplicationsTable.borrowerId, userId),
            inArray(loanApplicationsTable.status, [
              ...ACTIVE_LENDING_POOL_STATUSES
            ])
          )
        );
        if (existingActiveApplications.length > 0) {
          return res.status(400).json({
            message: "You already have an active Lending Pool case. Resolve it before starting another application."
          });
        }
        const { application, initialStatus } = await db.transaction(async (tx) => {
          await tx.execute(
            sql`select pg_advisory_xact_lock(${LOAN_APPLICATION_LOCK_KEY_A}, ${userId})`
          );
          const existingActiveApplications2 = await tx.select({
            id: loanApplicationsTable.id,
            status: loanApplicationsTable.status
          }).from(loanApplicationsTable).where(
            and(
              eq(loanApplicationsTable.borrowerId, userId),
              inArray(loanApplicationsTable.status, [
                ...ACTIVE_LENDING_POOL_STATUSES
              ])
            )
          );
          if (existingActiveApplications2.length > 0) {
            throw new Error(
              "You already have an active Lending Pool case. Resolve it before starting another application."
            );
          }
          const now = /* @__PURE__ */ new Date();
          const repaymentFrequency = templatePool?.repaymentFrequency ?? "MONTHLY";
          const processingFeePct = templatePool?.processingFeePct ?? null;
          const wwnMarginPct = templatePool?.wwnMarginPct ?? "0.00";
          const reserveContributionPct = templatePool?.reserveContributionPct ?? "0.00";
          const platformAppreciationSharePct = isP2PLendingLoanType(loanType) ? formatMoneyAmount(p2pPricing?.platformSharePctOfBorrowerRate ?? 0) : templatePool?.platformAppreciationSharePct ?? "0.00";
          const maxRequestAmount = templatePool?.maxRequestAmount ?? "25000.00";
          const minBorrowerPlanTier = templatePool?.minBorrowerPlanTier ?? "STARTER";
          const pricing = buildLoanPricingSnapshot({
            principalAmount: data.amount,
            appreciationAmount: effectiveSupportAmount,
            termMonths: selectedTermMonths,
            repaymentFrequency,
            processingFeePct: processingFeePct ?? "0.00"
          });
          const [application2] = await tx.insert(loanApplicationsTable).values({
            borrowerId: userId,
            loanType,
            templateId: templatePool?.id ?? null,
            requestedAmount: String(data.amount),
            purpose: data.purpose,
            term: pricing.termLabel,
            repaymentSchedule: pricing.repaymentScheduleLabel,
            termMonths: pricing.termMonths,
            borrowerAppreciationAmount: formatMoneyAmount(effectiveSupportAmount),
            repaymentFrequency: pricing.repaymentFrequency,
            processingFeePct: processingFeePct != null ? formatMoneyAmount(parseMoneyAmount(processingFeePct)) : null,
            wwnMarginPct: formatMoneyAmount(parseMoneyAmount(wwnMarginPct)),
            reserveContributionPct: formatMoneyAmount(
              parseMoneyAmount(reserveContributionPct)
            ),
            platformAppreciationSharePct: formatMoneyAmount(
              parseMoneyAmount(platformAppreciationSharePct)
            ),
            pricingLockedAt: now,
            totalRepayableAmount: formatMoneyAmount(pricing.totalRepayableAmount),
            estimatedInstallmentAmount: formatMoneyAmount(
              pricing.estimatedInstallmentAmount
            ),
            notes: data.notes || null,
            status: "SUBMITTED"
          }).returning();
          return { application: application2, initialStatus: "SUBMITTED" };
        });
        publishLiveEventToUser(userId, {
          kind: "DATA_CHANGED",
          scopes: ["lending", "notifications"],
          payload: {
            action: "lending_application_submitted",
            applicationId: application.id
          }
        });
        const actorName = await getAdminNotificationActorName(userId);
        void notifyAdminsWith(db, {
          category: "LENDING",
          severity: "INFO",
          title: loanType === "COMMUNITY_LENDING" ? "New Community Lending application" : "New P2P Lending application",
          body: loanType === "COMMUNITY_LENDING" ? `${actorName} submitted a Community Lending request.` : `${actorName} submitted a P2P Lending request.`,
          actionLabel: "Open Lending",
          actionHref: "/admin/lending"
        });
        return res.status(201).json({
          application: serializeLoanApplication(application),
          workflow: {
            action: "SUBMITTED",
            message: loanType === "COMMUNITY_LENDING" ? "Your Community Lending request has been submitted for review. Once approved, WWN will open it for member funding." : "Your P2P Lending request has been submitted for review. Once approved, WWN will open it for investor funding."
          }
        });
      } catch (err) {
        if (err instanceof MemberProductAccessError) {
          return res.status(err.statusCode).json({ message: err.message });
        }
        console.error("POST /lending/borrower/applications error:", err);
        return res.status(500).json({ message: "Failed to create Lending Pool application." });
      }
    });
    router8.get(
      "/lending/borrower/applications/:id/repayments",
      requireAuth2,
      async (req, res) => {
        const userId = req.userId;
        const applicationId = Number(req.params.id);
        if (!Number.isFinite(applicationId) || applicationId <= 0) {
          return res.status(400).json({ message: "Invalid application id." });
        }
        try {
          const [application] = await db.select().from(loanApplicationsTable).where(
            and(
              eq(loanApplicationsTable.id, applicationId),
              eq(loanApplicationsTable.borrowerId, userId)
            )
          );
          if (!application) {
            return res.status(404).json({ message: "Lending Pool application not found." });
          }
          let repayments = await db.select().from(loanRepaymentsTable).where(eq(loanRepaymentsTable.loanApplicationId, applicationId)).orderBy(asc(loanRepaymentsTable.dueDate));
          if (["FUNDED", "REPAYING", "CLOSED"].includes(application.status)) {
            const totalRepayableAmount = parseMoneyAmount(
              application.totalRepayableAmount
            );
            const termMonths = Number(application.termMonths ?? 0);
            const repaymentFrequency = application.repaymentFrequency ?? "MONTHLY";
            if (totalRepayableAmount > 0 && termMonths > 0) {
              const schedule = buildLendingRepaymentSchedule({
                totalAmount: totalRepayableAmount,
                termMonths,
                repaymentFrequency,
                firstDueDate: addLendingRepaymentPeriod(
                  application.disbursedAt ?? application.reviewedAt ?? /* @__PURE__ */ new Date(),
                  repaymentFrequency,
                  1
                )
              });
              const shouldReplaceSchedule = repayments.length > 0 && canReplaceLoanRepaymentSchedule(repayments) && !doesLoanRepaymentScheduleMatch(repayments, schedule);
              if (shouldReplaceSchedule) {
                await db.delete(loanRepaymentsTable).where(eq(loanRepaymentsTable.loanApplicationId, applicationId));
              }
              if (schedule.length > 0 && (repayments.length === 0 || shouldReplaceSchedule)) {
                await db.insert(loanRepaymentsTable).values(
                  schedule.map((entry) => ({
                    loanApplicationId: applicationId,
                    dueDate: entry.dueDate,
                    amount: entry.amount
                  }))
                );
                repayments = await db.select().from(loanRepaymentsTable).where(eq(loanRepaymentsTable.loanApplicationId, applicationId)).orderBy(asc(loanRepaymentsTable.dueDate));
              }
            }
          }
          return res.json({
            application: serializeLoanApplication(application),
            repayments: repayments.map(serializeLoanRepayment)
          });
        } catch (err) {
          console.error(
            "GET /lending/borrower/applications/:id/repayments error:",
            err
          );
          return res.status(500).json({ message: "Failed to fetch Lending Pool repayments." });
        }
      }
    );
    router8.post(
      "/lending/borrower/applications/:id/payments",
      requireAuth2,
      async (req, res) => {
        const userId = req.userId;
        const applicationId = Number(req.params.id);
        try {
          if (!Number.isFinite(applicationId) || applicationId <= 0) {
            return res.status(400).json({ message: "Invalid application id." });
          }
          const parsed = external_exports.object({
            amount: external_exports.coerce.number().positive().optional(),
            payAll: external_exports.coerce.boolean().optional(),
            idempotencyKey: external_exports.string().min(1).optional()
          }).safeParse(req.body ?? {});
          if (!parsed.success) {
            return res.status(400).json({ errors: parsed.error.flatten() });
          }
          if (!parsed.data.payAll && parsed.data.amount == null) {
            return res.status(400).json({
              message: "Provide an amount or set payAll to true."
            });
          }
          if (parsed.data.amount != null && hasMoreThanTwoDecimalPlaces(parsed.data.amount)) {
            return res.status(400).json({
              message: "Payment amount can have at most 2 decimal places."
            });
          }
          const result = await db.transaction(async (tx) => {
            const [application] = await tx.select({
              id: loanApplicationsTable.id,
              borrowerId: loanApplicationsTable.borrowerId,
              opportunityId: loanApplicationsTable.opportunityId,
              status: loanApplicationsTable.status,
              disbursedAmount: loanApplicationsTable.disbursedAmount,
              totalRepayableAmount: loanApplicationsTable.totalRepayableAmount,
              borrowerAppreciationAmount: loanApplicationsTable.borrowerAppreciationAmount,
              processingFeePct: loanApplicationsTable.processingFeePct,
              platformAppreciationSharePct: loanApplicationsTable.platformAppreciationSharePct
            }).from(loanApplicationsTable).where(
              and(
                eq(loanApplicationsTable.id, applicationId),
                eq(loanApplicationsTable.borrowerId, userId)
              )
            );
            if (!application) {
              return {
                status: 404,
                body: { message: "Lending Pool application not found." }
              };
            }
            if (!["FUNDED", "REPAYING"].includes(application.status)) {
              return {
                status: 400,
                body: {
                  message: "Loan repayments can only be made while the application is funded or repaying."
                }
              };
            }
            if (!application.opportunityId) {
              return {
                status: 400,
                body: {
                  message: "This Lending case is not linked to an approved opportunity yet."
                }
              };
            }
            const disbursedAmount = parseMoneyAmount(application.disbursedAmount);
            const totalRepayableAmount = parseMoneyAmount(
              application.totalRepayableAmount
            );
            if (disbursedAmount <= 0 || totalRepayableAmount <= 0) {
              return {
                status: 400,
                body: {
                  message: "This loan is not ready for repayment. Disbursement and repayment totals must be set first."
                }
              };
            }
            const repayments = await tx.select().from(loanRepaymentsTable).where(eq(loanRepaymentsTable.loanApplicationId, applicationId)).orderBy(asc(loanRepaymentsTable.dueDate));
            if (!repayments.length) {
              return {
                status: 400,
                body: { message: "No repayment schedule exists for this loan." }
              };
            }
            const toCents = (value) => Math.round(value * 100);
            const fromCents = (cents) => cents / 100;
            const outstandingCents = repayments.reduce((sum3, repayment) => {
              if (["PAID", "WAIVED"].includes(repayment.status)) return sum3;
              const installmentCents = toCents(parseMoneyAmount(repayment.amount));
              const paidCents = toCents(parseMoneyAmount(repayment.paidAmount));
              return sum3 + Math.max(0, installmentCents - paidCents);
            }, 0);
            if (outstandingCents <= 0) {
              return {
                status: 400,
                body: { message: "This loan has no outstanding balance." }
              };
            }
            const requestedCents = parsed.data.payAll ? outstandingCents : toCents(Number(parsed.data.amount ?? 0));
            if (requestedCents <= 0) {
              return {
                status: 400,
                body: { message: "Invalid payment amount." }
              };
            }
            if (requestedCents > outstandingCents) {
              return {
                status: 400,
                body: {
                  message: "Payment amount cannot exceed the outstanding balance."
                }
              };
            }
            const paymentAmount = fromCents(requestedCents);
            const userWallet = await ensureWalletWith6(
              tx,
              "USER",
              userId
            );
            const headerIdempotencyKeyRaw = req.headers["idempotency-key"] ?? req.headers["x-idempotency-key"];
            const headerIdempotencyKey = Array.isArray(headerIdempotencyKeyRaw) ? headerIdempotencyKeyRaw[0] : headerIdempotencyKeyRaw;
            const providedIdempotencyKey = parsed.data.idempotencyKey ?? (typeof headerIdempotencyKey === "string" ? headerIdempotencyKey : null);
            const idempotencyKey = providedIdempotencyKey ? `loan_repayment:${applicationId}:${providedIdempotencyKey}` : `loan_repayment:auto:${applicationId}:${userId}:${requestedCents}:${parsed.data.payAll ? 1 : 0}:${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}`;
            const [existingRepaymentTx] = await tx.select().from(walletTransactionsTable).where(eq(walletTransactionsTable.idempotencyKey, idempotencyKey));
            if (existingRepaymentTx) {
              const [latestApplication] = await tx.select({ status: loanApplicationsTable.status }).from(loanApplicationsTable).where(eq(loanApplicationsTable.id, applicationId));
              const walletBalance = await getWalletBalanceWith4(
                tx,
                userWallet.id
              );
              return {
                status: 200,
                body: {
                  appliedAmount: Number(existingRepaymentTx.amount),
                  walletBalance: Number(formatMoneyAmount(walletBalance)),
                  applicationStatus: latestApplication?.status ?? application.status,
                  walletTransactionId: existingRepaymentTx.id
                }
              };
            }
            const walletFunds = await getWalletFundsWith2(
              tx,
              userWallet.id
            );
            if (walletFunds.availableBalance < paymentAmount) {
              return {
                status: 400,
                body: { message: "Insufficient available wallet balance." }
              };
            }
            await tx.execute(
              sql`select pg_advisory_xact_lock(${LOAN_REPAYMENT_LOCK_KEY_A}, ${applicationId})`
            );
            const masterWallet = await ensureLendingMasterWalletWith3(
              tx
            );
            const [walletTransaction] = await tx.insert(walletTransactionsTable).values({
              type: "LOAN_REPAYMENT",
              idempotencyKey,
              fromWalletId: userWallet.id,
              toWalletId: masterWallet.id,
              amount: formatMoneyAmount(paymentAmount),
              metadata: {
                loanApplicationId: applicationId,
                opportunityId: application.opportunityId,
                borrowerId: userId,
                source: "LOAN_REPAYMENT"
              }
            }).returning();
            const [paidTotals] = await tx.select({
              principalPaid: sum(loanRepaymentsTable.principalPaidAmount),
              returnPaid: sum(loanRepaymentsTable.returnPaidAmount),
              feePaid: sum(loanRepaymentsTable.feePaidAmount)
            }).from(loanRepaymentsTable).where(eq(loanRepaymentsTable.loanApplicationId, applicationId));
            let remainingPrincipalCents = Math.max(
              0,
              toCents(disbursedAmount) - toCents(parseMoneyAmount(paidTotals?.principalPaid))
            );
            const lenderReturnDueCents = toCents(
              Math.max(
                0,
                parseMoneyAmount(application.borrowerAppreciationAmount) - calculatePlatformAppreciationShareAmount(
                  application.borrowerAppreciationAmount,
                  application.platformAppreciationSharePct
                )
              )
            );
            const platformAppreciationDueCents = Math.max(
              0,
              toCents(parseMoneyAmount(application.borrowerAppreciationAmount)) - lenderReturnDueCents
            );
            let remainingReturnCents = Math.max(
              0,
              lenderReturnDueCents - toCents(parseMoneyAmount(paidTotals?.returnPaid))
            );
            let remainingFeeCents = Math.max(
              0,
              toCents(
                calculateProcessingFeeAmount(
                  disbursedAmount,
                  application.processingFeePct
                )
              ) + platformAppreciationDueCents - toCents(parseMoneyAmount(paidTotals?.feePaid))
            );
            const totalDueCents = toCents(disbursedAmount) + lenderReturnDueCents + toCents(
              calculateProcessingFeeAmount(
                disbursedAmount,
                application.processingFeePct
              )
            ) + platformAppreciationDueCents;
            const returnDueCents = lenderReturnDueCents;
            const feeDueCents = toCents(
              calculateProcessingFeeAmount(
                disbursedAmount,
                application.processingFeePct
              )
            ) + platformAppreciationDueCents;
            let remainingPaymentCents = requestedCents;
            const now = /* @__PURE__ */ new Date();
            for (const repayment of repayments) {
              if (remainingPaymentCents <= 0) break;
              if (["PAID", "WAIVED"].includes(repayment.status)) continue;
              const installmentCents = toCents(parseMoneyAmount(repayment.amount));
              const paidCents = toCents(parseMoneyAmount(repayment.paidAmount));
              const remainingInstallmentCents = Math.max(
                0,
                installmentCents - paidCents
              );
              if (remainingInstallmentCents <= 0) continue;
              const appliedCents = Math.min(
                remainingInstallmentCents,
                remainingPaymentCents
              );
              if (appliedCents <= 0) continue;
              const desiredReturnCents = totalDueCents > 0 ? Math.round(appliedCents * returnDueCents / totalDueCents) : 0;
              const desiredFeeCents = totalDueCents > 0 ? Math.round(appliedCents * feeDueCents / totalDueCents) : 0;
              let appliedReturnCents = Math.min(
                appliedCents,
                remainingReturnCents,
                Math.max(0, desiredReturnCents)
              );
              let appliedFeeCents = Math.min(
                appliedCents - appliedReturnCents,
                remainingFeeCents,
                Math.max(0, desiredFeeCents)
              );
              let appliedPrincipalCents = appliedCents - appliedReturnCents - appliedFeeCents;
              if (appliedPrincipalCents > remainingPrincipalCents) {
                const overflow = appliedPrincipalCents - remainingPrincipalCents;
                appliedPrincipalCents = remainingPrincipalCents;
                const remainingAfterPrincipal = appliedCents - appliedPrincipalCents - appliedFeeCents;
                appliedReturnCents = Math.min(
                  remainingAfterPrincipal + overflow,
                  remainingReturnCents
                );
                appliedFeeCents = Math.min(
                  appliedCents - appliedPrincipalCents - appliedReturnCents,
                  remainingFeeCents
                );
              } else if (appliedReturnCents > remainingReturnCents) {
                const overflow = appliedReturnCents - remainingReturnCents;
                appliedReturnCents = remainingReturnCents;
                appliedPrincipalCents = Math.min(
                  appliedCents - appliedReturnCents - appliedFeeCents,
                  remainingPrincipalCents,
                  appliedPrincipalCents + overflow
                );
                appliedFeeCents = Math.min(
                  appliedCents - appliedPrincipalCents - appliedReturnCents,
                  remainingFeeCents
                );
              } else if (appliedFeeCents > remainingFeeCents) {
                const overflow = appliedFeeCents - remainingFeeCents;
                appliedFeeCents = remainingFeeCents;
                appliedPrincipalCents = Math.min(
                  appliedCents - appliedReturnCents - appliedFeeCents,
                  remainingPrincipalCents,
                  appliedPrincipalCents + overflow
                );
                appliedReturnCents = Math.min(
                  appliedCents - appliedPrincipalCents - appliedFeeCents,
                  remainingReturnCents
                );
              }
              remainingPrincipalCents = Math.max(
                0,
                remainingPrincipalCents - appliedPrincipalCents
              );
              remainingReturnCents = Math.max(
                0,
                remainingReturnCents - appliedReturnCents
              );
              remainingFeeCents = Math.max(0, remainingFeeCents - appliedFeeCents);
              const nextPaidCents = paidCents + appliedCents;
              const isSettled = nextPaidCents >= installmentCents;
              const nextStatus = isSettled ? "PAID" : repayment.dueDate.getTime() < now.getTime() ? "LATE" : "PENDING";
              const nextPaidAmount = isSettled ? fromCents(installmentCents) : fromCents(nextPaidCents);
              const creditedToPoolAmount = parseMoneyAmount(repayment.creditedToPoolAmount) + fromCents(appliedCents);
              const principalPaidAmount = parseMoneyAmount(repayment.principalPaidAmount) + fromCents(appliedPrincipalCents);
              const returnPaidAmount = parseMoneyAmount(repayment.returnPaidAmount) + fromCents(appliedReturnCents);
              const feePaidAmount = parseMoneyAmount(repayment.feePaidAmount) + fromCents(appliedFeeCents);
              const [updatedRepayment] = await tx.update(loanRepaymentsTable).set({
                paidAmount: formatMoneyAmount(nextPaidAmount),
                paidAt: isSettled ? now : null,
                status: nextStatus,
                method: "WALLET",
                creditedToPoolAmount: formatMoneyAmount(creditedToPoolAmount),
                principalPaidAmount: formatMoneyAmount(principalPaidAmount),
                returnPaidAmount: formatMoneyAmount(returnPaidAmount),
                feePaidAmount: formatMoneyAmount(feePaidAmount),
                updatedAt: now
              }).where(eq(loanRepaymentsTable.id, repayment.id)).returning();
              await createLendingReturnAllocationEvent2({
                conn: tx,
                opportunityId: application.opportunityId,
                applicationId,
                repaymentId: repayment.id,
                walletTransactionId: walletTransaction?.id ?? null,
                grossAmount: fromCents(appliedCents),
                principalAmount: fromCents(appliedPrincipalCents),
                returnAmount: fromCents(appliedReturnCents),
                occurredAt: updatedRepayment?.paidAt ?? now
              });
              if (appliedFeeCents > 0) {
                const platformWallet = await ensurePlatformWalletWith(
                  tx
                );
                const feeIdempotencyKey = `loan_platform_fee:${walletTransaction.id}:${repayment.id}`;
                const [existingFeeTx] = await tx.select({ id: walletTransactionsTable.id }).from(walletTransactionsTable).where(
                  eq(walletTransactionsTable.idempotencyKey, feeIdempotencyKey)
                );
                if (!existingFeeTx) {
                  await tx.insert(walletTransactionsTable).values({
                    type: "ADJUSTMENT",
                    idempotencyKey: feeIdempotencyKey,
                    fromWalletId: masterWallet.id,
                    toWalletId: platformWallet.id,
                    amount: formatMoneyAmount(fromCents(appliedFeeCents)),
                    metadata: {
                      source: "LOAN_PLATFORM_FEE",
                      loanApplicationId: applicationId,
                      opportunityId: application.opportunityId,
                      borrowerId: userId,
                      repaymentId: repayment.id
                    }
                  });
                }
              }
              remainingPaymentCents -= appliedCents;
            }
            if (remainingPaymentCents !== 0) {
              return {
                status: 500,
                body: { message: "Failed to fully allocate this payment." }
              };
            }
            const outstandingAfter = await tx.select({ status: loanRepaymentsTable.status }).from(loanRepaymentsTable).where(eq(loanRepaymentsTable.loanApplicationId, applicationId));
            const hasOutstandingRepayments = outstandingAfter.some(
              (repayment) => !["PAID", "WAIVED"].includes(repayment.status)
            );
            const nextApplicationStatus = hasOutstandingRepayments ? application.status === "FUNDED" ? "REPAYING" : application.status : "CLOSED";
            if (nextApplicationStatus !== application.status) {
              await tx.update(loanApplicationsTable).set({
                status: nextApplicationStatus,
                updatedAt: now
              }).where(eq(loanApplicationsTable.id, applicationId));
            }
            const nextWalletBalance = walletFunds.balance - paymentAmount;
            return {
              status: 200,
              body: {
                appliedAmount: Number(formatMoneyAmount(paymentAmount)),
                walletBalance: Number(formatMoneyAmount(nextWalletBalance)),
                applicationStatus: nextApplicationStatus,
                walletTransactionId: walletTransaction?.id ?? null
              }
            };
          });
          if (result.status === 200) {
            await updateCreditScore(userId);
          }
          return res.status(result.status).json(result.body);
        } catch (err) {
          console.error(
            "POST /lending/borrower/applications/:id/payments error:",
            err
          );
          return res.status(500).json({ message: "Failed to apply loan repayment." });
        }
      }
    );
    router8.get("/member/circles/available", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        await ensureMemberProductAccess(userId, "SUSU");
        const myMemberships = await db.select({ circleId: circleMembershipsTable.circleId }).from(circleMembershipsTable).where(eq(circleMembershipsTable.userId, userId));
        const myCircleIds = new Set(myMemberships.map((m) => m.circleId));
        const allCircles = await db.select().from(savingsCirclesTable).where(
          and(
            inArray(savingsCirclesTable.status, [
              "UPCOMING",
              "ACTIVE",
              "FORMING"
            ]),
            sql`${savingsCirclesTable.organizationId} is null`
          )
        ).orderBy(
          desc(savingsCirclesTable.createdAt),
          desc(savingsCirclesTable.id)
        );
        const memberCounts = allCircles.length > 0 ? await db.select({
          circleId: circleMembershipsTable.circleId,
          userId: circleMembershipsTable.userId,
          position: circleMembershipsTable.position
        }).from(circleMembershipsTable).where(
          inArray(
            circleMembershipsTable.circleId,
            allCircles.map((circle) => circle.id)
          )
        ) : [];
        const membersByCircleId = /* @__PURE__ */ new Map();
        for (const row of memberCounts) {
          const current = membersByCircleId.get(row.circleId) ?? [];
          current.push(row);
          membersByCircleId.set(row.circleId, current);
        }
        const result = [];
        for (const c of allCircles) {
          if (myCircleIds.has(c.id)) continue;
          const members = membersByCircleId.get(c.id) ?? [];
          const occupiedPositions = members.map((member) => member.position);
          const currentMembers = occupiedPositions.length;
          const spots = c.maxMembers - currentMembers;
          if (spots > 0) {
            const status = getCircleRuntimeStatus({
              status: c.status,
              startDate: c.startDate
            });
            result.push({
              id: c.id,
              name: c.name,
              description: c.description,
              contributionAmount: Number(c.contributionAmount),
              frequency: c.frequency,
              currentMembers,
              spotsAvailable: spots,
              maxMembers: c.maxMembers,
              isFreeToJoin: c.isFreeToJoin,
              startDate: c.startDate?.toISOString().split("T")[0] ?? null,
              status,
              canJoin: status === "FORMING" && isCircleCreatorSeatIntact({ circle: c, members }),
              occupiedPositions
            });
          }
        }
        return res.json({ circles: result });
      } catch (err) {
        if (err instanceof MemberProductAccessError) {
          return res.status(err.statusCode).json({ message: err.message });
        }
        console.error("GET /member/circles/available error:", err);
        return res.status(500).json({ message: "Failed to fetch available circles." });
      }
    });
    router8.post("/member/circles/:id/join", requireAuth2, async (req, res) => {
      const userId = req.userId;
      const circleId = Number(req.params.id);
      if (!circleId) return res.status(400).json({ message: "Invalid circle id." });
      try {
        await ensureMemberProductAccess(userId, "SUSU");
        const [user] = await db.select().from(usersTable).where(eq(usersTable.id, userId)).limit(1);
        if (user) {
          const lens = getInvestorPackageLens({
            membershipType: user.membershipType ?? null,
            membershipStatus: user.membershipStatus ?? null,
            userRole: user.userRole ?? null,
            segment: user.segment ?? null,
            investorCategory: user.investorCategory ?? null
          });
          if (!lens.canRosca) {
            return res.status(403).json({
              message: "Your investor package does not include access to ROSCA Circles (Susu)."
            });
          }
        }
        const result = await db.transaction(async (tx) => {
          const [circle] = await tx.select().from(savingsCirclesTable).where(eq(savingsCirclesTable.id, circleId));
          if (!circle) {
            return { status: 404, body: { message: "Circle not found." } };
          }
          if (circle.organizationId !== null) {
            return {
              status: 404,
              body: {
                message: "Organization-operated circles are available only from the organization workspace."
              }
            };
          }
          const runtimeStatus = getCircleRuntimeStatus({
            status: circle.status,
            startDate: circle.startDate
          });
          if (!["FORMING", "ACTIVE", "UPCOMING"].includes(runtimeStatus)) {
            return {
              status: 400,
              body: { message: "Circle is not open for joining." }
            };
          }
          if (runtimeStatus === "UPCOMING") {
            return {
              status: 400,
              body: {
                message: "This circle is upcoming. Join becomes available on its start date."
              }
            };
          }
          if (runtimeStatus !== "FORMING") {
            return {
              status: 400,
              body: { message: "Circle is not open for joining." }
            };
          }
          const parsedBody = external_exports.object({
            position: external_exports.number().int().min(2),
            autoDeductEnabled: external_exports.boolean().optional(),
            acceptedTerms: external_exports.boolean().optional()
          }).safeParse(req.body ?? {});
          if (!parsedBody.success) {
            return {
              status: 400,
              body: { message: "Invalid request payload." }
            };
          }
          const requestedPosition = parsedBody.data.position;
          const autoDeductEnabled = parsedBody.data.autoDeductEnabled ?? false;
          const acceptedTerms = parsedBody.data.acceptedTerms;
          const termsRequiredForJoin = Boolean(circle.termsHtml) && String(circle.termsHtml).trim().length > 0;
          if (termsRequiredForJoin && acceptedTerms !== true) {
            return {
              status: 400,
              body: {
                message: "You must accept the Savings Circle terms & conditions to join."
              }
            };
          }
          const creatorSeatIssue = await getCircleCreatorSeatIssueWith(
            tx,
            circleId
          );
          if (creatorSeatIssue) {
            return {
              status: 409,
              body: { message: creatorSeatIssue }
            };
          }
          const [existing] = await tx.select().from(circleMembershipsTable).where(
            and(
              eq(circleMembershipsTable.circleId, circleId),
              eq(circleMembershipsTable.userId, userId)
            )
          );
          if (existing) {
            return {
              status: 400,
              body: { message: "Already in this circle." }
            };
          }
          const existingMembers = await tx.select({ position: circleMembershipsTable.position }).from(circleMembershipsTable).where(eq(circleMembershipsTable.circleId, circleId));
          const currentMembers = existingMembers.length;
          if (currentMembers >= circle.maxMembers) {
            return { status: 400, body: { message: "Circle is full." } };
          }
          const occupiedPositions = new Set(existingMembers.map((m) => m.position));
          if (requestedPosition > circle.maxMembers) {
            return {
              status: 400,
              body: { message: "Requested spot is outside circle capacity." }
            };
          }
          if (occupiedPositions.has(requestedPosition)) {
            return {
              status: 400,
              body: { message: "Requested spot is already taken." }
            };
          }
          const assignedPosition = requestedPosition;
          const amount = String(circle.contributionAmount);
          const numericAmount = Number(circle.contributionAmount);
          if (!Number.isFinite(numericAmount) || numericAmount <= 0) {
            return {
              status: 400,
              body: { message: "Invalid contribution amount." }
            };
          }
          const userWallet = await ensureWalletWith6(tx, "USER", userId);
          const circleTreasuryWallet = await ensureCircleTreasuryWalletWith(
            tx,
            circle
          );
          if (!circleTreasuryWallet) {
            return {
              status: 404,
              body: { message: "Circle treasury was not found." }
            };
          }
          let contributionId = null;
          let paidAt = null;
          const dueDate = getNextCircleDueDate({
            anchorDate: circle.startDate,
            frequency: circle.frequency
          });
          if (!circle.isFreeToJoin) {
            const funds = await getWalletFundsWith2(tx, userWallet.id);
            if (funds.availableBalance < numericAmount) {
              return {
                status: 400,
                body: {
                  message: "Insufficient available wallet balance to join and fund your first contribution."
                }
              };
            }
            paidAt = /* @__PURE__ */ new Date();
            const [contribution] = await tx.insert(savingsContributionsTable).values({
              circleId,
              userId,
              dueDate,
              paidAt,
              amount,
              status: "PAID",
              method: "WALLET",
              receiptRef: `wallet_tx:susu:join:${circleId}:${userId}`
            }).returning();
            contributionId = contribution.id;
            const [transaction] = await tx.insert(walletTransactionsTable).values({
              type: "CONTRIBUTION",
              idempotencyKey: `susu:circle-join:${circleId}:${userId}`,
              fromWalletId: userWallet.id,
              toWalletId: circleTreasuryWallet.id,
              amount,
              metadata: {
                source: "susu_join_first_contribution",
                circleId,
                contributionId: contribution.id,
                userId,
                position: assignedPosition,
                dueDate: dueDate.toISOString()
              }
            }).returning();
            await tx.update(savingsContributionsTable).set({
              receiptRef: `wallet_tx:${transaction.id}`,
              updatedAt: /* @__PURE__ */ new Date()
            }).where(eq(savingsContributionsTable.id, contribution.id));
          }
          await tx.insert(circleMembershipsTable).values({
            circleId,
            userId,
            position: assignedPosition,
            memberAutoDeductEnabled: autoDeductEnabled
          });
          const activation = await activateCircleIfReadyWith(tx, circleId);
          if (!activation.activated) {
            await repairCircleContributionScheduleWith(tx, circleId);
          }
          await processCircleAutomationWith(tx, circleId);
          const nextFunds = await getWalletFundsWith2(tx, userWallet.id);
          return {
            status: 201,
            body: {
              circleId,
              position: assignedPosition,
              walletBalance: nextFunds.balance,
              availableBalance: nextFunds.availableBalance,
              contribution: contributionId ? {
                id: contributionId,
                amount: numericAmount,
                paidAt: paidAt?.toISOString()
              } : null,
              activated: activation.activated,
              workflow: circle.isFreeToJoin ? autoDeductEnabled ? "You joined the circle for free. Auto Deduct will cover future contributions whenever funds are available." : "You joined the circle for free. You will contribute after it starts." : autoDeductEnabled ? "You joined the circle, your first contribution was paid from wallet, and Auto Deduct is on for future contributions." : "You joined the circle and your first contribution was paid from wallet."
            }
          };
        });
        if (result?.meta?.kind === "investment_intent_submitted") {
          const intentId = typeof result?.meta?.intentId === "number" ? result.meta.intentId : null;
          if (intentId) {
            void (async () => {
              const key = `investment_intent_submitted:${intentId}:push`;
              const reserved = await reserveNotificationDeliveryWith(db, {
                userId,
                channel: "PUSH",
                category: "INVESTMENT",
                idempotencyKey: key,
                status: "SKIPPED",
                provider: null,
                metadata: { kind: "investment_intent_submitted", intentId }
              });
              if (!reserved.reserved) return;
              try {
                const pushResult = await deliverPushIfEnabled({
                  userId,
                  category: "INVESTMENT",
                  title: "Investment intent submitted",
                  body: "Your investment intent has been submitted for review.",
                  data: { actionHref: "/dashboard/investments" }
                });
                await finalizeNotificationDeliveryWith(db, {
                  idempotencyKey: key,
                  status: pushResult.status,
                  provider: pushResult.status === "SENT" ? "EXPO" : null,
                  errorMessage: pushResult.reason ?? null,
                  notificationId: null,
                  metadata: {
                    kind: "investment_intent_submitted",
                    reason: pushResult.reason ?? null,
                    intentId
                  }
                });
              } catch (err) {
                await finalizeNotificationDeliveryWith(db, {
                  idempotencyKey: key,
                  status: "FAILED",
                  provider: "EXPO",
                  errorMessage: err instanceof Error ? err.message : String(err),
                  notificationId: null,
                  metadata: { kind: "investment_intent_submitted", intentId }
                });
              }
            })();
          }
        }
        if (result.status === 201) {
          publishLiveEventToUser(userId, {
            kind: "DATA_CHANGED",
            scopes: ["wallet", "susu"],
            payload: { action: "susu_circle_joined", circleId }
          });
          const actorName = await getAdminNotificationActorName(userId);
          void notifyAdminsWith(db, {
            category: "SAVINGS",
            severity: "INFO",
            title: "ROSCA circle (Susu) joined",
            body: `${actorName} joined circle #${circleId}.`,
            actionLabel: "Open SUSU",
            actionHref: "/admin/susu"
          });
        }
        return res.status(result.status).json(result.body);
      } catch (err) {
        if (err instanceof MemberProductAccessError) {
          return res.status(err.statusCode).json({ message: err.message });
        }
        console.error("POST /member/circles/:id/join error:", err);
        return res.status(500).json({ message: "Failed to join circle." });
      }
    });
    router8.post("/member/circles/:id/contribute", requireAuth2, async (req, res) => {
      const userId = req.userId;
      const circleId = Number(req.params.id);
      let contributionNotification = null;
      if (!circleId) return res.status(400).json({ message: "Invalid circle id." });
      try {
        await ensureMemberProductAccess(userId, "SUSU");
        const parsedBody = external_exports.object({
          idempotencyKey: external_exports.string().optional(),
          metadata: external_exports.record(external_exports.unknown()).optional()
        }).safeParse(req.body ?? {});
        if (!parsedBody.success)
          return res.status(400).json({ errors: parsedBody.error.flatten() });
        const result = await db.transaction(async (tx) => {
          const [circle] = await tx.select().from(savingsCirclesTable).where(eq(savingsCirclesTable.id, circleId));
          if (!circle)
            return { status: 404, body: { message: "Circle not found." } };
          if (circle.organizationId !== null) {
            return {
              status: 404,
              body: {
                message: "Organization-operated circles are available only from the organization workspace."
              }
            };
          }
          const runtimeStatus = getCircleRuntimeStatus({
            status: circle.status,
            startDate: circle.startDate
          });
          if (runtimeStatus !== "ACTIVE")
            return {
              status: 400,
              body: { message: "Circle is not active." }
            };
          const membership = await tx.select().from(circleMembershipsTable).where(
            and(
              eq(circleMembershipsTable.circleId, circleId),
              eq(circleMembershipsTable.userId, userId)
            )
          );
          if (!membership.length)
            return {
              status: 400,
              body: { message: "You are not in this circle." }
            };
          await processCircleAutomationWith(tx, circleId);
          await repairCircleContributionScheduleWith(tx, circleId);
          const amount = String(circle.contributionAmount);
          const numericAmount = Number(circle.contributionAmount);
          if (!Number.isFinite(numericAmount) || numericAmount <= 0)
            return { status: 400, body: { message: "Invalid amount." } };
          const userWallet = await ensureWalletWith6(tx, "USER", userId);
          const circleTreasuryWallet = await ensureCircleTreasuryWalletWith(
            tx,
            circle
          );
          if (!circleTreasuryWallet) {
            return {
              status: 404,
              body: { message: "Circle treasury was not found." }
            };
          }
          const [nextDue] = await tx.select().from(savingsContributionsTable).where(
            and(
              eq(savingsContributionsTable.circleId, circleId),
              eq(savingsContributionsTable.userId, userId),
              eq(savingsContributionsTable.status, "PENDING"),
              lte(savingsContributionsTable.dueDate, /* @__PURE__ */ new Date())
            )
          ).orderBy(asc(savingsContributionsTable.dueDate)).limit(1);
          if (!nextDue) {
            return {
              status: 400,
              body: { message: "No pending contribution is due right now." }
            };
          }
          const deterministicKey = `contribution:${circleId}:${userId}:${nextDue.dueDate.toISOString()}`;
          const idempotencyKey = deterministicKey;
          const existing = await tx.select().from(walletTransactionsTable).where(eq(walletTransactionsTable.idempotencyKey, idempotencyKey));
          if (existing.length) {
            const t = existing[0];
            return {
              status: 200,
              body: {
                transaction: {
                  id: t.id,
                  type: t.type,
                  amount: Number(t.amount),
                  createdAt: t.createdAt.toISOString(),
                  reused: true
                }
              }
            };
          }
          const walletFunds = await getWalletFundsWith2(tx, userWallet.id);
          if (walletFunds.availableBalance < numericAmount)
            return {
              status: 400,
              body: { message: "Insufficient available wallet balance." }
            };
          let insertedTx;
          try {
            const [createdTx] = await tx.insert(walletTransactionsTable).values({
              type: "CONTRIBUTION",
              idempotencyKey,
              fromWalletId: userWallet.id,
              toWalletId: circleTreasuryWallet.id,
              amount,
              metadata: {
                ...parsedBody.data.metadata ?? {},
                circleId,
                contributionId: nextDue.id,
                dueDate: nextDue.dueDate.toISOString()
              }
            }).returning();
            insertedTx = createdTx;
          } catch (e) {
            if (!isUniqueViolation7(e)) throw e;
            const [t] = await tx.select().from(walletTransactionsTable).where(eq(walletTransactionsTable.idempotencyKey, idempotencyKey));
            if (!t) throw e;
            const reusedTx = t;
            return {
              status: 200,
              body: {
                transaction: {
                  id: reusedTx.id,
                  type: reusedTx.type,
                  amount: Number(reusedTx.amount),
                  createdAt: reusedTx.createdAt.toISOString(),
                  reused: true
                }
              }
            };
          }
          if (!insertedTx) {
            throw new Error("Failed to create transaction.");
          }
          const now = /* @__PURE__ */ new Date();
          const [contribution] = await tx.update(savingsContributionsTable).set({
            paidAt: now,
            status: "PAID",
            method: "WALLET",
            receiptRef: `wallet_tx:${insertedTx.id}`
          }).where(
            and(
              eq(savingsContributionsTable.id, nextDue.id),
              eq(savingsContributionsTable.status, "PENDING")
            )
          ).returning();
          if (!contribution) {
            throw new Error("Contribution already paid.");
          }
          await processCircleAutomationWith(tx, circleId);
          const inApp = await notifyInAppWith(tx, {
            userId,
            category: "SAVINGS",
            severity: "SUCCESS",
            title: "Contribution paid",
            body: `Your SUSU contribution of ${Number(formatMoneyAmount(numericAmount)).toLocaleString("en-CA", { style: "currency", currency: "CAD" })} for ${circle.name} has been recorded.`,
            actionLabel: "View Savings",
            actionHref: "/dashboard/savings"
          });
          contributionNotification = {
            transactionId: insertedTx.id,
            amount: Number(formatMoneyAmount(numericAmount)),
            circleName: circle.name ?? null,
            notificationId: inApp.id
          };
          return {
            status: 201,
            body: {
              contribution: {
                id: contribution.id,
                circleId: contribution.circleId,
                amount: Number(contribution.amount),
                paidAt: contribution.paidAt?.toISOString() ?? null,
                receiptRef: contribution.receiptRef ?? null
              },
              transaction: {
                id: insertedTx.id,
                type: insertedTx.type,
                amount: Number(insertedTx.amount),
                createdAt: insertedTx.createdAt.toISOString()
              }
            }
          };
        });
        if (result.status === 201) {
          void (async () => {
            const notification = contributionNotification;
            if (notification === null) return;
            const circleSuffix = notification.circleName?.trim() ? ` for ${notification.circleName.trim()}` : "";
            const amountLabel = notification.amount.toLocaleString("en-CA", {
              style: "currency",
              currency: "CAD"
            });
            const pushKey = `susu_contribution_paid:${notification.transactionId}:push`;
            const pushReserved = await reserveNotificationDeliveryWith(db, {
              userId,
              channel: "PUSH",
              category: "SAVINGS",
              idempotencyKey: pushKey,
              status: "SKIPPED",
              provider: null,
              metadata: {
                kind: "susu_contribution_paid",
                transactionId: notification.transactionId,
                circleName: notification.circleName
              }
            });
            if (pushReserved.reserved) {
              try {
                const pushResult = await deliverPushIfEnabled({
                  userId,
                  category: "SAVINGS",
                  title: "Contribution paid",
                  body: `Your SUSU contribution${circleSuffix} has been recorded.`,
                  data: { actionHref: "/dashboard/savings" }
                });
                await finalizeNotificationDeliveryWith(db, {
                  idempotencyKey: pushKey,
                  status: pushResult.status,
                  provider: pushResult.status === "SENT" ? "EXPO" : null,
                  errorMessage: pushResult.reason ?? null,
                  notificationId: notification.notificationId,
                  metadata: {
                    kind: "susu_contribution_paid",
                    reason: pushResult.reason ?? null,
                    transactionId: notification.transactionId,
                    circleName: notification.circleName
                  }
                });
              } catch (err) {
                await finalizeNotificationDeliveryWith(db, {
                  idempotencyKey: pushKey,
                  status: "FAILED",
                  provider: "EXPO",
                  errorMessage: err instanceof Error ? err.message : String(err),
                  notificationId: notification.notificationId,
                  metadata: {
                    kind: "susu_contribution_paid",
                    transactionId: notification.transactionId,
                    circleName: notification.circleName
                  }
                });
              }
            }
            const emailKey = `susu_contribution_paid:${notification.transactionId}:email`;
            const emailReserved = await reserveNotificationDeliveryWith(db, {
              userId,
              channel: "EMAIL",
              category: "SAVINGS",
              idempotencyKey: emailKey,
              status: "SKIPPED",
              provider: null,
              metadata: {
                kind: "susu_contribution_paid",
                transactionId: notification.transactionId,
                circleName: notification.circleName
              }
            });
            if (!emailReserved.reserved) return;
            const [user] = await db.select({
              email: usersTable.email,
              firstName: usersTable.firstName
            }).from(usersTable).where(eq(usersTable.id, userId)).limit(1);
            if (!user) return;
            try {
              const emailResult = await deliverReminderEmailIfEnabled({
                userId,
                to: user.email,
                firstName: user.firstName,
                category: "SAVINGS",
                title: "Contribution paid",
                intro: `Your SUSU contribution${circleSuffix} of ${amountLabel} has been recorded.`,
                lines: ["Open Savings to review your contribution details."],
                actionLabel: "View Savings",
                actionHref: "/dashboard/savings"
              });
              await finalizeNotificationDeliveryWith(db, {
                idempotencyKey: emailKey,
                status: emailResult.status,
                provider: emailResult.status === "SENT" ? "SMTP" : null,
                errorMessage: emailResult.reason ?? null,
                notificationId: notification.notificationId,
                metadata: {
                  kind: "susu_contribution_paid",
                  reason: emailResult.reason ?? null,
                  transactionId: notification.transactionId,
                  circleName: notification.circleName
                }
              });
            } catch (err) {
              await finalizeNotificationDeliveryWith(db, {
                idempotencyKey: emailKey,
                status: "FAILED",
                provider: "SMTP",
                errorMessage: err instanceof Error ? err.message : String(err),
                notificationId: notification.notificationId,
                metadata: {
                  kind: "susu_contribution_paid",
                  transactionId: notification.transactionId,
                  circleName: notification.circleName
                }
              });
            }
          })();
        }
        if (result.status === 201) {
          publishLiveEventToUser(userId, {
            kind: "DATA_CHANGED",
            scopes: ["wallet", "susu", "notifications"],
            payload: { action: "susu_contribution_paid", circleId }
          });
          const actorName = await getAdminNotificationActorName(userId);
          void notifyAdminsWith(db, {
            category: "SAVINGS",
            severity: "SUCCESS",
            title: "SUSU contribution paid",
            body: `${actorName} paid a contribution in circle #${circleId}.`,
            actionLabel: "Open SUSU",
            actionHref: "/admin/susu"
          });
        }
        return res.status(result.status).json(result.body);
      } catch (err) {
        if (err instanceof MemberProductAccessError) {
          return res.status(err.statusCode).json({ message: err.message });
        }
        console.error("POST /member/circles/:id/contribute error:", err);
        if (err instanceof Error && err.message === "Contribution already paid.") {
          return res.status(400).json({ message: err.message });
        }
        return res.status(500).json({ message: "Failed to contribute." });
      }
    });
    router8.get("/investment/opportunities", requireAuth2, async (req, res) => {
      try {
        const userId = req.userId;
        await ensureMemberProductAccess(userId, "INVESTMENTS");
        const [user] = await db.select({
          membershipType: usersTable.membershipType,
          organizationId: usersTable.organizationId
        }).from(usersTable).where(eq(usersTable.id, userId)).limit(1);
        const memberTier = (user?.membershipType ?? "").toUpperCase() === "INVESTOR" ? await getMemberMembershipPlanTier(userId) : null;
        const now = /* @__PURE__ */ new Date();
        const filters = [
          eq(investmentOpportunitiesTable.status, "OPEN"),
          gt(investmentOpportunitiesTable.deadline, now)
        ];
        const scope = await resolveInvestmentScopeForUser(userId);
        applyInvestmentScopeFilter(filters, scope);
        const opps = await db.select().from(investmentOpportunitiesTable).where(and(...filters)).orderBy(
          desc(investmentOpportunitiesTable.featured),
          asc(investmentOpportunitiesTable.deadline)
        );
        return res.json({
          opportunities: opps.filter(
            (o) => isInvestmentOpportunityAllowedForMember({
              membershipType: user?.membershipType,
              memberTier,
              eligibleInvestorTiers: o.eligibleInvestorTiers
            })
          ).map((o) => {
            const eligibleInvestorTiers = normalizeInvestmentOpportunityEligibleInvestorTiers(
              o.eligibleInvestorTiers
            );
            const pct = o.expectedReturnPct ?? null;
            return {
              id: String(o.id),
              title: o.title,
              organization: "WWN",
              category: o.category,
              fundingModel: o.fundingModel ?? "CROWD",
              riskLevel: o.riskLevel,
              minInvestment: Number(o.minInvestment),
              targetAmount: Number(o.targetAmount),
              raisedAmount: Number(o.raisedAmount),
              returnRateLow: pct,
              returnRateHigh: pct,
              closingDate: new Date(o.deadline).toISOString().split("T")[0],
              description: o.description,
              termsHtml: o.termsHtml ?? null,
              highlights: [],
              eligibleInvestorTiers
            };
          })
        });
      } catch (err) {
        if (err instanceof MemberProductAccessError) {
          return res.status(err.statusCode).json({ message: err.message });
        }
        console.error("GET /investment/opportunities error:", err);
        return res.status(500).json({ message: "Failed to fetch opportunities." });
      }
    });
    router8.post("/investment/interests", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        await ensureMemberProductAccess(userId, "INVESTMENTS");
        const [user] = await db.select({
          membershipType: usersTable.membershipType
        }).from(usersTable).where(eq(usersTable.id, userId)).limit(1);
        const schema = external_exports.object({
          opportunityId: external_exports.coerce.number().int().positive(),
          amount: external_exports.coerce.number().positive(),
          notes: external_exports.string().max(2e3).optional(),
          acceptedTerms: external_exports.boolean().optional()
        });
        const parsed = schema.safeParse(req.body);
        if (!parsed.success) {
          return res.status(400).json({ message: "Invalid request." });
        }
        const { opportunityId, amount } = parsed.data;
        const notes = parsed.data.notes?.trim() ? parsed.data.notes.trim() : null;
        const acceptedTerms = parsed.data.acceptedTerms;
        const [opp] = await db.select().from(investmentOpportunitiesTable).where(eq(investmentOpportunitiesTable.id, opportunityId));
        if (!opp) {
          return res.status(404).json({ message: "Opportunity not found." });
        }
        const scopeCheck = await validateInvestmentOpportunityScope(userId, {
          organizationId: opp.organizationId
        });
        if (!scopeCheck.allowed) {
          return res.status(403).json({ message: scopeCheck.reason ?? "Scope mismatch." });
        }
        const termsRequired = Boolean(opp.termsHtml) && String(opp.termsHtml).trim().length > 0;
        if (termsRequired && acceptedTerms !== true) {
          return res.status(400).json({
            message: "You must accept the Investment Opportunity terms & conditions to proceed."
          });
        }
        const now = /* @__PURE__ */ new Date();
        const deadline = opp.deadline ? new Date(opp.deadline) : null;
        if (opp.status !== "OPEN" || deadline && deadline.getTime() <= now.getTime()) {
          return res.status(400).json({
            message: "This opportunity is no longer accepting interests."
          });
        }
        const memberTier = (user?.membershipType ?? "").toUpperCase() === "INVESTOR" ? await getMemberMembershipPlanTier(userId) : null;
        if (!isInvestmentOpportunityAllowedForMember({
          membershipType: user?.membershipType,
          memberTier,
          eligibleInvestorTiers: opp.eligibleInvestorTiers
        })) {
          return res.status(403).json({
            message: "This opportunity is not available for your current investor tier."
          });
        }
        const minInvestment = Number(opp.minInvestment);
        if (amount < minInvestment) {
          return res.status(400).json({
            message: `Minimum investment is ${minInvestment}.`
          });
        }
        const result = await db.transaction(async (tx) => {
          const userWallet = await ensureWalletWith6(tx, "USER", userId);
          const [existing] = await tx.select().from(investmentInterestsTable).where(
            and(
              eq(investmentInterestsTable.userId, userId),
              eq(investmentInterestsTable.opportunityId, opportunityId)
            )
          );
          if (existing?.status === "CONFIRMED") {
            return {
              status: 400,
              body: {
                message: "Investment intent already approved for this opportunity."
              }
            };
          }
          const capacity = await getInvestmentOpportunityCapacityWith2(tx, {
            opportunityId,
            excludePendingInterestId: existing?.id
          });
          if (!capacity) {
            return {
              status: 404,
              body: { message: "Opportunity not found." }
            };
          }
          if (Number.isFinite(capacity.targetAmount) && capacity.targetAmount > 0 && capacity.confirmedTotal + capacity.reservedPendingTotal + amount > capacity.targetAmount) {
            return {
              status: 400,
              body: {
                message: "This opportunity does not have enough remaining capacity for that amount."
              }
            };
          }
          const effectiveFunds = await getWalletFundsWith2(
            tx,
            userWallet.id,
            existing?.id
          );
          if (effectiveFunds.availableBalance < amount) {
            return {
              status: 400,
              body: {
                message: `Insufficient available wallet balance. Available: ${effectiveFunds.availableBalance.toFixed(2)}.`
              }
            };
          }
          const now2 = /* @__PURE__ */ new Date();
          const amountText = amount.toFixed(2);
          let interest = existing;
          if (!interest) {
            [interest] = await tx.insert(investmentInterestsTable).values({
              userId,
              opportunityId,
              amount: amountText,
              notes,
              status: "PENDING",
              confirmedAt: null,
              cancelledAt: null,
              updatedAt: now2
            }).returning();
          } else {
            [interest] = await tx.update(investmentInterestsTable).set({
              amount: amountText,
              notes,
              status: "PENDING",
              confirmedAt: null,
              cancelledAt: null,
              updatedAt: now2
            }).where(eq(investmentInterestsTable.id, interest.id)).returning();
          }
          const [existingReservation] = await tx.select().from(investmentIntentReservationsTable).where(eq(investmentIntentReservationsTable.interestId, interest.id));
          if (!existingReservation) {
            await tx.insert(investmentIntentReservationsTable).values({
              interestId: interest.id,
              walletId: userWallet.id,
              amount: amountText,
              status: "RESERVED",
              reservedAt: now2,
              createdAt: now2,
              updatedAt: now2
            });
          } else {
            await tx.update(investmentIntentReservationsTable).set({
              walletId: userWallet.id,
              amount: amountText,
              status: "RESERVED",
              finalizedTransactionId: null,
              finalizedAt: null,
              releasedAt: null,
              updatedAt: now2
            }).where(
              eq(investmentIntentReservationsTable.id, existingReservation.id)
            );
          }
          await tx.insert(investmentTransactionsTable).values({
            userId,
            opportunityId,
            amount: amountText,
            type: existing ? "INVESTMENT_INTENT_UPDATED" : "INVESTMENT_INTENT_SUBMITTED",
            description: existing ? "Investment intent updated and wallet funds re-reserved." : "Investment intent submitted and wallet funds reserved.",
            processedAt: now2,
            createdAt: now2
          });
          await notifyInAppWith(tx, {
            userId,
            category: "INVESTMENT",
            severity: "INFO",
            title: existing ? "Investment intent updated" : "Investment intent submitted",
            body: existing ? "Your investment intent has been updated." : "Your investment intent has been submitted for review.",
            actionLabel: "View Susunomics",
            actionHref: "/dashboard/investments"
          });
          const funds = await getWalletFundsWith2(tx, userWallet.id);
          return {
            status: existing ? 200 : 201,
            body: {
              intent: {
                id: String(interest.id),
                status: interest.status,
                amount,
                reservedAmount: amount,
                walletBalance: funds.balance,
                reservedBalance: funds.reservedBalance,
                availableBalance: funds.availableBalance
              }
            },
            meta: {
              kind: existing ? "investment_intent_updated" : "investment_intent_submitted",
              intentId: interest.id
            }
          };
        });
        if (result.status === 200 || result.status === 201) {
          publishLiveEventToUser(userId, {
            kind: "DATA_CHANGED",
            scopes: ["wallet", "investments", "notifications"],
            payload: { action: "investment_intent_saved", opportunityId }
          });
          const actorName = await getAdminNotificationActorName(userId);
          void notifyAdminsWith(db, {
            category: "INVESTMENT",
            severity: "INFO",
            title: "Investment intent submitted",
            body: `${actorName} submitted an investment intent.`,
            actionLabel: "Open Investments",
            actionHref: "/admin/investments"
          });
        }
        return res.status(result.status).json(result.body);
      } catch (err) {
        if (err instanceof MemberProductAccessError) {
          return res.status(err.statusCode).json({ message: err.message });
        }
        console.error("POST /investment/interests error:", err);
        return res.status(500).json({ message: "Failed to submit investment interest." });
      }
    });
    router8.post(
      "/investment/interests/:id/cancel",
      requireAuth2,
      async (req, res) => {
        const userId = req.userId;
        try {
          await ensureMemberProductAccess(userId, "INVESTMENTS");
          const id = Number(req.params.id);
          if (!Number.isFinite(id) || id <= 0) {
            return res.status(400).json({ message: "Invalid intent id." });
          }
          const result = await db.transaction(async (tx) => {
            const rows = await tx.select({
              interest: investmentInterestsTable,
              opp: investmentOpportunitiesTable
            }).from(investmentInterestsTable).innerJoin(
              investmentOpportunitiesTable,
              eq(
                investmentInterestsTable.opportunityId,
                investmentOpportunitiesTable.id
              )
            ).where(
              and(
                eq(investmentInterestsTable.id, id),
                eq(investmentInterestsTable.userId, userId)
              )
            );
            if (!rows.length) {
              return {
                status: 404,
                body: { message: "Investment intent not found." }
              };
            }
            const { interest, opp } = rows[0];
            const scopeCheck = await validateInvestmentOpportunityScope(userId, {
              organizationId: opp.organizationId
            });
            if (!scopeCheck.allowed) {
              return {
                status: 403,
                body: { message: scopeCheck.reason ?? "Scope mismatch." }
              };
            }
            if (interest.status === "CONFIRMED") {
              return {
                status: 400,
                body: { message: "Approved investments cannot be cancelled here." }
              };
            }
            if (interest.status === "CANCELLED") {
              const userWallet2 = await ensureWalletWith6(tx, "USER", userId);
              const funds2 = await getWalletFundsWith2(tx, userWallet2.id);
              return {
                status: 200,
                body: {
                  intent: {
                    id: String(interest.id),
                    status: interest.status,
                    walletBalance: funds2.balance,
                    reservedBalance: funds2.reservedBalance,
                    availableBalance: funds2.availableBalance
                  }
                }
              };
            }
            const now = /* @__PURE__ */ new Date();
            const [updated] = await tx.update(investmentInterestsTable).set({
              status: "CANCELLED",
              cancelledAt: now,
              confirmedAt: null,
              updatedAt: now
            }).where(eq(investmentInterestsTable.id, interest.id)).returning();
            const [reservation] = await tx.select().from(investmentIntentReservationsTable).where(eq(investmentIntentReservationsTable.interestId, interest.id));
            if (reservation && reservation.status === "RESERVED") {
              await tx.update(investmentIntentReservationsTable).set({
                status: "RELEASED",
                releasedAt: now,
                updatedAt: now
              }).where(eq(investmentIntentReservationsTable.id, reservation.id));
            }
            await tx.insert(investmentTransactionsTable).values({
              userId,
              opportunityId: interest.opportunityId,
              amount: interest.amount,
              type: "INVESTMENT_INTENT_RELEASED",
              description: "Investment intent cancelled and reserved funds released.",
              processedAt: now,
              createdAt: now
            });
            await notifyInAppWith(tx, {
              userId,
              category: "INVESTMENT",
              severity: "WARNING",
              title: "Investment intent cancelled",
              body: "Your investment intent has been cancelled and reserved funds released.",
              actionLabel: "View Susunomics",
              actionHref: "/dashboard/investments"
            });
            const userWallet = await ensureWalletWith6(tx, "USER", userId);
            const funds = await getWalletFundsWith2(tx, userWallet.id);
            return {
              status: 200,
              body: {
                intent: {
                  id: String(updated.id),
                  status: updated.status,
                  walletBalance: funds.balance,
                  reservedBalance: funds.reservedBalance,
                  availableBalance: funds.availableBalance
                }
              },
              meta: {
                kind: "investment_intent_cancelled",
                intentId: updated.id
              }
            };
          });
          if (result?.meta?.kind === "investment_intent_cancelled") {
            const intentId = typeof result?.meta?.intentId === "number" ? result.meta.intentId : null;
            if (intentId) {
              void (async () => {
                const key = `investment_intent_cancelled:${intentId}:push`;
                const reserved = await reserveNotificationDeliveryWith(db, {
                  userId,
                  channel: "PUSH",
                  category: "INVESTMENT",
                  idempotencyKey: key,
                  status: "SKIPPED",
                  provider: null,
                  metadata: { kind: "investment_intent_cancelled", intentId }
                });
                if (!reserved.reserved) return;
                try {
                  const pushResult = await deliverPushIfEnabled({
                    userId,
                    category: "INVESTMENT",
                    title: "Investment intent cancelled",
                    body: "Your investment intent was cancelled and reserved funds released.",
                    data: { actionHref: "/dashboard/investments" }
                  });
                  await finalizeNotificationDeliveryWith(db, {
                    idempotencyKey: key,
                    status: pushResult.status,
                    provider: pushResult.status === "SENT" ? "EXPO" : null,
                    errorMessage: pushResult.reason ?? null,
                    notificationId: null,
                    metadata: {
                      kind: "investment_intent_cancelled",
                      reason: pushResult.reason ?? null,
                      intentId
                    }
                  });
                } catch (err) {
                  await finalizeNotificationDeliveryWith(db, {
                    idempotencyKey: key,
                    status: "FAILED",
                    provider: "EXPO",
                    errorMessage: err instanceof Error ? err.message : String(err),
                    notificationId: null,
                    metadata: { kind: "investment_intent_cancelled", intentId }
                  });
                }
              })();
            }
          }
          if (result.status === 200) {
            publishLiveEventToUser(userId, {
              kind: "DATA_CHANGED",
              scopes: ["wallet", "investments", "notifications"],
              payload: { action: "investment_intent_cancelled" }
            });
            const actorName = await getAdminNotificationActorName(userId);
            void notifyAdminsWith(db, {
              category: "INVESTMENT",
              severity: "WARNING",
              title: "Investment intent cancelled",
              body: `${actorName} cancelled an investment intent.`,
              actionLabel: "Open Investments",
              actionHref: "/admin/investments"
            });
          }
          return res.status(result.status).json(result.body);
        } catch (err) {
          if (err instanceof MemberProductAccessError) {
            return res.status(err.statusCode).json({ message: err.message });
          }
          console.error("POST /investment/interests/:id/cancel error:", err);
          return res.status(500).json({ message: "Failed to cancel investment intent." });
        }
      }
    );
    router8.get("/investment/portfolio", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        await ensureMemberProductAccess(userId, "INVESTMENTS");
        const now = /* @__PURE__ */ new Date();
        const portfolioFilters = [
          eq(investmentInterestsTable.userId, userId),
          ne(investmentInterestsTable.status, "CANCELLED")
        ];
        const scope = await resolveInvestmentScopeForUser(userId);
        applyInvestmentScopeFilter(portfolioFilters, scope);
        const interests = await db.select({ i: investmentInterestsTable, o: investmentOpportunitiesTable }).from(investmentInterestsTable).innerJoin(
          investmentOpportunitiesTable,
          eq(
            investmentInterestsTable.opportunityId,
            investmentOpportunitiesTable.id
          )
        ).where(and(...portfolioFilters)).orderBy(desc(investmentInterestsTable.createdAt));
        const ascaPortfolio = await getAscaBackedInvestmentPortfolioWith(
          db,
          userId,
          scope,
          now
        );
        const directPortfolio = interests.map(({ i, o }) => {
          const amount = Number(i.amount);
          const submittedAtIso = i.createdAt.toISOString().split("T")[0];
          const confirmedAt = i.confirmedAt ?? null;
          const confirmedAtIso = confirmedAt ? confirmedAt.toISOString().split("T")[0] : null;
          const annualRatePct = o.expectedReturnPct ?? null;
          const maturityAt = o.deadline;
          const matured = i.status === "CONFIRMED" && maturityAt.getTime() <= now.getTime();
          const stopAt = i.cancelledAt && maturityAt ? new Date(Math.min(i.cancelledAt.getTime(), maturityAt.getTime())) : i.cancelledAt ?? maturityAt ?? null;
          const returnEarned = i.status === "CONFIRMED" && annualRatePct !== null && confirmedAt !== null ? Number(
            calculateAccruedInterest({
              principal: amount,
              annualRatePct,
              startAt: confirmedAt,
              asOf: /* @__PURE__ */ new Date(),
              stopAt
            }).toFixed(2)
          ) : null;
          return {
            id: String(i.id),
            opportunityId: String(o.id),
            title: o.title,
            category: o.category,
            amount,
            status: matured ? "MATURED" : i.status,
            returnEarned,
            submittedAt: submittedAtIso,
            confirmedAt: confirmedAtIso,
            maturedAt: maturityAt.toISOString().split("T")[0]
          };
        });
        return res.json({
          portfolio: [...directPortfolio, ...ascaPortfolio].sort(
            (a, b) => (b.confirmedAt ?? b.submittedAt).localeCompare(
              a.confirmedAt ?? a.submittedAt
            )
          )
        });
      } catch (err) {
        if (err instanceof MemberProductAccessError) {
          return res.status(err.statusCode).json({ message: err.message });
        }
        console.error("GET /investment/portfolio error:", err);
        return res.status(500).json({ message: "Failed to fetch portfolio." });
      }
    });
    router8.get("/investment/activity", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        await ensureMemberProductAccess(userId, "INVESTMENTS");
        const activityFilters = [eq(investmentTransactionsTable.userId, userId)];
        const scope = await resolveInvestmentScopeForUser(userId);
        applyInvestmentScopeFilter(activityFilters, scope);
        const txs = await db.select({
          id: investmentTransactionsTable.id,
          opportunityId: investmentTransactionsTable.opportunityId,
          opportunityTitle: investmentOpportunitiesTable.title,
          amount: investmentTransactionsTable.amount,
          type: investmentTransactionsTable.type,
          description: investmentTransactionsTable.description,
          processedAt: investmentTransactionsTable.processedAt
        }).from(investmentTransactionsTable).leftJoin(
          investmentOpportunitiesTable,
          eq(
            investmentTransactionsTable.opportunityId,
            investmentOpportunitiesTable.id
          )
        ).where(and(...activityFilters)).orderBy(desc(investmentTransactionsTable.processedAt)).limit(30);
        const ascaActivity = await getAscaBackedInvestmentActivityWith(
          db,
          userId,
          scope
        );
        const directActivity = txs.map((t) => {
          const rawType = String(t.type ?? "").toUpperCase();
          const isCredit = rawType.includes("INTEREST") || rawType.includes("RETURN") || rawType.includes("CREDIT") || rawType.includes("PAYOUT") || rawType.includes("RELEASE");
          const direction = isCredit ? "IN" : "OUT";
          const opportunityTitle = t.opportunityTitle ?? "Investment";
          const title = rawType === "INVESTMENT_INTENT_SUBMITTED" ? `${opportunityTitle} intent submitted` : rawType === "INVESTMENT_INTENT_UPDATED" ? `${opportunityTitle} intent updated` : rawType === "INVESTMENT_INTENT_RELEASED" ? `${opportunityTitle} intent released` : rawType === "INVESTMENT_PURCHASE" ? `${opportunityTitle} funded from wallet` : rawType.includes("INTEREST") || rawType.includes("RETURN") ? `${opportunityTitle} return credited` : t.description?.trim() ? t.description.trim() : `${opportunityTitle} ${rawType || "transaction"}`.trim();
          return {
            id: `tx_${t.id}`,
            opportunityId: String(t.opportunityId),
            title,
            amount: Number(t.amount),
            direction,
            occurredAt: t.processedAt.toISOString()
          };
        });
        const items = [...directActivity, ...ascaActivity].sort(
          (a, b) => b.occurredAt.localeCompare(a.occurredAt)
        );
        return res.json({ activity: items.slice(0, 30) });
      } catch (err) {
        if (err instanceof MemberProductAccessError) {
          return res.status(err.statusCode).json({ message: err.message });
        }
        console.error("GET /investment/activity error:", err);
        return res.status(500).json({ message: "Failed to fetch investment activity." });
      }
    });
    router8.get(
      "/lending/community/opportunities",
      requireAuth2,
      async (_req, res) => {
        try {
          const userId = _req.userId;
          await ensureMemberProductAccess(userId, "LENDING_BORROWER");
          const opportunities = await db.select({
            opportunity: lendingOpportunitiesTable,
            applicationBorrowerId: loanApplicationsTable.borrowerId,
            templateTermsHtml: lendingTemplatesTable.termsHtml
          }).from(lendingOpportunitiesTable).leftJoin(
            loanApplicationsTable,
            eq(lendingOpportunitiesTable.applicationId, loanApplicationsTable.id)
          ).leftJoin(
            lendingTemplatesTable,
            eq(lendingOpportunitiesTable.templateId, lendingTemplatesTable.id)
          ).where(
            and(
              eq(lendingOpportunitiesTable.status, "OPEN"),
              eq(lendingOpportunitiesTable.loanType, "COMMUNITY_LENDING"),
              or(
                sql`${loanApplicationsTable.borrowerId} is null`,
                ne(loanApplicationsTable.borrowerId, userId)
              )
            )
          ).orderBy(desc(lendingOpportunitiesTable.createdAt));
          return res.json({
            opportunities: opportunities.map(
              ({ opportunity, templateTermsHtml }) => ({
                id: String(opportunity.id),
                loanType: normalizeLendingLoanType(opportunity.loanType),
                title: opportunity.title,
                description: opportunity.description,
                termsHtml: templateTermsHtml ?? null,
                targetAmount: Number(opportunity.targetAmount),
                committedAmount: Number(opportunity.committedAmount),
                minCommitment: Number(opportunity.minCommitment),
                expectedReturnPct: Number(opportunity.expectedReturnPct),
                termMonths: opportunity.termMonths,
                returnModel: opportunity.returnModel,
                expectedReturn: opportunity.expectedReturn,
                term: opportunity.term,
                status: opportunity.status.toLowerCase(),
                borrowerType: opportunity.borrowerType ?? ""
              })
            )
          });
        } catch (err) {
          if (err instanceof MemberProductAccessError) {
            return res.status(err.statusCode).json({ message: err.message });
          }
          console.error("GET /lending/community/opportunities error:", err);
          return res.status(500).json({ message: "Failed to fetch Community Lending opportunities." });
        }
      }
    );
    router8.post("/lending/community/commit", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        await ensureMemberProductAccess(userId, "LENDING_BORROWER");
        const [user] = await db.select().from(usersTable).where(eq(usersTable.id, userId)).limit(1);
        if (user) {
          const lens = getInvestorPackageLens({
            membershipType: user.membershipType ?? null,
            membershipStatus: user.membershipStatus ?? null,
            userRole: user.userRole ?? null,
            segment: user.segment ?? null,
            investorCategory: user.investorCategory ?? null
          });
          if (!lens.canLendingDirectLend) {
            return res.status(403).json({
              message: "Direct lender commitments are not available for your investor package. WWN manages approvals and disbursements from treasury capital."
            });
          }
        }
        const { opportunityId, amount, acceptedTerms } = req.body;
        const numericAmount = Number(amount);
        if (!opportunityId || !amount || !Number.isFinite(numericAmount) || numericAmount <= 0) {
          return res.status(400).json({ message: "opportunityId and a positive amount are required." });
        }
        const lendingOpportunityId = Number(opportunityId);
        const commitment = await db.transaction(async (tx) => {
          await tx.execute(
            sql`select 1 from lending_opportunities where id = ${lendingOpportunityId} for update`
          );
          const [{ pool: pool2, templateTermsHtml }] = await tx.select({
            pool: lendingOpportunitiesTable,
            templateTermsHtml: lendingTemplatesTable.termsHtml
          }).from(lendingOpportunitiesTable).leftJoin(
            lendingTemplatesTable,
            eq(lendingOpportunitiesTable.templateId, lendingTemplatesTable.id)
          ).where(eq(lendingOpportunitiesTable.id, lendingOpportunityId));
          if (!pool2) return null;
          if (pool2.status !== "OPEN") {
            throw new Error("This opportunity is no longer accepting commitments.");
          }
          if (!isCommunityLendingLoanType(pool2.loanType)) {
            throw new Error(
              "Only Community Lending opportunities can be funded from the member lane."
            );
          }
          const termsRequired = Boolean(templateTermsHtml) && String(templateTermsHtml).trim().length > 0;
          if (termsRequired && acceptedTerms !== true) {
            throw new Error(
              "You must accept the Community Lending terms & conditions to commit."
            );
          }
          if (pool2.applicationId) {
            const [application] = await tx.select({ borrowerId: loanApplicationsTable.borrowerId }).from(loanApplicationsTable).where(eq(loanApplicationsTable.id, pool2.applicationId));
            if (application?.borrowerId === userId) {
              throw new Error(
                "You cannot fund your own Community Lending request."
              );
            }
          }
          const minCommitment = parseMoneyAmount(pool2.minCommitment);
          if (numericAmount < minCommitment) {
            throw new Error(
              `Minimum commitment is ${formatMoneyAmount(minCommitment)} for this opportunity.`
            );
          }
          const [existingConflict] = await tx.select().from(lendingCommitmentsTable).where(
            and(
              eq(lendingCommitmentsTable.userId, userId),
              eq(lendingCommitmentsTable.opportunityId, lendingOpportunityId),
              inArray(lendingCommitmentsTable.status, [
                ...ACTIVE_COMMITMENT_STATUSES
              ])
            )
          );
          if (existingConflict) {
            throw new Error(
              "You already have an active commitment for this opportunity."
            );
          }
          const confirmedTotal = parseMoneyAmount(
            await getConfirmedPoolCommitmentTotalWith(tx, lendingOpportunityId)
          );
          const remainingCapacity = calculateRemainingPoolCapacity(
            pool2.targetAmount,
            confirmedTotal
          );
          if (numericAmount > remainingCapacity) {
            throw new Error(
              `Only ${formatMoneyAmount(remainingCapacity)} remains available in this opportunity.`
            );
          }
          const now = /* @__PURE__ */ new Date();
          const [created] = await tx.insert(lendingCommitmentsTable).values({
            userId,
            opportunityId: lendingOpportunityId,
            amount: formatMoneyAmount(numericAmount),
            status: "CONFIRMED",
            confirmedAt: now,
            statusChangedAt: now
          }).returning();
          const userWallet = await ensureWalletWith6(
            tx,
            "USER",
            userId
          );
          const walletFunds = await getWalletFundsWith2(
            tx,
            userWallet.id
          );
          if (walletFunds.availableBalance < numericAmount) {
            throw new Error("Insufficient available wallet balance.");
          }
          const masterWallet = await ensureLendingMasterWalletWith3(tx);
          const commitmentIdempotencyKey = `lending_commitment:community_member_confirm:${created.id}`;
          const [existingCommitmentTx] = await tx.select().from(walletTransactionsTable).where(
            eq(walletTransactionsTable.idempotencyKey, commitmentIdempotencyKey)
          );
          if (!existingCommitmentTx) {
            await tx.insert(walletTransactionsTable).values({
              type: "TOP_UP",
              idempotencyKey: commitmentIdempotencyKey,
              fromWalletId: userWallet.id,
              toWalletId: masterWallet.id,
              amount: formatMoneyAmount(numericAmount),
              metadata: {
                source: "lending_commitment_community_member_confirmation",
                commitmentId: created.id,
                memberId: userId,
                opportunityId: lendingOpportunityId
              }
            });
          }
          await reconcileLendingPoolCommittedAmountWith(tx, lendingOpportunityId);
          return created;
        });
        if (!commitment) {
          return res.status(404).json({ message: "Lending pool not found." });
        }
        return res.status(201).json({ commitment });
      } catch (err) {
        if (err instanceof MemberProductAccessError) {
          return res.status(err.statusCode).json({ message: err.message });
        }
        if (err instanceof Error) {
          return res.status(400).json({ message: err.message });
        }
        console.error("POST /lending/community/commit error:", err);
        return res.status(500).json({ message: "Failed to record commitment." });
      }
    });
    router8.get("/lending/community/portfolio", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        await ensureMemberProductAccess(userId, "LENDING_BORROWER");
        const commitments = await db.select({ c: lendingCommitmentsTable, p: lendingOpportunitiesTable }).from(lendingCommitmentsTable).innerJoin(
          lendingOpportunitiesTable,
          eq(lendingCommitmentsTable.opportunityId, lendingOpportunitiesTable.id)
        ).where(
          and(
            eq(lendingCommitmentsTable.userId, userId),
            eq(lendingOpportunitiesTable.loanType, "COMMUNITY_LENDING")
          )
        ).orderBy(desc(lendingCommitmentsTable.createdAt));
        const [totals] = await db.select({ total: sum(lendingCommitmentsTable.amount) }).from(lendingCommitmentsTable).innerJoin(
          lendingOpportunitiesTable,
          eq(lendingCommitmentsTable.opportunityId, lendingOpportunitiesTable.id)
        ).where(
          and(
            eq(lendingCommitmentsTable.userId, userId),
            eq(lendingCommitmentsTable.status, "CONFIRMED"),
            eq(lendingOpportunitiesTable.loanType, "COMMUNITY_LENDING")
          )
        );
        const summaryByCommitmentId = await getLendingCommitmentReturnSummaryMapWith(
          db,
          commitments.map(({ c }) => c.id)
        );
        const enrichedCommitments = commitments.map(({ c, p }) => {
          const realizedReturn = summaryByCommitmentId.get(c.id)?.realizedReturn ?? 0;
          const projectedReturn2 = c.status === "CONFIRMED" ? calculateProjectedReturnAmount(
            c.amount,
            p.expectedReturnPct,
            p.termMonths
          ) : 0;
          return {
            id: String(c.id),
            opportunityId: String(p.id),
            loanType: normalizeLendingLoanType(p.loanType),
            opportunityTitle: p.title,
            amount: Number(c.amount),
            status: c.status,
            opportunityStatus: p.status,
            confirmedAt: c.confirmedAt?.toISOString().split("T")[0] ?? c.createdAt.toISOString().split("T")[0],
            expectedReturnPct: Number(p.expectedReturnPct),
            termMonths: p.termMonths,
            expectedReturn: p.expectedReturn,
            term: p.term,
            projectedReturn: projectedReturn2,
            realizedReturn,
            unrealizedReturn: Math.max(0, projectedReturn2 - realizedReturn)
          };
        });
        const totalCommitted = Number(totals?.total ?? 0);
        const totalEarned = enrichedCommitments.reduce((sum3, commitment) => {
          return sum3 + commitment.realizedReturn;
        }, 0);
        const projectedReturn = enrichedCommitments.reduce((sum3, commitment) => {
          return sum3 + commitment.projectedReturn;
        }, 0);
        const activeOpportunities = commitments.filter(
          (r) => r.p.status === "OPEN"
        ).length;
        return res.json({
          totalCommitted,
          totalEarned,
          activeOpportunities,
          projectedReturn,
          paidBack: totalCommitted + totalEarned,
          commitments: enrichedCommitments
        });
      } catch (err) {
        if (err instanceof MemberProductAccessError) {
          return res.status(err.statusCode).json({ message: err.message });
        }
        console.error("GET /lending/community/portfolio error:", err);
        return res.status(500).json({ message: "Failed to fetch Community Lending portfolio." });
      }
    });
    router8.get("/lending/lender/opportunities", requireAuth2, async (_req, res) => {
      try {
        const userId = _req.userId;
        await ensureMemberProductAccess(userId, "LENDING_LENDER");
        const [user] = await db.select().from(usersTable).where(eq(usersTable.id, userId)).limit(1);
        const lens = user ? getInvestorPackageLens({
          membershipType: user.membershipType ?? null,
          membershipStatus: user.membershipStatus ?? null,
          userRole: user.userRole ?? null,
          segment: user.segment ?? null,
          investorCategory: user.investorCategory ?? null
        }) : null;
        const userSegment = user ? normalizeInvestorSegment(
          user.segment ?? null,
          user.investorCategory ?? null
        ) : null;
        if (user?.membershipType === "INVESTOR" && lens && !lens.canInvestOneTime && !lens.canInvestCrowd) {
          return res.json({ opportunities: [] });
        }
        const pools = await db.select({
          pool: lendingOpportunitiesTable,
          templateTermsHtml: lendingTemplatesTable.termsHtml
        }).from(lendingOpportunitiesTable).leftJoin(
          lendingTemplatesTable,
          eq(lendingOpportunitiesTable.templateId, lendingTemplatesTable.id)
        ).where(
          and(
            eq(lendingOpportunitiesTable.status, "OPEN"),
            eq(lendingOpportunitiesTable.loanType, "P2P_LENDING")
          )
        ).orderBy(desc(lendingOpportunitiesTable.createdAt));
        const opportunities = pools.filter(({ pool: pool2 }) => {
          if (userSegment !== "IMPACT_INVESTOR") return true;
          const rm = String(pool2.returnModel ?? "");
          const hasFixedReturn = rm === "FIXED" || rm === "FIXED_WITH_BONUS" || rm === "FIXED_SIMPLE";
          const hasReturnPct = Number(pool2.expectedReturnPct ?? 0) > 0 && Number.isFinite(Number(pool2.expectedReturnPct));
          const hasTerm = typeof pool2.termMonths === "number" && pool2.termMonths > 0;
          return hasFixedReturn && hasReturnPct && hasTerm;
        }).map(({ pool: pool2, templateTermsHtml }) => ({
          id: String(pool2.id),
          loanType: normalizeLendingLoanType(pool2.loanType),
          title: pool2.title,
          description: pool2.description,
          termsHtml: templateTermsHtml ?? null,
          targetAmount: Number(pool2.targetAmount),
          committedAmount: Number(pool2.committedAmount),
          minCommitment: Number(pool2.minCommitment),
          expectedReturnPct: Number(pool2.expectedReturnPct),
          termMonths: pool2.termMonths,
          returnModel: pool2.returnModel,
          expectedReturn: pool2.expectedReturn,
          term: pool2.term,
          status: pool2.status.toLowerCase(),
          borrowerType: pool2.borrowerType ?? ""
        }));
        return res.json({ opportunities });
      } catch (err) {
        if (err instanceof MemberProductAccessError) {
          return res.status(err.statusCode).json({ message: err.message });
        }
        console.error("GET /lending/lender/opportunities error:", err);
        return res.status(500).json({ message: "Failed to fetch lending opportunities." });
      }
    });
    router8.post("/lending/lender/commit", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        await ensureMemberProductAccess(userId, "LENDING_LENDER");
        const [user] = await db.select().from(usersTable).where(eq(usersTable.id, userId)).limit(1);
        if (user) {
          const lens = getInvestorPackageLens({
            membershipType: user.membershipType ?? null,
            membershipStatus: user.membershipStatus ?? null,
            userRole: user.userRole ?? null,
            segment: user.segment ?? null,
            investorCategory: user.investorCategory ?? null
          });
          if (!lens.canLendingDirectLend) {
            return res.status(403).json({
              message: "Direct P2P lender commitments are not available for your investor package. WWN manages approvals and disbursements from treasury capital."
            });
          }
        }
        const { opportunityId, amount, acceptedTerms } = req.body;
        const numericAmount = Number(amount);
        if (!opportunityId || !amount || !Number.isFinite(numericAmount) || numericAmount <= 0) {
          return res.status(400).json({ message: "opportunityId and a positive amount are required." });
        }
        const lendingOpportunityId = Number(opportunityId);
        const commitment = await db.transaction(async (tx) => {
          await tx.execute(
            sql`select 1 from lending_opportunities where id = ${lendingOpportunityId} for update`
          );
          const [{ pool: pool2, templateTermsHtml }] = await tx.select({
            pool: lendingOpportunitiesTable,
            templateTermsHtml: lendingTemplatesTable.termsHtml
          }).from(lendingOpportunitiesTable).leftJoin(
            lendingTemplatesTable,
            eq(lendingOpportunitiesTable.templateId, lendingTemplatesTable.id)
          ).where(eq(lendingOpportunitiesTable.id, lendingOpportunityId));
          if (!pool2) return null;
          if (pool2.status !== "OPEN") {
            throw new Error("This opportunity is no longer accepting commitments.");
          }
          if (!isP2PLendingLoanType(pool2.loanType)) {
            throw new Error(
              "Only P2P Lending opportunities can be funded from the investor lane."
            );
          }
          const termsRequired = Boolean(templateTermsHtml) && String(templateTermsHtml).trim().length > 0;
          if (termsRequired && acceptedTerms !== true) {
            throw new Error(
              "You must accept the P2P Lending terms & conditions to commit."
            );
          }
          const minCommitment = parseMoneyAmount(pool2.minCommitment);
          if (numericAmount < minCommitment) {
            throw new Error(
              `Minimum commitment is ${formatMoneyAmount(minCommitment)} for this opportunity.`
            );
          }
          const [existingConflict] = await tx.select().from(lendingCommitmentsTable).where(
            and(
              eq(lendingCommitmentsTable.userId, userId),
              eq(lendingCommitmentsTable.opportunityId, lendingOpportunityId),
              inArray(lendingCommitmentsTable.status, [
                ...ACTIVE_COMMITMENT_STATUSES
              ])
            )
          );
          if (existingConflict) {
            throw new Error(
              "You already have an active commitment for this opportunity."
            );
          }
          const confirmedTotal = parseMoneyAmount(
            await getConfirmedPoolCommitmentTotalWith(tx, lendingOpportunityId)
          );
          const remainingCapacity = calculateRemainingPoolCapacity(
            pool2.targetAmount,
            confirmedTotal
          );
          if (numericAmount > remainingCapacity) {
            throw new Error(
              `Only ${formatMoneyAmount(remainingCapacity)} remains available in this opportunity.`
            );
          }
          const now = /* @__PURE__ */ new Date();
          const [created] = await tx.insert(lendingCommitmentsTable).values({
            userId,
            opportunityId: lendingOpportunityId,
            amount: formatMoneyAmount(numericAmount),
            status: "CONFIRMED",
            confirmedAt: now,
            statusChangedAt: now
          }).returning();
          const userWallet = await ensureWalletWith6(
            tx,
            "USER",
            userId
          );
          const walletFunds = await getWalletFundsWith2(
            tx,
            userWallet.id
          );
          if (walletFunds.availableBalance < numericAmount) {
            throw new Error("Insufficient available wallet balance.");
          }
          const masterWallet = await ensureLendingMasterWalletWith3(tx);
          const commitmentIdempotencyKey = `lending_commitment:member_confirm:${created.id}`;
          const [existingCommitmentTx] = await tx.select().from(walletTransactionsTable).where(
            eq(walletTransactionsTable.idempotencyKey, commitmentIdempotencyKey)
          );
          if (!existingCommitmentTx) {
            await tx.insert(walletTransactionsTable).values({
              type: "TOP_UP",
              idempotencyKey: commitmentIdempotencyKey,
              fromWalletId: userWallet.id,
              toWalletId: masterWallet.id,
              amount: formatMoneyAmount(numericAmount),
              metadata: {
                source: "lending_commitment_member_confirmation",
                commitmentId: created.id,
                investorId: userId,
                opportunityId: lendingOpportunityId
              }
            });
          }
          await reconcileLendingPoolCommittedAmountWith(tx, lendingOpportunityId);
          return created;
        });
        if (!commitment) {
          return res.status(404).json({ message: "Lending pool not found." });
        }
        return res.status(201).json({ commitment });
      } catch (err) {
        if (err instanceof MemberProductAccessError) {
          return res.status(err.statusCode).json({ message: err.message });
        }
        if (err instanceof Error) {
          return res.status(400).json({ message: err.message });
        }
        console.error("POST /lending/lender/commit error:", err);
        return res.status(500).json({ message: "Failed to record commitment." });
      }
    });
    router8.get("/lending/lender/portfolio", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        await ensureMemberProductAccess(userId, "LENDING_LENDER");
        const commitments = await db.select({ c: lendingCommitmentsTable, p: lendingOpportunitiesTable }).from(lendingCommitmentsTable).innerJoin(
          lendingOpportunitiesTable,
          eq(lendingCommitmentsTable.opportunityId, lendingOpportunitiesTable.id)
        ).where(eq(lendingCommitmentsTable.userId, userId)).orderBy(desc(lendingCommitmentsTable.createdAt));
        const [totals] = await db.select({ total: sum(lendingCommitmentsTable.amount) }).from(lendingCommitmentsTable).where(
          and(
            eq(lendingCommitmentsTable.userId, userId),
            eq(lendingCommitmentsTable.status, "CONFIRMED")
          )
        );
        const summaryByCommitmentId = await getLendingCommitmentReturnSummaryMapWith(
          db,
          commitments.map(({ c }) => c.id)
        );
        const enrichedCommitments = commitments.map(({ c, p }) => {
          const realizedReturn = summaryByCommitmentId.get(c.id)?.realizedReturn ?? 0;
          const projectedReturn2 = c.status === "CONFIRMED" ? calculateProjectedReturnAmount(
            c.amount,
            p.expectedReturnPct,
            p.termMonths
          ) : 0;
          return {
            id: String(c.id),
            opportunityId: String(p.id),
            loanType: normalizeLendingLoanType(p.loanType),
            opportunityTitle: p.title,
            amount: Number(c.amount),
            status: c.status,
            opportunityStatus: p.status,
            confirmedAt: c.confirmedAt?.toISOString().split("T")[0] ?? c.createdAt.toISOString().split("T")[0],
            expectedReturnPct: Number(p.expectedReturnPct),
            termMonths: p.termMonths,
            expectedReturn: p.expectedReturn,
            term: p.term,
            projectedReturn: projectedReturn2,
            realizedReturn,
            unrealizedReturn: Math.max(0, projectedReturn2 - realizedReturn)
          };
        });
        const totalCommitted = Number(totals?.total ?? 0);
        const totalEarned = enrichedCommitments.reduce((sum3, commitment) => {
          return sum3 + commitment.realizedReturn;
        }, 0);
        const projectedReturn = enrichedCommitments.reduce((sum3, commitment) => {
          return sum3 + commitment.projectedReturn;
        }, 0);
        const activeOpportunities = commitments.filter(
          (r) => r.p.status === "OPEN"
        ).length;
        return res.json({
          totalCommitted,
          totalEarned,
          activeOpportunities,
          projectedReturn,
          paidBack: totalCommitted + totalEarned,
          commitments: enrichedCommitments
        });
      } catch (err) {
        if (err instanceof MemberProductAccessError) {
          return res.status(err.statusCode).json({ message: err.message });
        }
        console.error("GET /lending/lender/portfolio error:", err);
        return res.status(500).json({ message: "Failed to fetch lending portfolio." });
      }
    });
    router8.post(
      "/member/credit-score/recalculate",
      requireAuth2,
      async (req, res) => {
        const userId = req.userId;
        try {
          const result = await updateCreditScore(userId);
          return res.json(result);
        } catch (err) {
          console.error("POST /member/credit-score/recalculate error:", err);
          return res.status(500).json({ message: "Failed to recalculate Susu Score." });
        }
      }
    );
    router8.get(
      "/member/wallets/treasury-summary",
      requireAuth2,
      async (req, res) => {
        try {
          const access = await requireTreasuryAccess(req, res);
          if (!access) return;
          const [investmentWallet, lendingMasterWallet] = await Promise.all([
            ensureInvestmentWalletWith2(db),
            ensureLendingMasterWalletWith3(db)
          ]);
          const [invBal, lmBal] = await Promise.all([
            getWalletBalanceWith4(db, investmentWallet.id),
            getWalletBalanceWith4(db, lendingMasterWallet.id)
          ]);
          return res.json({
            investmentWallet: {
              id: investmentWallet.id,
              currency: investmentWallet.currency,
              balance: invBal
            },
            lendingMasterWallet: {
              id: lendingMasterWallet.id,
              currency: lendingMasterWallet.currency,
              balance: lmBal
            }
          });
        } catch (err) {
          console.error("GET /member/wallets/treasury-summary error:", err);
          return res.status(500).json({ message: "Failed to load treasury summary." });
        }
      }
    );
    router8.post(
      "/member/wallets/treasury-transfer",
      requireAuth2,
      async (req, res) => {
        try {
          const access = await requireTreasuryAccess(req, res);
          if (!access) return;
          const parsed = external_exports.object({
            amount: external_exports.string().min(1),
            note: external_exports.string().trim().max(500).optional().nullable()
          }).safeParse(req.body ?? {});
          if (!parsed.success) {
            return res.status(400).json({ errors: parsed.error.flatten() });
          }
          const numericAmount = Number(parsed.data.amount);
          if (!Number.isFinite(numericAmount) || numericAmount <= 0 || hasMoreThanTwoDecimalPlaces(numericAmount)) {
            return res.status(400).json({ message: "Amount must be a positive monetary value." });
          }
          const result = await db.transaction(async (tx) => {
            const [investmentWallet, lendingMasterWallet] = await Promise.all([
              ensureInvestmentWalletWith2(tx),
              ensureLendingMasterWalletWith3(tx)
            ]);
            const invBalance = await getWalletBalanceWith4(
              tx,
              investmentWallet.id
            );
            if (invBalance < numericAmount) {
              throw new Error(
                "Insufficient balance in the Investment treasury wallet."
              );
            }
            const nonce = crypto.randomUUID ? crypto.randomUUID() : String(Date.now());
            const idempotencyKey = `treasury:INVESTMENT:LENDING_MASTER:${numericAmount.toFixed(
              2
            )}:${nonce}`;
            const [transferTx] = await tx.insert(walletTransactionsTable).values({
              type: "TRANSFER",
              fromWalletId: investmentWallet.id,
              toWalletId: lendingMasterWallet.id,
              amount: parsed.data.amount,
              currency: investmentWallet.currency,
              idempotencyKey,
              metadata: {
                purpose: "TREASURY_TRANSFER",
                source: "INVESTMENT_WALLET",
                destination: "LENDING_MASTER_WALLET",
                note: parsed.data.note ?? null,
                initiatedByUserId: access.userId,
                initiatedByUserRole: access.user.userRole ?? null,
                initiatedBySegment: normalizeInvestorSegment(
                  access.user.segment ?? null,
                  access.user.investorCategory ?? null
                )
              },
              createdAt: /* @__PURE__ */ new Date()
            }).returning();
            const [invBalAfter, lmBalAfter] = await Promise.all([
              getWalletBalanceWith4(tx, investmentWallet.id),
              getWalletBalanceWith4(tx, lendingMasterWallet.id)
            ]);
            return {
              transaction: transferTx,
              investmentWalletBalance: invBalAfter,
              lendingMasterWalletBalance: lmBalAfter
            };
          });
          return res.status(201).json(result);
        } catch (err) {
          if (err instanceof Error) {
            if (/Insufficient balance/i.test(err.message)) {
              return res.status(400).json({ message: err.message });
            }
          }
          console.error("POST /member/wallets/treasury-transfer error:", err);
          return res.status(500).json({ message: "Failed to complete treasury transfer." });
        }
      }
    );
    router8.get("/member/reports/board-metrics", requireAuth2, async (req, res) => {
      const userId = req.userId;
      try {
        const [user] = await db.select().from(usersTable).where(eq(usersTable.id, userId)).limit(1);
        if (!user) {
          return res.status(401).json({ message: "Authentication required." });
        }
        const lens = getInvestorPackageLens({
          membershipType: user.membershipType ?? null,
          membershipStatus: user.membershipStatus ?? null,
          userRole: user.userRole ?? null,
          segment: user.segment ?? null,
          investorCategory: user.investorCategory ?? null
        });
        if (!lens.canSeeBoardMetrics) {
          return res.status(403).json({
            message: "Board metrics are available only for Worker Owner and Admin roles."
          });
        }
        const [
          [paymentStats],
          [subscriptionStats],
          [memberStats],
          [contributionStats],
          lendingPoolStats,
          commitmentStats,
          lendingReturnStats
        ] = await Promise.all([
          db.select({
            total: sql`sum(${paymentsTable.amount}) filter (where ${paymentsTable.status} = 'COMPLETED')`,
            completedPayments: sql`count(*) filter (where ${paymentsTable.status} = 'COMPLETED')`,
            pendingPayments: sql`count(*) filter (where ${paymentsTable.status} = 'PENDING')`
          }).from(paymentsTable),
          db.select({
            total: count(),
            active: sql`count(*) filter (where ${membershipSubscriptionsTable.status} = 'ACTIVE')`
          }).from(membershipSubscriptionsTable),
          db.select({
            total: count(),
            active: sql`count(*) filter (where ${usersTable.membershipStatus} = 'ACTIVE')`,
            investorCount: sql`count(*) filter (where ${usersTable.membershipType} = 'INVESTOR')`
          }).from(usersTable),
          db.select({
            totalContributions: sum(savingsContributionsTable.amount),
            paidContributions: sql`sum(${savingsContributionsTable.amount}) filter (where ${savingsContributionsTable.status} = 'PAID')`
          }).from(savingsContributionsTable),
          db.select({
            loanType: lendingOpportunitiesTable.loanType,
            count: count()
          }).from(lendingOpportunitiesTable).groupBy(lendingOpportunitiesTable.loanType),
          db.select({
            loanType: lendingOpportunitiesTable.loanType,
            total: sum(lendingCommitmentsTable.amount)
          }).from(lendingCommitmentsTable).innerJoin(
            lendingOpportunitiesTable,
            eq(
              lendingCommitmentsTable.opportunityId,
              lendingOpportunitiesTable.id
            )
          ).where(eq(lendingCommitmentsTable.status, "CONFIRMED")).groupBy(lendingOpportunitiesTable.loanType),
          db.select({
            loanType: lendingOpportunitiesTable.loanType,
            total: sum(
              lendingOpportunityReturnAllocationsTable.allocatedReturnAmount
            )
          }).from(lendingOpportunityReturnAllocationsTable).innerJoin(
            lendingOpportunitiesTable,
            eq(
              lendingOpportunityReturnAllocationsTable.opportunityId,
              lendingOpportunitiesTable.id
            )
          ).groupBy(lendingOpportunitiesTable.loanType)
        ]);
        const lendingByType = {
          COMMUNITY_LENDING: {
            poolCount: 0,
            totalCommitted: "0",
            recognizedReturn: "0"
          },
          P2P_LENDING: {
            poolCount: 0,
            totalCommitted: "0",
            recognizedReturn: "0"
          }
        };
        for (const row of lendingPoolStats) {
          lendingByType[normalizeLendingLoanType(row.loanType)].poolCount = Number(
            row.count
          );
        }
        for (const row of commitmentStats) {
          lendingByType[normalizeLendingLoanType(row.loanType)].totalCommitted = row.total ?? "0";
        }
        for (const row of lendingReturnStats) {
          lendingByType[normalizeLendingLoanType(row.loanType)].recognizedReturn = row.total ?? "0";
        }
        const [investmentWallet, lendingMasterWallet] = await Promise.all([
          ensureInvestmentWalletWith2(db),
          ensureLendingMasterWalletWith3(db)
        ]);
        const [investmentFunds, lendingMasterFunds] = await Promise.all([
          getWalletFundsWith2(db, investmentWallet.id),
          getWalletFundsWith2(db, lendingMasterWallet.id)
        ]);
        return res.json({
          revenue: {
            ...buildPlatformRevenueSummary({
              completedPaymentTotal: paymentStats.total
            }),
            completedPayments: Number(paymentStats.completedPayments),
            pendingPayments: Number(paymentStats.pendingPayments)
          },
          subscriptions: {
            total: Number(subscriptionStats.total),
            active: Number(subscriptionStats.active)
          },
          members: {
            total: Number(memberStats.total),
            active: Number(memberStats.active),
            investorCount: Number(memberStats.investorCount)
          },
          savings: {
            totalContributions: contributionStats.totalContributions ?? "0",
            paidContributions: contributionStats.paidContributions ?? "0"
          },
          lending: {
            community: lendingByType.COMMUNITY_LENDING,
            p2p: lendingByType.P2P_LENDING
          },
          treasury: {
            investmentWallet: {
              id: String(investmentWallet.id),
              balance: String(investmentFunds.balance),
              available: String(investmentFunds.availableBalance),
              pending: String(investmentFunds.reservedBalance)
            },
            lendingMasterWallet: {
              id: String(lendingMasterWallet.id),
              balance: String(lendingMasterFunds.balance),
              available: String(lendingMasterFunds.availableBalance),
              pending: String(lendingMasterFunds.reservedBalance)
            }
          }
        });
      } catch (err) {
        if (err instanceof MemberProductAccessError) {
          return res.status(err.statusCode).json({ message: err.message });
        }
        if (err instanceof Error) {
          return res.status(400).json({ message: err.message });
        }
        console.error("GET /member/reports/board-metrics error:", err);
        return res.status(500).json({ message: "Failed to fetch board metrics." });
      }
    });
    member_default = router8;
  }
});

// src/routes/onboarding.ts
var onboarding_exports = {};
__export(onboarding_exports, {
  default: () => onboarding_default
});
var import_express9, router9, onboarding_default;
var init_onboarding = __esm({
  "src/routes/onboarding.ts"() {
    "use strict";
    import_express9 = __toESM(require_express2(), 1);
    init_src2();
    init_schema2();
    init_drizzle_orm();
    init_logger();
    router9 = (0, import_express9.Router)();
    router9.get("/onboarding/slides", async (_req, res) => {
      try {
        const slides = await db.select().from(onboardingSlidesTable).where(eq(onboardingSlidesTable.isActive, true)).orderBy(asc(onboardingSlidesTable.sortOrder));
        return res.json({ slides });
      } catch (err) {
        logger.error({ err }, "Failed to load onboarding slides");
        return res.status(500).json({ message: "Could not load onboarding slides." });
      }
    });
    onboarding_default = router9;
  }
});

// src/routes/asca.ts
var asca_exports = {};
__export(asca_exports, {
  default: () => asca_default
});
function requireAuth3(req, res, next) {
  void (async () => {
    const user = await resolveAuthenticatedUser(req.cookies?.wwn_token);
    if (!user) {
      res.status(401).json({ message: "Invalid or expired token." });
      return;
    }
    req.userId = user.id;
    req.user = user;
    next();
  })();
}
function requireNonOrganizationWorkspace(req, res) {
  const user = req.user;
  if (user?.membershipType === "ORGANIZATION") {
    res.status(403).json({
      message: "Organization ASCAs are available only in the organization workspace."
    });
    return false;
  }
  return true;
}
async function requireAscaManagementAccess(req, res) {
  const user = req.user;
  const userId = req.userId;
  if (!user) {
    res.status(401).json({ message: "Invalid or expired token." });
    return false;
  }
  if (user.userRole === "ADMIN" || user.userRole === "SUPER_ADMIN") {
    return true;
  }
  res.status(403).json({
    message: "ASCA creation and management is restricted to WWN Admins."
  });
  return false;
}
var import_express10, router10, asca_default;
var init_asca2 = __esm({
  "src/routes/asca.ts"() {
    "use strict";
    import_express10 = __toESM(require_express2(), 1);
    init_zod();
    init_src2();
    init_src2();
    init_drizzle_orm();
    init_auth_session();
    init_asca();
    router10 = (0, import_express10.Router)();
    router10.get("/", requireAuth3, async (req, res) => {
      if (!requireNonOrganizationWorkspace(req, res)) return;
      const userId = req.userId;
      try {
        const memberAscas = await db.select({
          asca: {
            id: ascasTable.id,
            name: ascasTable.name,
            description: ascasTable.description,
            termsHtml: ascasTable.termsHtml,
            organizationId: ascasTable.organizationId,
            type: ascasTable.type,
            status: ascasTable.status,
            investmentId: ascasTable.investmentId,
            escrowWalletId: ascasTable.escrowWalletId,
            targetAmount: ascasTable.targetAmount,
            currentAmount: ascasTable.currentAmount,
            fundingStartAt: ascasTable.fundingStartAt,
            fundingEndAt: ascasTable.fundingEndAt,
            constitution: ascasTable.constitution,
            createdAt: ascasTable.createdAt,
            updatedAt: ascasTable.updatedAt,
            memberCount: sql`(
            select count(*)::int from asca_members am where am.asca_id = ${ascasTable.id}
          )`,
            contributionCount: sql`(
            select count(*)::int
            from asca_members am
            where am.asca_id = ${ascasTable.id}
              and coalesce(am.contributed_amount, 0) > 0
          )`
          },
          member: ascaMembersTable
        }).from(ascaMembersTable).innerJoin(ascasTable, eq(ascaMembersTable.ascaId, ascasTable.id)).where(
          and(
            eq(ascaMembersTable.userId, userId),
            isNull(ascasTable.organizationId)
          )
        );
        res.json({ ascas: memberAscas });
      } catch (error40) {
        console.error("List ASCAs Error:", error40);
        res.status(500).json({
          message: "Failed to list ASCAs",
          error: error40.message
        });
      }
    });
    router10.get("/:id", requireAuth3, async (req, res) => {
      if (!requireNonOrganizationWorkspace(req, res)) return;
      const ascaId = parseInt(req.params.id, 10);
      if (isNaN(ascaId)) {
        res.status(400).json({ message: "Invalid ASCA ID" });
        return;
      }
      try {
        const [asca] = await db.select().from(ascasTable).where(eq(ascasTable.id, ascaId));
        if (!asca) {
          res.status(404).json({ message: "ASCA not found" });
          return;
        }
        if (asca.organizationId !== null && asca.organizationId !== void 0) {
          res.status(404).json({ message: "ASCA not found" });
          return;
        }
        const members = await db.select({
          id: ascaMembersTable.id,
          ascaId: ascaMembersTable.ascaId,
          userId: ascaMembersTable.userId,
          targetContribution: ascaMembersTable.targetContribution,
          contributedAmount: ascaMembersTable.contributedAmount,
          status: ascaMembersTable.status,
          joinedAt: ascaMembersTable.joinedAt,
          firstName: usersTable.firstName,
          lastName: usersTable.lastName
        }).from(ascaMembersTable).innerJoin(usersTable, eq(ascaMembersTable.userId, usersTable.id)).where(eq(ascaMembersTable.ascaId, ascaId)).orderBy(desc(ascaMembersTable.contributedAmount));
        res.json({ asca, members });
      } catch (error40) {
        res.status(500).json({ message: "Failed to load ASCA details", error: error40 });
      }
    });
    router10.post("/", requireAuth3, async (req, res) => {
      if (!requireNonOrganizationWorkspace(req, res)) return;
      const userId = req.userId;
      try {
        const allowed = await requireAscaManagementAccess(req, res);
        if (!allowed) return;
        const parsed = CreateAscaSchema.safeParse(req.body);
        if (!parsed.success) {
          res.status(400).json({ errors: parsed.error.flatten() });
          return;
        }
        const asca = await createAsca(parsed.data, userId, {
          organizationId: null
        });
        res.status(201).json({ message: "ASCA created successfully", asca });
      } catch (error40) {
        if (error40 instanceof Error) {
          res.status(400).json({ message: error40.message });
          return;
        }
        res.status(500).json({ message: "Failed to create ASCA" });
      }
    });
    router10.post("/:id/publish", requireAuth3, async (req, res) => {
      if (!requireNonOrganizationWorkspace(req, res)) return;
      const ascaId = parseInt(req.params.id, 10);
      if (isNaN(ascaId)) {
        res.status(400).json({ message: "Invalid ASCA ID" });
        return;
      }
      try {
        const [ascaRow] = await db.select({ organizationId: ascasTable.organizationId }).from(ascasTable).where(eq(ascasTable.id, ascaId));
        if (!ascaRow || ascaRow.organizationId !== null) {
          res.status(404).json({ message: "ASCA not found" });
          return;
        }
        const allowed = await requireAscaManagementAccess(req, res);
        if (!allowed) return;
        const asca = await publishAsca(ascaId, { organizationId: null });
        res.json({ message: "ASCA published successfully", asca });
      } catch (error40) {
        res.status(400).json({ message: error40.message });
      }
    });
    router10.post("/:id/unpublish", requireAuth3, async (req, res) => {
      if (!requireNonOrganizationWorkspace(req, res)) return;
      const ascaId = parseInt(req.params.id, 10);
      if (isNaN(ascaId)) {
        res.status(400).json({ message: "Invalid ASCA ID" });
        return;
      }
      try {
        const [ascaRow] = await db.select({ organizationId: ascasTable.organizationId }).from(ascasTable).where(eq(ascasTable.id, ascaId));
        if (!ascaRow || ascaRow.organizationId !== null) {
          res.status(404).json({ message: "ASCA not found" });
          return;
        }
        const allowed = await requireAscaManagementAccess(req, res);
        if (!allowed) return;
        const asca = await unpublishAsca(ascaId, { organizationId: null });
        res.json({ message: "ASCA unpublished successfully", asca });
      } catch (error40) {
        res.status(400).json({ message: error40.message });
      }
    });
    router10.post("/:id/join", requireAuth3, async (req, res) => {
      if (!requireNonOrganizationWorkspace(req, res)) return;
      const userId = req.userId;
      const ascaId = parseInt(req.params.id, 10);
      if (isNaN(ascaId)) {
        res.status(400).json({ message: "Invalid ASCA ID" });
        return;
      }
      const bodySchema = external_exports.object({
        targetContribution: external_exports.string().optional(),
        catchUpAmount: external_exports.number().optional(),
        acceptedTerms: external_exports.boolean().optional()
      }).strict();
      const parsed = bodySchema.safeParse(req.body ?? {});
      if (!parsed.success) {
        res.status(400).json({ errors: parsed.error.flatten() });
        return;
      }
      try {
        const [asca] = await db.select({
          termsHtml: ascasTable.termsHtml,
          organizationId: ascasTable.organizationId
        }).from(ascasTable).where(eq(ascasTable.id, ascaId));
        if (!asca || asca.organizationId !== null) {
          res.status(404).json({ message: "ASCA not found" });
          return;
        }
        const termsRequired = Boolean(asca?.termsHtml) && String(asca?.termsHtml).trim().length > 0;
        if (termsRequired && parsed.data.acceptedTerms !== true) {
          res.status(400).json({
            message: "You must accept the ASCA terms & conditions to join."
          });
          return;
        }
        const member = await joinAsca(ascaId, userId, {
          targetContribution: parsed.data.targetContribution,
          catchUpAmount: parsed.data.catchUpAmount
        });
        res.json({ message: "Successfully joined ASCA", member });
      } catch (error40) {
        if (error40 instanceof AscaCatchUpRequiredError) {
          res.status(400).json({
            message: error40.message,
            code: "ASCA_CATCH_UP_REQUIRED",
            requiredCatchUpAmount: error40.requiredCatchUpAmount
          });
          return;
        }
        res.status(400).json({ message: error40.message });
      }
    });
    router10.post("/:id/contribute", requireAuth3, async (req, res) => {
      if (!requireNonOrganizationWorkspace(req, res)) return;
      const userId = req.userId;
      const ascaId = parseInt(req.params.id, 10);
      if (isNaN(ascaId)) {
        res.status(400).json({ message: "Invalid ASCA ID" });
        return;
      }
      const { amount } = req.body;
      if (typeof amount !== "number" || amount <= 0) {
        res.status(400).json({ message: "Valid positive amount is required" });
        return;
      }
      try {
        const [asca] = await db.select({ organizationId: ascasTable.organizationId }).from(ascasTable).where(eq(ascasTable.id, ascaId));
        if (!asca || asca.organizationId !== null) {
          res.status(404).json({ message: "ASCA not found" });
          return;
        }
        const contribution = await contributeToAsca(ascaId, userId, amount);
        res.json({ message: "Contribution successful", contribution });
      } catch (error40) {
        res.status(400).json({ message: error40.message });
      }
    });
    router10.post("/:id/cancel", requireAuth3, async (req, res) => {
      if (!requireNonOrganizationWorkspace(req, res)) return;
      const userId = req.userId;
      const ascaId = parseInt(req.params.id, 10);
      if (isNaN(ascaId)) {
        res.status(400).json({ message: "Invalid ASCA ID" });
        return;
      }
      try {
        const [asca] = await db.select({ organizationId: ascasTable.organizationId }).from(ascasTable).where(eq(ascasTable.id, ascaId));
        if (!asca || asca.organizationId !== null) {
          res.status(404).json({ message: "ASCA not found" });
          return;
        }
        const allowed = await requireAscaManagementAccess(req, res);
        if (!allowed) return;
        await cancelAsca(ascaId, userId);
        res.json({ message: "ASCA cancelled and funds refunded successfully" });
      } catch (error40) {
        res.status(400).json({ message: error40.message });
      }
    });
    router10.post("/:id/withdraw", requireAuth3, async (req, res) => {
      if (!requireNonOrganizationWorkspace(req, res)) return;
      const userId = req.userId;
      const ascaId = parseInt(req.params.id, 10);
      if (isNaN(ascaId)) {
        res.status(400).json({ message: "Invalid ASCA ID" });
        return;
      }
      try {
        const [asca] = await db.select({ organizationId: ascasTable.organizationId }).from(ascasTable).where(eq(ascasTable.id, ascaId));
        if (!asca || asca.organizationId !== null) {
          res.status(404).json({ message: "ASCA not found" });
          return;
        }
        const allowed = await requireAscaManagementAccess(req, res);
        if (!allowed) return;
        await withdrawAsca(ascaId, userId);
        res.json({ message: "ASCA withdrawn successfully" });
      } catch (error40) {
        res.status(400).json({ message: error40.message });
      }
    });
    router10.post("/:id/withdraw-offline", requireAuth3, async (req, res) => {
      if (!requireNonOrganizationWorkspace(req, res)) return;
      const userId = req.userId;
      const ascaId = parseInt(req.params.id, 10);
      if (isNaN(ascaId)) {
        res.status(400).json({ message: "Invalid ASCA ID" });
        return;
      }
      try {
        const [asca] = await db.select({ organizationId: ascasTable.organizationId }).from(ascasTable).where(eq(ascasTable.id, ascaId));
        if (!asca || asca.organizationId !== null) {
          res.status(404).json({ message: "ASCA not found" });
          return;
        }
        const allowed = await requireAscaManagementAccess(req, res);
        if (!allowed) return;
        await withdrawAscaOffline(ascaId, userId);
        res.json({ message: "ASCA withdrawn offline successfully" });
      } catch (error40) {
        res.status(400).json({ message: error40.message });
      }
    });
    router10.post("/:id/invest", requireAuth3, async (req, res) => {
      if (!requireNonOrganizationWorkspace(req, res)) return;
      const userId = req.userId;
      const ascaId = parseInt(req.params.id, 10);
      if (isNaN(ascaId)) {
        res.status(400).json({ message: "Invalid ASCA ID" });
        return;
      }
      const { investmentId } = req.body;
      if (!investmentId) {
        res.status(400).json({ message: "investmentId is required" });
        return;
      }
      try {
        const [asca] = await db.select({ organizationId: ascasTable.organizationId }).from(ascasTable).where(eq(ascasTable.id, ascaId));
        if (!asca || asca.organizationId !== null) {
          res.status(404).json({ message: "ASCA not found" });
          return;
        }
        const allowed = await requireAscaManagementAccess(req, res);
        if (!allowed) return;
        await convertAscaToInvestment(ascaId, Number(investmentId), userId);
        res.json({ message: "ASCA successfully converted to investment" });
      } catch (error40) {
        res.status(400).json({ message: error40.message });
      }
    });
    router10.get("/public/discover", requireAuth3, async (req, res) => {
      if (!requireNonOrganizationWorkspace(req, res)) return;
      try {
        const now = /* @__PURE__ */ new Date();
        const publicAscas = await db.select({
          id: ascasTable.id,
          name: ascasTable.name,
          description: ascasTable.description,
          termsHtml: ascasTable.termsHtml,
          organizationId: ascasTable.organizationId,
          type: ascasTable.type,
          status: ascasTable.status,
          investmentId: ascasTable.investmentId,
          escrowWalletId: ascasTable.escrowWalletId,
          targetAmount: ascasTable.targetAmount,
          currentAmount: ascasTable.currentAmount,
          fundingStartAt: ascasTable.fundingStartAt,
          fundingEndAt: ascasTable.fundingEndAt,
          constitution: ascasTable.constitution,
          createdAt: ascasTable.createdAt,
          updatedAt: ascasTable.updatedAt,
          memberCount: sql`(
          select count(*)::int from asca_members am where am.asca_id = ${ascasTable.id}
        )`,
          contributionCount: sql`(
          select count(*)::int
          from asca_members am
          where am.asca_id = ${ascasTable.id}
            and coalesce(am.contributed_amount, 0) > 0
        )`
        }).from(ascasTable).where(
          and(
            eq(ascasTable.status, "FUNDING"),
            isNull(ascasTable.organizationId),
            or(
              isNull(ascasTable.fundingEndAt),
              gte(ascasTable.fundingEndAt, now)
            )
          )
        );
        res.json({ ascas: publicAscas });
      } catch (error40) {
        console.error("Discover ASCAs Error:", error40);
        res.status(500).json({
          message: "Failed to load discoverable ASCAs",
          error: error40.message
        });
      }
    });
    asca_default = router10;
  }
});

// src/routes/community.ts
var community_exports = {};
__export(community_exports, {
  default: () => community_default
});
function requireAuth4(req, res, next) {
  void (async () => {
    try {
      const user = await resolveAuthenticatedUser(req.cookies?.wwn_token);
      if (!user) {
        res.status(401).json({ message: "Unauthorized" });
        return;
      }
      req.user = user;
      req.userId = user.id;
      next();
    } catch (err) {
      handleError5(err, res);
    }
  })();
}
function handleError5(err, res) {
  if (err?.status && err?.message) {
    return res.status(err.status).json({ message: err.message });
  }
  console.error("Community API Error:", err);
  return res.status(500).json({ message: "Internal server error" });
}
var import_express11, router11, community_default;
var init_community = __esm({
  "src/routes/community.ts"() {
    "use strict";
    import_express11 = __toESM(require_express2(), 1);
    init_src2();
    init_schema2();
    init_drizzle_orm();
    init_auth_session();
    router11 = (0, import_express11.Router)();
    router11.get("/feed", requireAuth4, async (req, res) => {
      try {
        const user = req.user;
        const isInvestor = user.tier !== "INDIVIDUAL";
        const adminStoryFilter = and(
          eq(communityPostsTable.postType, "ADMIN_STORY"),
          eq(communityPostsTable.isPublished, true),
          or(
            eq(communityPostsTable.showToIndividuals, true),
            isInvestor ? eq(communityPostsTable.showToInvestors, true) : void 0
          )
        );
        const feedFilter = or(
          adminStoryFilter,
          eq(communityPostsTable.postType, "USER_UPDATE"),
          eq(communityPostsTable.postType, "MILESTONE")
        );
        const posts = await db.select().from(communityPostsTable).where(feedFilter).orderBy(desc(communityPostsTable.createdAt)).limit(50);
        return res.json({ posts });
      } catch (err) {
        return handleError5(err, res);
      }
    });
    router11.get("/stories/:slug", requireAuth4, async (req, res) => {
      try {
        const slug = req.params.slug;
        const [story] = await db.select().from(communityPostsTable).where(
          and(
            eq(communityPostsTable.postType, "ADMIN_STORY"),
            eq(communityPostsTable.slug, slug),
            eq(communityPostsTable.isPublished, true)
          )
        );
        if (!story) return res.status(404).json({ message: "Story not found" });
        return res.json({ story });
      } catch (err) {
        return handleError5(err, res);
      }
    });
    community_default = router11;
  }
});

// src/routes/messages.ts
var messages_exports = {};
__export(messages_exports, {
  default: () => messages_default
});
function requireAuth5(req, res, next) {
  void (async () => {
    try {
      const user = await resolveAuthenticatedUser(req.cookies?.wwn_token);
      if (!user) {
        res.status(401).json({ message: "Unauthorized" });
        return;
      }
      req.user = user;
      req.session = { userId: user.id };
      next();
    } catch (error40) {
      res.status(500).json({ message: "Internal server error" });
    }
  })();
}
var import_express12, router12, messages_default;
var init_messages = __esm({
  "src/routes/messages.ts"() {
    "use strict";
    import_express12 = __toESM(require_express2(), 1);
    init_auth_session();
    init_src2();
    init_schema2();
    init_drizzle_orm();
    router12 = (0, import_express12.Router)();
    router12.use(requireAuth5);
    router12.get("/threads", async (req, res) => {
      try {
        const userId = req.user.id;
        const participants = await db.select().from(messageThreadParticipantsTable).where(eq(messageThreadParticipantsTable.userId, userId));
        if (participants.length === 0) {
          res.json({ threads: [] });
          return;
        }
        const threadIds = participants.map((p) => p.threadId);
        const threads = await db.select({
          id: messageThreadsTable.id,
          isGroup: messageThreadsTable.isGroup,
          name: messageThreadsTable.name,
          ascaId: messageThreadsTable.ascaId,
          updatedAt: messageThreadsTable.updatedAt
        }).from(messageThreadsTable).where(inArray(messageThreadsTable.id, threadIds)).orderBy(desc(messageThreadsTable.updatedAt));
        res.json({ threads });
      } catch (error40) {
        console.error("Error fetching message threads:", error40);
        res.status(500).json({ message: "Internal server error" });
      }
    });
    router12.post("/threads/dm", async (req, res) => {
      try {
        const userId = req.user.id;
        const { targetUserId } = req.body;
        if (!targetUserId) {
          res.status(400).json({ message: "targetUserId is required" });
          return;
        }
        const myThreads = await db.select({ threadId: messageThreadParticipantsTable.threadId }).from(messageThreadParticipantsTable).where(eq(messageThreadParticipantsTable.userId, userId));
        if (myThreads.length > 0) {
          const myThreadIds = myThreads.map((t) => t.threadId);
          const targetThreads = await db.select({ threadId: messageThreadParticipantsTable.threadId }).from(messageThreadParticipantsTable).where(
            and(
              eq(messageThreadParticipantsTable.userId, targetUserId),
              inArray(messageThreadParticipantsTable.threadId, myThreadIds)
            )
          );
          if (targetThreads.length > 0) {
            const commonThreadIds = targetThreads.map((t) => t.threadId);
            const existingDm = await db.select().from(messageThreadsTable).where(
              and(
                inArray(messageThreadsTable.id, commonThreadIds),
                eq(messageThreadsTable.isGroup, false)
              )
            ).limit(1);
            if (existingDm.length > 0) {
              res.json({ thread: existingDm[0] });
              return;
            }
          }
        }
        const [newThread] = await db.insert(messageThreadsTable).values({ isGroup: false }).returning();
        await db.insert(messageThreadParticipantsTable).values([
          { threadId: newThread.id, userId },
          { threadId: newThread.id, userId: targetUserId }
        ]);
        res.status(201).json({ thread: newThread });
      } catch (error40) {
        console.error("Error creating DM thread:", error40);
        res.status(500).json({ message: "Internal server error" });
      }
    });
    router12.get("/threads/:threadId/messages", async (req, res) => {
      try {
        const userId = req.user.id;
        const threadId = parseInt(req.params.threadId, 10);
        const participant = await db.select().from(messageThreadParticipantsTable).where(
          and(
            eq(messageThreadParticipantsTable.threadId, threadId),
            eq(messageThreadParticipantsTable.userId, userId)
          )
        ).limit(1);
        if (participant.length === 0) {
          res.status(403).json({ message: "Not a participant of this thread" });
          return;
        }
        const messages = await db.select({
          id: directMessagesTable.id,
          content: directMessagesTable.content,
          senderId: directMessagesTable.senderId,
          createdAt: directMessagesTable.createdAt,
          sender: {
            firstName: usersTable.firstName,
            lastName: usersTable.lastName,
            avatarUrl: usersTable.avatarUrl
          }
        }).from(directMessagesTable).leftJoin(usersTable, eq(directMessagesTable.senderId, usersTable.id)).where(eq(directMessagesTable.threadId, threadId)).orderBy(desc(directMessagesTable.createdAt)).limit(50);
        res.json({ messages: messages.reverse() });
      } catch (error40) {
        console.error("Error fetching messages:", error40);
        res.status(500).json({ message: "Internal server error" });
      }
    });
    router12.post("/threads/:threadId/messages", async (req, res) => {
      try {
        const userId = req.user.id;
        const threadId = parseInt(req.params.threadId, 10);
        const { content } = req.body;
        if (!content) {
          res.status(400).json({ message: "Content is required" });
          return;
        }
        const participant = await db.select().from(messageThreadParticipantsTable).where(
          and(
            eq(messageThreadParticipantsTable.threadId, threadId),
            eq(messageThreadParticipantsTable.userId, userId)
          )
        ).limit(1);
        if (participant.length === 0) {
          res.status(403).json({ message: "Not a participant of this thread" });
          return;
        }
        const [newMessage] = await db.insert(directMessagesTable).values({
          threadId,
          senderId: userId,
          content
        }).returning();
        await db.update(messageThreadsTable).set({ updatedAt: /* @__PURE__ */ new Date() }).where(eq(messageThreadsTable.id, threadId));
        res.status(201).json({ message: newMessage });
      } catch (error40) {
        console.error("Error sending message:", error40);
        res.status(500).json({ message: "Internal server error" });
      }
    });
    messages_default = router12;
  }
});

// src/routes/forums.ts
var forums_exports = {};
__export(forums_exports, {
  default: () => forums_default
});
function requireAuth6(req, res, next) {
  void (async () => {
    try {
      const user = await resolveAuthenticatedUser(req.cookies?.wwn_token);
      if (!user) {
        res.status(401).json({ message: "Unauthorized" });
        return;
      }
      req.user = user;
      req.session = { userId: user.id };
      next();
    } catch (error40) {
      res.status(500).json({ message: "Internal server error" });
    }
  })();
}
var import_express13, router13, forums_default;
var init_forums = __esm({
  "src/routes/forums.ts"() {
    "use strict";
    import_express13 = __toESM(require_express2(), 1);
    init_auth_session();
    init_src2();
    init_schema2();
    init_drizzle_orm();
    router13 = (0, import_express13.Router)();
    router13.use(requireAuth6);
    router13.get("/", async (req, res) => {
      try {
        const forums = await db.select().from(communityForumsTable).orderBy(communityForumsTable.sortOrder);
        res.json({ forums });
      } catch (error40) {
        console.error("Error fetching forums:", error40);
        res.status(500).json({ message: "Internal server error" });
      }
    });
    router13.get("/:forumId/threads", async (req, res) => {
      try {
        const forumId = parseInt(req.params.forumId, 10);
        const threads = await db.select({
          id: forumThreadsTable.id,
          title: forumThreadsTable.title,
          slug: forumThreadsTable.slug,
          isPinned: forumThreadsTable.isPinned,
          isLocked: forumThreadsTable.isLocked,
          viewCount: forumThreadsTable.viewCount,
          lastActivityAt: forumThreadsTable.lastActivityAt,
          author: {
            firstName: usersTable.firstName,
            lastName: usersTable.lastName,
            avatarUrl: usersTable.avatarUrl
          }
        }).from(forumThreadsTable).leftJoin(usersTable, eq(forumThreadsTable.authorId, usersTable.id)).where(eq(forumThreadsTable.forumId, forumId)).orderBy(
          desc(forumThreadsTable.isPinned),
          desc(forumThreadsTable.lastActivityAt)
        );
        res.json({ threads });
      } catch (error40) {
        console.error("Error fetching forum threads:", error40);
        res.status(500).json({ message: "Internal server error" });
      }
    });
    router13.post("/:forumId/threads", async (req, res) => {
      try {
        const userId = req.user.id;
        const forumId = parseInt(req.params.forumId, 10);
        const { title, contentHtml } = req.body;
        if (!title || !contentHtml) {
          res.status(400).json({ message: "Title and content are required" });
          return;
        }
        const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, "-") + "-" + Date.now();
        const [newThread] = await db.insert(forumThreadsTable).values({
          forumId,
          authorId: userId,
          title,
          slug,
          contentHtml
        }).returning();
        res.status(201).json({ thread: newThread });
      } catch (error40) {
        console.error("Error creating thread:", error40);
        res.status(500).json({ message: "Internal server error" });
      }
    });
    forums_default = router13;
  }
});

// src/routes/gamification.ts
var gamification_exports = {};
__export(gamification_exports, {
  default: () => gamification_default
});
function requireAdminAuth(req, res, next) {
  void (async () => {
    try {
      const user = await resolveAuthenticatedUser(req.cookies?.wwn_token);
      if (!user) {
        res.status(401).json({ message: "Unauthorized" });
        return;
      }
      if (user.userRole !== "ADMIN" && user.userRole !== "SUPER_ADMIN") {
        res.status(403).json({ message: "Forbidden. Admin access required." });
        return;
      }
      req.user = user;
      next();
    } catch (err) {
      handleError6(err, res);
    }
  })();
}
function handleError6(err, res) {
  if (err?.status && err?.message) {
    return res.status(err.status).json({ message: err.message });
  }
  console.error("Gamification API Error:", err);
  return res.status(500).json({ message: "Internal server error" });
}
var import_express14, router14, awardBadgeSchema, gamification_default;
var init_gamification = __esm({
  "src/routes/gamification.ts"() {
    "use strict";
    import_express14 = __toESM(require_express2(), 1);
    init_src2();
    init_schema2();
    init_drizzle_orm();
    init_zod();
    init_auth_session();
    router14 = (0, import_express14.Router)();
    awardBadgeSchema = external_exports.object({
      userId: external_exports.number(),
      badge: external_exports.string(),
      reason: external_exports.string().optional()
    });
    router14.post("/award-badge", requireAdminAuth, async (req, res) => {
      try {
        const { userId, badge, reason } = awardBadgeSchema.parse(req.body);
        let [profile] = await db.select().from(communityProfilesTable).where(eq(communityProfilesTable.userId, userId));
        if (!profile) {
          [profile] = await db.insert(communityProfilesTable).values({
            userId,
            badges: [badge]
          }).returning();
        } else {
          const currentBadges = profile.badges || [];
          if (!currentBadges.includes(badge)) {
            [profile] = await db.update(communityProfilesTable).set({ badges: [...currentBadges, badge], updatedAt: /* @__PURE__ */ new Date() }).where(eq(communityProfilesTable.id, profile.id)).returning();
          }
        }
        const [user] = await db.select().from(usersTable).where(eq(usersTable.id, userId));
        const userName = user ? `${user.firstName} ${user.lastName}` : "A member";
        await db.insert(communityPostsTable).values({
          postType: "MILESTONE",
          authorId: userId,
          title: "New Badge Earned! \u{1F3C6}",
          contentHtml: `<p><strong>${userName}</strong> just earned the <strong>${badge}</strong> badge!</p>${reason ? `<p><em>"${reason}"</em></p>` : ""}`,
          isPublished: true,
          publishedAt: /* @__PURE__ */ new Date()
        });
        return res.json({ profile });
      } catch (err) {
        return handleError6(err, res);
      }
    });
    gamification_default = router14;
  }
});

// src/routes/index.ts
var import_express15, router15, routes_default;
var init_routes = __esm({
  async "src/routes/index.ts"() {
    "use strict";
    import_express15 = __toESM(require_express2(), 1);
    init_health();
    init_logger();
    router15 = (0, import_express15.Router)();
    router15.use(health_default);
    if (process.env.DATABASE_URL) {
      const [
        { default: authRouter },
        { default: adminRouter },
        { default: adminAscaRouter },
        { default: orgRouter },
        { default: plansRouter },
        { default: paymentsRouter },
        { default: memberRouter },
        { default: onboardingRouter },
        { default: ascaRouter },
        { default: communityRouter },
        { default: messagesRouter },
        { default: forumsRouter },
        { default: gamificationRouter }
      ] = await Promise.all([
        Promise.resolve().then(() => (init_auth(), auth_exports)),
        Promise.resolve().then(() => (init_admin(), admin_exports)),
        Promise.resolve().then(() => (init_admin_asca(), admin_asca_exports)),
        Promise.resolve().then(() => (init_org(), org_exports)),
        Promise.resolve().then(() => (init_plans(), plans_exports)),
        Promise.resolve().then(() => (init_payments(), payments_exports)),
        Promise.resolve().then(() => (init_member(), member_exports)),
        Promise.resolve().then(() => (init_onboarding(), onboarding_exports)),
        Promise.resolve().then(() => (init_asca2(), asca_exports)),
        Promise.resolve().then(() => (init_community(), community_exports)),
        Promise.resolve().then(() => (init_messages(), messages_exports)),
        Promise.resolve().then(() => (init_forums(), forums_exports)),
        Promise.resolve().then(() => (init_gamification(), gamification_exports))
      ]);
      router15.use("/auth", authRouter);
      router15.use("/admin", adminRouter);
      router15.use("/admin", adminAscaRouter);
      router15.use(orgRouter);
      router15.use(paymentsRouter);
      router15.use(plansRouter);
      router15.use(memberRouter);
      router15.use(onboardingRouter);
      router15.use("/member/asca", ascaRouter);
      router15.use("/community", communityRouter);
      router15.use("/messages", messagesRouter);
      router15.use("/forums", forumsRouter);
      router15.use("/gamification", gamificationRouter);
    } else {
      logger.warn(
        "DATABASE_URL is not set; API routes are disabled except /api/healthz"
      );
      router15.use((_req, res) => {
        return res.status(503).json({
          message: "API is not configured. Set DATABASE_URL to enable the full API. Health is available at /api/healthz."
        });
      });
    }
    routes_default = router15;
  }
});

// src/app.ts
var app_exports = {};
__export(app_exports, {
  default: () => app_default
});
var import_express16, import_cors, import_cookie_parser, import_pino_http, app, nodeEnv3, apiLimiter, app_default;
var init_app = __esm({
  async "src/app.ts"() {
    "use strict";
    import_express16 = __toESM(require_express2(), 1);
    import_cors = __toESM(require_lib3(), 1);
    import_cookie_parser = __toESM(require_cookie_parser(), 1);
    import_pino_http = __toESM(require_logger(), 1);
    init_helmet();
    init_dist();
    await init_routes();
    init_logger();
    init_config();
    app = (0, import_express16.default)();
    nodeEnv3 = process.env.NODE_ENV ?? "development";
    app.set("trust proxy", TRUST_PROXY);
    app.use(helmet());
    apiLimiter = rate_limit_default({
      windowMs: 15 * 60 * 1e3,
      // 15 minutes
      max: nodeEnv3 === "production" ? 100 : 1e4,
      standardHeaders: true,
      legacyHeaders: false,
      skip(req) {
        return req.path === "/healthz";
      }
    });
    app.use("/api", apiLimiter);
    app.use(
      (0, import_pino_http.default)({
        logger,
        serializers: {
          req(req) {
            return {
              id: req.id,
              method: req.method,
              url: req.url?.split("?")[0]
            };
          },
          res(res) {
            return {
              statusCode: res.statusCode
            };
          }
        }
      })
    );
    app.use(
      (0, import_cors.default)({
        origin: nodeEnv3 !== "production" && !process.env.CORS_ORIGIN ? true : CORS_ORIGIN,
        credentials: true
      })
    );
    app.use((0, import_cookie_parser.default)());
    app.use(
      "/api/payments/webhooks/stripe",
      import_express16.default.raw({ type: "application/json" })
    );
    app.use(import_express16.default.json());
    app.use(import_express16.default.urlencoded({ extended: true }));
    app.use("/api", routes_default);
    app_default = app;
  }
});

// src/lib/investment-return-scheduler.ts
async function runTasksWithConcurrencyLimit(tasks, limit) {
  if (tasks.length === 0) return;
  const running = /* @__PURE__ */ new Set();
  for (const task of tasks) {
    const promise2 = task().finally(() => {
      running.delete(promise2);
    });
    running.add(promise2);
    if (running.size >= limit) {
      await Promise.race(running);
    }
  }
  await Promise.all(running);
}
async function runWithSchedulerLock(work) {
  const client = await pool.connect();
  try {
    const lockResult = await client.query(
      "select pg_try_advisory_lock($1, $2) as acquired",
      [INVESTMENT_RETURN_SCHEDULER_LOCK_KEY_A, INVESTMENT_RETURN_SCHEDULER_LOCK_KEY_B]
    );
    const acquired = lockResult.rows[0]?.acquired === true;
    if (!acquired) return { acquired: false };
    try {
      return { acquired: true, value: await work() };
    } finally {
      await client.query("select pg_advisory_unlock($1, $2)", [
        INVESTMENT_RETURN_SCHEDULER_LOCK_KEY_A,
        INVESTMENT_RETURN_SCHEDULER_LOCK_KEY_B
      ]);
    }
  } finally {
    client.release();
  }
}
async function processDueInvestmentReturnPayouts() {
  const now = /* @__PURE__ */ new Date();
  const dueInterestIds = await listDueInvestmentReturnInterestIdsWith(db, now);
  const summary = {
    dueInterests: dueInterestIds.length,
    paidInterests: 0,
    totalPaid: 0,
    insufficientBalanceSkips: 0,
    noPayableAmountSkips: 0,
    errors: 0
  };
  const notificationTasks = [];
  for (const interestId of dueInterestIds) {
    try {
      const result = await db.transaction(
        async (tx) => payoutInvestmentReturnWith(tx, {
          interestId,
          source: "AUTO_MATURITY",
          asOf: now
        })
      );
      summary.paidInterests += 1;
      summary.totalPaid += result.amountPaid;
      const pushTitle = result.principalAmountPaid > 0 && result.returnAmountPaid > 0 ? "Investment principal and return paid" : result.principalAmountPaid > 0 ? "Investment principal paid" : "Investment return paid";
      const pushBody = result.principalAmountPaid > 0 && result.returnAmountPaid > 0 ? "Your investment principal and return have been credited to your wallet." : result.principalAmountPaid > 0 ? "Your investment principal has been credited to your wallet." : "Your investment return has been credited to your wallet.";
      notificationTasks.push(async () => {
        const userId = result.snapshot.userId;
        const walletTransactionId = result.walletTransactionId;
        if (!walletTransactionId) return;
        const key = `investment_return_paid:${walletTransactionId}:push`;
        const reserved = await reserveNotificationDeliveryWith(db, {
          userId,
          channel: "PUSH",
          category: "INVESTMENT",
          idempotencyKey: key,
          status: "SKIPPED",
          provider: null,
          metadata: {
            kind: "investment_return_paid",
            interestId,
            walletTransactionId,
            source: "AUTO_MATURITY"
          }
        });
        if (!reserved.reserved) return;
        try {
          const pushResult = await deliverPushIfEnabled({
            userId,
            category: "INVESTMENT",
            title: pushTitle,
            body: pushBody,
            data: { actionHref: "/dashboard/investments" }
          });
          await finalizeNotificationDeliveryWith(db, {
            idempotencyKey: key,
            status: pushResult.status,
            provider: pushResult.status === "SENT" ? "EXPO" : null,
            errorMessage: pushResult.reason ?? null,
            notificationId: null,
            metadata: {
              kind: "investment_return_paid",
              reason: pushResult.reason ?? null,
              interestId,
              walletTransactionId,
              source: "AUTO_MATURITY"
            }
          });
        } catch (err) {
          await finalizeNotificationDeliveryWith(db, {
            idempotencyKey: key,
            status: "FAILED",
            provider: "EXPO",
            errorMessage: err instanceof Error ? err.message : String(err),
            notificationId: null,
            metadata: {
              kind: "investment_return_paid",
              interestId,
              walletTransactionId,
              source: "AUTO_MATURITY"
            }
          });
        }
      });
    } catch (error40) {
      if (error40 instanceof Error) {
        if (error40.message.includes("enough balance")) {
          summary.insufficientBalanceSkips += 1;
          continue;
        }
        if (error40.message.includes("No unpaid investment payout")) {
          summary.noPayableAmountSkips += 1;
          continue;
        }
      }
      summary.errors += 1;
      logger.error(
        { err: error40, interestId },
        "Automatic investment return payout failed for a matured investment."
      );
    }
  }
  await runTasksWithConcurrencyLimit(notificationTasks, 3);
  summary.totalPaid = Number(summary.totalPaid.toFixed(2));
  return summary;
}
function startInvestmentReturnScheduler() {
  if (!ENABLE_INVESTMENT_RETURN_SCHEDULER) {
    logger.info("Investment return scheduler is disabled by configuration.");
    return { stop() {
    } };
  }
  let intervalHandle = null;
  let startupHandle = null;
  let shutdownRequested = false;
  let runInFlight = false;
  const runTick = async (reason) => {
    if (shutdownRequested || runInFlight) return;
    runInFlight = true;
    const startedAt = Date.now();
    try {
      const result = await runWithSchedulerLock(
        () => processDueInvestmentReturnPayouts()
      );
      if (!result.acquired) {
        logger.debug(
          { reason },
          "Skipped investment return scheduler tick because another worker holds the advisory lock."
        );
        return;
      }
      const durationMs = Date.now() - startedAt;
      const summary = result.value;
      const hasWork = summary.dueInterests > 0 || summary.paidInterests > 0 || summary.totalPaid > 0 || summary.insufficientBalanceSkips > 0 || summary.errors > 0;
      if (hasWork || reason === "startup") {
        logger.info(
          { reason, durationMs, ...summary },
          "Investment return scheduler tick completed."
        );
      } else {
        logger.debug(
          { reason, durationMs, ...summary },
          "Investment return scheduler tick completed with no due investment return work."
        );
      }
    } catch (error40) {
      logger.error({ err: error40, reason }, "Investment return scheduler tick failed.");
    } finally {
      runInFlight = false;
    }
  };
  logger.info(
    {
      intervalMs: INVESTMENT_RETURN_SCHEDULER_INTERVAL_MS,
      runOnStartup: INVESTMENT_RETURN_SCHEDULER_RUN_ON_STARTUP,
      startupDelayMs: INVESTMENT_RETURN_SCHEDULER_STARTUP_DELAY_MS
    },
    "Starting investment return scheduler."
  );
  if (INVESTMENT_RETURN_SCHEDULER_RUN_ON_STARTUP) {
    startupHandle = setTimeout(() => {
      startupHandle = null;
      void runTick("startup");
    }, INVESTMENT_RETURN_SCHEDULER_STARTUP_DELAY_MS);
    startupHandle.unref?.();
  }
  intervalHandle = setInterval(() => {
    void runTick("interval");
  }, INVESTMENT_RETURN_SCHEDULER_INTERVAL_MS);
  intervalHandle.unref?.();
  return {
    stop() {
      shutdownRequested = true;
      if (startupHandle) {
        clearTimeout(startupHandle);
        startupHandle = null;
      }
      if (intervalHandle) {
        clearInterval(intervalHandle);
        intervalHandle = null;
      }
      logger.info("Stopped investment return scheduler.");
    }
  };
}
var INVESTMENT_RETURN_SCHEDULER_LOCK_KEY_A, INVESTMENT_RETURN_SCHEDULER_LOCK_KEY_B;
var init_investment_return_scheduler = __esm({
  "src/lib/investment-return-scheduler.ts"() {
    "use strict";
    init_src2();
    init_config();
    init_logger();
    init_investment_returns();
    init_notification_dispatcher();
    init_notification_deliveries();
    INVESTMENT_RETURN_SCHEDULER_LOCK_KEY_A = 84217;
    INVESTMENT_RETURN_SCHEDULER_LOCK_KEY_B = 2;
  }
});

// src/lib/notification-scheduler.ts
function addDays7(date6, days) {
  const next = new Date(date6);
  next.setUTCDate(next.getUTCDate() + days);
  return next;
}
function ymdUtc(value) {
  return value.toISOString().slice(0, 10);
}
function formatSusuCircleSuffix2(circleName) {
  const normalized = circleName?.trim();
  return normalized ? ` for ${normalized}` : "";
}
function getYmdPartsInTimeZone(date6, timeZone) {
  const dtf = new Intl.DateTimeFormat("en-CA", {
    timeZone,
    year: "numeric",
    month: "2-digit",
    day: "2-digit"
  });
  const parts = dtf.formatToParts(date6);
  const values = {};
  for (const p of parts) {
    if (p.type !== "literal") values[p.type] = p.value;
  }
  return {
    year: Number(values.year),
    month: Number(values.month),
    day: Number(values.day)
  };
}
function getTimeZoneOffsetMs(timeZone, date6) {
  const dtf = new Intl.DateTimeFormat("en-US", {
    timeZone,
    hour12: false,
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit"
  });
  const parts = dtf.formatToParts(date6);
  const values = {};
  for (const p of parts) {
    if (p.type !== "literal") values[p.type] = p.value;
  }
  const asUtc = Date.UTC(
    Number(values.year),
    Number(values.month) - 1,
    Number(values.day),
    Number(values.hour),
    Number(values.minute),
    Number(values.second)
  );
  return asUtc - date6.getTime();
}
function utcFromZonedParts(input) {
  const naiveUtc = Date.UTC(
    input.year,
    input.month - 1,
    input.day,
    input.hour,
    input.minute,
    input.second
  );
  let adjusted = naiveUtc - getTimeZoneOffsetMs(input.timeZone, new Date(naiveUtc));
  adjusted = adjusted - getTimeZoneOffsetMs(input.timeZone, new Date(adjusted));
  return new Date(adjusted);
}
function startOfDayUtc(date6, timeZone) {
  if (timeZone === "UTC") {
    return new Date(Date.UTC(date6.getUTCFullYear(), date6.getUTCMonth(), date6.getUTCDate()));
  }
  const { year, month, day } = getYmdPartsInTimeZone(date6, timeZone);
  return utcFromZonedParts({ timeZone, year, month, day, hour: 0, minute: 0, second: 0 });
}
function endOfDayUtc(date6, timeZone) {
  if (timeZone === "UTC") {
    return new Date(
      Date.UTC(
        date6.getUTCFullYear(),
        date6.getUTCMonth(),
        date6.getUTCDate(),
        23,
        59,
        59,
        999
      )
    );
  }
  const start = startOfDayUtc(date6, timeZone);
  const next = addDays7(start, 1);
  return new Date(next.getTime() - 1);
}
function ymdInTimeZone(date6, timeZone) {
  if (timeZone === "UTC") return ymdUtc(date6);
  const { year, month, day } = getYmdPartsInTimeZone(date6, timeZone);
  return `${String(year).padStart(4, "0")}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
}
async function applyNotificationRetentionWith(nowUtcStart) {
  const deliveriesCutoff = addDays7(nowUtcStart, -NOTIFICATION_DELIVERIES_RETENTION_DAYS);
  const readCutoff = addDays7(nowUtcStart, -NOTIFICATIONS_READ_RETENTION_DAYS);
  const notificationsCutoff = addDays7(nowUtcStart, -NOTIFICATIONS_RETENTION_DAYS);
  await db.delete(notificationDeliveriesTable).where(lt(notificationDeliveriesTable.occurredAt, deliveriesCutoff));
  await db.delete(notificationsTable).where(
    or(
      lt(notificationsTable.createdAt, notificationsCutoff),
      and(
        eq(notificationsTable.read, true),
        lt(notificationsTable.readAt, readCutoff)
      )
    )
  );
}
async function runWithSchedulerLock2(work) {
  const client = await pool.connect();
  try {
    const lockResult = await client.query(
      "select pg_try_advisory_lock($1, $2) as acquired",
      [NOTIFICATION_SCHEDULER_LOCK_KEY_A, NOTIFICATION_SCHEDULER_LOCK_KEY_B]
    );
    const acquired = lockResult.rows[0]?.acquired === true;
    if (!acquired) return { acquired: false };
    try {
      return { acquired: true, value: await work() };
    } finally {
      await client.query("select pg_advisory_unlock($1, $2)", [
        NOTIFICATION_SCHEDULER_LOCK_KEY_A,
        NOTIFICATION_SCHEDULER_LOCK_KEY_B
      ]);
    }
  } finally {
    client.release();
  }
}
async function processReminderOnce(input) {
  const reserved = await reserveNotificationDeliveryWith(db, {
    userId: input.userId,
    channel: "PUSH",
    category: input.category,
    idempotencyKey: input.pushKey,
    status: "SKIPPED",
    provider: null,
    metadata: { kind: "reminder" }
  });
  if (!reserved.reserved) return { ran: false };
  const inApp = await notifyInAppWith(db, {
    userId: input.userId,
    category: input.category,
    severity: input.severity,
    title: input.title,
    body: input.body,
    actionLabel: input.actionLabel,
    actionHref: input.actionHref
  });
  try {
    const pushResult = await deliverPushIfEnabled({
      userId: input.userId,
      category: input.category,
      title: input.title,
      body: input.body,
      data: { actionHref: input.actionHref }
    });
    await finalizeNotificationDeliveryWith(db, {
      idempotencyKey: input.pushKey,
      status: pushResult.status,
      provider: pushResult.status === "SENT" ? "EXPO" : null,
      errorMessage: pushResult.reason ?? null,
      notificationId: inApp.id,
      metadata: { kind: "reminder", reason: pushResult.reason ?? null }
    });
  } catch (err) {
    await finalizeNotificationDeliveryWith(db, {
      idempotencyKey: input.pushKey,
      status: "FAILED",
      provider: "EXPO",
      errorMessage: err instanceof Error ? err.message : String(err),
      notificationId: inApp.id,
      metadata: { kind: "reminder" }
    });
  }
  const emailReserved = await reserveNotificationDeliveryWith(db, {
    userId: input.userId,
    channel: "EMAIL",
    category: input.category,
    idempotencyKey: input.emailKey,
    status: "SKIPPED",
    provider: null,
    metadata: { kind: "reminder" }
  });
  if (emailReserved.reserved) {
    try {
      const emailResult = await deliverReminderEmailIfEnabled({
        userId: input.userId,
        to: input.userEmail,
        firstName: input.userFirstName,
        category: input.category,
        title: input.title,
        intro: input.body,
        lines: input.lines,
        actionLabel: input.actionLabel,
        actionHref: input.actionHref
      });
      await finalizeNotificationDeliveryWith(db, {
        idempotencyKey: input.emailKey,
        status: emailResult.status,
        provider: emailResult.status === "SENT" ? "SMTP" : null,
        errorMessage: emailResult.reason ?? null,
        notificationId: inApp.id,
        metadata: { kind: "reminder", reason: emailResult.reason ?? null }
      });
    } catch (err) {
      await finalizeNotificationDeliveryWith(db, {
        idempotencyKey: input.emailKey,
        status: "FAILED",
        provider: "SMTP",
        errorMessage: err instanceof Error ? err.message : String(err),
        notificationId: inApp.id,
        metadata: { kind: "reminder" }
      });
    }
  }
  return { ran: true };
}
async function processOneTimeEventOnce(input) {
  const reserved = await reserveNotificationDeliveryWith(db, {
    userId: input.userId,
    channel: "PUSH",
    category: input.category,
    idempotencyKey: input.pushKey,
    status: "SKIPPED",
    provider: null,
    metadata: { kind: input.kind, ...input.metadata ?? {} }
  });
  if (!reserved.reserved) return { ran: false };
  const inApp = await notifyInAppWith(db, {
    userId: input.userId,
    category: input.category,
    severity: input.severity,
    title: input.title,
    body: input.body,
    actionLabel: input.actionLabel,
    actionHref: input.actionHref
  });
  try {
    const pushResult = await deliverPushIfEnabled({
      userId: input.userId,
      category: input.category,
      title: input.title,
      body: input.body,
      data: { actionHref: input.actionHref }
    });
    await finalizeNotificationDeliveryWith(db, {
      idempotencyKey: input.pushKey,
      status: pushResult.status,
      provider: pushResult.status === "SENT" ? "EXPO" : null,
      errorMessage: pushResult.reason ?? null,
      notificationId: inApp.id,
      metadata: {
        kind: input.kind,
        reason: pushResult.reason ?? null,
        ...input.metadata ?? {}
      }
    });
  } catch (err) {
    await finalizeNotificationDeliveryWith(db, {
      idempotencyKey: input.pushKey,
      status: "FAILED",
      provider: "EXPO",
      errorMessage: err instanceof Error ? err.message : String(err),
      notificationId: inApp.id,
      metadata: { kind: input.kind, ...input.metadata ?? {} }
    });
  }
  const emailReserved = await reserveNotificationDeliveryWith(db, {
    userId: input.userId,
    channel: "EMAIL",
    category: input.category,
    idempotencyKey: input.emailKey,
    status: "SKIPPED",
    provider: null,
    metadata: { kind: input.kind, ...input.metadata ?? {} }
  });
  if (emailReserved.reserved) {
    try {
      const emailResult = await deliverReminderEmailIfEnabled({
        userId: input.userId,
        to: input.userEmail,
        firstName: input.userFirstName,
        category: input.category,
        title: input.title,
        intro: input.body,
        lines: input.lines,
        actionLabel: input.actionLabel,
        actionHref: input.actionHref
      });
      await finalizeNotificationDeliveryWith(db, {
        idempotencyKey: input.emailKey,
        status: emailResult.status,
        provider: emailResult.status === "SENT" ? "SMTP" : null,
        errorMessage: emailResult.reason ?? null,
        notificationId: inApp.id,
        metadata: {
          kind: input.kind,
          reason: emailResult.reason ?? null,
          ...input.metadata ?? {}
        }
      });
    } catch (err) {
      await finalizeNotificationDeliveryWith(db, {
        idempotencyKey: input.emailKey,
        status: "FAILED",
        provider: "SMTP",
        errorMessage: err instanceof Error ? err.message : String(err),
        notificationId: inApp.id,
        metadata: { kind: input.kind, ...input.metadata ?? {} }
      });
    }
  }
  return { ran: true };
}
async function processRemindersWith() {
  const now = /* @__PURE__ */ new Date();
  const timeZone = NOTIFICATION_SCHEDULER_TIMEZONE;
  const todayStart = startOfDayUtc(now, timeZone);
  const dueSoonEnd = endOfDayUtc(addDays7(todayStart, 3), timeZone);
  const today = ymdInTimeZone(todayStart, timeZone);
  if (lastRetentionRunYmd !== today) {
    await applyNotificationRetentionWith(todayStart);
    lastRetentionRunYmd = today;
  }
  const [dueInvoices, overdueInvoices, dueContribs, overdueContribs, dueRepay, overdueRepay] = await Promise.all([
    db.select({
      invoiceId: invoicesTable.id,
      userId: invoicesTable.userId,
      dueDate: invoicesTable.dueDate
    }).from(invoicesTable).where(
      and(
        inArray(invoicesTable.status, ["SENT", "DRAFT", "OVERDUE"]),
        gte(invoicesTable.dueDate, todayStart),
        lte(invoicesTable.dueDate, dueSoonEnd)
      )
    ),
    db.select({
      invoiceId: invoicesTable.id,
      userId: invoicesTable.userId,
      dueDate: invoicesTable.dueDate
    }).from(invoicesTable).where(
      and(
        inArray(invoicesTable.status, ["SENT", "DRAFT", "OVERDUE"]),
        lt(invoicesTable.dueDate, todayStart)
      )
    ),
    db.select({
      contributionId: savingsContributionsTable.id,
      userId: savingsContributionsTable.userId,
      dueDate: savingsContributionsTable.dueDate,
      circleName: savingsCirclesTable.name
    }).from(savingsContributionsTable).innerJoin(
      savingsCirclesTable,
      eq(savingsContributionsTable.circleId, savingsCirclesTable.id)
    ).where(
      and(
        eq(savingsContributionsTable.status, "PENDING"),
        gte(savingsContributionsTable.dueDate, todayStart),
        lte(savingsContributionsTable.dueDate, dueSoonEnd)
      )
    ),
    db.select({
      contributionId: savingsContributionsTable.id,
      userId: savingsContributionsTable.userId,
      dueDate: savingsContributionsTable.dueDate,
      circleName: savingsCirclesTable.name
    }).from(savingsContributionsTable).innerJoin(
      savingsCirclesTable,
      eq(savingsContributionsTable.circleId, savingsCirclesTable.id)
    ).where(
      and(
        eq(savingsContributionsTable.status, "PENDING"),
        lt(savingsContributionsTable.dueDate, todayStart)
      )
    ),
    db.select({
      repaymentId: loanRepaymentsTable.id,
      userId: loanApplicationsTable.borrowerId,
      dueDate: loanRepaymentsTable.dueDate
    }).from(loanRepaymentsTable).innerJoin(
      loanApplicationsTable,
      eq(loanRepaymentsTable.loanApplicationId, loanApplicationsTable.id)
    ).where(
      and(
        eq(loanRepaymentsTable.status, "PENDING"),
        gte(loanRepaymentsTable.dueDate, todayStart),
        lte(loanRepaymentsTable.dueDate, dueSoonEnd)
      )
    ),
    db.select({
      repaymentId: loanRepaymentsTable.id,
      userId: loanApplicationsTable.borrowerId,
      dueDate: loanRepaymentsTable.dueDate
    }).from(loanRepaymentsTable).innerJoin(
      loanApplicationsTable,
      eq(loanRepaymentsTable.loanApplicationId, loanApplicationsTable.id)
    ).where(
      or(
        and(
          eq(loanRepaymentsTable.status, "PENDING"),
          lt(loanRepaymentsTable.dueDate, todayStart)
        ),
        eq(loanRepaymentsTable.status, "LATE")
      )
    )
  ]);
  const userIds = /* @__PURE__ */ new Set();
  for (const row of dueInvoices) userIds.add(row.userId);
  for (const row of overdueInvoices) userIds.add(row.userId);
  for (const row of dueContribs) userIds.add(row.userId);
  for (const row of overdueContribs) userIds.add(row.userId);
  for (const row of dueRepay) userIds.add(row.userId);
  for (const row of overdueRepay) userIds.add(row.userId);
  const users = userIds.size > 0 ? await db.select({
    id: usersTable.id,
    email: usersTable.email,
    firstName: usersTable.firstName
  }).from(usersTable).where(inArray(usersTable.id, [...userIds])) : [];
  const userById = new Map(users.map((u) => [u.id, u]));
  let created = 0;
  for (const inv of dueInvoices) {
    const u = userById.get(inv.userId);
    if (!u) continue;
    if (ymdInTimeZone(inv.dueDate, timeZone) === today) {
      const result2 = await processOneTimeEventOnce({
        userId: u.id,
        userEmail: u.email,
        userFirstName: u.firstName,
        category: "PAYMENT",
        severity: "WARNING",
        title: "Invoice due today",
        body: `Your invoice is due today (${inv.dueDate.toLocaleDateString("en-CA")}).`,
        actionHref: "/dashboard/billing",
        actionLabel: "Open Billing",
        pushKey: `invoice_due_today:${inv.invoiceId}:push`,
        emailKey: `invoice_due_today:${inv.invoiceId}:email`,
        lines: ["Please review your billing page and settle it today."],
        kind: "invoice_due_today",
        metadata: { invoiceId: inv.invoiceId, dueDate: inv.dueDate.toISOString() }
      });
      if (result2.ran) created += 1;
      continue;
    }
    const keyBase = `invoice_due:${inv.invoiceId}:${today}`;
    const result = await processReminderOnce({
      userId: u.id,
      userEmail: u.email,
      userFirstName: u.firstName,
      category: "PAYMENT",
      severity: "WARNING",
      title: "Invoice due soon",
      body: `Your invoice is due on ${inv.dueDate.toLocaleDateString("en-CA")}.`,
      actionHref: "/dashboard/billing",
      actionLabel: "Open Billing",
      pushKey: `push:${keyBase}`,
      emailKey: `email:${keyBase}`,
      lines: ["Please review your billing page to avoid interruptions."]
    });
    if (result.ran) created += 1;
  }
  for (const inv of overdueInvoices) {
    const u = userById.get(inv.userId);
    if (!u) continue;
    const [markedOverdue] = await db.update(invoicesTable).set({ status: "OVERDUE", updatedAt: now }).where(
      and(
        eq(invoicesTable.id, inv.invoiceId),
        inArray(invoicesTable.status, ["SENT", "DRAFT"]),
        lt(invoicesTable.dueDate, todayStart)
      )
    ).returning({ id: invoicesTable.id });
    if (markedOverdue) {
      const result2 = await processOneTimeEventOnce({
        userId: u.id,
        userEmail: u.email,
        userFirstName: u.firstName,
        category: "PAYMENT",
        severity: "ERROR",
        title: "Invoice overdue",
        body: `Your invoice due on ${inv.dueDate.toLocaleDateString("en-CA")} is now overdue.`,
        actionHref: "/dashboard/billing",
        actionLabel: "Open Billing",
        pushKey: `invoice_overdue_event:${inv.invoiceId}:push`,
        emailKey: `invoice_overdue_event:${inv.invoiceId}:email`,
        lines: ["Please settle it as soon as possible to keep your access active."],
        kind: "invoice_overdue_event",
        metadata: { invoiceId: inv.invoiceId, dueDate: inv.dueDate.toISOString() }
      });
      if (result2.ran) created += 1;
      continue;
    }
    const keyBase = `invoice_overdue:${inv.invoiceId}:${today}`;
    const result = await processReminderOnce({
      userId: u.id,
      userEmail: u.email,
      userFirstName: u.firstName,
      category: "PAYMENT",
      severity: "ERROR",
      title: "Invoice overdue",
      body: `Your invoice due on ${inv.dueDate.toLocaleDateString("en-CA")} is overdue.`,
      actionHref: "/dashboard/billing",
      actionLabel: "Open Billing",
      pushKey: `push:${keyBase}`,
      emailKey: `email:${keyBase}`,
      lines: ["Please settle it as soon as possible to keep your access active."]
    });
    if (result.ran) created += 1;
  }
  for (const c of dueContribs) {
    const u = userById.get(c.userId);
    if (!u) continue;
    const keyBase = `susu_due:${c.contributionId}:${today}`;
    const circleSuffix = formatSusuCircleSuffix2(c.circleName);
    const result = await processReminderOnce({
      userId: u.id,
      userEmail: u.email,
      userFirstName: u.firstName,
      category: "SAVINGS",
      severity: "WARNING",
      title: "Contribution due soon",
      body: `Your SUSU contribution${circleSuffix} is due on ${c.dueDate.toLocaleDateString("en-CA")}.`,
      actionHref: "/dashboard/savings",
      actionLabel: "Open Savings",
      pushKey: `push:${keyBase}`,
      emailKey: `email:${keyBase}`,
      lines: [
        `Open Savings to pay your contribution${circleSuffix} when it becomes due.`
      ]
    });
    if (result.ran) created += 1;
  }
  for (const c of overdueContribs) {
    const u = userById.get(c.userId);
    if (!u) continue;
    const keyBase = `susu_overdue:${c.contributionId}:${today}`;
    const circleSuffix = formatSusuCircleSuffix2(c.circleName);
    const result = await processReminderOnce({
      userId: u.id,
      userEmail: u.email,
      userFirstName: u.firstName,
      category: "SAVINGS",
      severity: "ERROR",
      title: "Contribution overdue",
      body: `Your SUSU contribution${circleSuffix} due on ${c.dueDate.toLocaleDateString("en-CA")} is overdue.`,
      actionHref: "/dashboard/savings",
      actionLabel: "Open Savings",
      pushKey: `push:${keyBase}`,
      emailKey: `email:${keyBase}`,
      lines: [
        `Please settle your contribution${circleSuffix} as soon as possible to stay in good standing.`
      ]
    });
    if (result.ran) created += 1;
  }
  for (const r of dueRepay) {
    const u = userById.get(r.userId);
    if (!u) continue;
    if (ymdInTimeZone(r.dueDate, timeZone) === today) {
      const result2 = await processOneTimeEventOnce({
        userId: u.id,
        userEmail: u.email,
        userFirstName: u.firstName,
        category: "LENDING",
        severity: "WARNING",
        title: "Loan repayment due today",
        body: `Your loan repayment is due today (${r.dueDate.toLocaleDateString("en-CA")}).`,
        actionHref: "/dashboard/lending",
        actionLabel: "Open Lending",
        pushKey: `loan_due_today:${r.repaymentId}:push`,
        emailKey: `loan_due_today:${r.repaymentId}:email`,
        lines: ["Please review your schedule and make a payment today."],
        kind: "loan_due_today",
        metadata: { repaymentId: r.repaymentId, dueDate: r.dueDate.toISOString() }
      });
      if (result2.ran) created += 1;
    }
    const keyBase = `loan_due:${r.repaymentId}:${today}`;
    const result = await processReminderOnce({
      userId: u.id,
      userEmail: u.email,
      userFirstName: u.firstName,
      category: "LENDING",
      severity: "WARNING",
      title: "Loan repayment due soon",
      body: `Your loan repayment is due on ${r.dueDate.toLocaleDateString("en-CA")}.`,
      actionHref: "/dashboard/lending",
      actionLabel: "Open Lending",
      pushKey: `push:${keyBase}`,
      emailKey: `email:${keyBase}`,
      lines: ["Open Lending to review your schedule and make a payment."]
    });
    if (result.ran) created += 1;
  }
  for (const r of overdueRepay) {
    const u = userById.get(r.userId);
    if (!u) continue;
    const [markedLate] = await db.update(loanRepaymentsTable).set({ status: "LATE", updatedAt: now }).where(
      and(
        eq(loanRepaymentsTable.id, r.repaymentId),
        eq(loanRepaymentsTable.status, "PENDING"),
        lt(loanRepaymentsTable.dueDate, todayStart)
      )
    ).returning({ id: loanRepaymentsTable.id });
    if (markedLate) {
      const result2 = await processOneTimeEventOnce({
        userId: u.id,
        userEmail: u.email,
        userFirstName: u.firstName,
        category: "LENDING",
        severity: "ERROR",
        title: "Loan repayment late",
        body: `A loan repayment due on ${r.dueDate.toLocaleDateString("en-CA")} is now late.`,
        actionHref: "/dashboard/lending",
        actionLabel: "Open Lending",
        pushKey: `loan_repayment_late:${r.repaymentId}:push`,
        emailKey: `loan_repayment_late:${r.repaymentId}:email`,
        lines: ["Please make a payment as soon as possible to avoid penalties."],
        kind: "loan_repayment_late",
        metadata: { repaymentId: r.repaymentId, dueDate: r.dueDate.toISOString() }
      });
      if (result2.ran) created += 1;
    }
    const keyBase = `loan_overdue:${r.repaymentId}:${today}`;
    const result = await processReminderOnce({
      userId: u.id,
      userEmail: u.email,
      userFirstName: u.firstName,
      category: "LENDING",
      severity: "ERROR",
      title: "Loan repayment overdue",
      body: `A loan repayment due on ${r.dueDate.toLocaleDateString("en-CA")} is overdue.`,
      actionHref: "/dashboard/lending",
      actionLabel: "Open Lending",
      pushKey: `push:${keyBase}`,
      emailKey: `email:${keyBase}`,
      lines: ["Please settle it as soon as possible to avoid penalties."]
    });
    if (result.ran) created += 1;
  }
  return { created };
}
function startNotificationScheduler() {
  if (!ENABLE_NOTIFICATION_SCHEDULER) {
    logger.info("Notification scheduler is disabled by configuration.");
    return { stop() {
    } };
  }
  let intervalHandle = null;
  let startupHandle = null;
  let shutdownRequested = false;
  let runInFlight = false;
  const runTick = async (reason) => {
    if (shutdownRequested || runInFlight) return;
    runInFlight = true;
    const startedAt = Date.now();
    try {
      const result = await runWithSchedulerLock2(() => processRemindersWith());
      if (!result.acquired) {
        logger.debug(
          { reason },
          "Skipped notification scheduler tick because another worker holds the advisory lock."
        );
        return;
      }
      const durationMs = Date.now() - startedAt;
      if (result.value.created > 0 || reason === "startup") {
        logger.info(
          { reason, durationMs, created: result.value.created },
          "Notification scheduler tick completed."
        );
      } else {
        logger.debug(
          { reason, durationMs, created: result.value.created },
          "Notification scheduler tick completed with no due reminder work."
        );
      }
    } catch (error40) {
      logger.error({ err: error40, reason }, "Notification scheduler tick failed.");
    } finally {
      runInFlight = false;
    }
  };
  logger.info(
    {
      intervalMs: NOTIFICATION_SCHEDULER_INTERVAL_MS,
      runOnStartup: NOTIFICATION_SCHEDULER_RUN_ON_STARTUP,
      startupDelayMs: NOTIFICATION_SCHEDULER_STARTUP_DELAY_MS
    },
    "Starting notification scheduler."
  );
  if (NOTIFICATION_SCHEDULER_RUN_ON_STARTUP) {
    startupHandle = setTimeout(() => {
      startupHandle = null;
      void runTick("startup");
    }, NOTIFICATION_SCHEDULER_STARTUP_DELAY_MS);
    startupHandle.unref?.();
  } else {
    logger.info(
      { intervalMs: NOTIFICATION_SCHEDULER_INTERVAL_MS },
      "Skipping notification scheduler startup run by configuration."
    );
  }
  intervalHandle = setInterval(() => {
    void runTick("interval");
  }, NOTIFICATION_SCHEDULER_INTERVAL_MS);
  intervalHandle.unref?.();
  return {
    stop() {
      shutdownRequested = true;
      if (startupHandle) {
        clearTimeout(startupHandle);
        startupHandle = null;
      }
      if (intervalHandle) {
        clearInterval(intervalHandle);
        intervalHandle = null;
      }
      logger.info("Stopped notification scheduler.");
    }
  };
}
var NOTIFICATION_SCHEDULER_LOCK_KEY_A, NOTIFICATION_SCHEDULER_LOCK_KEY_B, lastRetentionRunYmd;
var init_notification_scheduler = __esm({
  "src/lib/notification-scheduler.ts"() {
    "use strict";
    init_src2();
    init_schema2();
    init_drizzle_orm();
    init_config();
    init_logger();
    init_notification_dispatcher();
    init_notification_deliveries();
    NOTIFICATION_SCHEDULER_LOCK_KEY_A = 84218;
    NOTIFICATION_SCHEDULER_LOCK_KEY_B = 1;
    lastRetentionRunYmd = null;
  }
});

// src/lib/susu-scheduler.ts
async function runWithSchedulerLock3(work) {
  const client = await pool.connect();
  try {
    const lockResult = await client.query(
      "select pg_try_advisory_lock($1, $2) as acquired",
      [SUSU_SCHEDULER_LOCK_KEY_A, SUSU_SCHEDULER_LOCK_KEY_B]
    );
    const acquired = lockResult.rows[0]?.acquired === true;
    if (!acquired) return { acquired: false };
    try {
      return { acquired: true, value: await work() };
    } finally {
      await client.query("select pg_advisory_unlock($1, $2)", [
        SUSU_SCHEDULER_LOCK_KEY_A,
        SUSU_SCHEDULER_LOCK_KEY_B
      ]);
    }
  } finally {
    client.release();
  }
}
function startSusuScheduler() {
  if (!ENABLE_SUSU_SCHEDULER) {
    logger.info("SUSU scheduler is disabled by configuration.");
    return { stop() {
    } };
  }
  let intervalHandle = null;
  let startupHandle = null;
  let shutdownRequested = false;
  let runInFlight = false;
  const runTick = async (reason) => {
    if (shutdownRequested || runInFlight) return;
    runInFlight = true;
    const startedAt = Date.now();
    try {
      const result = await runWithSchedulerLock3(() => processAllActiveCirclesWith(db));
      if (!result.acquired) {
        logger.debug({ reason }, "Skipped SUSU scheduler tick because another worker holds the advisory lock.");
        return;
      }
      const durationMs = Date.now() - startedAt;
      const summary = result.value;
      const hasWork = summary.processedCircles > 0 || summary.autoPaidContributions > 0 || summary.autoPaidPayouts > 0 || summary.completedCircles > 0;
      if (hasWork || reason === "startup") {
        logger.info(
          {
            reason,
            durationMs,
            ...summary
          },
          "SUSU scheduler tick completed."
        );
      } else {
        logger.debug(
          {
            reason,
            durationMs,
            ...summary
          },
          "SUSU scheduler tick completed with no due SUSU work."
        );
      }
    } catch (error40) {
      logger.error({ err: error40, reason }, "SUSU scheduler tick failed.");
    } finally {
      runInFlight = false;
    }
  };
  logger.info(
    {
      intervalMs: SUSU_SCHEDULER_INTERVAL_MS,
      runOnStartup: SUSU_SCHEDULER_RUN_ON_STARTUP,
      startupDelayMs: SUSU_SCHEDULER_STARTUP_DELAY_MS
    },
    "Starting SUSU scheduler."
  );
  if (SUSU_SCHEDULER_RUN_ON_STARTUP) {
    startupHandle = setTimeout(() => {
      startupHandle = null;
      void runTick("startup");
    }, SUSU_SCHEDULER_STARTUP_DELAY_MS);
    startupHandle.unref?.();
  } else {
    logger.info(
      {
        intervalMs: SUSU_SCHEDULER_INTERVAL_MS
      },
      "Skipping SUSU scheduler startup run by configuration."
    );
  }
  intervalHandle = setInterval(() => {
    void runTick("interval");
  }, SUSU_SCHEDULER_INTERVAL_MS);
  intervalHandle.unref?.();
  return {
    stop() {
      shutdownRequested = true;
      if (startupHandle) {
        clearTimeout(startupHandle);
        startupHandle = null;
      }
      if (intervalHandle) {
        clearInterval(intervalHandle);
        intervalHandle = null;
      }
      logger.info("Stopped SUSU scheduler.");
    }
  };
}
var SUSU_SCHEDULER_LOCK_KEY_A, SUSU_SCHEDULER_LOCK_KEY_B;
var init_susu_scheduler = __esm({
  "src/lib/susu-scheduler.ts"() {
    "use strict";
    init_src2();
    init_config();
    init_logger();
    init_susu();
    SUSU_SCHEDULER_LOCK_KEY_A = 84217;
    SUSU_SCHEDULER_LOCK_KEY_B = 1;
  }
});

// src/lib/background-jobs.ts
var background_jobs_exports = {};
__export(background_jobs_exports, {
  startBackgroundJobsCoordinator: () => startBackgroundJobsCoordinator
});
function startBackgroundJobsCoordinator() {
  if (!ENABLE_BACKGROUND_JOBS) {
    logger.info("Background jobs coordinator is disabled by configuration.");
    return { stop() {
    } };
  }
  let shutdownRequested = false;
  let retryHandle = null;
  let leadershipAttemptInFlight = false;
  let leaderClient = null;
  let schedulerHandles = [];
  const stopSchedulers = () => {
    for (const handle of schedulerHandles) {
      try {
        handle.stop();
      } catch {
      }
    }
    schedulerHandles = [];
  };
  const clearRetry = () => {
    if (!retryHandle) return;
    clearTimeout(retryHandle);
    retryHandle = null;
  };
  const scheduleRetry = () => {
    if (shutdownRequested || retryHandle || leaderClient) return;
    retryHandle = setTimeout(() => {
      retryHandle = null;
      void attemptLeadership("retry");
    }, BACKGROUND_JOBS_LEADER_RETRY_MS);
    retryHandle.unref?.();
  };
  const releaseLeadership = async () => {
    const client = leaderClient;
    leaderClient = null;
    if (!client) return;
    try {
      await client.query("select pg_advisory_unlock($1, $2)", [
        BACKGROUND_JOBS_LOCK_KEY_A,
        BACKGROUND_JOBS_LOCK_KEY_B
      ]);
    } catch (error40) {
      logger.warn(
        { err: error40 },
        "Failed to release background jobs leadership lock cleanly."
      );
    } finally {
      client.release();
    }
  };
  const handleLeadershipLoss = () => {
    if (shutdownRequested) return;
    logger.warn(
      "Background jobs leadership was lost; stopping schedulers and retrying."
    );
    stopSchedulers();
    if (leaderClient) {
      leaderClient.release();
      leaderClient = null;
    }
    scheduleRetry();
  };
  const startSchedulers = () => {
    if (schedulerHandles.length > 0) return;
    schedulerHandles = [
      startSusuScheduler(),
      startInvestmentReturnScheduler(),
      startNotificationScheduler()
    ];
  };
  const attemptLeadership = async (reason) => {
    if (shutdownRequested || leadershipAttemptInFlight || leaderClient != null) {
      return;
    }
    leadershipAttemptInFlight = true;
    try {
      const client = await pool.connect();
      const lockResult = await client.query(
        "select pg_try_advisory_lock($1, $2) as acquired",
        [BACKGROUND_JOBS_LOCK_KEY_A, BACKGROUND_JOBS_LOCK_KEY_B]
      );
      if (lockResult.rows[0]?.acquired !== true) {
        client.release();
        logger.info(
          { reason, retryMs: BACKGROUND_JOBS_LEADER_RETRY_MS },
          "Another API instance owns background jobs leadership."
        );
        scheduleRetry();
        return;
      }
      leaderClient = client;
      clearRetry();
      client.once("error", handleLeadershipLoss);
      client.once("end", handleLeadershipLoss);
      logger.info(
        { reason },
        "This API instance became the background jobs leader."
      );
      startSchedulers();
    } catch (error40) {
      logger.error(
        { err: error40, reason },
        "Failed to acquire background jobs leadership."
      );
      scheduleRetry();
    } finally {
      leadershipAttemptInFlight = false;
    }
  };
  void attemptLeadership("startup");
  return {
    stop() {
      shutdownRequested = true;
      clearRetry();
      stopSchedulers();
      void releaseLeadership();
      logger.info("Stopped background jobs coordinator.");
    }
  };
}
var BACKGROUND_JOBS_LOCK_KEY_A, BACKGROUND_JOBS_LOCK_KEY_B;
var init_background_jobs = __esm({
  "src/lib/background-jobs.ts"() {
    "use strict";
    init_src2();
    init_config();
    init_logger();
    init_investment_return_scheduler();
    init_notification_scheduler();
    init_susu_scheduler();
    BACKGROUND_JOBS_LOCK_KEY_A = 84219;
    BACKGROUND_JOBS_LOCK_KEY_B = 1;
  }
});

// src/index.ts
init_logger();
import { setDefaultResultOrder } from "node:dns";
import { existsSync as existsSync2 } from "node:fs";
import { readFileSync as readFileSync4 } from "node:fs";
import path3 from "node:path";
import { fileURLToPath as fileURLToPath2 } from "node:url";
var moduleDir = path3.dirname(fileURLToPath2(import.meta.url));
var repoRoot = path3.resolve(moduleDir, "../../..");
var envPath = path3.resolve(repoRoot, ".env");
var nodeEnv4 = process.env.NODE_ENV ?? "development";
if (nodeEnv4 !== "production" && existsSync2(envPath)) {
  const raw = readFileSync4(envPath, "utf8");
  for (const line2 of raw.split(/\r?\n/)) {
    const trimmed = line2.trim();
    if (!trimmed || trimmed.startsWith("#")) continue;
    const eqIndex = trimmed.indexOf("=");
    if (eqIndex <= 0) continue;
    const key = trimmed.slice(0, eqIndex).trim();
    let value = trimmed.slice(eqIndex + 1).trim();
    if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
      value = value.slice(1, -1);
    }
    if (process.env[key] === void 0) {
      process.env[key] = value;
    }
  }
}
setDefaultResultOrder("ipv4first");
var { default: app2 } = await init_app().then(() => app_exports);
var { startBackgroundJobsCoordinator: startBackgroundJobsCoordinator2 } = await Promise.resolve().then(() => (init_background_jobs(), background_jobs_exports));
var rawPort = process.env["PORT"] ?? "8080";
var port = Number(rawPort);
if (Number.isNaN(port) || port <= 0) {
  throw new Error(`Invalid PORT value: "${rawPort}"`);
}
var server = app2.listen(port, () => {
  logger.info(`Server listening on port ${port}`);
});
var backgroundJobsCoordinator = startBackgroundJobsCoordinator2();
var shutdownStarted = false;
var shutdown = (signal) => {
  if (shutdownStarted) return;
  shutdownStarted = true;
  logger.info({ signal }, "Shutting down API server.");
  backgroundJobsCoordinator.stop();
  server.close((error40) => {
    if (error40) {
      logger.error({ err: error40, signal }, "Failed to close API server cleanly.");
      process.exitCode = 1;
    } else {
      logger.info({ signal }, "API server shutdown complete.");
    }
  });
};
process.once("SIGINT", () => shutdown("SIGINT"));
process.once("SIGTERM", () => shutdown("SIGTERM"));
/*! Bundled license information:

depd/index.js:
  (*!
   * depd
   * Copyright(c) 2014-2018 Douglas Christopher Wilson
   * MIT Licensed
   *)

bytes/index.js:
  (*!
   * bytes
   * Copyright(c) 2012-2014 TJ Holowaychuk
   * Copyright(c) 2015 Jed Watson
   * MIT Licensed
   *)

content-type/index.js:
  (*!
   * content-type
   * Copyright(c) 2015 Douglas Christopher Wilson
   * MIT Licensed
   *)

statuses/index.js:
  (*!
   * statuses
   * Copyright(c) 2014 Jonathan Ong
   * Copyright(c) 2016 Douglas Christopher Wilson
   * MIT Licensed
   *)

toidentifier/index.js:
  (*!
   * toidentifier
   * Copyright(c) 2016 Douglas Christopher Wilson
   * MIT Licensed
   *)

http-errors/index.js:
  (*!
   * http-errors
   * Copyright(c) 2014 Jonathan Ong
   * Copyright(c) 2016 Douglas Christopher Wilson
   * MIT Licensed
   *)

destroy/index.js:
  (*!
   * destroy
   * Copyright(c) 2014 Jonathan Ong
   * Copyright(c) 2015-2022 Douglas Christopher Wilson
   * MIT Licensed
   *)

unpipe/index.js:
  (*!
   * unpipe
   * Copyright(c) 2015 Douglas Christopher Wilson
   * MIT Licensed
   *)

raw-body/index.js:
  (*!
   * raw-body
   * Copyright(c) 2013-2014 Jonathan Ong
   * Copyright(c) 2014-2022 Douglas Christopher Wilson
   * MIT Licensed
   *)

ee-first/index.js:
  (*!
   * ee-first
   * Copyright(c) 2014 Jonathan Ong
   * MIT Licensed
   *)

on-finished/index.js:
  (*!
   * on-finished
   * Copyright(c) 2013 Jonathan Ong
   * Copyright(c) 2014 Douglas Christopher Wilson
   * MIT Licensed
   *)

body-parser/lib/read.js:
body-parser/lib/types/raw.js:
body-parser/lib/types/text.js:
body-parser/index.js:
  (*!
   * body-parser
   * Copyright(c) 2014-2015 Douglas Christopher Wilson
   * MIT Licensed
   *)

media-typer/index.js:
  (*!
   * media-typer
   * Copyright(c) 2014 Douglas Christopher Wilson
   * MIT Licensed
   *)

mime-db/index.js:
  (*!
   * mime-db
   * Copyright(c) 2014 Jonathan Ong
   * Copyright(c) 2015-2022 Douglas Christopher Wilson
   * MIT Licensed
   *)

mime-types/index.js:
  (*!
   * mime-types
   * Copyright(c) 2014 Jonathan Ong
   * Copyright(c) 2015 Douglas Christopher Wilson
   * MIT Licensed
   *)

type-is/index.js:
  (*!
   * type-is
   * Copyright(c) 2014 Jonathan Ong
   * Copyright(c) 2014-2015 Douglas Christopher Wilson
   * MIT Licensed
   *)

body-parser/lib/types/json.js:
body-parser/lib/types/urlencoded.js:
  (*!
   * body-parser
   * Copyright(c) 2014 Jonathan Ong
   * Copyright(c) 2014-2015 Douglas Christopher Wilson
   * MIT Licensed
   *)

merge-descriptors/index.js:
  (*!
   * merge-descriptors
   * Copyright(c) 2014 Jonathan Ong
   * Copyright(c) 2015 Douglas Christopher Wilson
   * MIT Licensed
   *)

encodeurl/index.js:
encodeurl/index.js:
  (*!
   * encodeurl
   * Copyright(c) 2016 Douglas Christopher Wilson
   * MIT Licensed
   *)

escape-html/index.js:
  (*!
   * escape-html
   * Copyright(c) 2012-2013 TJ Holowaychuk
   * Copyright(c) 2015 Andreas Lubbe
   * Copyright(c) 2015 Tiancheng "Timothy" Gu
   * MIT Licensed
   *)

parseurl/index.js:
  (*!
   * parseurl
   * Copyright(c) 2014 Jonathan Ong
   * Copyright(c) 2014-2017 Douglas Christopher Wilson
   * MIT Licensed
   *)

finalhandler/index.js:
  (*!
   * finalhandler
   * Copyright(c) 2014-2022 Douglas Christopher Wilson
   * MIT Licensed
   *)

express/lib/router/layer.js:
express/lib/router/route.js:
express/lib/router/index.js:
express/lib/middleware/init.js:
express/lib/middleware/query.js:
express/lib/view.js:
express/lib/application.js:
express/lib/request.js:
express/lib/express.js:
express/index.js:
  (*!
   * express
   * Copyright(c) 2009-2013 TJ Holowaychuk
   * Copyright(c) 2013 Roman Shtylman
   * Copyright(c) 2014-2015 Douglas Christopher Wilson
   * MIT Licensed
   *)

methods/index.js:
  (*!
   * methods
   * Copyright(c) 2013-2014 TJ Holowaychuk
   * Copyright(c) 2015-2016 Douglas Christopher Wilson
   * MIT Licensed
   *)

safe-buffer/index.js:
  (*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)

content-disposition/index.js:
  (*!
   * content-disposition
   * Copyright(c) 2014-2017 Douglas Christopher Wilson
   * MIT Licensed
   *)

etag/index.js:
  (*!
   * etag
   * Copyright(c) 2014-2016 Douglas Christopher Wilson
   * MIT Licensed
   *)

fresh/index.js:
  (*!
   * fresh
   * Copyright(c) 2012 TJ Holowaychuk
   * Copyright(c) 2016-2017 Douglas Christopher Wilson
   * MIT Licensed
   *)

range-parser/index.js:
  (*!
   * range-parser
   * Copyright(c) 2012-2014 TJ Holowaychuk
   * Copyright(c) 2015-2016 Douglas Christopher Wilson
   * MIT Licensed
   *)

send/index.js:
  (*!
   * send
   * Copyright(c) 2012 TJ Holowaychuk
   * Copyright(c) 2014-2022 Douglas Christopher Wilson
   * MIT Licensed
   *)

forwarded/index.js:
  (*!
   * forwarded
   * Copyright(c) 2014-2017 Douglas Christopher Wilson
   * MIT Licensed
   *)

proxy-addr/index.js:
  (*!
   * proxy-addr
   * Copyright(c) 2014-2016 Douglas Christopher Wilson
   * MIT Licensed
   *)

express/lib/utils.js:
express/lib/response.js:
  (*!
   * express
   * Copyright(c) 2009-2013 TJ Holowaychuk
   * Copyright(c) 2014-2015 Douglas Christopher Wilson
   * MIT Licensed
   *)

negotiator/index.js:
  (*!
   * negotiator
   * Copyright(c) 2012 Federico Romero
   * Copyright(c) 2012-2014 Isaac Z. Schlueter
   * Copyright(c) 2015 Douglas Christopher Wilson
   * MIT Licensed
   *)

accepts/index.js:
  (*!
   * accepts
   * Copyright(c) 2014 Jonathan Ong
   * Copyright(c) 2015 Douglas Christopher Wilson
   * MIT Licensed
   *)

cookie/index.js:
cookie/index.js:
  (*!
   * cookie
   * Copyright(c) 2012-2014 Roman Shtylman
   * Copyright(c) 2015 Douglas Christopher Wilson
   * MIT Licensed
   *)

vary/index.js:
  (*!
   * vary
   * Copyright(c) 2014-2017 Douglas Christopher Wilson
   * MIT Licensed
   *)

serve-static/index.js:
  (*!
   * serve-static
   * Copyright(c) 2010 Sencha Inc.
   * Copyright(c) 2011 TJ Holowaychuk
   * Copyright(c) 2014-2016 Douglas Christopher Wilson
   * MIT Licensed
   *)

object-assign/index.js:
  (*
  object-assign
  (c) Sindre Sorhus
  @license MIT
  *)

cookie-parser/index.js:
  (*!
   * cookie-parser
   * Copyright(c) 2014 TJ Holowaychuk
   * Copyright(c) 2015 Douglas Christopher Wilson
   * MIT Licensed
   *)
*/
//# sourceMappingURL=index.mjs.map
