craby-gateway 0.9.2 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist-sea/gateway.cjs +35 -34
- package/package.json +1 -1
package/dist-sea/gateway.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let l=require(`node:crypto`),u=require(`node:fs`);u=c(u);let d=require(`node:fs/promises`);d=c(d);let f=require(`node:os`);f=c(f);let p=require(`node:path`);p=c(p);let m=require(`node:child_process`),h=require(`node:module`),g=require(`node:url`),_=require(`node:readline`);_=c(_);let v=require(`node:process`);v=c(v);let y=require(`fs`);y=c(y);let b=require(`path`);b=c(b);let x=require(`module`),S=require(`net`),C=require(`child_process`),w=require(`@anthropic-ai/claude-agent-sdk`);var T={name:`@remote-agent/desktop-gateway`,private:!0,version:`0.9.2`,description:`Craby desktop gateway CLI`,type:`module`,bin:{"craby-gateway":`dist-sea/gateway.cjs`},files:[`dist-sea`,`README.md`],publishConfig:{access:`public`,registry:`https://registry.npmjs.org/`},engines:{node:`>=20`},repository:{type:`git`,url:`git+https://github.com/wuyongzhi/anycoding.git`,directory:`apps/desktop-gateway`},scripts:{dev:`GATEWAY_PORT=18787 GATEWAY_HTTPS_PORT=18787 GATEWAY_AUDIT_LOG_PATH=./logs/audit.log GATEWAY_LOG_PATH=./logs/gateway.log GATEWAY_SESSION_HISTORY_DIR=./logs/sessions-v2 GATEWAY_PROJECT_STORE_DIR=./logs/projects GATEWAY_AUTH_STORE_DIR=./logs/auth tsx watch src/index.ts --config ./logs/gateway.dev.yaml`,build:`tsup src/index.ts --format esm --dts`,"build:bundle":`tsdown --config tsdown.config.ts`,"build:npm":`pnpm run build:bundle && node ./scripts/preparePublishPackage.mjs`,"start:bundle":`node dist-sea/gateway.cjs`,"build:blob:darwin":`pnpm run build:bundle && node --experimental-sea-config sea-config.darwin.json`,"build:blob:linux":`pnpm run build:bundle && node --experimental-sea-config sea-config.linux.json`,"build:blob:win32":`pnpm run build:bundle && node --experimental-sea-config sea-config.win32.json`,"build:bin":`pnpm run build:bin:current`,"build:bin:current":`pnpm run build:bundle && node ./scripts/buildSea.mjs`,"build:bin:darwin":`pnpm run build:bundle && node ./scripts/buildSea.mjs darwin`,"build:bin:linux":`pnpm run build:bundle && node ./scripts/buildSea.mjs linux`,"build:bin:win32":`pnpm run build:bundle && node ./scripts/buildSea.mjs win32`,test:`vitest run --passWithNoTests`,typecheck:`tsc -p tsconfig.json --noEmit`,"dump:codex-history":`tsx src/dumpCodexSessionHistory.ts`,"export:codex-project-history":`tsx src/exportCodexProjectHistory.ts`,"pairing:start":`tsx src/pairingStart.ts`,"pack:check":`pnpm run build:npm && npm pack --dry-run ./dist-npm --userconfig ../../.npmrc`,"publish:npm":`pnpm run build:npm && npm publish ./dist-npm --access public --userconfig ../../.npmrc`},dependencies:{"@anthropic-ai/claude-agent-sdk":`^0.2.71`,"@fastify/cors":`^10.0.2`,"@fastify/websocket":`^11.0.2`,diff:`^7.0.0`,fastify:`^5.2.1`,jsonwebtoken:`^9.0.2`,nanoid:`^5.1.5`,pino:`^10.3.1`,"qrcode-terminal":`^0.12.0`,ws:`^8.18.3`,yaml:`^2.8.2`},devDependencies:{"@openai/codex":`^0.111.0`,"@remote-agent/contracts":`workspace:*`,"@remote-agent/provider-adapters":`workspace:*`,"@types/diff":`^7.0.1`,"@types/jsonwebtoken":`^9.0.9`,"@types/qrcode-terminal":`^0.12.2`,"@types/ws":`^8.5.13`,postject:`^1.0.0-alpha.6`,tsdown:`^0.21.0`}};const E=/(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/;function D(e){let t=e.match(E);return t?t[0]:null}function O(e){return typeof e==`string`?D(e):null}function k(e,t){let n=j(e),r=j(t);if(!n||!r)throw Error(`Invalid version comparison: ${e} vs ${t}`);return n.major===r.major?n.minor===r.minor?n.patch===r.patch?n.prerelease===r.prerelease?0:n.prerelease?r.prerelease?n.prerelease.localeCompare(r.prerelease):-1:1:n.patch-r.patch:n.minor-r.minor:n.major-r.major}function A(e,t){return k(e,t)>=0}function j(e){let t=e.match(E);return t?{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:typeof t[4]==`string`?t[4]:null}:null}const M=T,ee=M.dependencies??{};function N(e){return ee[e]??``}const te={packageName:`craby-gateway`,cliName:`craby-gateway`,version:M.version??`0.0.0`,providerRequirements:[{id:`codex`,dependencyName:null,dependencyRange:``,minimumVersion:null,systemCommand:`codex`,versionArgs:[`--version`],systemCommandRequired:!0,displayName:`Codex`},{id:`claude`,dependencyName:`@anthropic-ai/claude-agent-sdk`,dependencyRange:N(`@anthropic-ai/claude-agent-sdk`),minimumVersion:O(N(`@anthropic-ai/claude-agent-sdk`)),systemCommand:`claude`,versionArgs:[`--version`],systemCommandRequired:!1,displayName:`Claude Code`}]};function P(e){let t=`start`,n,r=!1,i=!1,a=[...e],o=a[0]?.trim();if(o&&!o.startsWith(`-`))if(o===`start`||o===`init`||o===`doctor`||o===`help`||o===`__worker`)t=o,a.shift();else throw Error(`Unknown command: ${o}`);for(let e=0;e<a.length;e+=1){let o=a[e];if(o===`--config`){n=ne(o,a[e+1]),e+=1;continue}if(o===`--force`){r=!0;continue}if(o===`--log`){i=!0;continue}if(o===`--help`||o===`-h`){t=`help`;continue}if(o===`--version`||o===`-v`){t=`version`;continue}throw Error(`Unknown argument: ${o}`)}return{command:t,configPath:n,force:r,logToConsole:i}}function ne(e,t){let n=t?.trim();if(!n)throw Error(`${e} requires a value`);return n}var F=o((e=>{let t=Symbol.for(`yaml.alias`),n=Symbol.for(`yaml.document`),r=Symbol.for(`yaml.map`),i=Symbol.for(`yaml.pair`),a=Symbol.for(`yaml.scalar`),o=Symbol.for(`yaml.seq`),s=Symbol.for(`yaml.node.type`),c=e=>!!e&&typeof e==`object`&&e[s]===t,l=e=>!!e&&typeof e==`object`&&e[s]===n,u=e=>!!e&&typeof e==`object`&&e[s]===r,d=e=>!!e&&typeof e==`object`&&e[s]===i,f=e=>!!e&&typeof e==`object`&&e[s]===a,p=e=>!!e&&typeof e==`object`&&e[s]===o;function m(e){if(e&&typeof e==`object`)switch(e[s]){case r:case o:return!0}return!1}function h(e){if(e&&typeof e==`object`)switch(e[s]){case t:case r:case a:case o:return!0}return!1}e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=s,e.PAIR=i,e.SCALAR=a,e.SEQ=o,e.hasAnchor=e=>(f(e)||m(e))&&!!e.anchor,e.isAlias=c,e.isCollection=m,e.isDocument=l,e.isMap=u,e.isNode=h,e.isPair=d,e.isScalar=f,e.isSeq=p})),I=o((e=>{var t=F();let n=Symbol(`break visit`),r=Symbol(`skip children`),i=Symbol(`remove node`);function a(e,n){let r=l(n);t.isDocument(e)?o(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):o(null,e,r,Object.freeze([]))}a.BREAK=n,a.SKIP=r,a.REMOVE=i;function o(e,r,a,s){let c=u(e,r,a,s);if(t.isNode(c)||t.isPair(c))return d(e,s,c),o(e,c,a,s);if(typeof c!=`symbol`){if(t.isCollection(r)){s=Object.freeze(s.concat(r));for(let e=0;e<r.items.length;++e){let t=o(e,r.items[e],a,s);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){s=Object.freeze(s.concat(r));let e=o(`key`,r.key,a,s);if(e===n)return n;e===i&&(r.key=null);let t=o(`value`,r.value,a,s);if(t===n)return n;t===i&&(r.value=null)}}return c}async function s(e,n){let r=l(n);t.isDocument(e)?await c(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):await c(null,e,r,Object.freeze([]))}s.BREAK=n,s.SKIP=r,s.REMOVE=i;async function c(e,r,a,o){let s=await u(e,r,a,o);if(t.isNode(s)||t.isPair(s))return d(e,o,s),c(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=await c(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=await c(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=await c(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}function l(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function u(e,n,r,i){if(typeof r==`function`)return r(e,n,i);if(t.isMap(n))return r.Map?.(e,n,i);if(t.isSeq(n))return r.Seq?.(e,n,i);if(t.isPair(n))return r.Pair?.(e,n,i);if(t.isScalar(n))return r.Scalar?.(e,n,i);if(t.isAlias(n))return r.Alias?.(e,n,i)}function d(e,n,r){let i=n[n.length-1];if(t.isCollection(i))i.items[e]=r;else if(t.isPair(i))e===`key`?i.key=r:i.value=r;else if(t.isDocument(i))i.contents=r;else{let e=t.isAlias(i)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=a,e.visitAsync=s})),re=o((e=>{var t=F(),n=I();let r={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},i=e=>e.replace(/[!,[\]{}]/g,e=>r[e]);var a=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+i(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],i=Object.entries(this.tags),a;if(e&&i.length>0&&t.isNode(e.contents)){let r={};n.visit(e.contents,(e,n)=>{t.isNode(n)&&n.tag&&(r[n.tag]=!0)}),a=Object.keys(r)}else a=[];for(let[t,n]of i)t===`!!`&&n===`tag:yaml.org,2002:`||(!e||a.some(e=>e.startsWith(n)))&&r.push(`%TAG ${t} ${n}`);return r.join(`
|
|
2
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let l=require(`node:crypto`),u=require(`node:fs`);u=c(u);let d=require(`node:fs/promises`);d=c(d);let f=require(`node:os`);f=c(f);let p=require(`node:path`);p=c(p);let m=require(`node:child_process`),h=require(`node:module`),g=require(`node:url`),_=require(`node:readline`);_=c(_);let v=require(`node:process`);v=c(v);let y=require(`fs`);y=c(y);let b=require(`path`);b=c(b);let x=require(`module`),S=require(`net`),C=require(`child_process`),w=require(`@anthropic-ai/claude-agent-sdk`);var T={name:`@remote-agent/desktop-gateway`,private:!0,version:`0.10.0`,description:`Craby desktop gateway CLI`,type:`module`,bin:{"craby-gateway":`dist-sea/gateway.cjs`},files:[`dist-sea`,`README.md`],publishConfig:{access:`public`,registry:`https://registry.npmjs.org/`},engines:{node:`>=20`},repository:{type:`git`,url:`git+https://github.com/wuyongzhi/anycoding.git`,directory:`apps/desktop-gateway`},scripts:{dev:`GATEWAY_PORT=18787 GATEWAY_HTTPS_PORT=18787 GATEWAY_AUDIT_LOG_PATH=./logs/audit.log GATEWAY_LOG_PATH=./logs/gateway.log GATEWAY_SESSION_HISTORY_DIR=./logs/sessions-v2 GATEWAY_PROJECT_STORE_DIR=./logs/projects GATEWAY_AUTH_STORE_DIR=./logs/auth tsx watch src/index.ts --config ./logs/gateway.dev.yaml`,build:`tsup src/index.ts --format esm --dts`,"build:bundle":`tsdown --config tsdown.config.ts`,"build:npm":`pnpm run build:bundle && node ./scripts/preparePublishPackage.mjs`,"start:bundle":`node dist-sea/gateway.cjs`,"build:blob:darwin":`pnpm run build:bundle && node --experimental-sea-config sea-config.darwin.json`,"build:blob:linux":`pnpm run build:bundle && node --experimental-sea-config sea-config.linux.json`,"build:blob:win32":`pnpm run build:bundle && node --experimental-sea-config sea-config.win32.json`,"build:bin":`pnpm run build:bin:current`,"build:bin:current":`pnpm run build:bundle && node ./scripts/buildSea.mjs`,"build:bin:darwin":`pnpm run build:bundle && node ./scripts/buildSea.mjs darwin`,"build:bin:linux":`pnpm run build:bundle && node ./scripts/buildSea.mjs linux`,"build:bin:win32":`pnpm run build:bundle && node ./scripts/buildSea.mjs win32`,test:`vitest run --passWithNoTests`,typecheck:`tsc -p tsconfig.json --noEmit`,"dump:codex-history":`tsx src/dumpCodexSessionHistory.ts`,"export:codex-project-history":`tsx src/exportCodexProjectHistory.ts`,"pairing:start":`tsx src/pairingStart.ts`,"pack:check":`pnpm run build:npm && npm pack --dry-run ./dist-npm --userconfig ../../.npmrc`,"publish:npm":`pnpm run build:npm && npm publish ./dist-npm --access public --userconfig ../../.npmrc`},dependencies:{"@anthropic-ai/claude-agent-sdk":`^0.2.71`,"@fastify/cors":`^10.0.2`,"@fastify/websocket":`^11.0.2`,diff:`^7.0.0`,fastify:`^5.2.1`,jsonwebtoken:`^9.0.2`,nanoid:`^5.1.5`,pino:`^10.3.1`,"qrcode-terminal":`^0.12.0`,ws:`^8.18.3`,yaml:`^2.8.2`},devDependencies:{"@openai/codex":`^0.111.0`,"@remote-agent/contracts":`workspace:*`,"@remote-agent/provider-adapters":`workspace:*`,"@types/diff":`^7.0.1`,"@types/jsonwebtoken":`^9.0.9`,"@types/qrcode-terminal":`^0.12.2`,"@types/ws":`^8.5.13`,postject:`^1.0.0-alpha.6`,tsdown:`^0.21.0`}};const E=/(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/;function D(e){let t=e.match(E);return t?t[0]:null}function O(e){return typeof e==`string`?D(e):null}function k(e,t){let n=j(e),r=j(t);if(!n||!r)throw Error(`Invalid version comparison: ${e} vs ${t}`);return n.major===r.major?n.minor===r.minor?n.patch===r.patch?n.prerelease===r.prerelease?0:n.prerelease?r.prerelease?n.prerelease.localeCompare(r.prerelease):-1:1:n.patch-r.patch:n.minor-r.minor:n.major-r.major}function A(e,t){return k(e,t)>=0}function j(e){let t=e.match(E);return t?{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:typeof t[4]==`string`?t[4]:null}:null}const M=T,ee=M.dependencies??{};function N(e){return ee[e]??``}const te={packageName:`craby-gateway`,cliName:`craby-gateway`,version:M.version??`0.0.0`,providerRequirements:[{id:`codex`,dependencyName:null,dependencyRange:``,minimumVersion:null,systemCommand:`codex`,versionArgs:[`--version`],systemCommandRequired:!0,displayName:`Codex`},{id:`claude`,dependencyName:`@anthropic-ai/claude-agent-sdk`,dependencyRange:N(`@anthropic-ai/claude-agent-sdk`),minimumVersion:O(N(`@anthropic-ai/claude-agent-sdk`)),systemCommand:`claude`,versionArgs:[`--version`],systemCommandRequired:!1,displayName:`Claude Code`}]};function P(e){let t=`start`,n,r=!1,i=!1,a=[...e],o=a[0]?.trim();if(o&&!o.startsWith(`-`))if(o===`start`||o===`init`||o===`doctor`||o===`help`||o===`__worker`)t=o,a.shift();else throw Error(`Unknown command: ${o}`);for(let e=0;e<a.length;e+=1){let o=a[e];if(o===`--config`){n=ne(o,a[e+1]),e+=1;continue}if(o===`--force`){r=!0;continue}if(o===`--log`){i=!0;continue}if(o===`--help`||o===`-h`){t=`help`;continue}if(o===`--version`||o===`-v`){t=`version`;continue}throw Error(`Unknown argument: ${o}`)}return{command:t,configPath:n,force:r,logToConsole:i}}function ne(e,t){let n=t?.trim();if(!n)throw Error(`${e} requires a value`);return n}var F=o((e=>{let t=Symbol.for(`yaml.alias`),n=Symbol.for(`yaml.document`),r=Symbol.for(`yaml.map`),i=Symbol.for(`yaml.pair`),a=Symbol.for(`yaml.scalar`),o=Symbol.for(`yaml.seq`),s=Symbol.for(`yaml.node.type`),c=e=>!!e&&typeof e==`object`&&e[s]===t,l=e=>!!e&&typeof e==`object`&&e[s]===n,u=e=>!!e&&typeof e==`object`&&e[s]===r,d=e=>!!e&&typeof e==`object`&&e[s]===i,f=e=>!!e&&typeof e==`object`&&e[s]===a,p=e=>!!e&&typeof e==`object`&&e[s]===o;function m(e){if(e&&typeof e==`object`)switch(e[s]){case r:case o:return!0}return!1}function h(e){if(e&&typeof e==`object`)switch(e[s]){case t:case r:case a:case o:return!0}return!1}e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=s,e.PAIR=i,e.SCALAR=a,e.SEQ=o,e.hasAnchor=e=>(f(e)||m(e))&&!!e.anchor,e.isAlias=c,e.isCollection=m,e.isDocument=l,e.isMap=u,e.isNode=h,e.isPair=d,e.isScalar=f,e.isSeq=p})),I=o((e=>{var t=F();let n=Symbol(`break visit`),r=Symbol(`skip children`),i=Symbol(`remove node`);function a(e,n){let r=l(n);t.isDocument(e)?o(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):o(null,e,r,Object.freeze([]))}a.BREAK=n,a.SKIP=r,a.REMOVE=i;function o(e,r,a,s){let c=u(e,r,a,s);if(t.isNode(c)||t.isPair(c))return d(e,s,c),o(e,c,a,s);if(typeof c!=`symbol`){if(t.isCollection(r)){s=Object.freeze(s.concat(r));for(let e=0;e<r.items.length;++e){let t=o(e,r.items[e],a,s);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){s=Object.freeze(s.concat(r));let e=o(`key`,r.key,a,s);if(e===n)return n;e===i&&(r.key=null);let t=o(`value`,r.value,a,s);if(t===n)return n;t===i&&(r.value=null)}}return c}async function s(e,n){let r=l(n);t.isDocument(e)?await c(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):await c(null,e,r,Object.freeze([]))}s.BREAK=n,s.SKIP=r,s.REMOVE=i;async function c(e,r,a,o){let s=await u(e,r,a,o);if(t.isNode(s)||t.isPair(s))return d(e,o,s),c(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=await c(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=await c(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=await c(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}function l(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function u(e,n,r,i){if(typeof r==`function`)return r(e,n,i);if(t.isMap(n))return r.Map?.(e,n,i);if(t.isSeq(n))return r.Seq?.(e,n,i);if(t.isPair(n))return r.Pair?.(e,n,i);if(t.isScalar(n))return r.Scalar?.(e,n,i);if(t.isAlias(n))return r.Alias?.(e,n,i)}function d(e,n,r){let i=n[n.length-1];if(t.isCollection(i))i.items[e]=r;else if(t.isPair(i))e===`key`?i.key=r:i.value=r;else if(t.isDocument(i))i.contents=r;else{let e=t.isAlias(i)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=a,e.visitAsync=s})),re=o((e=>{var t=F(),n=I();let r={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},i=e=>e.replace(/[!,[\]{}]/g,e=>r[e]);var a=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+i(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],i=Object.entries(this.tags),a;if(e&&i.length>0&&t.isNode(e.contents)){let r={};n.visit(e.contents,(e,n)=>{t.isNode(n)&&n.tag&&(r[n.tag]=!0)}),a=Object.keys(r)}else a=[];for(let[t,n]of i)t===`!!`&&n===`tag:yaml.org,2002:`||(!e||a.some(e=>e.startsWith(n)))&&r.push(`%TAG ${t} ${n}`);return r.join(`
|
|
3
3
|
`)}};a.defaultYaml={explicit:!1,version:`1.2`},a.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=a})),L=o((e=>{var t=F(),n=I();function r(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function i(e){let t=new Set;return n.visit(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function a(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function o(e,n){let r=[],o=new Map,s=null;return{onAnchor:t=>{r.push(t),s??=i(e);let o=a(n,s);return s.add(o),o},setAnchors:()=>{for(let e of r){let n=o.get(e);if(typeof n==`object`&&n.anchor&&(t.isScalar(n.node)||t.isCollection(n.node)))n.node.anchor=n.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:o}}e.anchorIsValid=r,e.anchorNames=i,e.createNodeAnchors=o,e.findNewAnchor=a})),ie=o((e=>{function t(e,n,r,i){if(i&&typeof i==`object`)if(Array.isArray(i))for(let n=0,r=i.length;n<r;++n){let r=i[n],a=t(e,i,String(n),r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let r=i.get(n),a=t(e,i,n,r);a===void 0?i.delete(n):a!==r&&i.set(n,a)}else if(i instanceof Set)for(let n of Array.from(i)){let r=t(e,i,n,n);r===void 0?i.delete(n):r!==n&&(i.delete(n),i.add(r))}else for(let[n,r]of Object.entries(i)){let a=t(e,i,n,r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}return e.call(n,r,i)}e.applyReviver=t})),ae=o((e=>{var t=F();function n(e,r,i){if(Array.isArray(e))return e.map((e,t)=>n(e,String(t),i));if(e&&typeof e.toJSON==`function`){if(!i||!t.hasAnchor(e))return e.toJSON(r,i);let n={aliasCount:0,count:1,res:void 0};i.anchors.set(e,n),i.onCreate=e=>{n.res=e,delete i.onCreate};let a=e.toJSON(r,i);return i.onCreate&&i.onCreate(a),a}return typeof e==`bigint`&&!i?.keep?Number(e):e}e.toJS=n})),R=o((e=>{var t=ie(),n=F(),r=ae();e.NodeBase=class{constructor(e){Object.defineProperty(this,n.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:i,maxAliasCount:a,onAnchor:o,reviver:s}={}){if(!n.isDocument(e))throw TypeError(`A document argument is required`);let c={anchors:new Map,doc:e,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof a==`number`?a:100},l=r.toJS(this,``,c);if(typeof o==`function`)for(let{count:e,res:t}of c.anchors.values())o(t,e);return typeof s==`function`?t.applyReviver(s,{"":l},``,l):l}}})),oe=o((e=>{var t=L(),n=I(),r=F(),i=R(),a=ae(),o=class extends i.NodeBase{constructor(e){super(r.ALIAS),this.source=e,Object.defineProperty(this,`tag`,{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){let i;t?.aliasResolveCache?i=t.aliasResolveCache:(i=[],n.visit(e,{Node:(e,t)=>{(r.isAlias(t)||r.hasAnchor(t))&&i.push(t)}}),t&&(t.aliasResolveCache=i));let a;for(let e of i){if(e===this)break;e.anchor===this.source&&(a=e)}return a}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:r,maxAliasCount:i}=t,o=this.resolve(r,t);if(!o){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}let c=n.get(o);if(c||=(a.toJS(o,null,t),n.get(o)),c?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(i>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=s(r,o,n)),c.count*c.aliasCount>i))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`);return c.res}toString(e,n,r){let i=`*${this.source}`;if(e){if(t.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${i} `}return i}};function s(e,t,n){if(r.isAlias(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}else if(r.isCollection(t)){let r=0;for(let i of t.items){let t=s(e,i,n);t>r&&(r=t)}return r}else if(r.isPair(t)){let r=s(e,t.key,n),i=s(e,t.value,n);return Math.max(r,i)}return 1}e.Alias=o})),se=o((e=>{var t=F(),n=R(),r=ae();let i=e=>!e||typeof e!=`function`&&typeof e!=`object`;var a=class extends n.NodeBase{constructor(e){super(t.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:r.toJS(this.value,e,t)}toString(){return String(this.value)}};a.BLOCK_FOLDED=`BLOCK_FOLDED`,a.BLOCK_LITERAL=`BLOCK_LITERAL`,a.PLAIN=`PLAIN`,a.QUOTE_DOUBLE=`QUOTE_DOUBLE`,a.QUOTE_SINGLE=`QUOTE_SINGLE`,e.Scalar=a,e.isScalarValue=i})),ce=o((e=>{var t=oe(),n=F(),r=se();function i(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function a(e,a,o){if(n.isDocument(e)&&(e=e.contents),n.isNode(e))return e;if(n.isPair(e)){let t=o.schema[n.MAP].createNode?.(o.schema,null,o);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:s,onAnchor:c,onTagObj:l,schema:u,sourceObjects:d}=o,f;if(s&&e&&typeof e==`object`){if(f=d.get(e),f)return f.anchor??=c(e),new t.Alias(f.anchor);f={anchor:null,node:null},d.set(e,f)}a?.startsWith(`!!`)&&(a=`tag:yaml.org,2002:`+a.slice(2));let p=i(e,a,u.tags);if(!p){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new r.Scalar(e);return f&&(f.node=t),t}p=e instanceof Map?u[n.MAP]:Symbol.iterator in Object(e)?u[n.SEQ]:u[n.MAP]}l&&(l(p),delete o.onTagObj);let m=p?.createNode?p.createNode(o.schema,e,o):typeof p?.nodeClass?.from==`function`?p.nodeClass.from(o.schema,e,o):new r.Scalar(e);return a?m.tag=a:p.default||(m.tag=p.tag),f&&(f.node=m),m}e.createNode=a})),le=o((e=>{var t=ce(),n=F(),r=R();function i(e,n,r){let i=r;for(let e=n.length-1;e>=0;--e){let t=n[e];if(typeof t==`number`&&Number.isInteger(t)&&t>=0){let e=[];e[t]=i,i=e}else i=new Map([[t,i]])}return t.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}let a=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done;e.Collection=class extends r.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,`schema`,{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>n.isNode(t)||n.isPair(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(a(e))this.add(t);else{let[r,...a]=e,o=this.get(r,!0);if(n.isCollection(o))o.addIn(a,t);else if(o===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}deleteIn(e){let[t,...r]=e;if(r.length===0)return this.delete(t);let i=this.get(t,!0);if(n.isCollection(i))return i.deleteIn(r);throw Error(`Expected YAML collection at ${t}. Remaining path: ${r}`)}getIn(e,t){let[r,...i]=e,a=this.get(r,!0);return i.length===0?!t&&n.isScalar(a)?a.value:a:n.isCollection(a)?a.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!n.isPair(t))return!1;let r=t.value;return r==null||e&&n.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[t,...r]=e;if(r.length===0)return this.has(t);let i=this.get(t,!0);return n.isCollection(i)?i.hasIn(r):!1}setIn(e,t){let[r,...a]=e;if(a.length===0)this.set(r,t);else{let e=this.get(r,!0);if(n.isCollection(e))e.setIn(a,t);else if(e===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}},e.collectionFromPath=i,e.isEmptyPath=a})),ue=o((e=>{let t=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function n(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}e.indentComment=n,e.lineComment=(e,t,r)=>e.endsWith(`
|
|
4
4
|
`)?n(r,t):r.includes(`
|
|
5
5
|
`)?`
|
|
@@ -126,14 +126,14 @@ causes have become circular...`;let o=r(e);return o?(t.add(e),a+`
|
|
|
126
126
|
caused by: `+i(o,t)):a},a=e=>i(e,new Set),o=(e,t,i)=>{if(!n(e))return``;let a=i?``:e.message||``;if(t.has(e))return a+`: ...`;let s=r(e);if(s){t.add(e);let n=typeof e.cause==`function`;return a+(n?``:`: `)+o(s,t,n)}else return a};t.exports={isErrorLike:n,getErrorCause:r,stackWithCauses:a,messageWithCauses:e=>o(e,new Set)}})),Eu=o(((e,t)=>{let n=Symbol(`circular-ref-tag`),r=Symbol(`pino-raw-err-ref`),i=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[r]},set:function(e){this[r]=e}}});Object.defineProperty(i,r,{writable:!0,value:{}}),t.exports={pinoErrProto:i,pinoErrorSymbols:{seen:n,rawSymbol:r}}})),Du=o(((e,t)=>{t.exports=l;let{messageWithCauses:n,stackWithCauses:r,isErrorLike:i}=Tu(),{pinoErrProto:a,pinoErrorSymbols:o}=Eu(),{seen:s}=o,{toString:c}=Object.prototype;function l(e){if(!i(e))return e;e[s]=void 0;let t=Object.create(a);t.type=c.call(e.constructor)===`[object Function]`?e.constructor.name:e.name,t.message=n(e),t.stack=r(e),Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(e=>l(e)));for(let n in e)if(t[n]===void 0){let r=e[n];i(r)?n!==`cause`&&!Object.prototype.hasOwnProperty.call(r,s)&&(t[n]=l(r)):t[n]=r}return delete e[s],t.raw=e,t}})),Ou=o(((e,t)=>{t.exports=s;let{isErrorLike:n}=Tu(),{pinoErrProto:r,pinoErrorSymbols:i}=Eu(),{seen:a}=i,{toString:o}=Object.prototype;function s(e){if(!n(e))return e;e[a]=void 0;let t=Object.create(r);t.type=o.call(e.constructor)===`[object Function]`?e.constructor.name:e.name,t.message=e.message,t.stack=e.stack,Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(e=>s(e))),n(e.cause)&&!Object.prototype.hasOwnProperty.call(e.cause,a)&&(t.cause=s(e.cause));for(let r in e)if(t[r]===void 0){let i=e[r];n(i)?Object.prototype.hasOwnProperty.call(i,a)||(t[r]=s(i)):t[r]=i}return delete e[a],t.raw=e,t}})),ku=o(((e,t)=>{t.exports={mapHttpRequest:a,reqSerializer:i};let n=Symbol(`pino-raw-req-ref`),r=Object.create({},{id:{enumerable:!0,writable:!0,value:``},method:{enumerable:!0,writable:!0,value:``},url:{enumerable:!0,writable:!0,value:``},query:{enumerable:!0,writable:!0,value:``},params:{enumerable:!0,writable:!0,value:``},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:``},remotePort:{enumerable:!0,writable:!0,value:``},raw:{enumerable:!1,get:function(){return this[n]},set:function(e){this[n]=e}}});Object.defineProperty(r,n,{writable:!0,value:{}});function i(e){let t=e.info||e.socket,n=Object.create(r);if(n.id=typeof e.id==`function`?e.id():e.id||(e.info?e.info.id:void 0),n.method=e.method,e.originalUrl)n.url=e.originalUrl;else{let t=e.path;n.url=typeof t==`string`?t:e.url?e.url.path||e.url:void 0}return e.query&&(n.query=e.query),e.params&&(n.params=e.params),n.headers=e.headers,n.remoteAddress=t&&t.remoteAddress,n.remotePort=t&&t.remotePort,n.raw=e.raw||e,n}function a(e){return{req:i(e)}}})),Au=o(((e,t)=>{t.exports={mapHttpResponse:a,resSerializer:i};let n=Symbol(`pino-raw-res-ref`),r=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:``},raw:{enumerable:!1,get:function(){return this[n]},set:function(e){this[n]=e}}});Object.defineProperty(r,n,{writable:!0,value:{}});function i(e){let t=Object.create(r);return t.statusCode=e.headersSent?e.statusCode:null,t.headers=e.getHeaders?e.getHeaders():e._headers,t.raw=e,t}function a(e){return{res:i(e)}}})),ju=o(((e,t)=>{let n=Du(),r=Ou(),i=ku(),a=Au();t.exports={err:n,errWithCause:r,mapHttpRequest:i.mapHttpRequest,mapHttpResponse:a.mapHttpResponse,req:i.reqSerializer,res:a.resSerializer,wrapErrorSerializer:function(e){return e===n?e:function(t){return e(n(t))}},wrapRequestSerializer:function(e){return e===i.reqSerializer?e:function(t){return e(i.reqSerializer(t))}},wrapResponseSerializer:function(e){return e===a.resSerializer?e:function(t){return e(a.resSerializer(t))}}}})),Mu=o(((e,t)=>{function n(e,t){return t}t.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=n;let t=Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(t))return;let r=t.slice(2),i=[];for(let e of r)e&&i.push(e.getFileName());return i}})),Nu=o(((e,t)=>{function n(e){if(typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof Array){let t=[];for(let r=0;r<e.length;r++)t[r]=n(e[r]);return t}if(typeof e==`object`){let t=Object.create(Object.getPrototypeOf(e));for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=n(e[r]));return t}return e}function r(e){let t=[],n=``,r=!1,i=!1,a=``;for(let o=0;o<e.length;o++){let s=e[o];!r&&s===`.`?n&&=(t.push(n),``):s===`[`?(n&&=(t.push(n),``),r=!0):s===`]`&&r?(t.push(n),n=``,r=!1,i=!1):(s===`"`||s===`'`)&&r?i?s===a?(i=!1,a=``):n+=s:(i=!0,a=s):n+=s}return n&&t.push(n),t}function i(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){let n=t[e];if(typeof r!=`object`||!r||!(n in r)||typeof r[n]!=`object`||r[n]===null)return!1;r=r[n]}let i=t[t.length-1];if(i===`*`){if(Array.isArray(r))for(let e=0;e<r.length;e++)r[e]=n;else if(typeof r==`object`&&r)for(let e in r)Object.prototype.hasOwnProperty.call(r,e)&&(r[e]=n)}else typeof r==`object`&&r&&i in r&&Object.prototype.hasOwnProperty.call(r,i)&&(r[i]=n);return!0}function a(e,t){let n=e;for(let e=0;e<t.length-1;e++){let r=t[e];if(typeof n!=`object`||!n||!(r in n)||typeof n[r]!=`object`||n[r]===null)return!1;n=n[r]}let r=t[t.length-1];if(r===`*`){if(Array.isArray(n))for(let e=0;e<n.length;e++)n[e]=void 0;else if(typeof n==`object`&&n)for(let e in n)Object.prototype.hasOwnProperty.call(n,e)&&delete n[e]}else typeof n==`object`&&n&&r in n&&Object.prototype.hasOwnProperty.call(n,r)&&delete n[r];return!0}let o=Symbol(`PATH_NOT_FOUND`);function s(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n||!n||!(e in n))return o;n=n[e]}return n}function c(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n||!n)return;n=n[e]}return n}function l(e,t,n,c=!1){for(let l of t){let t=r(l);if(t.includes(`*`))u(e,t,n,l,c);else if(c)a(e,t);else{let r=s(e,t);if(r===o)continue;i(e,t,typeof n==`function`?n(r,t):n)}}}function u(e,t,n,r,i=!1){let a=t.indexOf(`*`);if(a===t.length-1){let r=t.slice(0,-1),a=e;for(let e of r){if(typeof a!=`object`||!a||!a)return;a=a[e]}if(Array.isArray(a))if(i)for(let e=0;e<a.length;e++)a[e]=void 0;else for(let e=0;e<a.length;e++){let t=[...r,e.toString()],i=typeof n==`function`?n(a[e],t):n;a[e]=i}else if(typeof a==`object`&&a)if(i){let e=[];for(let t in a)Object.prototype.hasOwnProperty.call(a,t)&&e.push(t);for(let t of e)delete a[t]}else for(let e in a){let t=[...r,e],i=typeof n==`function`?n(a[e],t):n;a[e]=i}}else d(e,t,n,a,r,i)}function d(e,t,n,r,o,s=!1){let l=t.slice(0,r),d=t.slice(r+1),f=[];function p(e,t){if(t===l.length){if(Array.isArray(e))for(let n=0;n<e.length;n++)f[t]=n.toString(),p(e[n],t+1);else if(typeof e==`object`&&e)for(let n in e)f[t]=n,p(e[n],t+1)}else if(t<l.length){let n=l[t];e&&typeof e==`object`&&e&&n in e&&(f[t]=n,p(e[n],t+1))}else d.includes(`*`)?u(e,d,typeof n==`function`?(e,r)=>n(e,[...f.slice(0,t),...r]):n,o,s):s?a(e,d):i(e,d,typeof n==`function`?n(c(e,d),[...f.slice(0,t),...d]):n)}if(l.length===0)p(e,0);else{let t=e;for(let e=0;e<l.length;e++){let n=l[e];if(typeof t!=`object`||!t||!t)return;t=t[n],f[e]=n}t!=null&&p(t,l.length)}}function f(e){if(e.length===0)return null;let t=new Map;for(let n of e){let e=r(n),i=t;for(let t=0;t<e.length;t++){let n=e[t];i.has(n)||i.set(n,new Map),i=i.get(n)}}return t}function p(e,t){if(!t)return e;function n(e,t,r=0){if(!t||t.size===0||typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e)){let r=[];for(let i=0;i<e.length;i++){let a=i.toString();t.has(a)||t.has(`*`)?r[i]=n(e[i],t.get(a)||t.get(`*`)):r[i]=e[i]}return r}let i=Object.create(Object.getPrototypeOf(e));for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t.has(r)||t.has(`*`)?i[r]=n(e[r],t.get(r)||t.get(`*`)):i[r]=e[r]);return i}return n(e,t)}function m(e){if(typeof e!=`string`)throw Error(`Paths must be (non-empty) strings`);if(e===``)throw Error(`Invalid redaction path ()`);if(e.includes(`..`)||e.includes(`,`))throw Error(`Invalid redaction path (${e})`);let t=0,n=!1,r=``;for(let i=0;i<e.length;i++){let a=e[i];if((a===`"`||a===`'`)&&t>0)n?a===r&&(n=!1,r=``):(n=!0,r=a);else if(a===`[`&&!n)t++;else if(a===`]`&&!n&&(t--,t<0))throw Error(`Invalid redaction path (${e})`)}if(t!==0)throw Error(`Invalid redaction path (${e})`)}function h(e){if(!Array.isArray(e))throw TypeError(`paths must be an array`);for(let t of e)m(t)}function g(e={}){let{paths:t=[],censor:r=`[REDACTED]`,serialize:i=JSON.stringify,strict:a=!0,remove:o=!1}=e;h(t);let s=f(t);return function(e){if(a&&(typeof e!=`object`||!e)&&(typeof e!=`object`||!e))return i?i(e):e;let c=p(e,s),u=e,d=r;return typeof r==`function`&&(d=r),l(c,t,d,o),i===!1?(c.restore=function(){return n(u)},c):typeof i==`function`?i(c):JSON.stringify(c)}}t.exports=g})),Pu=o(((e,t)=>{let n=Symbol(`pino.setLevel`),r=Symbol(`pino.getLevel`),i=Symbol(`pino.levelVal`),a=Symbol(`pino.levelComp`),o=Symbol(`pino.useLevelLabels`),s=Symbol(`pino.useOnlyCustomLevels`),c=Symbol(`pino.mixin`),l=Symbol(`pino.lsCache`),u=Symbol(`pino.chindings`),d=Symbol(`pino.asJson`),f=Symbol(`pino.write`),p=Symbol(`pino.redactFmt`),m=Symbol(`pino.time`),h=Symbol(`pino.timeSliceIndex`),g=Symbol(`pino.stream`),_=Symbol(`pino.stringify`),v=Symbol(`pino.stringifySafe`),y=Symbol(`pino.stringifiers`),b=Symbol(`pino.end`),x=Symbol(`pino.formatOpts`),S=Symbol(`pino.messageKey`),C=Symbol(`pino.errorKey`),w=Symbol(`pino.nestedKey`),T=Symbol(`pino.nestedKeyStr`),E=Symbol(`pino.mixinMergeStrategy`),D=Symbol(`pino.msgPrefix`),O=Symbol(`pino.wildcardFirst`),k=Symbol.for(`pino.serializers`),A=Symbol.for(`pino.formatters`),j=Symbol.for(`pino.hooks`);t.exports={setLevelSym:n,getLevelSym:r,levelValSym:i,levelCompSym:a,useLevelLabelsSym:o,mixinSym:c,lsCacheSym:l,chindingsSym:u,asJsonSym:d,writeSym:f,serializersSym:k,redactFmtSym:p,timeSym:m,timeSliceIndexSym:h,streamSym:g,stringifySym:_,stringifySafeSym:v,stringifiersSym:y,endSym:b,formatOptsSym:x,messageKeySym:S,errorKeySym:C,nestedKeySym:w,wildcardFirstSym:O,needsMetadataGsym:Symbol.for(`pino.metadata`),useOnlyCustomLevelsSym:s,formattersSym:A,hooksSym:j,nestedKeyStrSym:T,mixinMergeStrategySym:E,msgPrefixSym:D}})),Fu=o(((e,t)=>{let n=Nu(),{redactFmtSym:r,wildcardFirstSym:i}=Pu(),a=/[^.[\]]+|\[([^[\]]*?)\]/g,o=`[Redacted]`;function s(e,t){let{paths:o,censor:s,remove:l}=c(e),u=o.reduce((e,t)=>{a.lastIndex=0;let n=a.exec(t),r=a.exec(t),o=n[1]===void 0?n[0]:n[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,`$1`);if(o===`*`&&(o=i),r===null)return e[o]=null,e;if(e[o]===null)return e;let{index:s}=r,c=`${t.substr(s,t.length-1)}`;return e[o]=e[o]||[],o!==i&&e[o].length===0&&e[o].push(...e[i]||[]),o===i&&Object.keys(e).forEach(function(t){e[t]&&e[t].push(c)}),e[o].push(c),e},{}),d={[r]:n({paths:o,censor:s,serialize:t,strict:!1,remove:l})},f=(...e)=>t(typeof s==`function`?s(...e):s);return[...Object.keys(u),...Object.getOwnPropertySymbols(u)].reduce((e,r)=>{if(u[r]===null)e[r]=e=>f(e,[r]);else{let i=typeof s==`function`?(e,t)=>s(e,[r,...t]):s;e[r]=n({paths:u[r],censor:i,serialize:t,strict:!1,remove:l})}return e},d)}function c(e){if(Array.isArray(e))return e={paths:e,censor:o},e;let{paths:t,censor:n=o,remove:r}=e;if(Array.isArray(t)===!1)throw Error(`pino – redact must contain an array of strings`);return r===!0&&(n=void 0),{paths:t,censor:n,remove:r}}t.exports=s})),Iu=o(((e,t)=>{let n=()=>``,r=()=>`,"time":${Date.now()}`,i=()=>`,"time":${Math.round(Date.now()/1e3)}`,a=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,o=1000000000n,s=BigInt(Date.now())*1000000n,c=process.hrtime.bigint();t.exports={nullTime:n,epochTime:r,unixTime:i,isoTime:a,isoTimeNano:()=>{let e=s+(process.hrtime.bigint()-c),t=e/o,n=e%o,r=Number(t*1000n+n/1000000n),i=new Date(r);return`,"time":"${i.getUTCFullYear()}-${(i.getUTCMonth()+1).toString().padStart(2,`0`)}-${i.getUTCDate().toString().padStart(2,`0`)}T${i.getUTCHours().toString().padStart(2,`0`)}:${i.getUTCMinutes().toString().padStart(2,`0`)}:${i.getUTCSeconds().toString().padStart(2,`0`)}.${n.toString().padStart(9,`0`)}Z"`}}})),Lu=o(((e,t)=>{function n(e){try{return JSON.stringify(e)}catch{return`"[Circular]"`}}t.exports=r;function r(e,t,r){var i=r&&r.stringify||n,a=1;if(typeof e==`object`&&e){var o=t.length+a;if(o===1)return e;var s=Array(o);s[0]=i(e);for(var c=1;c<o;c++)s[c]=i(t[c]);return s.join(` `)}if(typeof e!=`string`)return e;var l=t.length;if(l===0)return e;for(var u=``,d=1-a,f=-1,p=e&&e.length||0,m=0;m<p;){if(e.charCodeAt(m)===37&&m+1<p){switch(f=f>-1?f:0,e.charCodeAt(m+1)){case 100:case 102:if(d>=l||t[d]==null)break;f<m&&(u+=e.slice(f,m)),u+=Number(t[d]),f=m+2,m++;break;case 105:if(d>=l||t[d]==null)break;f<m&&(u+=e.slice(f,m)),u+=Math.floor(Number(t[d])),f=m+2,m++;break;case 79:case 111:case 106:if(d>=l||t[d]===void 0)break;f<m&&(u+=e.slice(f,m));var h=typeof t[d];if(h===`string`){u+=`'`+t[d]+`'`,f=m+2,m++;break}if(h===`function`){u+=t[d].name||`<anonymous>`,f=m+2,m++;break}u+=i(t[d]),f=m+2,m++;break;case 115:if(d>=l)break;f<m&&(u+=e.slice(f,m)),u+=String(t[d]),f=m+2,m++;break;case 37:f<m&&(u+=e.slice(f,m)),u+=`%`,f=m+2,m++,d--;break}++d}++m}return f===-1?e:(f<p&&(u+=e.slice(f)),u)}})),Ru=o(((e,t)=>{if(typeof SharedArrayBuffer<`u`&&typeof Atomics<`u`){let e=new Int32Array(new SharedArrayBuffer(4));function n(t){if(!(t>0&&t<1/0))throw typeof t!=`number`&&typeof t!=`bigint`?TypeError(`sleep: ms must be a number`):RangeError(`sleep: ms must be a number that is greater than 0 but less than Infinity`);Atomics.wait(e,0,0,Number(t))}t.exports=n}else{function e(e){if(!(e>0&&e<1/0))throw typeof e!=`number`&&typeof e!=`bigint`?TypeError(`sleep: ms must be a number`):RangeError(`sleep: ms must be a number that is greater than 0 but less than Infinity`);let t=Date.now()+Number(e);for(;t>Date.now(););}t.exports=e}})),zu=o(((e,t)=>{let n=require(`fs`),r=require(`events`),i=require(`util`).inherits,a=require(`path`),o=Ru(),s=require(`assert`),c=Buffer.allocUnsafe(0),l=`buffer`,u=`utf8`,[d,f]=(process.versions.node||`0.0`).split(`.`).map(Number),p=d>=22&&f>=7;function m(e,t){t._opening=!0,t._writing=!0,t._asyncDrainScheduled=!1;function r(n,r){if(n){t._reopening=!1,t._writing=!1,t._opening=!1,t.sync?process.nextTick(()=>{t.listenerCount(`error`)>0&&t.emit(`error`,n)}):t.emit(`error`,n);return}let i=t._reopening;t.fd=r,t.file=e,t._reopening=!1,t._opening=!1,t._writing=!1,t.sync?process.nextTick(()=>t.emit(`ready`)):t.emit(`ready`),!t.destroyed&&(!t._writing&&t._len>t.minLength||t._flushPending?t._actualWrite():i&&process.nextTick(()=>t.emit(`drain`)))}let i=t.append?`a`:`w`,o=t.mode;if(t.sync)try{t.mkdir&&n.mkdirSync(a.dirname(e),{recursive:!0}),r(null,n.openSync(e,i,o))}catch(e){throw r(e),e}else t.mkdir?n.mkdir(a.dirname(e),{recursive:!0},t=>{if(t)return r(t);n.open(e,i,o,r)}):n.open(e,i,o,r)}function h(e){if(!(this instanceof h))return new h(e);let{fd:t,dest:r,minLength:i,maxLength:a,maxWrite:s,periodicFlush:d,sync:f,append:p=!0,mkdir:v,retryEAGAIN:x,fsync:k,contentMode:A,mode:j}=e||{};t||=r,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(i||0,16387),this.file=null,this.destroyed=!1,this.minLength=i||0,this.maxLength=a||0,this.maxWrite=s||16384,this._periodicFlush=d||0,this._periodicFlushTimer=void 0,this.sync=f||!1,this.writable=!0,this._fsync=k||!1,this.append=p||!1,this.mode=j,this.retryEAGAIN=x||(()=>!0),this.mkdir=v||!1;let M,ee;if(A===l)this._writingBuf=c,this.write=b,this.flush=C,this.flushSync=T,this._actualWrite=D,M=()=>n.writeSync(this.fd,this._writingBuf),ee=()=>n.write(this.fd,this._writingBuf,this.release);else if(A===void 0||A===u)this._writingBuf=``,this.write=y,this.flush=S,this.flushSync=w,this._actualWrite=E,M=()=>Buffer.isBuffer(this._writingBuf)?n.writeSync(this.fd,this._writingBuf):n.writeSync(this.fd,this._writingBuf,`utf8`),ee=()=>Buffer.isBuffer(this._writingBuf)?n.write(this.fd,this._writingBuf,this.release):n.write(this.fd,this._writingBuf,`utf8`,this.release);else throw Error(`SonicBoom supports "${u}" and "${l}", but passed ${A}`);if(typeof t==`number`)this.fd=t,process.nextTick(()=>this.emit(`ready`));else if(typeof t==`string`)m(t,this);else throw Error(`SonicBoom supports only file descriptors and files`);if(this.minLength>=this.maxWrite)throw Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(e,t)=>{if(e){if((e.code===`EAGAIN`||e.code===`EBUSY`)&&this.retryEAGAIN(e,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{o(100),this.release(void 0,0)}catch(e){this.release(e)}else setTimeout(ee,100);else this._writing=!1,this.emit(`error`,e);return}this.emit(`write`,t);let r=g(this._writingBuf,this._len,t);if(this._len=r.len,this._writingBuf=r.writingBuf,this._writingBuf.length){if(!this.sync){ee();return}try{do{let e=M(),t=g(this._writingBuf,this._len,e);this._len=t.len,this._writingBuf=t.writingBuf}while(this._writingBuf.length)}catch(e){this.release(e);return}}this._fsync&&n.fsyncSync(this.fd);let i=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):i>this.minLength?this._actualWrite():this._ending?i>0?this._actualWrite():(this._writing=!1,O(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(_,this)):this.emit(`drain`))},this.on(`newListener`,function(e){e===`drain`&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function g(e,t,n){return typeof e==`string`&&(e=Buffer.from(e)),t=Math.max(t-n,0),e=e.subarray(n),{writingBuf:e,len:t}}function _(e){e.listenerCount(`drain`)>0&&(e._asyncDrainScheduled=!1,e.emit(`drain`))}i(h,r);function v(e,t){return e.length===0?c:e.length===1?e[0]:Buffer.concat(e,t)}function y(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);e=``+e;let t=Buffer.byteLength(e),n=this._len+t,r=this._bufs;return this.maxLength&&n>this.maxLength?(this.emit(`drop`,e),this._len<this._hwm):(r.length===0||Buffer.byteLength(r[r.length-1])+t>this.maxWrite?r.push(e):r[r.length-1]+=e,this._len=n,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function b(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);let t=this._len+e.length,n=this._bufs,r=this._lens;return this.maxLength&&t>this.maxLength?(this.emit(`drop`,e),this._len<this._hwm):(n.length===0||r[r.length-1]+e.length>this.maxWrite?(n.push([e]),r.push(e.length)):(n[n.length-1].push(e),r[r.length-1]+=e.length),this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function x(e){this._flushPending=!0;let t=()=>{if(this._fsync)this._flushPending=!1,e();else try{n.fsync(this.fd,t=>{this._flushPending=!1,e(t)})}catch(t){e(t)}this.off(`error`,r)},r=n=>{this._flushPending=!1,e(n),this.off(`drain`,t)};this.once(`drain`,t),this.once(`error`,r)}function S(e){if(e!=null&&typeof e!=`function`)throw Error(`flush cb must be a function`);if(this.destroyed){let t=Error(`SonicBoom destroyed`);if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&x.call(this,e),!this._writing&&(this._bufs.length===0&&this._bufs.push(``),this._actualWrite())}function C(e){if(e!=null&&typeof e!=`function`)throw Error(`flush cb must be a function`);if(this.destroyed){let t=Error(`SonicBoom destroyed`);if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&x.call(this,e),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}h.prototype.reopen=function(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this._opening){this.once(`ready`,()=>{this.reopen(e)});return}if(this._ending)return;if(!this.file)throw Error(`Unable to reopen a file descriptor, you must pass a file to SonicBoom`);if(e&&(this.file=e),this._reopening=!0,this._writing)return;let t=this.fd;this.once(`ready`,()=>{t!==this.fd&&n.close(t,e=>{if(e)return this.emit(`error`,e)})}),m(this.file,this)},h.prototype.end=function(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this._opening){this.once(`ready`,()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():O(this)))};function w(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this.fd<0)throw Error(`sonic boom is not ready yet`);!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf=``);let e=``;for(;this._bufs.length||e.length;){e.length<=0&&(e=this._bufs[0]);try{let t=Buffer.isBuffer(e)?n.writeSync(this.fd,e):n.writeSync(this.fd,e,`utf8`),r=g(e,this._len,t);e=r.writingBuf,this._len=r.len,e.length<=0&&this._bufs.shift()}catch(t){if((t.code===`EAGAIN`||t.code===`EBUSY`)&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;o(100)}}try{n.fsyncSync(this.fd)}catch{}}function T(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this.fd<0)throw Error(`sonic boom is not ready yet`);!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=c);let e=c;for(;this._bufs.length||e.length;){e.length<=0&&(e=v(this._bufs[0],this._lens[0]));try{let t=n.writeSync(this.fd,e);e=e.subarray(t),this._len=Math.max(this._len-t,0),e.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(t){if((t.code===`EAGAIN`||t.code===`EBUSY`)&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;o(100)}}}h.prototype.destroy=function(){this.destroyed||O(this)};function E(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||``,this.sync)try{e(null,Buffer.isBuffer(this._writingBuf)?n.writeSync(this.fd,this._writingBuf):n.writeSync(this.fd,this._writingBuf,`utf8`))}catch(t){e(t)}else n.write(this.fd,this._writingBuf,e)}function D(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:v(this._bufs.shift(),this._lens.shift()),this.sync)try{e(null,n.writeSync(this.fd,this._writingBuf))}catch(t){e(t)}else p&&(this._writingBuf=Buffer.from(this._writingBuf)),n.write(this.fd,this._writingBuf,e)}function O(e){if(e.fd===-1){e.once(`ready`,O.bind(null,e));return}e._periodicFlushTimer!==void 0&&clearInterval(e._periodicFlushTimer),e.destroyed=!0,e._bufs=[],e._lens=[],s(typeof e.fd==`number`,`sonic.fd must be a number, got ${typeof e.fd}`);try{n.fsync(e.fd,t)}catch{}function t(){e.fd!==1&&e.fd!==2?n.close(e.fd,r):r()}function r(t){if(t){e.emit(`error`,t);return}e._ending&&!e._writing&&e.emit(`finish`),e.emit(`close`)}}h.SonicBoom=h,h.default=h,t.exports=h})),Bu=o(((e,t)=>{let n={exit:[],beforeExit:[]},r={exit:c,beforeExit:l},i;function a(){i===void 0&&(i=new FinalizationRegistry(d))}function o(e){n[e].length>0||process.on(e,r[e])}function s(e){n[e].length>0||(process.removeListener(e,r[e]),n.exit.length===0&&n.beforeExit.length===0&&(i=void 0))}function c(){u(`exit`)}function l(){u(`beforeExit`)}function u(e){for(let t of n[e]){let n=t.deref(),r=t.fn;n!==void 0&&r(n,e)}n[e]=[]}function d(e){for(let t of[`exit`,`beforeExit`]){let r=n[t].indexOf(e);n[t].splice(r,r+1),s(t)}}function f(e,t,r){if(t===void 0)throw Error(`the object can't be undefined`);o(e);let s=new WeakRef(t);s.fn=r,a(),i.register(t,s),n[e].push(s)}function p(e,t){f(`exit`,e,t)}function m(e,t){f(`beforeExit`,e,t)}function h(e){if(i!==void 0){i.unregister(e);for(let t of[`exit`,`beforeExit`])n[t]=n[t].filter(t=>{let n=t.deref();return n&&n!==e}),s(t)}}t.exports={register:p,registerBeforeExit:m,unregister:h}})),Vu=o(((e,t)=>{t.exports={name:`thread-stream`,version:`4.0.0`,description:`A streaming way to send data to a Node.js Worker Thread`,main:`index.js`,types:`index.d.ts`,engines:{node:`>=20`},dependencies:{"real-require":`^0.2.0`},devDependencies:{"@types/node":`^22.0.0`,"@yao-pkg/pkg":`^6.0.0`,borp:`^0.21.0`,desm:`^1.3.0`,eslint:`^9.39.1`,fastbench:`^1.0.1`,husky:`^9.0.6`,neostandard:`^0.12.2`,"pino-elasticsearch":`^8.0.0`,"sonic-boom":`^4.0.1`,"ts-node":`^10.8.0`,typescript:`~5.7.3`},scripts:{build:`tsc --noEmit`,lint:`eslint`,test:`npm run lint && npm run build && npm run transpile && borp --pattern 'test/*.test.{js,mjs}'`,"test:ci":`npm run lint && npm run transpile && borp --pattern 'test/*.test.{js,mjs}'`,"test:yarn":`npm run transpile && borp --pattern 'test/*.test.js'`,transpile:`sh ./test/ts/transpile.sh`,prepare:`husky install`},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`}})),Hu=o(((e,t)=>{let n=1e4;function r(e,t,r,i,a){let o=i===1/0?1/0:Date.now()+i,s=()=>{let i=Atomics.load(e,t);if(i===r){a(null,`ok`);return}if(o!==1/0&&Date.now()>o){a(null,`timed-out`);return}let c=o===1/0?n:Math.min(n,Math.max(1,o-Date.now())),l=Atomics.waitAsync(e,t,i,c);l.async?l.value.then(s):setImmediate(s)};s()}function i(e,t,r,i,a){let o=i===1/0?1/0:Date.now()+i,s=()=>{if(Atomics.load(e,t)!==r){a(null,`ok`);return}if(o!==1/0&&Date.now()>o){a(null,`timed-out`);return}let i=o===1/0?n:Math.min(n,Math.max(1,o-Date.now())),c=Atomics.waitAsync(e,t,r,i);c.async?c.value.then(s):setImmediate(s)};s()}t.exports={wait:r,waitDiff:i}})),Uu=o(((e,t)=>{t.exports={WRITE_INDEX:4,READ_INDEX:8}})),Wu=o(((e,t)=>{let{version:n}=Vu(),{EventEmitter:r}=require(`events`),{Worker:i}=require(`worker_threads`),{join:a}=require(`path`),{pathToFileURL:o}=require(`url`),{wait:s}=Hu(),{WRITE_INDEX:c,READ_INDEX:l}=Uu(),u=require(`buffer`),d=require(`assert`),f=Symbol(`kImpl`),p=u.constants.MAX_STRING_LENGTH;var m=class{constructor(e){this._value=e}deref(){return this._value}},h=class{register(){}unregister(){}};let g=process.env.NODE_V8_COVERAGE?h:global.FinalizationRegistry||h,_=process.env.NODE_V8_COVERAGE?m:global.WeakRef||m,v=new g(e=>{e.exited||e.terminate()});function y(e,t){let{filename:r,workerData:s}=t,c=new i((`__bundlerPathsOverrides`in globalThis?globalThis.__bundlerPathsOverrides:{})[`thread-stream-worker`]||a(__dirname,`lib`,`worker.js`),{...t.workerOpts,trackUnmanagedFds:!1,workerData:{filename:r.indexOf(`file://`)===0?r:o(r).href,dataBuf:e[f].dataBuf,stateBuf:e[f].stateBuf,workerData:{$context:{threadStreamVersion:n},...s}}});return c.stream=new m(e),c.on(`message`,S),c.on(`exit`,C),v.register(e,c),c}function b(e){d(!e[f].sync),e[f].needDrain&&(e[f].needDrain=!1,e.emit(`drain`))}function x(e){let t=Atomics.load(e[f].state,c),n=e[f].data.length-t;if(n>0){if(e[f].buf.length===0){e[f].flushing=!1,e[f].ending?O(e):e[f].needDrain&&process.nextTick(b,e);return}let t=e[f].buf.slice(0,n),r=Buffer.byteLength(t);r<=n?(e[f].buf=e[f].buf.slice(n),D(e,t,x.bind(null,e))):e.flush(()=>{if(!e.destroyed){for(Atomics.store(e[f].state,l,0),Atomics.store(e[f].state,c,0),Atomics.notify(e[f].state,l);r>e[f].data.length;)n/=2,t=e[f].buf.slice(0,n),r=Buffer.byteLength(t);e[f].buf=e[f].buf.slice(n),D(e,t,x.bind(null,e))}})}else if(n===0){if(t===0&&e[f].buf.length===0)return;e.flush(()=>{Atomics.store(e[f].state,l,0),Atomics.store(e[f].state,c,0),Atomics.notify(e[f].state,l),x(e)})}else E(e,Error(`overwritten`))}function S(e){let t=this.stream.deref();if(t===void 0){this.exited=!0,this.terminate();return}switch(e.code){case`READY`:this.stream=new _(t),t.flush(()=>{t[f].ready=!0,t.emit(`ready`)});break;case`ERROR`:E(t,e.err);break;case`EVENT`:Array.isArray(e.args)?t.emit(e.name,...e.args):t.emit(e.name,e.args);break;case`WARNING`:process.emitWarning(e.err);break;default:E(t,Error(`this should not happen: `+e.code))}}function C(e){let t=this.stream.deref();t!==void 0&&(v.unregister(t),t.worker.exited=!0,t.worker.off(`exit`,C),E(t,e===0?null:Error(`the worker thread exited`)))}var w=class extends r{constructor(e={}){if(super(),e.bufferSize<4)throw Error(`bufferSize must at least fit a 4-byte utf-8 char`);this[f]={},this[f].stateBuf=new SharedArrayBuffer(128),this[f].state=new Int32Array(this[f].stateBuf),this[f].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[f].data=Buffer.from(this[f].dataBuf),this[f].sync=e.sync||!1,this[f].ending=!1,this[f].ended=!1,this[f].needDrain=!1,this[f].destroyed=!1,this[f].flushing=!1,this[f].ready=!1,this[f].finished=!1,this[f].errored=null,this[f].closed=!1,this[f].buf=``,this.worker=y(this,e),this.on(`message`,(e,t)=>{this.worker.postMessage(e,t)})}write(e){if(this[f].destroyed)return T(this,Error(`the worker has exited`)),!1;if(this[f].ending)return T(this,Error(`the worker is ending`)),!1;if(this[f].flushing&&this[f].buf.length+e.length>=p)try{k(this),this[f].flushing=!0}catch(e){return E(this,e),!1}if(this[f].buf+=e,this[f].sync)try{return k(this),!0}catch(e){return E(this,e),!1}return this[f].flushing||(this[f].flushing=!0,setImmediate(x,this)),this[f].needDrain=this[f].data.length-this[f].buf.length-Atomics.load(this[f].state,c)<=0,!this[f].needDrain}end(){this[f].destroyed||(this[f].ending=!0,O(this))}flush(e){if(this[f].destroyed){typeof e==`function`&&process.nextTick(e,Error(`the worker has exited`));return}let t=Atomics.load(this[f].state,c);s(this[f].state,l,t,1/0,(t,n)=>{if(t){E(this,t),process.nextTick(e,t);return}if(n===`not-equal`){this.flush(e);return}process.nextTick(e)})}flushSync(){this[f].destroyed||(k(this),A(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[f].ready}get destroyed(){return this[f].destroyed}get closed(){return this[f].closed}get writable(){return!this[f].destroyed&&!this[f].ending}get writableEnded(){return this[f].ending}get writableFinished(){return this[f].finished}get writableNeedDrain(){return this[f].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[f].errored}};function T(e,t){setImmediate(()=>{e.emit(`error`,t)})}function E(e,t){e[f].destroyed||(e[f].destroyed=!0,t&&(e[f].errored=t,T(e,t)),e.worker.exited?setImmediate(()=>{e[f].closed=!0,e.emit(`close`)}):e.worker.terminate().catch(()=>{}).then(()=>{e[f].closed=!0,e.emit(`close`)}))}function D(e,t,n){let r=Atomics.load(e[f].state,c),i=Buffer.byteLength(t);return e[f].data.write(t,r),Atomics.store(e[f].state,c,r+i),Atomics.notify(e[f].state,c),n(),!0}function O(e){if(!(e[f].ended||!e[f].ending||e[f].flushing)){e[f].ended=!0;try{e.flushSync();let t=Atomics.load(e[f].state,l);Atomics.store(e[f].state,c,-1),Atomics.notify(e[f].state,c);let n=0;for(;t!==-1;){if(Atomics.wait(e[f].state,l,t,1e3),t=Atomics.load(e[f].state,l),t===-2){E(e,Error(`end() failed`));return}if(++n===10){E(e,Error(`end() took too long (10s)`));return}}process.nextTick(()=>{e[f].finished=!0,e.emit(`finish`)})}catch(t){E(e,t)}}}function k(e){let t=()=>{e[f].ending?O(e):e[f].needDrain&&process.nextTick(b,e)};for(e[f].flushing=!1;e[f].buf.length!==0;){let n=Atomics.load(e[f].state,c),r=e[f].data.length-n;if(r===0){A(e),Atomics.store(e[f].state,l,0),Atomics.store(e[f].state,c,0),Atomics.notify(e[f].state,l);continue}else if(r<0)throw Error(`overwritten`);let i=e[f].buf.slice(0,r),a=Buffer.byteLength(i);if(a<=r)e[f].buf=e[f].buf.slice(r),D(e,i,t);else{for(A(e),Atomics.store(e[f].state,l,0),Atomics.store(e[f].state,c,0),Atomics.notify(e[f].state,l);a>e[f].buf.length;)r/=2,i=e[f].buf.slice(0,r),a=Buffer.byteLength(i);e[f].buf=e[f].buf.slice(r),D(e,i,t)}}}function A(e){if(e[f].flushing)throw Error(`unable to flush while flushing`);let t=Atomics.load(e[f].state,c),n=0;for(;;){let r=Atomics.load(e[f].state,l);if(r===-2)throw Error(`_flushSync failed`);if(r!==t)Atomics.wait(e[f].state,l,r,1e3);else break;if(++n===10)throw Error(`_flushSync took too long (10s)`)}}t.exports=w})),Gu=o(((e,t)=>{let{createRequire:n}=require(`module`),{existsSync:r}=require(`node:fs`),i=Mu(),{join:a,isAbsolute:o,sep:s}=require(`node:path`),{fileURLToPath:c}=require(`node:url`),l=Ru(),u=Bu(),d=Wu();function f(e){u.register(e,v),u.registerBeforeExit(e,y),e.on(`close`,function(){u.unregister(e)})}function p(){let e=process.execArgv;for(let t=0;t<e.length;t++){let n=e[t];if(n===`--import`||n===`--require`||n===`-r`||n.startsWith(`--import=`)||n.startsWith(`--require=`)||n.startsWith(`-r=`))return!0}return!1}function m(e){let t=e.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!t)return e;let n=[],r=!1;for(let e=0;e<t.length;e++){let i=t[e];if(i===`--require`||i===`-r`||i===`--import`){let a=t[e+1];if(a&&h(a)){r=!0,e++;continue}n.push(i),a&&(n.push(a),e++);continue}if((i.startsWith(`--require=`)||i.startsWith(`-r=`)||i.startsWith(`--import=`))&&h(i.slice(i.indexOf(`=`)+1))){r=!0;continue}n.push(i)}return r?n.join(` `):e}function h(e){let t=g(e);if(!t)return!1;let n=t;if(n.startsWith(`file://`))try{n=c(n)}catch{return!1}return o(n)&&!r(n)}function g(e){let t=e[0],n=e[e.length-1];return t===`"`&&n===`"`||t===`'`&&n===`'`?e.slice(1,-1):e}function _(e,t,n,r,i){if(!n.execArgv&&p()&&require.main===void 0&&(n={...n,execArgv:[]}),!n.env&&process.env.NODE_OPTIONS){let e=m(process.env.NODE_OPTIONS);e!==process.env.NODE_OPTIONS&&(n={...n,env:{...process.env,NODE_OPTIONS:e}})}n={...n,name:i};let a=new d({filename:e,workerData:t,workerOpts:n,sync:r});a.on(`ready`,o),a.on(`close`,function(){process.removeListener(`exit`,s)}),process.on(`exit`,s);function o(){process.removeListener(`exit`,s),a.unref(),n.autoEnd!==!1&&f(a)}function s(){a.closed||(a.flushSync(),l(100),a.end())}return a}function v(e){e.ref(),e.flushSync(),e.end(),e.once(`close`,function(){e.unref()})}function y(e){e.flushSync()}function b(e){let{pipeline:t,targets:r,levels:c,dedupe:l,worker:u={},caller:d=i(),sync:f=!1}=e,p={...e.options},m=typeof d==`string`?[d]:d,h=typeof globalThis==`object`&&Object.prototype.hasOwnProperty.call(globalThis,`__bundlerPathsOverrides`)&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides==`object`?globalThis.__bundlerPathsOverrides:Object.create(null),g=e.target;if(g&&r)throw Error(`only one of target or targets can be specified`);r?(g=h[`pino-worker`]||a(__dirname,`worker.js`),p.targets=r.filter(e=>e.target).map(e=>({...e,target:y(e.target)})),p.pipelines=r.filter(e=>e.pipeline).map(e=>e.pipeline.map(t=>({...t,level:e.level,target:y(t.target)})))):t&&(g=h[`pino-worker`]||a(__dirname,`worker.js`),p.pipelines=[t.map(e=>({...e,target:y(e.target)}))]),c&&(p.levels=c),l&&(p.dedupe=l),p.pinoWillSendConfig=!0;let v=r||t?`pino.transport`:g;return _(y(g),p,u,f,v);function y(e){if(e=h[e]||e,o(e)||e.indexOf(`file://`)===0)return e;if(e===`pino/file`)return a(__dirname,`..`,`file.js`);let t;for(let r of m)try{t=n(r===`node:repl`?process.cwd()+s:r).resolve(e);break}catch{continue}if(!t)throw Error(`unable to determine transport target for "${e}"`);return t}}t.exports=b})),Ku=o(((e,t)=>{let n=require(`node:diagnostics_channel`),r=Lu(),{mapHttpRequest:i,mapHttpResponse:a}=ju(),o=zu(),s=Bu(),{lsCacheSym:c,chindingsSym:l,writeSym:u,serializersSym:d,formatOptsSym:f,endSym:p,stringifiersSym:m,stringifySym:h,stringifySafeSym:g,wildcardFirstSym:_,nestedKeySym:v,formattersSym:y,messageKeySym:b,errorKeySym:x,nestedKeyStrSym:S,msgPrefixSym:C}=Pu(),{isMainThread:w}=require(`worker_threads`),T=Gu(),[E]=process.versions.node.split(`.`).map(e=>Number(e)),D=n.tracingChannel(`pino_asJson`),O=E>=25?e=>JSON.stringify(e):j;function k(){}function A(e,t){if(!t)return n;return function(...r){t.call(this,r,n,e)};function n(t,...n){if(typeof t==`object`){let o=t;t!==null&&(t.method&&t.headers&&t.socket?t=i(t):typeof t.setHeader==`function`&&(t=a(t)));let s;o===null&&n.length===0?s=[null]:(o=n.shift(),s=n),typeof this[C]==`string`&&o!=null&&(o=this[C]+o),this[u](t,r(o,s,this[f]),e)}else{let i=t===void 0?n.shift():t;typeof this[C]==`string`&&i!=null&&(i=this[C]+i),this[u](null,r(i,n,this[f]),e)}}}function j(e){let t=``,n=0,r=!1,i=255,a=e.length;if(a>100)return JSON.stringify(e);for(var o=0;o<a&&i>=32;o++)i=e.charCodeAt(o),(i===34||i===92)&&(t+=e.slice(n,o)+`\\`,n=o,r=!0);return r?t+=e.slice(n):t=e,i<32?JSON.stringify(e):`"`+t+`"`}function M(e,t,n,r){if(D.hasSubscribers===!1)return ee.call(this,e,t,n,r);let i={instance:this,arguments};return D.traceSync(ee,i,this,e,t,n,r)}function ee(e,t,n,r){let i=this[h],a=this[g],o=this[m],s=this[p],u=this[l],f=this[d],C=this[y],w=this[b],T=this[x],E=this[c][n]+r;E+=u;let D;C.log&&(e=C.log(e));let k=o[_],A=``;for(let t in e)if(D=e[t],Object.prototype.hasOwnProperty.call(e,t)&&D!==void 0){f[t]?D=f[t](D):t===T&&f.err&&(D=f.err(D));let e=o[t]||k;switch(typeof D){case`undefined`:case`function`:continue;case`number`:Number.isFinite(D)===!1&&(D=null);case`boolean`:e&&(D=e(D));break;case`string`:D=(e||O)(D);break;default:D=(e||i)(D,a)}if(D===void 0)continue;let n=O(t);A+=`,`+n+`:`+D}let j=``;if(t!==void 0){D=f[w]?f[w](t):t;let e=o[w]||k;switch(typeof D){case`function`:break;case`number`:Number.isFinite(D)===!1&&(D=null);case`boolean`:e&&(D=e(D)),j=`,"`+w+`":`+D;break;case`string`:D=(e||O)(D),j=`,"`+w+`":`+D;break;default:D=(e||i)(D,a),j=`,"`+w+`":`+D}}return this[v]&&A?E+this[S]+A.slice(1)+`}`+j+s:E+A+j+s}function N(e,t){let n,r=e[l],i=e[h],a=e[g],o=e[m],s=o[_],c=e[d],u=e[y].bindings;t=u(t);for(let e in t)if(n=t[e],((e.length<5||e!==`level`&&e!==`serializers`&&e!==`formatters`&&e!==`customLevels`)&&t.hasOwnProperty(e)&&n!==void 0)===!0){if(n=c[e]?c[e](n):n,n=(o[e]||s||i)(n,a),n===void 0)continue;r+=`,"`+e+`":`+n}return r}function te(e){return e.write!==e.constructor.prototype.write}function P(e){let t=new o(e);return t.on(`error`,n),!e.sync&&w&&(s.register(t,ne),t.on(`close`,function(){s.unregister(t)})),t;function n(e){if(e.code===`EPIPE`){t.write=k,t.end=k,t.flushSync=k,t.destroy=k;return}t.removeListener(`error`,n),t.emit(`error`,e)}}function ne(e,t){e.destroyed||(t===`beforeExit`?(e.flush(),e.on(`drain`,function(){e.end()})):e.flushSync())}function F(e){return function(t,n,r={},i){if(typeof r==`string`)i=P({dest:r}),r={};else if(typeof i==`string`){if(r&&r.transport)throw Error(`only one of option.transport or stream can be specified`);i=P({dest:i})}else if(r instanceof o||r.writable||r._writableState)i=r,r={};else if(r.transport){if(r.transport instanceof o||r.transport.writable||r.transport._writableState)throw Error(`option.transport do not allow stream, please pass to option directly. e.g. pino(transport)`);if(r.transport.targets&&r.transport.targets.length&&r.formatters&&typeof r.formatters.level==`function`)throw Error(`option.transport.targets do not allow custom level formatters`);let e;r.customLevels&&(e=r.useOnlyCustomLevels?r.customLevels:Object.assign({},r.levels,r.customLevels)),i=T({caller:n,...r.transport,levels:e})}if(r=Object.assign({},e,r),r.serializers=Object.assign({},e.serializers,r.serializers),r.formatters=Object.assign({},e.formatters,r.formatters),r.prettyPrint)throw Error(`prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)`);let{enabled:a,onChild:s}=r;return a===!1&&(r.level=`silent`),s||(r.onChild=k),i||=te(process.stdout)?process.stdout:P({fd:process.stdout.fd||1}),{opts:r,stream:i}}}function I(e,t){try{return JSON.stringify(e)}catch{try{return(t||this[g])(e)}catch{return`"[unable to serialize, circular reference is too complex to analyze]"`}}}function re(e,t,n){return{level:e,bindings:t,log:n}}function L(e){let t=Number(e);return typeof e==`string`&&Number.isFinite(t)?t:e===void 0?1:e}t.exports={noop:k,buildSafeSonicBoom:P,asChindings:N,asJson:M,genLog:A,createArgsNormalizer:F,stringify:I,buildFormatters:re,normalizeDestFileDescriptor:L}})),qu=o(((e,t)=>{t.exports={DEFAULT_LEVELS:{trace:10,debug:20,info:30,warn:40,error:50,fatal:60},SORTING_ORDER:{ASC:`ASC`,DESC:`DESC`}}})),Ju=o(((e,t)=>{let{lsCacheSym:n,levelValSym:r,useOnlyCustomLevelsSym:i,streamSym:a,formattersSym:o,hooksSym:s,levelCompSym:c}=Pu(),{noop:l,genLog:u}=Ku(),{DEFAULT_LEVELS:d,SORTING_ORDER:f}=qu(),p={fatal:e=>{let t=u(d.fatal,e);return function(...e){let n=this[a];if(t.call(this,...e),typeof n.flushSync==`function`)try{n.flushSync()}catch{}}},error:e=>u(d.error,e),warn:e=>u(d.warn,e),info:e=>u(d.info,e),debug:e=>u(d.debug,e),trace:e=>u(d.trace,e)},m=Object.keys(d).reduce((e,t)=>(e[d[t]]=t,e),{}),h=Object.keys(m).reduce((e,t)=>(e[t]=`{"level":`+Number(t),e),{});function g(e){let t=e[o].level,{labels:r}=e.levels,i={};for(let e in r){let n=t(r[e],Number(e));i[e]=JSON.stringify(n).slice(0,-1)}return e[n]=i,e}function _(e,t){if(t)return!1;switch(e){case`fatal`:case`error`:case`warn`:case`info`:case`debug`:case`trace`:return!0;default:return!1}}function v(e){let{labels:t,values:n}=this.levels;if(typeof e==`number`){if(t[e]===void 0)throw Error(`unknown level value`+e);e=t[e]}if(n[e]===void 0)throw Error(`unknown level `+e);let a=this[r],o=this[r]=n[e],d=this[i],f=this[c],m=this[s].logMethod;for(let e in n){if(f(n[e],o)===!1){this[e]=l;continue}this[e]=_(e,d)?p[e](m):u(n[e],m)}this.emit(`level-change`,e,o,t[a],a,this)}function y(e){let{levels:t,levelVal:n}=this;return t&&t.labels?t.labels[n]:``}function b(e){let{values:t}=this.levels,n=t[e];return n!==void 0&&this[c](n,this[r])}function x(e,t,n){return e===f.DESC?t<=n:t>=n}function S(e){return typeof e==`string`?x.bind(null,e):e}function C(e=null,t=!1){let n=e?Object.keys(e).reduce((t,n)=>(t[e[n]]=n,t),{}):null;return{labels:Object.assign(Object.create(Object.prototype,{Infinity:{value:`silent`}}),t?null:m,n),values:Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),t?null:d,e)}}function w(e,t,n){if(typeof e==`number`){if(![].concat(Object.keys(t||{}).map(e=>t[e]),n?[]:Object.keys(m).map(e=>+e),1/0).includes(e))throw Error(`default level:${e} must be included in custom levels`);return}if(!(e in Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),n?null:d,t)))throw Error(`default level:${e} must be included in custom levels`)}function T(e,t){let{labels:n,values:r}=e;for(let e in t){if(e in r)throw Error(`levels cannot be overridden`);if(t[e]in n)throw Error(`pre-existing level values cannot be used for new levels`)}}function E(e){if(typeof e!=`function`&&!(typeof e==`string`&&Object.values(f).includes(e)))throw Error(`Levels comparison should be one of "ASC", "DESC" or "function" type`)}t.exports={initialLsCache:h,genLsCache:g,levelMethods:p,getLevel:y,setLevel:v,isLevelEnabled:b,mappings:C,assertNoLevelCollisions:T,assertDefaultLevelFound:w,genLevelComparison:S,assertLevelComparison:E}})),Yu=o(((e,t)=>{t.exports={version:`10.3.1`}})),Xu=o(((e,t)=>{let{EventEmitter:n}=require(`node:events`),{lsCacheSym:r,levelValSym:i,setLevelSym:a,getLevelSym:o,chindingsSym:s,mixinSym:c,asJsonSym:l,writeSym:u,mixinMergeStrategySym:d,timeSym:f,timeSliceIndexSym:p,streamSym:m,serializersSym:h,formattersSym:g,errorKeySym:_,messageKeySym:v,useOnlyCustomLevelsSym:y,needsMetadataGsym:b,redactFmtSym:x,stringifySym:S,formatOptsSym:C,stringifiersSym:w,msgPrefixSym:T,hooksSym:E}=Pu(),{getLevel:D,setLevel:O,isLevelEnabled:k,mappings:A,initialLsCache:j,genLsCache:M,assertNoLevelCollisions:ee}=Ju(),{asChindings:N,asJson:te,buildFormatters:P,stringify:ne,noop:F}=Ku(),{version:I}=Yu(),re=Fu(),L={constructor:class{},child:ae,bindings:R,setBindings:oe,flush:le,isLevelEnabled:k,version:I,get level(){return this[o]()},set level(e){this[a](e)},get levelVal(){return this[i]},set levelVal(e){throw Error(`levelVal is read-only`)},get msgPrefix(){return this[T]},get[Symbol.toStringTag](){return`Pino`},[r]:j,[u]:ce,[l]:te,[o]:D,[a]:O};Object.setPrototypeOf(L,n.prototype),t.exports=function(){return Object.create(L)};let ie=e=>e;function ae(e,t){if(!e)throw Error(`missing bindings for child Pino`);let n=this[h],r=this[g],i=Object.create(this);if(t==null)return i[g].bindings!==ie&&(i[g]=P(r.level,ie,r.log)),i[s]=N(i,e),this.onChild!==F&&this.onChild(i),i;if(t.hasOwnProperty(`serializers`)===!0){i[h]=Object.create(null);for(let e in n)i[h][e]=n[e];let e=Object.getOwnPropertySymbols(n);for(var o=0;o<e.length;o++){let t=e[o];i[h][t]=n[t]}for(let e in t.serializers)i[h][e]=t.serializers[e];let r=Object.getOwnPropertySymbols(t.serializers);for(var c=0;c<r.length;c++){let e=r[c];i[h][e]=t.serializers[e]}}else i[h]=n;if(t.hasOwnProperty(`formatters`)){let{level:e,bindings:n,log:a}=t.formatters;i[g]=P(e||r.level,n||ie,a||r.log)}else i[g]=P(r.level,ie,r.log);if(t.hasOwnProperty(`customLevels`)===!0&&(ee(this.levels,t.customLevels),i.levels=A(t.customLevels,i[y]),M(i)),typeof t.redact==`object`&&t.redact!==null||Array.isArray(t.redact)){i.redact=t.redact;let e=re(i.redact,ne),n={stringify:e[x]};i[S]=ne,i[w]=e,i[C]=n}if(typeof t.msgPrefix==`string`&&(i[T]=(this[T]||``)+t.msgPrefix),i[s]=N(i,e),t.level!==void 0&&t.level!==this.level||t.hasOwnProperty(`customLevels`)){let e=t.level||this.level;i[a](e)}return this.onChild(i),i}function R(){let e=`{${this[s].substr(1)}}`,t=JSON.parse(e);return delete t.pid,delete t.hostname,t}function oe(e){this[s]=N(this,e)}function se(e,t){return Object.assign(t,e)}function ce(e,t,n){let r=this[f](),i=this[c],a=this[_],o=this[v],s=this[d]||se,u,h=this[E].streamWrite;e==null?u={}:e instanceof Error?(u={[a]:e},t===void 0&&(t=e.message)):(u=e,t===void 0&&e[o]===void 0&&e[a]&&(t=e[a].message)),i&&(u=s(u,i(u,n,this)));let g=this[l](u,t,n,r),y=this[m];y[b]===!0&&(y.lastLevel=n,y.lastObj=u,y.lastMsg=t,y.lastTime=r.slice(this[p]),y.lastLogger=this),y.write(h?h(g):g)}function le(e){if(e!=null&&typeof e!=`function`)throw Error(`callback must be a function`);let t=this[m];typeof t.flush==`function`?t.flush(e||F):e&&e()}})),Zu=o(((e,t)=>{let{hasOwnProperty:n}=Object.prototype,r=_();r.configure=_,r.stringify=r,r.default=r,e.stringify=r,e.configure=_,t.exports=r;let i=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function a(e){return e.length<5e3&&!i.test(e)?`"${e}"`:JSON.stringify(e)}function o(e,t){if(e.length>200||t)return e.sort(t);for(let t=1;t<e.length;t++){let n=e[t],r=t;for(;r!==0&&e[r-1]>n;)e[r]=e[r-1],r--;e[r]=n}return e}let s=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function c(e){return s.call(e)!==void 0&&e.length!==0}function l(e,t,n){e.length<n&&(n=e.length);let r=t===`,`?``:` `,i=`"0":${r}${e[0]}`;for(let a=1;a<n;a++)i+=`${t}"${a}":${r}${e[a]}`;return i}function u(e){if(n.call(e,`circularValue`)){let t=e.circularValue;if(typeof t==`string`)return`"${t}"`;if(t==null)return t;if(t===Error||t===TypeError)return{toString(){throw TypeError(`Converting circular structure to JSON`)}};throw TypeError(`The "circularValue" argument must be of type string or the value null or undefined`)}return`"[Circular]"`}function d(e){let t;if(n.call(e,`deterministic`)&&(t=e.deterministic,typeof t!=`boolean`&&typeof t!=`function`))throw TypeError(`The "deterministic" argument must be of type boolean or comparator function`);return t===void 0?!0:t}function f(e,t){let r;if(n.call(e,t)&&(r=e[t],typeof r!=`boolean`))throw TypeError(`The "${t}" argument must be of type boolean`);return r===void 0?!0:r}function p(e,t){let r;if(n.call(e,t)){if(r=e[t],typeof r!=`number`)throw TypeError(`The "${t}" argument must be of type number`);if(!Number.isInteger(r))throw TypeError(`The "${t}" argument must be an integer`);if(r<1)throw RangeError(`The "${t}" argument must be >= 1`)}return r===void 0?1/0:r}function m(e){return e===1?`1 item`:`${e} items`}function h(e){let t=new Set;for(let n of e)(typeof n==`string`||typeof n==`number`)&&t.add(String(n));return t}function g(e){if(n.call(e,`strict`)){let t=e.strict;if(typeof t!=`boolean`)throw TypeError(`The "strict" argument must be of type boolean`);if(t)return e=>{let t=`Object can not safely be stringified. Received type ${typeof e}`;throw typeof e!=`function`&&(t+=` (${e.toString()})`),Error(t)}}}function _(e){e={...e};let t=g(e);t&&(e.bigint===void 0&&(e.bigint=!1),`circularValue`in e||(e.circularValue=Error));let n=u(e),r=f(e,`bigint`),i=d(e),s=typeof i==`function`?i:void 0,_=p(e,`maximumDepth`),v=p(e,`maximumBreadth`);function y(e,l,u,d,f,p){let h=l[e];switch(typeof h==`object`&&h&&typeof h.toJSON==`function`&&(h=h.toJSON(e)),h=d.call(l,e,h),typeof h){case`string`:return a(h);case`object`:{if(h===null)return`null`;if(u.indexOf(h)!==-1)return n;let e=``,t=`,`,r=p;if(Array.isArray(h)){if(h.length===0)return`[]`;if(_<u.length+1)return`"[Array]"`;u.push(h),f!==``&&(p+=f,e+=`\n${p}`,t=`,\n${p}`);let n=Math.min(h.length,v),i=0;for(;i<n-1;i++){let n=y(String(i),h,u,d,f,p);e+=n===void 0?`null`:n,e+=t}let a=y(String(i),h,u,d,f,p);if(e+=a===void 0?`null`:a,h.length-1>v){let n=h.length-v-1;e+=`${t}"... ${m(n)} not stringified"`}return f!==``&&(e+=`\n${r}`),u.pop(),`[${e}]`}let l=Object.keys(h),g=l.length;if(g===0)return`{}`;if(_<u.length+1)return`"[Object]"`;let b=``,x=``;f!==``&&(p+=f,t=`,\n${p}`,b=` `);let S=Math.min(g,v);i&&!c(h)&&(l=o(l,s)),u.push(h);for(let n=0;n<S;n++){let r=l[n],i=y(r,h,u,d,f,p);i!==void 0&&(e+=`${x}${a(r)}:${b}${i}`,x=t)}if(g>v){let n=g-v;e+=`${x}"...":${b}"${m(n)} not stringified"`,x=t}return f!==``&&x.length>1&&(e=`\n${p}${e}\n${r}`),u.pop(),`{${e}}`}case`number`:return isFinite(h)?String(h):t?t(h):`null`;case`boolean`:return h===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(h);default:return t?t(h):void 0}}function b(e,i,o,s,c,l){switch(typeof i==`object`&&i&&typeof i.toJSON==`function`&&(i=i.toJSON(e)),typeof i){case`string`:return a(i);case`object`:{if(i===null)return`null`;if(o.indexOf(i)!==-1)return n;let e=l,t=``,r=`,`;if(Array.isArray(i)){if(i.length===0)return`[]`;if(_<o.length+1)return`"[Array]"`;o.push(i),c!==``&&(l+=c,t+=`\n${l}`,r=`,\n${l}`);let n=Math.min(i.length,v),a=0;for(;a<n-1;a++){let e=b(String(a),i[a],o,s,c,l);t+=e===void 0?`null`:e,t+=r}let u=b(String(a),i[a],o,s,c,l);if(t+=u===void 0?`null`:u,i.length-1>v){let e=i.length-v-1;t+=`${r}"... ${m(e)} not stringified"`}return c!==``&&(t+=`\n${e}`),o.pop(),`[${t}]`}o.push(i);let u=``;c!==``&&(l+=c,r=`,\n${l}`,u=` `);let d=``;for(let e of s){let n=b(e,i[e],o,s,c,l);n!==void 0&&(t+=`${d}${a(e)}:${u}${n}`,d=r)}return c!==``&&d.length>1&&(t=`\n${l}${t}\n${e}`),o.pop(),`{${t}}`}case`number`:return isFinite(i)?String(i):t?t(i):`null`;case`boolean`:return i===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(i);default:return t?t(i):void 0}}function x(e,u,d,f,p){switch(typeof u){case`string`:return a(u);case`object`:{if(u===null)return`null`;if(typeof u.toJSON==`function`){if(u=u.toJSON(e),typeof u!=`object`)return x(e,u,d,f,p);if(u===null)return`null`}if(d.indexOf(u)!==-1)return n;let t=p;if(Array.isArray(u)){if(u.length===0)return`[]`;if(_<d.length+1)return`"[Array]"`;d.push(u),p+=f;let e=`\n${p}`,n=`,\n${p}`,r=Math.min(u.length,v),i=0;for(;i<r-1;i++){let t=x(String(i),u[i],d,f,p);e+=t===void 0?`null`:t,e+=n}let a=x(String(i),u[i],d,f,p);if(e+=a===void 0?`null`:a,u.length-1>v){let t=u.length-v-1;e+=`${n}"... ${m(t)} not stringified"`}return e+=`\n${t}`,d.pop(),`[${e}]`}let r=Object.keys(u),h=r.length;if(h===0)return`{}`;if(_<d.length+1)return`"[Object]"`;p+=f;let g=`,\n${p}`,y=``,b=``,S=Math.min(h,v);c(u)&&(y+=l(u,g,v),r=r.slice(u.length),S-=u.length,b=g),i&&(r=o(r,s)),d.push(u);for(let e=0;e<S;e++){let t=r[e],n=x(t,u[t],d,f,p);n!==void 0&&(y+=`${b}${a(t)}: ${n}`,b=g)}if(h>v){let e=h-v;y+=`${b}"...": "${m(e)} not stringified"`,b=g}return b!==``&&(y=`\n${p}${y}\n${t}`),d.pop(),`{${y}}`}case`number`:return isFinite(u)?String(u):t?t(u):`null`;case`boolean`:return u===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(u);default:return t?t(u):void 0}}function S(e,u,d){switch(typeof u){case`string`:return a(u);case`object`:{if(u===null)return`null`;if(typeof u.toJSON==`function`){if(u=u.toJSON(e),typeof u!=`object`)return S(e,u,d);if(u===null)return`null`}if(d.indexOf(u)!==-1)return n;let t=``,r=u.length!==void 0;if(r&&Array.isArray(u)){if(u.length===0)return`[]`;if(_<d.length+1)return`"[Array]"`;d.push(u);let e=Math.min(u.length,v),n=0;for(;n<e-1;n++){let e=S(String(n),u[n],d);t+=e===void 0?`null`:e,t+=`,`}let r=S(String(n),u[n],d);if(t+=r===void 0?`null`:r,u.length-1>v){let e=u.length-v-1;t+=`,"... ${m(e)} not stringified"`}return d.pop(),`[${t}]`}let f=Object.keys(u),p=f.length;if(p===0)return`{}`;if(_<d.length+1)return`"[Object]"`;let h=``,g=Math.min(p,v);r&&c(u)&&(t+=l(u,`,`,v),f=f.slice(u.length),g-=u.length,h=`,`),i&&(f=o(f,s)),d.push(u);for(let e=0;e<g;e++){let n=f[e],r=S(n,u[n],d);r!==void 0&&(t+=`${h}${a(n)}:${r}`,h=`,`)}if(p>v){let e=p-v;t+=`${h}"...":"${m(e)} not stringified"`}return d.pop(),`{${t}}`}case`number`:return isFinite(u)?String(u):t?t(u):`null`;case`boolean`:return u===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(u);default:return t?t(u):void 0}}function C(e,t,n){if(arguments.length>1){let r=``;if(typeof n==`number`?r=` `.repeat(Math.min(n,10)):typeof n==`string`&&(r=n.slice(0,10)),t!=null){if(typeof t==`function`)return y(``,{"":e},[],t,r,``);if(Array.isArray(t))return b(``,e,[],h(t),r,``)}if(r.length!==0)return x(``,e,[],r,``)}return S(``,e,[])}return C}})),Qu=o(((e,t)=>{let n=Symbol.for(`pino.metadata`),{DEFAULT_LEVELS:r}=qu(),i=r.info;function a(e,t){e||=[],t||={dedupe:!1};let a=Object.create(r);a.silent=1/0,t.levels&&typeof t.levels==`object`&&Object.keys(t.levels).forEach(e=>{a[e]=t.levels[e]});let u={write:d,add:m,remove:h,emit:f,flushSync:p,end:g,minLevel:0,lastId:0,streams:[],clone:_,[n]:!0,streamLevels:a};return Array.isArray(e)?e.forEach(m,u):m.call(u,e),e=null,u;function d(e){let r,i=this.lastLevel,{streams:a}=this,o=0,u;for(let d=s(a.length,t.dedupe);l(d,a.length,t.dedupe);d=c(d,t.dedupe))if(r=a[d],r.level<=i){if(o!==0&&o!==r.level)break;if(u=r.stream,u[n]){let{lastTime:e,lastMsg:t,lastObj:n,lastLogger:r}=this;u.lastLevel=i,u.lastTime=e,u.lastMsg=t,u.lastObj=n,u.lastLogger=r}u.write(e),t.dedupe&&(o=r.level)}else if(!t.dedupe)break}function f(...e){for(let{stream:t}of this.streams)typeof t.emit==`function`&&t.emit(...e)}function p(){for(let{stream:e}of this.streams)typeof e.flushSync==`function`&&e.flushSync()}function m(e){if(!e)return u;let t=typeof e.write==`function`||e.stream,n=e.write?e:e.stream;if(!t)throw Error(`stream object needs to implement either StreamEntry or DestinationStream interface`);let{streams:r,streamLevels:a}=this,s;s=typeof e.levelVal==`number`?e.levelVal:typeof e.level==`string`?a[e.level]:typeof e.level==`number`?e.level:i;let c={stream:n,level:s,levelVal:void 0,id:++u.lastId};return r.unshift(c),r.sort(o),this.minLevel=r[0].level,u}function h(e){let{streams:t}=this,n=t.findIndex(t=>t.id===e);return n>=0&&(t.splice(n,1),t.sort(o),this.minLevel=t.length>0?t[0].level:-1),u}function g(){for(let{stream:e}of this.streams)typeof e.flushSync==`function`&&e.flushSync(),e.end()}function _(e){let t=Array(this.streams.length);for(let n=0;n<t.length;n++)t[n]={level:e,stream:this.streams[n].stream};return{write:d,add:m,remove:h,minLevel:e,streams:t,clone:_,emit:f,flushSync:p,[n]:!0}}}function o(e,t){return e.level-t.level}function s(e,t){return t?e-1:0}function c(e,t){return t?e-1:e+1}function l(e,t,n){return n?e>=0:e<t}t.exports=a})),$u=o(((e,t)=>{let n=require(`node:os`),r=ju(),i=Mu(),a=Fu(),o=Iu(),s=Xu(),c=Pu(),{configure:l}=Zu(),{assertDefaultLevelFound:u,mappings:d,genLsCache:f,genLevelComparison:p,assertLevelComparison:m}=Ju(),{DEFAULT_LEVELS:h,SORTING_ORDER:g}=qu(),{createArgsNormalizer:_,asChindings:v,buildSafeSonicBoom:y,buildFormatters:b,stringify:x,normalizeDestFileDescriptor:S,noop:C}=Ku(),{version:w}=Yu(),{chindingsSym:T,redactFmtSym:E,serializersSym:D,timeSym:O,timeSliceIndexSym:k,streamSym:A,stringifySym:j,stringifySafeSym:M,stringifiersSym:ee,setLevelSym:N,endSym:te,formatOptsSym:P,messageKeySym:ne,errorKeySym:F,nestedKeySym:I,mixinSym:re,levelCompSym:L,useOnlyCustomLevelsSym:ie,formattersSym:ae,hooksSym:R,nestedKeyStrSym:oe,mixinMergeStrategySym:se,msgPrefixSym:ce}=c,{epochTime:le,nullTime:ue}=o,{pid:de}=process,z=n.hostname(),fe=r.err,pe=_({level:`info`,levelComparison:g.ASC,levels:h,messageKey:`msg`,errorKey:`err`,nestedKey:null,enabled:!0,base:{pid:de,hostname:z},serializers:Object.assign(Object.create(null),{err:fe}),formatters:Object.assign(Object.create(null),{bindings(e){return e},level(e,t){return{level:t}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:le,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100}),me=Object.assign(Object.create(null),r);function he(...e){let t={},{opts:n,stream:r}=pe(t,i(),...e);n.level&&typeof n.level==`string`&&h[n.level.toLowerCase()]!==void 0&&(n.level=n.level.toLowerCase());let{redact:o,crlf:c,serializers:g,timestamp:_,messageKey:y,errorKey:S,nestedKey:w,base:de,name:z,level:fe,customLevels:me,levelComparison:he,mixin:ge,mixinMergeStrategy:_e,useOnlyCustomLevels:ve,formatters:ye,hooks:be,depthLimit:xe,edgeLimit:Se,onChild:Ce,msgPrefix:we}=n,Te=l({maximumDepth:xe,maximumBreadth:Se}),Ee=b(ye.level,ye.bindings,ye.log),De=x.bind({[M]:Te}),Oe=o?a(o,De):{},ke=o?{stringify:Oe[E]}:{stringify:De},Ae=`}`+(c?`\r
|
|
127
127
|
`:`
|
|
128
128
|
`),je=v.bind(null,{[T]:``,[D]:g,[ee]:Oe,[j]:x,[M]:Te,[ae]:Ee}),Me=``;de!==null&&(Me=je(z===void 0?de:Object.assign({},de,{name:z})));let Ne=_ instanceof Function?_:_?le:ue,Pe=Ne().indexOf(`:`)+1;if(ve&&!me)throw Error(`customLevels is required if useOnlyCustomLevels is set true`);if(ge&&typeof ge!=`function`)throw Error(`Unknown mixin type "${typeof ge}" - expected "function"`);if(we&&typeof we!=`string`)throw Error(`Unknown msgPrefix type "${typeof we}" - expected "string"`);u(fe,me,ve);let Fe=d(me,ve);typeof r.emit==`function`&&r.emit(`message`,{code:`PINO_CONFIG`,config:{levels:Fe,messageKey:y,errorKey:S}}),m(he);let Ie=p(he);return Object.assign(t,{levels:Fe,[L]:Ie,[ie]:ve,[A]:r,[O]:Ne,[k]:Pe,[j]:x,[M]:Te,[ee]:Oe,[te]:Ae,[P]:ke,[ne]:y,[F]:S,[I]:w,[oe]:w?`,${JSON.stringify(w)}:{`:``,[D]:g,[re]:ge,[se]:_e,[T]:Me,[ae]:Ee,[R]:be,silent:C,onChild:Ce,[ce]:we}),Object.setPrototypeOf(t,s()),f(t),t[N](fe),t}t.exports=he,t.exports.destination=(e=process.stdout.fd)=>typeof e==`object`?(e.dest=S(e.dest||process.stdout.fd),y(e)):y({dest:S(e),minLength:0}),t.exports.transport=Gu(),t.exports.multistream=Qu(),t.exports.levels=d(),t.exports.stdSerializers=me,t.exports.stdTimeFunctions=Object.assign({},o),t.exports.symbols=c,t.exports.version=w,t.exports.default=he,t.exports.pino=he})),ed=o(((e,t)=>{let n=$u(),{serializersSym:r}=n.symbols,{FST_ERR_LOG_INVALID_DESTINATION:i}=mu();function a(e){if(e.stream&&e.file)throw new i;e.file&&(e.stream=n.destination(e.file),delete e.file);let t=e.logger,a=e.genReqId,o=null;return t?(e.logger=void 0,e.genReqId=void 0,t[r]&&(e.serializers=Object.assign({},e.serializers,t[r])),o=t.child({},e),e.logger=t,e.genReqId=a):o=n(e,e.stream),o}t.exports={serializers:{req:function(e){return{method:e.method,url:e.url,version:e.headers&&e.headers[`accept-version`],host:e.host,remoteAddress:e.ip,remotePort:e.socket?e.socket.remotePort:void 0}},err:n.stdSerializers.err,res:function(e){return{statusCode:e.statusCode}}},createPinoLogger:a}})),td=o(((e,t)=>{let{FST_ERR_LOG_LOGGER_AND_LOGGER_INSTANCE_PROVIDED:n,FST_ERR_LOG_INVALID_LOGGER_CONFIG:r,FST_ERR_LOG_INVALID_LOGGER_INSTANCE:i,FST_ERR_LOG_INVALID_LOGGER:a}=mu();function o(e,t,n,r,i){let a={[e.requestIdLogLabel]:r},o=e.childLoggerFactory.call(e.server,t,a,i||{},n);return e.childLoggerFactory!==s&&c(o,!0),o}function s(e,t,n){return e.child(t,n)}function c(e,t){let n=[`info`,`error`,`debug`,`fatal`,`warn`,`trace`,`child`],r=e?n.filter(t=>!e[t]||typeof e[t]!=`function`):n;if(!r.length)return!0;if(r.length===n.length&&!t)return!1;throw a(r.join(`,`))}function l(e){if(e.logger&&e.loggerInstance)throw new n;if(!e.loggerInstance&&!e.logger){let e=wu();return e.child=()=>e,{logger:e,hasLogger:!1}}let{createPinoLogger:t,serializers:a}=ed();if(c(e.loggerInstance))return{logger:t({logger:e.loggerInstance,serializers:Object.assign({},a,e.loggerInstance.serializers)}),hasLogger:!0};if(c(e.logger))throw r();if(e.loggerInstance)throw i();let o={};return Object.prototype.toString.call(e.logger)===`[object Object]`&&Reflect.ownKeys(e.logger).forEach(t=>{Object.defineProperty(o,t,{value:e.logger[t],writable:!0,enumerable:!0,configurable:!0})}),o.level=o.level||`info`,o.serializers=Object.assign({},a,o.serializers),e.logger=o,{logger:t(e.logger),hasLogger:!0}}function u(){let e=process.hrtime();return e[0]*1e3+e[1]/1e6}t.exports={createChildLogger:o,defaultChildLoggerFactory:s,createLogger:l,validateLogger:c,now:u}})),nd=o(((e,t)=>{t.exports=r;function n(e){return e instanceof Buffer?Buffer.from(e):new e.constructor(e.buffer.slice(),e.byteOffset,e.length)}function r(e){if(e||={},e.circles)return i(e);let t=new Map;if(t.set(Date,e=>new Date(e)),t.set(Map,(e,t)=>new Map(a(Array.from(e),t))),t.set(Set,(e,t)=>new Set(a(Array.from(e),t))),e.constructorHandlers)for(let n of e.constructorHandlers)t.set(n[0],n[1]);let r=null;return e.proto?s:o;function a(e,i){let a=Object.keys(e),o=Array(a.length);for(let s=0;s<a.length;s++){let c=a[s],l=e[c];typeof l!=`object`||!l?o[c]=l:l.constructor!==Object&&(r=t.get(l.constructor))?o[c]=r(l,i):ArrayBuffer.isView(l)?o[c]=n(l):o[c]=i(l)}return o}function o(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return a(e,o);if(e.constructor!==Object&&(r=t.get(e.constructor)))return r(e,o);let i={};for(let a in e){if(Object.hasOwnProperty.call(e,a)===!1)continue;let s=e[a];typeof s!=`object`||!s?i[a]=s:s.constructor!==Object&&(r=t.get(s.constructor))?i[a]=r(s,o):ArrayBuffer.isView(s)?i[a]=n(s):i[a]=o(s)}return i}function s(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return a(e,s);if(e.constructor!==Object&&(r=t.get(e.constructor)))return r(e,s);let i={};for(let a in e){let o=e[a];typeof o!=`object`||!o?i[a]=o:o.constructor!==Object&&(r=t.get(o.constructor))?i[a]=r(o,s):ArrayBuffer.isView(o)?i[a]=n(o):i[a]=s(o)}return i}}function i(e){let t=[],r=[],i=new Map;if(i.set(Date,e=>new Date(e)),i.set(Map,(e,t)=>new Map(o(Array.from(e),t))),i.set(Set,(e,t)=>new Set(o(Array.from(e),t))),e.constructorHandlers)for(let t of e.constructorHandlers)i.set(t[0],t[1]);let a=null;return e.proto?c:s;function o(e,o){let s=Object.keys(e),c=Array(s.length);for(let l=0;l<s.length;l++){let u=s[l],d=e[u];if(typeof d!=`object`||!d)c[u]=d;else if(d.constructor!==Object&&(a=i.get(d.constructor)))c[u]=a(d,o);else if(ArrayBuffer.isView(d))c[u]=n(d);else{let e=t.indexOf(d);e===-1?c[u]=o(d):c[u]=r[e]}}return c}function s(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return o(e,s);if(e.constructor!==Object&&(a=i.get(e.constructor)))return a(e,s);let c={};t.push(e),r.push(c);for(let o in e){if(Object.hasOwnProperty.call(e,o)===!1)continue;let l=e[o];if(typeof l!=`object`||!l)c[o]=l;else if(l.constructor!==Object&&(a=i.get(l.constructor)))c[o]=a(l,s);else if(ArrayBuffer.isView(l))c[o]=n(l);else{let e=t.indexOf(l);e===-1?c[o]=s(l):c[o]=r[e]}}return t.pop(),r.pop(),c}function c(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return o(e,c);if(e.constructor!==Object&&(a=i.get(e.constructor)))return a(e,c);let s={};t.push(e),r.push(s);for(let o in e){let l=e[o];if(typeof l!=`object`||!l)s[o]=l;else if(l.constructor!==Object&&(a=i.get(l.constructor)))s[o]=a(l,c);else if(ArrayBuffer.isView(l))s[o]=n(l);else{let e=t.indexOf(l);e===-1?s[o]=c(l):s[o]=r[e]}}return t.pop(),r.pop(),s}}})),rd=o(((e,t)=>{let n=nd()({circles:!1,proto:!0}),{kSchemaVisited:r,kSchemaResponse:i}=du(),a=Symbol.for(`fluent-schema-object`),{FST_ERR_SCH_MISSING_ID:o,FST_ERR_SCH_ALREADY_PRESENT:s,FST_ERR_SCH_DUPLICATE:c,FST_ERR_SCH_CONTENT_MISSING_SCHEMA:l}=mu(),u=[`params`,`body`,`querystring`,`query`,`headers`];function d(e){this.store=e||{}}d.prototype.add=function(e){let t=n(e.isFluentSchema||e.isFluentJSONSchema||e[a]?e.valueOf():e),r=t.$id;if(!r)throw new o;if(this.store[r])throw new s(r);this.store[r]=t},d.prototype.getSchemas=function(){return Object.assign({},this.store)},d.prototype.getSchema=function(e){return this.store[e]};function f(e){return typeof e==`object`&&Object.getPrototypeOf(e)!==Object.prototype}function p(e,t){if(e[r])return e;if(e.query){if(e.querystring)throw new c(`querystring`);e.querystring=e.query}m(e);for(let t of u){let n=e[t];if(n&&!f(n)&&t===`body`&&n.content){let e=n.content,t=Object.keys(e);for(let n=0;n<t.length;n++){let r=t[n];if(!e[r].schema)throw new l(r)}continue}}if(e.response){let t=Object.keys(e.response);for(let n of t){if(f(e.response[n]))continue;let t=e.response[n].content;if(t){let e=Object.keys(t);for(let n=0;n<e.length;n++){let r=e[n];if(!t[r].schema)throw new l(r)}}}}return e[r]=!0,e}function m(e){for(let t of u)e[t]&&(e[t].isFluentSchema||e[t][a])&&(e[t]=e[t].valueOf());if(e.response){let t=Object.keys(e.response);for(let n of t)(e.response[n].isFluentSchema||e.response[n][a])&&(e.response[n]=e.response[n].valueOf())}}function h(e,t,n){let r=e[i];if(!r)return!1;if(r[t]){if(r[t].constructor===Object&&n){let e=n.split(`;`,1)[0];return r[t][e]?r[t][e]:r[t][`*/*`]?r[t][`*/*`]:!1}return r[t]}let a=(t+``)[0]+`xx`;if(r[a]){if(r[a].constructor===Object&&n){let e=n.split(`;`,1)[0];return r[a][e]?r[a][e]:r[a][`*/*`]?r[a][`*/*`]:!1}return r[a]}if(r.default){if(r.default.constructor===Object&&n){let e=n.split(`;`,1)[0];return r.default[e]?r.default[e]:r.default[`*/*`]?r.default[`*/*`]:!1}return r.default}return!1}t.exports={buildSchemas(e){return new d(e)},getSchemaSerializer:h,normalizeSchema:p}})),id=o(((e,t)=>{let n=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;t.exports=class e{constructor(e){switch(e&&e.rounding){case`floor`:this.parseInteger=Math.floor;break;case`ceil`:this.parseInteger=Math.ceil;break;case`round`:this.parseInteger=Math.round;break;default:this.parseInteger=Math.trunc;break}this._options=e}asInteger(e){if(Number.isInteger(e))return``+e;if(typeof e==`bigint`)return e.toString();let t=this.parseInteger(e);if(t===1/0||t===-1/0||t!==t)throw Error(`The value "${e}" cannot be converted to an integer.`);return``+t}asNumber(e){let t=Number(e);if(t!==t)throw Error(`The value "${e}" cannot be converted to a number.`);return t===1/0||t===-1/0?`null`:``+t}asBoolean(e){return e&&`true`||`false`}asDateTime(e){if(e===null)return`""`;if(e instanceof Date)return`"`+e.toISOString()+`"`;if(typeof e==`string`)return`"`+e+`"`;throw Error(`The value "${e}" cannot be converted to a date-time.`)}asDate(e){if(e===null)return`""`;if(e instanceof Date)return`"`+new Date(e.getTime()-e.getTimezoneOffset()*6e4).toISOString().slice(0,10)+`"`;if(typeof e==`string`)return`"`+e+`"`;throw Error(`The value "${e}" cannot be converted to a date.`)}asTime(e){if(e===null)return`""`;if(e instanceof Date)return`"`+new Date(e.getTime()-e.getTimezoneOffset()*6e4).toISOString().slice(11,19)+`"`;if(typeof e==`string`)return`"`+e+`"`;throw Error(`The value "${e}" cannot be converted to a time.`)}asString(e){let t=e.length;if(t===0)return`""`;if(t<42){let n=``,r=-1,i=255;for(let a=0;a<t;a++)if(i=e.charCodeAt(a),i===34||i===92)r===-1&&(r=0),n+=e.slice(r,a)+`\\`,r=a;else if(i<32||i>=55296&&i<=57343)return JSON.stringify(e);return r===-1&&`"`+e+`"`||`"`+n+e.slice(r)+`"`}else if(t<5e3&&n.test(e)===!1)return`"`+e+`"`;else return JSON.stringify(e)}asUnsafeString(e){return`"`+e+`"`}getState(){return this._options}static restoreFromState(t){return new e(t)}}})),ad=o(((e,t)=>{t.exports=function(e,t){let{asString:n,asNumber:r,asBoolean:i,asDateTime:a,asDate:o,asTime:s,asUnsafeString:c}=t;t.asInteger.bind(t);function l(e){let t=e&&typeof e.toJSON==`function`?e.toJSON():e;if(t===null)return`{}`;let i,a=`{`,o=!1;return i=t.statusCode,i!==void 0&&(!o&&(o=!0)||(a+=`,`),a+=`"statusCode":`,a+=r(i)),i=t.code,i!==void 0&&(!o&&(o=!0)||(a+=`,`),a+=`"code":`,typeof i==`string`?a+=n(i):i===null?a+=`""`:i instanceof Date?a+=`"`+i.toISOString()+`"`:i instanceof RegExp?a+=n(i.source):a+=n(i.toString())),i=t.error,i!==void 0&&(!o&&(o=!0)||(a+=`,`),a+=`"error":`,typeof i==`string`?a+=n(i):i===null?a+=`""`:i instanceof Date?a+=`"`+i.toISOString()+`"`:i instanceof RegExp?a+=n(i.source):a+=n(i.toString())),i=t.message,i!==void 0&&(!o&&(o=!0)||(a+=`,`),a+=`"message":`,typeof i==`string`?a+=n(i):i===null?a+=`""`:i instanceof Date?a+=`"`+i.toISOString()+`"`:i instanceof RegExp?a+=n(i.source):a+=n(i.toString())),a+`}`}return l}(null,id().restoreFromState({mode:`standalone`}))})),od=o(((e,t)=>{let n=require(`node:http`).STATUS_CODES,r=xu(),{setErrorStatusCode:i}=bu(),{kReplyHeaders:a,kReplyNextErrorHandler:o,kReplyIsRunningOnErrorHook:s,kRouteContext:c,kDisableRequestLogging:l}=du(),{FST_ERR_REP_INVALID_PAYLOAD_TYPE:u,FST_ERR_FAILED_ERROR_SERIALIZATION:d}=mu(),{getSchemaSerializer:f}=rd(),p=ad(),m={func:g,toJSON(){return this.func.name.toString()+`()`}};function h(e,t,n){e[s]=!1;let i=e[c];if(e[o]===!1){_(t,e,function(e,t){try{e.raw.writeHead(e.raw.statusCode,e[a])}catch(t){e.log[l]||e.log.warn({req:e.request,res:e,err:t},t?.message),e.raw.writeHead(e.raw.statusCode)}e.raw.end(t)});return}let u=e[o]||i.errorHandler;e[o]=Object.getPrototypeOf(u),delete e[a][`content-type`],delete e[a][`content-length`];let d=u.func;if(!d){e[o]=!1,_(t,e,n);return}try{let n=d(t,e.request,e);n!==void 0&&(n!==null&&typeof n.then==`function`?r(n,e):e.send(n))}catch(t){e.send(t)}}function g(e,t,n){y(e,n),i(n,e),n.statusCode<500?n.log[l]||n.log.info({res:n,err:e},e?.message):n.log[l]||n.log.error({req:t,res:n,err:e},e?.message),n.send(e)}function _(e,t,r){let i=t.raw,o=t.statusCode;t[a][`content-type`]=t[a][`content-type`]??`application/json; charset=utf-8`;let s;try{let r=f(t[c],o,t[a][`content-type`]);s=r===!1?p({error:n[o+``],code:e.code,message:e.message,statusCode:o}):r(Object.create(e,{error:{value:n[o+``]},message:{value:e.message},statusCode:{value:o}}))}catch(n){t.log[l]||t.log.error({err:n,statusCode:i.statusCode},`The serializer for the given status code failed`),t.code(500),s=p(new d(n.message,e.message))}typeof s!=`string`&&!Buffer.isBuffer(s)&&(s=p(new u(typeof s))),t[a][`content-length`]=``+Buffer.byteLength(s),r(t,s)}function v(e=m,t){if(!t)return e;let n=Object.create(e);return n.func=t,n}function y(e,t){let n=t.raw,r=n.statusCode;r=r>=400?r:500,e!=null&&(e.headers!==void 0&&t.headers(e.headers),e.status>=400?r=e.status:e.statusCode>=400&&(r=e.statusCode)),n.statusCode=r}t.exports={buildErrorHandler:v,handleError:h}})),sd=o(((e,t)=>{let{kReply:n,kRequest:r,kState:i,kHasBeenDecorated:a}=du(),{FST_ERR_DEC_ALREADY_PRESENT:o,FST_ERR_DEC_MISSING_DEPENDENCY:s,FST_ERR_DEC_AFTER_START:c,FST_ERR_DEC_REFERENCE_TYPE:l,FST_ERR_DEC_DEPENDENCY_INVALID_TYPE:u,FST_ERR_DEC_UNDECLARED:d}=mu();function f(e,t,n,r){if(Object.hasOwn(e,t))throw new o(t);x(e,t,r),n&&(typeof n.getter==`function`||typeof n.setter==`function`)?Object.defineProperty(e,t,{get:n.getter,set:n.setter}):e[t]=n}function p(e){if(!_(this,e))throw new d(e,`instance`);return typeof this[e]==`function`?this[e].bind(this):this[e]}function m(e,t,n,r){let i=e.prototype;if(Object.hasOwn(i,t)||v(e,t))throw new o(t);e[a]=!0,x(e,t,r),n&&(typeof n.getter==`function`||typeof n.setter==`function`)?Object.defineProperty(i,t,{get:n.getter,set:n.setter}):typeof n==`function`?i[t]=n:e.props.push({key:t,value:n})}function h(e,t){if(typeof t==`object`&&t&&!(typeof t.getter==`function`||typeof t.setter==`function`))throw new l(e,typeof t)}function g(e,t,n){return w(this,e),f(this,e,t,n),this}function _(e,t){return t?t in e||e.prototype&&t in e.prototype||v(e,t):e in this}function v(e,t){return e.props?e.props.find(({key:e})=>e===t):!1}function y(e){return e&&v(this[r],e)?!0:_(this[r].prototype,e)}function b(e){return e&&v(this[n],e)?!0:_(this[n].prototype,e)}function x(e,t,n){if(n!=null){if(!Array.isArray(n))throw new u(t);for(let t=0;t!==n.length;++t)if(!_(e,n[t]))throw new s(n[t])}}function S(e,t,r){return w(this,e),h(e,t),m(this[n],e,t,r),this}function C(e,t,n){return w(this,e),h(e,t),m(this[r],e,t,n),this}function w(e,t){if(e[i].started)throw new c(t)}t.exports={add:g,exist:_,existRequest:y,existReply:b,dependencies:x,decorateReply:S,decorateRequest:C,getInstanceDecorator:p,hasKey:v}})),cd=o(((e,t)=>{let n=require(`node:stream`).finished,{kFourOhFourContext:r,kReplyErrorHandlerCalled:i,kReplyHijacked:a,kReplyStartTime:o,kReplyEndTime:s,kReplySerializer:c,kReplySerializerDefault:l,kReplyIsError:u,kReplyHeaders:d,kReplyTrailers:f,kReplyHasStatusCode:p,kReplyIsRunningOnErrorHook:m,kReplyNextErrorHandler:h,kDisableRequestLogging:g,kSchemaResponse:_,kReplyCacheSerializeFns:v,kSchemaController:y,kOptions:b,kRouteContext:x}=du(),{onSendHookRunner:S,onResponseHookRunner:C,preHandlerHookRunner:w,preSerializationHookRunner:T}=hu(),E=Cu()[Symbol.for(`internals`)],D=td().now,{handleError:O}=od(),{getSchemaSerializer:k}=rd(),A={JSON:`application/json; charset=utf-8`,PLAIN:`text/plain; charset=utf-8`,OCTET:`application/octet-stream`},{FST_ERR_REP_INVALID_PAYLOAD_TYPE:j,FST_ERR_REP_RESPONSE_BODY_CONSUMED:M,FST_ERR_REP_READABLE_STREAM_LOCKED:ee,FST_ERR_REP_ALREADY_SENT:N,FST_ERR_SEND_INSIDE_ONERR:te,FST_ERR_BAD_STATUS_CODE:P,FST_ERR_BAD_TRAILER_NAME:ne,FST_ERR_BAD_TRAILER_VALUE:F,FST_ERR_MISSING_SERIALIZATION_FN:I,FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FN:re,FST_ERR_DEC_UNDECLARED:L}=mu(),ie=sd(),ae=Object.prototype.toString;function R(e,t,n){this.raw=e,this[c]=null,this[i]=!1,this[u]=!1,this[m]=!1,this.request=t,this[d]={},this[f]=null,this[p]=!1,this[o]=void 0,this.log=n}R.props=[],Object.defineProperties(R.prototype,{[x]:{get(){return this.request[x]}},elapsedTime:{get(){return this[o]===void 0?0:(this[s]||D())-this[o]}},server:{get(){return this.request[x].server}},sent:{enumerable:!0,get(){return(this[a]||this.raw.writableEnded)===!0}},statusCode:{get(){return this.raw.statusCode},set(e){this.code(e)}},routeOptions:{get(){return this.request.routeOptions}}}),R.prototype.writeEarlyHints=function(e,t){return this.raw.writeEarlyHints(e,t),this},R.prototype.hijack=function(){return this[a]=!0,this},R.prototype.send=function(e){if(this[m])throw new te;if(this.sent===!0)return this.log.warn({err:new N(this.request.url,this.request.method)}),this;if(this[u]||e instanceof Error)return this[u]=!1,ve(this,e,ue),this;if(e===void 0)return ue(this,e),this;let t=this.getHeader(`content-type`),n=t!==void 0;if(e!==null){if(typeof e.pipe==`function`||typeof e.getReader==`function`||ae.call(e)===`[object Response]`)return ue(this,e),this;if(e.buffer instanceof ArrayBuffer){n||(this[d][`content-type`]=A.OCTET);let t=Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength);return ue(this,t),this}if(!n&&typeof e==`string`)return this[d][`content-type`]=A.PLAIN,ue(this,e),this}if(this[c]!==null){if(typeof e!=`string`)return se(this,e),this;e=this[c](e)}else if(!n||t.indexOf(`json`)!==-1){if(!n)this[d][`content-type`]=A.JSON;else if(t.indexOf(`charset`)===-1){let e=t.trim();e.endsWith(`;`)?this[d][`content-type`]=`${e} charset=utf-8`:this[d][`content-type`]=`${e}; charset=utf-8`}if(typeof e!=`string`)return se(this,e),this}return ue(this,e),this},R.prototype.getHeader=function(e){e=e.toLowerCase();let t=this[d][e];return t===void 0?this.raw.getHeader(e):t},R.prototype.getHeaders=function(){return{...this.raw.getHeaders(),...this[d]}},R.prototype.hasHeader=function(e){return e=e.toLowerCase(),this[d][e]!==void 0||this.raw.hasHeader(e)},R.prototype.removeHeader=function(e){return delete this[d][e.toLowerCase()],this},R.prototype.header=function(e,t=``){return e=e.toLowerCase(),this[d][e]&&e===`set-cookie`?(typeof this[d][e]==`string`&&(this[d][e]=[this[d][e]]),Array.isArray(t)?Array.prototype.push.apply(this[d][e],t):this[d][e].push(t)):this[d][e]=t,this},R.prototype.headers=function(e){let t=Object.keys(e);for(let n=0;n!==t.length;++n){let r=t[n];this.header(r,e[r])}return this};let oe=new Set([`transfer-encoding`,`content-length`,`host`,`cache-control`,`max-forwards`,`te`,`authorization`,`set-cookie`,`content-encoding`,`content-type`,`content-range`,`trailer`]);R.prototype.trailer=function(e,t){if(e=e.toLowerCase(),oe.has(e))throw new ne(e);if(typeof t!=`function`)throw new F(e,typeof t);return this[f]===null&&(this[f]={}),this[f][e]=t,this},R.prototype.hasTrailer=function(e){return this[f]?.[e.toLowerCase()]!==void 0},R.prototype.removeTrailer=function(e){return this[f]===null||(this[f][e.toLowerCase()]=void 0),this},R.prototype.code=function(e){let t=+e;if(!(t>=100&&t<=599))throw new P(e||String(e));return this.raw.statusCode=t,this[p]=!0,this},R.prototype.status=R.prototype.code,R.prototype.getSerializationFunction=function(e,t){let n;return typeof e==`string`||typeof e==`number`?n=typeof t==`string`?this[x][_]?.[e]?.[t]:this[x][_]?.[e]:typeof e==`object`&&(n=this[x][v]?.get(e)),n},R.prototype.compileSerializationSchema=function(e,t=null,n=null){let{request:r}=this,{method:i,url:a}=r;if(this[x][v]?.has(e))return this[x][v].get(e);let o=(this[x].serializerCompiler||this.server[y].serializerCompiler||this.server[y].setupSerializer(this.server[b])||this.server[y].serializerCompiler)({schema:e,method:i,url:a,httpStatus:t,contentType:n});return this[x][v]??(this[x][v]=new WeakMap),this[x][v].set(e,o),o},R.prototype.serializeInput=function(e,t,n,r){let i=n,a;if(n=typeof t==`string`||typeof t==`number`?t:n,r=n&&i!==n?i:r,n!=null){if(a=r==null?this[x][_]?.[n]:this[x][_]?.[n]?.[r],a==null)throw r?new re(n,r):new I(n)}else a=this[x][v]?.has(t)?this[x][v].get(t):this.compileSerializationSchema(t,n,r);return a(e)},R.prototype.serialize=function(e){return this[c]===null?this[x]&&this[x][l]?this[x][l](e,this.raw.statusCode):Ce(this[x],e,this.raw.statusCode):this[c](e)},R.prototype.serializer=function(e){return this[c]=e,this},R.prototype.type=function(e){return this[d][`content-type`]=e,this},R.prototype.redirect=function(e,t){return t||=this[p]?this.raw.statusCode:302,this.header(`location`,e).code(t).send()},R.prototype.callNotFound=function(){return Se(this),this},R.prototype.then=function(e,t){if(this.sent){e();return}n(this.raw,n=>{n&&n.code!==`ERR_STREAM_PREMATURE_CLOSE`?t?t(n):this.log&&this.log.warn(`unhandled rejection on reply.then`):e()})},R.prototype.getDecorator=function(e){if(!ie.hasKey(this,e)&&!ie.exist(this,e))throw new L(e,`reply`);let t=this[e];return typeof t==`function`?t.bind(this):t};function se(e,t){e[x].preSerialization===null?ce(null,void 0,e,t):T(e[x].preSerialization,e.request,e,t,ce)}function ce(e,t,n,r){if(e!=null){ve(n,e);return}try{r=n[c]===null?n[x]&&n[x][l]?n[x][l](r,n.raw.statusCode):Ce(n[x],r,n.raw.statusCode,n[d][`content-type`]):n[c](r)}catch(e){le(e,n),ve(n,e);return}ue(n,r)}function le(e,t){e.serialization=t[x].config}function ue(e,t){e[x].onSend===null?fe(e,t):S(e[x].onSend,e.request,e,t,de)}function de(e,t,n,r){e==null?fe(n,r):ve(n,e)}function z(e,t){let n=e.raw;try{n.writeHead(t,e[d])}catch(t){throw t.code===`ERR_HTTP_HEADERS_SENT`&&e.log.warn(`Reply was already sent, did you forget to "return reply" in the "${e.request.raw.url}" (${e.request.raw.method}) route?`),t}}function fe(e,t){let n=e.raw,r=e.request;if(e[f]!==null){let t=Object.keys(e[f]),n=``;for(let r of t)typeof e[f][r]==`function`&&(n+=` `,n+=r);e.header(`Transfer-Encoding`,`chunked`),e.header(`Trailer`,n.trim())}if(ae.call(t)===`[object Response]`){if(typeof t.status==`number`&&e.code(t.status),typeof t.headers==`object`&&typeof t.headers.forEach==`function`)for(let[n,r]of t.headers)e.header(n,r);if(t.body!==null&&t.bodyUsed)throw new M;t=t.body}let i=n.statusCode;if(t==null){i>=200&&i!==204&&i!==304&&r.method!==`HEAD`&&e[f]===null&&(e[d][`content-length`]=`0`),z(e,i),ge(t,n,e);return}if(i>=100&&i<200||i===204){e.removeHeader(`content-type`),e.removeHeader(`content-length`),z(e,i),ge(void 0,n,e),typeof t.resume==`function`&&(t.on(`error`,we),t.resume());return}if(typeof t.pipe==`function`){he(t,n,e);return}if(typeof t.getReader==`function`){me(t,n,e);return}if(typeof t!=`string`&&!Buffer.isBuffer(t))throw new j(typeof t);if(e[f]===null){let n=e[d][`content-length`];(!n||r.raw.method!==`HEAD`&&Number(n)!==Buffer.byteLength(t))&&(e[d][`content-length`]=``+Buffer.byteLength(t))}z(e,i),n.write(t),ge(t,n,e)}function pe(e,t,n){t.code===`ERR_STREAM_PREMATURE_CLOSE`?e[g]||e.info({res:n},`stream closed prematurely`):e.warn({err:t},`response terminated with an error with headers already sent`)}function me(e,t,r){if(e.locked)throw new ee;let i=!0,a=!1,o=!1,s=e.getReader();if(n(t,function(e){i&&(e!=null&&t.headersSent&&!a&&(a=!0,pe(r.log,e,t)),s.cancel().catch(we))}),t.headersSent)r.log.warn(`response will send, but you shouldn't use res.writeHead in stream mode`);else for(let e in r[d])t.setHeader(e,r[d][e]);function c(e){if(e.done){i=!1,ge(null,t,r);return}if(t.destroyed){i=!1,s.cancel().catch(we);return}if(t.write(e.value)===!1){o=!0,t.once(`drain`,l);return}s.read().then(c,u)}function l(){!o||!i||t.destroyed||(o=!1,s.read().then(c,u))}function u(e){i=!1,t.headersSent||r.request.raw.aborted===!0?(a||(a=!0,pe(r.log,e,r)),t.destroy()):ve(r,e)}s.read().then(c,u)}function he(e,t,r){let i=!0,a=!1;if(_e(e,t,r),n(e,{readable:!0,writable:!1},function(e){i=!1,e!=null&&(t.headersSent||r.request.raw.aborted===!0?(a||(a=!0,pe(r.log,e,r)),t.destroy()):ve(r,e))}),n(t,function(n){i&&(n!=null&&t.headersSent&&!a&&(a=!0,pe(r.log,n,t)),typeof e.destroy==`function`?e.destroy():typeof e.close==`function`?e.close(we):typeof e.abort==`function`?e.abort():r.log.warn(`stream payload does not end properly`))}),t.headersSent)r.log.warn(`response will send, but you shouldn't use res.writeHead in stream mode`);else for(let e in r[d])t.setHeader(e,r[d][e]);e.pipe(t)}function ge(e,t,n){if(n[f]===null){t.end(null,null,null);return}let r=Object.keys(n[f]),i={},a=0,o=!0;function s(){a===0&&(t.addTrailers(i),t.end(null,null,null))}for(let t of r){if(typeof n[f][t]!=`function`)continue;o=!1,a--;function r(e,r){a++,e?n.log.debug(e):i[t]=r,process.nextTick(s)}let c=n[f][t](n,e,r);typeof c==`object`&&typeof c.then==`function`&&c.then(e=>r(null,e),r)}o&&t.end(null,null,null)}function _e(e,t,n){n[f]!==null&&e.on(`end`,()=>ge(null,t,n))}function ve(e,t,n){e[x].onError!==null&&!e[h]?(e[m]=!0,S(e[x].onError,e.request,e,t,()=>O(e,t,n))):O(e,t,n)}function ye(e){e[o]=D();let t=n=>{e[s]=D(),e.raw.removeListener(`finish`,t),e.raw.removeListener(`error`,t);let r=e[x];r&&r.onResponse!==null?C(r.onResponse,e.request,e,be):be(n,e.request,e)};e.raw.on(`finish`,t),e.raw.on(`error`,t)}function be(e,t,n){if(n.log[g])return;let r=n.elapsedTime;if(e!=null){n.log.error({res:n,err:e,responseTime:r},`request errored`);return}n.log.info({res:n,responseTime:r},`request completed`)}function xe(e){let t=e.props.slice();function n(e,n,r){this.raw=e,this[u]=!1,this[i]=!1,this[a]=!1,this[c]=null,this.request=n,this[d]={},this[f]=null,this[o]=void 0,this[s]=void 0,this.log=r;let l;for(let e=0;e<t.length;e++)l=t[e],this[l.key]=l.value}return Object.setPrototypeOf(n.prototype,e.prototype),Object.setPrototypeOf(n,e),n.parent=e,n.props=t,n}function Se(e){if(e[x][r]===null){e.log.warn(`Trying to send a NotFound error inside a 404 handler. Sending basic 404 response.`),e.code(404).send(`404 Not Found`);return}e.request[x]=e[x][r],e[x].preHandler===null?E.preHandlerCallback(null,e.request,e):w(e[x].preHandler,e.request,e,E.preHandlerCallback)}function Ce(e,t,n,r){let i=k(e,n,r);return i?i(t):JSON.stringify(t)}function we(){}t.exports=R,t.exports.buildReply=xe,t.exports.setupResponseListeners=ye})),ld=o(((e,t)=>{function n(e){if(!e)throw TypeError(`argument req is required`);let t=e.headers[`x-forwarded-for`],n=e.socket.remoteAddress;if(!t||typeof t!=`string`)return[n];if(t.indexOf(`,`)===-1){let e=t.trim();return e.length?[n,e]:[n]}else return r(t,n)}function r(e,t){let n=[t],r=e.length,i=r,a,o;for(o=r-1;o>=0;--o)a=e[o],a===` `?i===r&&(i=r=o):a===`,`?(i!==r&&n.push(e.slice(i,r)),i=r=o):i=o;return i!==r&&n.push(e.substring(i,r)),n}t.exports=n,t.exports.default=n,t.exports.forwarded=n})),ud=o(((e,t)=>{(function(e){"use strict";let n=`(0?\\d+|0x[a-f0-9]+)`,r={fourOctet:RegExp(`^${n}\\.${n}\\.${n}\\.${n}$`,`i`),threeOctet:RegExp(`^${n}\\.${n}\\.${n}$`,`i`),twoOctet:RegExp(`^${n}\\.${n}$`,`i`),longValue:RegExp(`^${n}$`,`i`)},i=RegExp(`^0[0-7]+$`,`i`),a=RegExp(`^0x[a-f0-9]+$`,`i`),o=`%[0-9a-z]{1,}`,s=`(?:[0-9a-f]+::?)+`,c={zoneIndex:new RegExp(o,`i`),native:RegExp(`^(::)?(${s})?([0-9a-f]+)?(::)?(${o})?$`,`i`),deprecatedTransitional:RegExp(`^(?:::)(${n}\\.${n}\\.${n}\\.${n}(${o})?)$`,`i`),transitional:RegExp(`^((?:${s})|(?:::)(?:${s})?)${n}\\.${n}\\.${n}\\.${n}(${o})?$`,`i`)};function l(e,t){if(e.indexOf(`::`)!==e.lastIndexOf(`::`))return null;let n=0,r=-1,i=(e.match(c.zoneIndex)||[])[0],a,o;for(i&&(i=i.substring(1),e=e.replace(/%.+$/,``));(r=e.indexOf(`:`,r+1))>=0;)n++;if(e.substr(0,2)===`::`&&n--,e.substr(-2,2)===`::`&&n--,n>t)return null;for(o=t-n,a=`:`;o--;)a+=`0:`;return e=e.replace(`::`,a),e[0]===`:`&&(e=e.slice(1)),e[e.length-1]===`:`&&(e=e.slice(0,-1)),t=(function(){let t=e.split(`:`),n=[];for(let e=0;e<t.length;e++)n.push(parseInt(t[e],16));return n})(),{parts:t,zoneId:i}}function u(e,t,n,r){if(e.length!==t.length)throw Error(`ipaddr: cannot match CIDR for objects with different lengths`);let i=0,a;for(;r>0;){if(a=n-r,a<0&&(a=0),e[i]>>a!==t[i]>>a)return!1;r-=n,i+=1}return!0}function d(e){if(a.test(e))return parseInt(e,16);if(e[0]===`0`&&!isNaN(parseInt(e[1],10))){if(i.test(e))return parseInt(e,8);throw Error(`ipaddr: cannot parse ${e} as octal`)}return parseInt(e,10)}function f(e,t){for(;e.length<t;)e=`0${e}`;return e}let p={};p.IPv4=(function(){function e(e){if(e.length!==4)throw Error(`ipaddr: ipv4 octet count should be 4`);let t,n;for(t=0;t<e.length;t++)if(n=e[t],!(0<=n&&n<=255))throw Error(`ipaddr: ipv4 octet should fit in 8 bits`);this.octets=e}return e.prototype.SpecialRanges={unspecified:[[new e([0,0,0,0]),8]],broadcast:[[new e([255,255,255,255]),32]],multicast:[[new e([224,0,0,0]),4]],linkLocal:[[new e([169,254,0,0]),16]],loopback:[[new e([127,0,0,0]),8]],carrierGradeNat:[[new e([100,64,0,0]),10]],private:[[new e([10,0,0,0]),8],[new e([172,16,0,0]),12],[new e([192,168,0,0]),16]],reserved:[[new e([192,0,0,0]),24],[new e([192,0,2,0]),24],[new e([192,88,99,0]),24],[new e([198,18,0,0]),15],[new e([198,51,100,0]),24],[new e([203,0,113,0]),24],[new e([240,0,0,0]),4]],as112:[[new e([192,175,48,0]),24],[new e([192,31,196,0]),24]],amt:[[new e([192,52,193,0]),24]]},e.prototype.kind=function(){return`ipv4`},e.prototype.match=function(e,t){let n;if(t===void 0&&(n=e,e=n[0],t=n[1]),e.kind()!==`ipv4`)throw Error(`ipaddr: cannot match ipv4 address with non-ipv4 one`);return u(this.octets,e.octets,8,t)},e.prototype.prefixLengthFromSubnetMask=function(){let e=0,t=!1,n={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},r,i,a;for(r=3;r>=0;--r)if(i=this.octets[r],i in n){if(a=n[i],t&&a!==0)return null;a!==8&&(t=!0),e+=a}else return null;return 32-e},e.prototype.range=function(){return p.subnetMatch(this,this.SpecialRanges)},e.prototype.toByteArray=function(){return this.octets.slice(0)},e.prototype.toIPv4MappedAddress=function(){return p.IPv6.parse(`::ffff:${this.toString()}`)},e.prototype.toNormalizedString=function(){return this.toString()},e.prototype.toString=function(){return this.octets.join(`.`)},e})(),p.IPv4.broadcastAddressFromCIDR=function(e){try{let t=this.parseCIDR(e),n=t[0].toByteArray(),r=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],a=0;for(;a<4;)i.push(parseInt(n[a],10)|parseInt(r[a],10)^255),a++;return new this(i)}catch{throw Error(`ipaddr: the address does not have IPv4 CIDR format`)}},p.IPv4.isIPv4=function(e){return this.parser(e)!==null},p.IPv4.isValid=function(e){try{return new this(this.parser(e)),!0}catch{return!1}},p.IPv4.isValidCIDR=function(e){try{return this.parseCIDR(e),!0}catch{return!1}},p.IPv4.isValidFourPartDecimal=function(e){return!!(p.IPv4.isValid(e)&&e.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},p.IPv4.isValidCIDRFourPartDecimal=function(e){let t=e.match(/^(.+)\/(\d+)$/);return!p.IPv4.isValidCIDR(e)||!t?!1:p.IPv4.isValidFourPartDecimal(t[1])},p.IPv4.networkAddressFromCIDR=function(e){let t,n,r,i,a;try{for(t=this.parseCIDR(e),r=t[0].toByteArray(),a=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],n=0;n<4;)i.push(parseInt(r[n],10)&parseInt(a[n],10)),n++;return new this(i)}catch{throw Error(`ipaddr: the address does not have IPv4 CIDR format`)}},p.IPv4.parse=function(e){let t=this.parser(e);if(t===null)throw Error(`ipaddr: string is not formatted like an IPv4 Address`);return new this(t)},p.IPv4.parseCIDR=function(e){let t;if(t=e.match(/^(.+)\/(\d+)$/)){let e=parseInt(t[2]);if(e>=0&&e<=32){let n=[this.parse(t[1]),e];return Object.defineProperty(n,`toString`,{value:function(){return this.join(`/`)}}),n}}throw Error(`ipaddr: string is not formatted like an IPv4 CIDR range`)},p.IPv4.parser=function(e){let t,n,i;if(t=e.match(r.fourOctet))return(function(){let e=t.slice(1,6),r=[];for(let t=0;t<e.length;t++)n=e[t],r.push(d(n));return r})();if(t=e.match(r.longValue)){if(i=d(t[1]),i>4294967295||i<0)throw Error(`ipaddr: address outside defined range`);return(function(){let e=[],t;for(t=0;t<=24;t+=8)e.push(i>>t&255);return e})().reverse()}else if(t=e.match(r.twoOctet))return(function(){let e=t.slice(1,4),n=[];if(i=d(e[1]),i>16777215||i<0)throw Error(`ipaddr: address outside defined range`);return n.push(d(e[0])),n.push(i>>16&255),n.push(i>>8&255),n.push(i&255),n})();else if(t=e.match(r.threeOctet))return(function(){let e=t.slice(1,5),n=[];if(i=d(e[2]),i>65535||i<0)throw Error(`ipaddr: address outside defined range`);return n.push(d(e[0])),n.push(d(e[1])),n.push(i>>8&255),n.push(i&255),n})();else return null},p.IPv4.subnetMaskFromPrefixLength=function(e){if(e=parseInt(e),e<0||e>32)throw Error(`ipaddr: invalid IPv4 prefix length`);let t=[0,0,0,0],n=0,r=Math.floor(e/8);for(;n<r;)t[n]=255,n++;return r<4&&(t[r]=2**(e%8)-1<<8-e%8),new this(t)},p.IPv6=(function(){function e(e,t){let n,r;if(e.length===16)for(this.parts=[],n=0;n<=14;n+=2)this.parts.push(e[n]<<8|e[n+1]);else if(e.length===8)this.parts=e;else throw Error(`ipaddr: ipv6 part count should be 8 or 16`);for(n=0;n<this.parts.length;n++)if(r=this.parts[n],!(0<=r&&r<=65535))throw Error(`ipaddr: ipv6 part should fit in 16 bits`);t&&(this.zoneId=t)}return e.prototype.SpecialRanges={unspecified:[new e([0,0,0,0,0,0,0,0]),128],linkLocal:[new e([65152,0,0,0,0,0,0,0]),10],multicast:[new e([65280,0,0,0,0,0,0,0]),8],loopback:[new e([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new e([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new e([0,0,0,0,0,65535,0,0]),96],discard:[new e([256,0,0,0,0,0,0,0]),64],rfc6145:[new e([0,0,0,0,65535,0,0,0]),96],rfc6052:[new e([100,65435,0,0,0,0,0,0]),96],"6to4":[new e([8194,0,0,0,0,0,0,0]),16],teredo:[new e([8193,0,0,0,0,0,0,0]),32],benchmarking:[new e([8193,2,0,0,0,0,0,0]),48],amt:[new e([8193,3,0,0,0,0,0,0]),32],as112v6:[[new e([8193,4,274,0,0,0,0,0]),48],[new e([9760,79,32768,0,0,0,0,0]),48]],deprecated:[new e([8193,16,0,0,0,0,0,0]),28],orchid2:[new e([8193,32,0,0,0,0,0,0]),28],droneRemoteIdProtocolEntityTags:[new e([8193,48,0,0,0,0,0,0]),28],reserved:[[new e([8193,0,0,0,0,0,0,0]),23],[new e([8193,3512,0,0,0,0,0,0]),32]]},e.prototype.isIPv4MappedAddress=function(){return this.range()===`ipv4Mapped`},e.prototype.kind=function(){return`ipv6`},e.prototype.match=function(e,t){let n;if(t===void 0&&(n=e,e=n[0],t=n[1]),e.kind()!==`ipv6`)throw Error(`ipaddr: cannot match ipv6 address with non-ipv6 one`);return u(this.parts,e.parts,16,t)},e.prototype.prefixLengthFromSubnetMask=function(){let e=0,t=!1,n={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},r,i;for(let a=7;a>=0;--a)if(r=this.parts[a],r in n){if(i=n[r],t&&i!==0)return null;i!==16&&(t=!0),e+=i}else return null;return 128-e},e.prototype.range=function(){return p.subnetMatch(this,this.SpecialRanges)},e.prototype.toByteArray=function(){let e,t=[],n=this.parts;for(let r=0;r<n.length;r++)e=n[r],t.push(e>>8),t.push(e&255);return t},e.prototype.toFixedLengthString=function(){let e=(function(){let e=[];for(let t=0;t<this.parts.length;t++)e.push(f(this.parts[t].toString(16),4));return e}).call(this).join(`:`),t=``;return this.zoneId&&(t=`%${this.zoneId}`),e+t},e.prototype.toIPv4Address=function(){if(!this.isIPv4MappedAddress())throw Error(`ipaddr: trying to convert a generic ipv6 address to ipv4`);let e=this.parts.slice(-2),t=e[0],n=e[1];return new p.IPv4([t>>8,t&255,n>>8,n&255])},e.prototype.toNormalizedString=function(){let e=(function(){let e=[];for(let t=0;t<this.parts.length;t++)e.push(this.parts[t].toString(16));return e}).call(this).join(`:`),t=``;return this.zoneId&&(t=`%${this.zoneId}`),e+t},e.prototype.toRFC5952String=function(){let e=/((^|:)(0(:|$)){2,})/g,t=this.toNormalizedString(),n=0,r=-1,i;for(;i=e.exec(t);)i[0].length>r&&(n=i.index,r=i[0].length);return r<0?t:`${t.substring(0,n)}::${t.substring(n+r)}`},e.prototype.toString=function(){return this.toRFC5952String()},e})(),p.IPv6.broadcastAddressFromCIDR=function(e){try{let t=this.parseCIDR(e),n=t[0].toByteArray(),r=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],a=0;for(;a<16;)i.push(parseInt(n[a],10)|parseInt(r[a],10)^255),a++;return new this(i)}catch(e){throw Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`)}},p.IPv6.isIPv6=function(e){return this.parser(e)!==null},p.IPv6.isValid=function(e){if(typeof e==`string`&&e.indexOf(`:`)===-1)return!1;try{let t=this.parser(e);return new this(t.parts,t.zoneId),!0}catch{return!1}},p.IPv6.isValidCIDR=function(e){if(typeof e==`string`&&e.indexOf(`:`)===-1)return!1;try{return this.parseCIDR(e),!0}catch{return!1}},p.IPv6.networkAddressFromCIDR=function(e){let t,n,r,i,a;try{for(t=this.parseCIDR(e),r=t[0].toByteArray(),a=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],n=0;n<16;)i.push(parseInt(r[n],10)&parseInt(a[n],10)),n++;return new this(i)}catch(e){throw Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`)}},p.IPv6.parse=function(e){let t=this.parser(e);if(t.parts===null)throw Error(`ipaddr: string is not formatted like an IPv6 Address`);return new this(t.parts,t.zoneId)},p.IPv6.parseCIDR=function(e){let t,n,r;if((n=e.match(/^(.+)\/(\d+)$/))&&(t=parseInt(n[2]),t>=0&&t<=128))return r=[this.parse(n[1]),t],Object.defineProperty(r,`toString`,{value:function(){return this.join(`/`)}}),r;throw Error(`ipaddr: string is not formatted like an IPv6 CIDR range`)},p.IPv6.parser=function(e){let t,n,r,i,a,o;if(r=e.match(c.deprecatedTransitional))return this.parser(`::ffff:${r[1]}`);if(c.native.test(e))return l(e,8);if((r=e.match(c.transitional))&&(o=r[6]||``,t=r[1],r[1].endsWith(`::`)||(t=t.slice(0,-1)),t=l(t+o,6),t.parts)){for(a=[parseInt(r[2]),parseInt(r[3]),parseInt(r[4]),parseInt(r[5])],n=0;n<a.length;n++)if(i=a[n],!(0<=i&&i<=255))return null;return t.parts.push(a[0]<<8|a[1]),t.parts.push(a[2]<<8|a[3]),{parts:t.parts,zoneId:t.zoneId}}return null},p.IPv6.subnetMaskFromPrefixLength=function(e){if(e=parseInt(e),e<0||e>128)throw Error(`ipaddr: invalid IPv6 prefix length`);let t=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],n=0,r=Math.floor(e/8);for(;n<r;)t[n]=255,n++;return r<16&&(t[r]=2**(e%8)-1<<8-e%8),new this(t)},p.fromByteArray=function(e){let t=e.length;if(t===4)return new p.IPv4(e);if(t===16)return new p.IPv6(e);throw Error(`ipaddr: the binary input is neither an IPv6 nor IPv4 address`)},p.isValid=function(e){return p.IPv6.isValid(e)||p.IPv4.isValid(e)},p.isValidCIDR=function(e){return p.IPv6.isValidCIDR(e)||p.IPv4.isValidCIDR(e)},p.parse=function(e){if(p.IPv6.isValid(e))return p.IPv6.parse(e);if(p.IPv4.isValid(e))return p.IPv4.parse(e);throw Error(`ipaddr: the address has neither IPv6 nor IPv4 format`)},p.parseCIDR=function(e){try{return p.IPv6.parseCIDR(e)}catch{try{return p.IPv4.parseCIDR(e)}catch{throw Error(`ipaddr: the address has neither IPv6 nor IPv4 CIDR format`)}}},p.process=function(e){let t=this.parse(e);return t.kind()===`ipv6`&&t.isIPv4MappedAddress()?t.toIPv4Address():t},p.subnetMatch=function(e,t,n){let r,i,a,o;for(i in n??=`unicast`,t)if(Object.prototype.hasOwnProperty.call(t,i)){for(a=t[i],a[0]&&!(a[0]instanceof Array)&&(a=[a]),r=0;r<a.length;r++)if(o=a[r],e.kind()===o[0].kind()&&e.match.apply(e,o))return i}return n},t!==void 0&&t.exports?t.exports=p:e.ipaddr=p})(e)})),dd=o(((e,t)=>{t.exports=m,t.exports.default=m,t.exports.proxyaddr=m,t.exports.all=c,t.exports.compile=l;let n=ld(),r=ud(),i=/^\d+$/u,a=r.isValid,o=r.parse,s={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 c(e,t){let r=n(e);if(!t)return r;typeof t!=`function`&&(t=l(t));for(let e=0;e<r.length-1;e++)t(r[e],e)||(r.length=e+1);return r}function l(e){if(!e)throw TypeError(`argument is required`);let t;if(typeof e==`string`)t=[e];else if(Array.isArray(e))t=e.slice();else throw TypeError(`unsupported trust argument`);for(let n=0;n<t.length;n++)e=t[n],Object.hasOwn(s,e)&&(e=s[e],t.splice.apply(t,[n,1].concat(e)),n+=e.length-1);return d(u(t))}function u(e){let t=Array(e.length);for(let n=0;n<e.length;n++)t[n]=f(e[n]);return t}function d(e){let t=e.length;return t===0?h:t===1?_(e[0]):g(e)}function f(e){let t=e.lastIndexOf(`/`),n=t===-1?e:e.substring(0,t);if(!a(n))throw TypeError(`invalid IP address: `+n);let r=o(n);t===-1&&r.kind()===`ipv6`&&r.isIPv4MappedAddress()&&(r=r.toIPv4Address());let s=r.kind()===`ipv6`?128:32,c=t===-1?null:e.substring(t+1,e.length);if(c=c===null?s:i.test(c)?parseInt(c,10):r.kind()===`ipv4`&&a(c)?p(c):null,c<=0||c>s)throw TypeError(`invalid range on address: `+e);return[r,c]}function p(e){let t=o(e);return t.kind()===`ipv4`?t.prefixLengthFromSubnetMask():null}function m(e,t){if(!e)throw TypeError(`req argument is required`);if(!t)throw TypeError(`trust argument is required`);let n=c(e,t);return n[n.length-1]}function h(){return!1}function g(e){return function(t){if(!a(t))return!1;let n=o(t),r,i=n.kind();for(let t=0;t<e.length;t++){let a=e[t],o=a[0],s=o.kind(),c=a[1],l=n;if(i!==s){let e=s===`ipv4`;if(e&&!n.isIPv4MappedAddress())continue;r||=e?n.toIPv4Address():n.toIPv4MappedAddress(),l=r}if(l.match(o,c))return!0}return!1}}function _(e){let t=e[0],n=t.kind(),r=n===`ipv4`,i=e[1];return function(e){if(!a(e))return!1;let s=o(e);if(s.kind()!==n){if(r&&!s.isIPv4MappedAddress())return!1;s=r?s.toIPv4Address():s.toIPv4MappedAddress()}return s.match(t,i)}}})),fd=o(((e,t)=>{let n=dd(),{kHasBeenDecorated:r,kSchemaBody:i,kSchemaHeaders:a,kSchemaParams:o,kSchemaQuerystring:s,kSchemaController:c,kOptions:l,kRequestCacheValidateFns:u,kRouteContext:d,kRequestOriginalUrl:f}=du(),{FST_ERR_REQ_INVALID_VALIDATION_INVOCATION:p,FST_ERR_DEC_UNDECLARED:m}=mu(),h=sd(),g={body:i,headers:a,params:o,querystring:s,query:s};function _(e,t,n,r,i,a){this.id=e,this[d]=a,this.params=t,this.raw=n,this.query=r,this.log=i,this.body=void 0}_.props=[];function v(e){if(typeof e==`function`)return e;if(e===!0)return null;if(typeof e==`number`)return function(t,n){return n<e};if(typeof e==`string`){let t=e.split(`,`).map(e=>e.trim());return n.compile(t)}return n.compile(e)}function y(e,t){return t?S(e,t):b(e)}function b(e){let t=e.props.slice();function n(e,n,r,i,a,o){this.id=e,this[d]=o,this.params=n,this.raw=r,this.query=i,this.log=a,this.body=void 0;let s;for(let e=0;e<t.length;e++)s=t[e],this[s.key]=s.value}return Object.setPrototypeOf(n.prototype,e.prototype),Object.setPrototypeOf(n,e),n.props=t,n.parent=e,n}function x(e){let t=e.lastIndexOf(`,`);return t===-1?e.trim():e.slice(t+1).trim()}function S(e,t){let i=b(e),a=v(t);return i[r]=!0,Object.defineProperties(i.prototype,{ip:{get(){let e=n.all(this.raw,a);return e[e.length-1]}},ips:{get(){return n.all(this.raw,a)}},host:{get(){return this.ip!==void 0&&this.headers[`x-forwarded-host`]?x(this.headers[`x-forwarded-host`]):this.headers.host??this.headers[`:authority`]??``}},protocol:{get(){if(this.headers[`x-forwarded-proto`])return x(this.headers[`x-forwarded-proto`]);if(this.socket)return this.socket.encrypted?`https`:`http`}}}),i}function C(e,t){if(!h.hasKey(e,t)&&!h.exist(e,t))throw new m(t,`request`)}Object.defineProperties(_.prototype,{server:{get(){return this[d].server}},url:{get(){return this.raw.url}},originalUrl:{get(){return this[f]||(this[f]=this.raw.originalUrl||this.raw.url),this[f]}},method:{get(){return this.raw.method}},routeOptions:{get(){let e=this[d],t=e._parserOptions.limit,n=e.server.initialConfig.bodyLimit,r=e.server.hasConstraintStrategy(`version`)?this.raw.headers[`accept-version`]:void 0;return{method:e.config?.method,url:e.config?.url,bodyLimit:t||n,attachValidation:e.attachValidation,logLevel:e.logLevel,exposeHeadRoute:e.exposeHeadRoute,prefixTrailingSlash:e.prefixTrailingSlash,handler:e.handler,config:e.config,schema:e.schema,version:r}}},is404:{get(){return this[d].config?.url===void 0}},socket:{get(){return this.raw.socket}},ip:{get(){if(this.socket)return this.socket.remoteAddress}},host:{get(){return this.raw.headers.host??this.raw.headers[`:authority`]??``}},hostname:{get(){return this.host[0]===`[`?this.host.slice(0,this.host.indexOf(`]`)+1):this.host.split(`:`,1)[0]}},port:{get(){let e=parseInt(this.host.split(`:`).slice(-1)[0]);if(!isNaN(e))return e;let t=this.headers.host??this.headers[`:authority`]??``,n=parseInt(t.split(`:`).slice(-1)[0]);return isNaN(n)?null:n}},protocol:{get(){if(this.socket)return this.socket.encrypted?`https`:`http`}},headers:{get(){return this.additionalHeaders?Object.assign({},this.raw.headers,this.additionalHeaders):this.raw.headers},set(e){this.additionalHeaders=e}},getValidationFunction:{value:function(e){if(typeof e==`string`){let t=g[e];return this[d][t]}else if(typeof e==`object`)return this[d][u]?.get(e)}},compileValidationSchema:{value:function(e,t=null){let{method:n,url:r}=this;if(this[d][u]?.has(e))return this[d][u].get(e);let i=(this[d].validatorCompiler||this.server[c].validatorCompiler||this.server[c].setupValidator(this.server[l])||this.server[c].validatorCompiler)({schema:e,method:n,url:r,httpPart:t});return this[d][u]??(this[d][u]=new WeakMap),this[d][u].set(e,i),i}},validateInput:{value:function(e,t,n){n=typeof t==`string`?t:n;let r=n!=null&&typeof n==`string`&&g[n],i;if(r&&(i=this[d][r]),i==null&&(typeof t!=`object`||!t||Array.isArray(t)))throw new p(n);return i??=this[d][u]?.has(t)?this[d][u].get(t):this.compileValidationSchema(t,n),i(e)}},getDecorator:{value:function(e){C(this,e);let t=this[e];return typeof t==`function`?t.bind(this):t}},setDecorator:{value:function(e,t){C(this,e),this[e]=t}}}),t.exports=_,t.exports.buildRequest=y})),pd=o(((e,t)=>{let{kFourOhFourContext:n,kReplySerializerDefault:r,kSchemaErrorFormatter:i,kErrorHandler:a,kChildLoggerFactory:o,kOptions:s,kReply:c,kRequest:l,kBodyLimit:u,kLogLevel:d,kContentTypeParser:f,kRouteByFastify:p,kRequestCacheValidateFns:m,kReplyCacheSerializeFns:h}=du();function g({schema:e,handler:t,config:g,requestIdLogLabel:v,childLoggerFactory:y,errorHandler:b,bodyLimit:x,logLevel:S,logSerializers:C,attachValidation:w,validatorCompiler:T,serializerCompiler:E,replySerializer:D,schemaErrorFormatter:O,exposeHeadRoute:k,prefixTrailingSlash:A,server:j,isFastify:M}){this.schema=e,this.handler=t,this.Reply=j[c],this.Request=j[l],this.contentTypeParser=j[f],this.onRequest=null,this.onSend=null,this.onError=null,this.onTimeout=null,this.preHandler=null,this.onResponse=null,this.preSerialization=null,this.onRequestAbort=null,this.config=g,this.errorHandler=b||j[a],this.requestIdLogLabel=v||j[s].requestIdLogLabel,this.childLoggerFactory=y||j[o],this._middie=null,this._parserOptions={limit:x||j[u]},this.exposeHeadRoute=k,this.prefixTrailingSlash=A,this.logLevel=S||j[d],this.logSerializers=C,this[n]=null,this.attachValidation=w,this[r]=D,this.schemaErrorFormatter=O||j[i]||_,this[p]=M,this[m]=null,this[h]=null,this.validatorCompiler=T||null,this.serializerCompiler=E||null,this.server=j}function _(e,t){let n=``;for(let r=0;r!==e.length;++r){let i=e[r];n+=t+(i.instancePath||``)+` `+i.message+`, `}return Error(n.slice(0,-2))}t.exports=g})),md=o((e=>{var t=class{constructor(e=1e3,t=0){if(isNaN(e)||e<0)throw Error(`Invalid max value`);if(isNaN(t)||t<0)throw Error(`Invalid ttl value`);this.first=null,this.items=new Map,this.last=null,this.max=e,this.ttl=t}get size(){return this.items.size}clear(){this.items=new Map,this.first=null,this.last=null}delete(e){if(this.items.has(e)){let t=this.items.get(e);this.items.delete(e),t.prev!==null&&(t.prev.next=t.next),t.next!==null&&(t.next.prev=t.prev),this.first===t&&(this.first=t.next),this.last===t&&(this.last=t.prev)}}deleteMany(e){for(var t=0;t<e.length;t++)this.delete(e[t])}evict(){if(this.size>0){let e=this.first;this.items.delete(e.key),this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}}expiresAt(e){if(this.items.has(e))return this.items.get(e).expiry}get(e){if(this.items.has(e)){let t=this.items.get(e);if(this.ttl>0&&t.expiry<=Date.now()){this.delete(e);return}return t.value}}getMany(e){let t=[];for(var n=0;n<e.length;n++)t.push(this.get(e[n]));return t}keys(){return this.items.keys()}set(e,t){if(this.items.has(e)){let n=this.items.get(e);n.value=t,n.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl;return}this.max>0&&this.size===this.max&&this.evict();let n={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:t};this.items.set(e,n),this.size===1?this.first=n:this.last.next=n,this.last=n}},n=class{constructor(e=1e3,t=0){if(isNaN(e)||e<0)throw Error(`Invalid max value`);if(isNaN(t)||t<0)throw Error(`Invalid ttl value`);this.first=null,this.items=new Map,this.last=null,this.max=e,this.ttl=t}get size(){return this.items.size}bumpLru(e){if(this.last===e)return;let t=this.last,n=e.next,r=e.prev;this.first===e&&(this.first=n),e.next=null,e.prev=t,t.next=e,r!==null&&(r.next=n),n!==null&&(n.prev=r),this.last=e}clear(){this.items=new Map,this.first=null,this.last=null}delete(e){if(this.items.has(e)){let t=this.items.get(e);this.items.delete(e),t.prev!==null&&(t.prev.next=t.next),t.next!==null&&(t.next.prev=t.prev),this.first===t&&(this.first=t.next),this.last===t&&(this.last=t.prev)}}deleteMany(e){for(var t=0;t<e.length;t++)this.delete(e[t])}evict(){if(this.size>0){let e=this.first;this.items.delete(e.key),this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}}expiresAt(e){if(this.items.has(e))return this.items.get(e).expiry}get(e){if(this.items.has(e)){let t=this.items.get(e);if(this.ttl>0&&t.expiry<=Date.now()){this.delete(e);return}return this.bumpLru(t),t.value}}getMany(e){let t=[];for(var n=0;n<e.length;n++)t.push(this.get(e[n]));return t}keys(){return this.items.keys()}set(e,t){if(this.items.has(e)){let n=this.items.get(e);n.value=t,n.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl,this.last!==n&&this.bumpLru(n);return}this.max>0&&this.size===this.max&&this.evict();let n={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:t};this.items.set(e,n),this.size===1?this.first=n:this.last.next=n,this.last=n}},r=class{constructor(e=1e3,t=0){if(isNaN(e)||e<0)throw Error(`Invalid max value`);if(isNaN(t)||t<0)throw Error(`Invalid ttl value`);this.first=null,this.items=Object.create(null),this.last=null,this.size=0,this.max=e,this.ttl=t}bumpLru(e){if(this.last===e)return;let t=this.last,n=e.next,r=e.prev;this.first===e&&(this.first=n),e.next=null,e.prev=t,t.next=e,r!==null&&(r.next=n),n!==null&&(n.prev=r),this.last=e}clear(){this.items=Object.create(null),this.first=null,this.last=null,this.size=0}delete(e){if(Object.prototype.hasOwnProperty.call(this.items,e)){let t=this.items[e];delete this.items[e],this.size--,t.prev!==null&&(t.prev.next=t.next),t.next!==null&&(t.next.prev=t.prev),this.first===t&&(this.first=t.next),this.last===t&&(this.last=t.prev)}}deleteMany(e){for(var t=0;t<e.length;t++)this.delete(e[t])}evict(){if(this.size>0){let e=this.first;delete this.items[e.key],--this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}}expiresAt(e){if(Object.prototype.hasOwnProperty.call(this.items,e))return this.items[e].expiry}get(e){if(Object.prototype.hasOwnProperty.call(this.items,e)){let t=this.items[e];if(this.ttl>0&&t.expiry<=Date.now()){this.delete(e);return}return this.bumpLru(t),t.value}}getMany(e){let t=[];for(var n=0;n<e.length;n++)t.push(this.get(e[n]));return t}keys(){return Object.keys(this.items)}set(e,t){if(Object.prototype.hasOwnProperty.call(this.items,e)){let n=this.items[e];n.value=t,n.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl,this.last!==n&&this.bumpLru(n);return}this.max>0&&this.size===this.max&&this.evict();let n={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:t};this.items[e]=n,++this.size===1?this.first=n:this.last.next=n,this.last=n}},i=class{constructor(){this.records={}}initForCache(e,t){this.records[e]={[t]:{cacheSize:0,hits:0,falsyHits:0,emptyHits:0,misses:0,expirations:0,evictions:0,invalidateOne:0,invalidateAll:0,sets:0}}}resetForCache(e){for(let t of Object.keys(this.records[e]))this.records[e][t]={cacheSize:0,hits:0,falsyHits:0,emptyHits:0,misses:0,expirations:0,evictions:0,invalidateOne:0,invalidateAll:0,sets:0}}getStatistics(){return this.records}};function a(e){return`${e.getFullYear()}-${(e.getMonth()+1).toString().padStart(2,`0`)}-${e.getDate().toString().padStart(2,`0`)}`}var o=class{constructor(e,t,n){this.cacheId=e,this.statisticTtlInHours=t,this.collectionStart=new Date,this.currentTimeStamp=a(this.collectionStart),this.records=n||new i,this.records.initForCache(this.cacheId,this.currentTimeStamp)}get currentRecord(){return this.records.records[this.cacheId][this.currentTimeStamp]||(this.records.records[this.cacheId][this.currentTimeStamp]={cacheSize:0,hits:0,falsyHits:0,emptyHits:0,misses:0,expirations:0,evictions:0,sets:0,invalidateOne:0,invalidateAll:0}),this.records.records[this.cacheId][this.currentTimeStamp]}hoursPassed(){return(Date.now()-this.collectionStart)/1e3/60/60}addHit(){this.archiveIfNeeded(),this.currentRecord.hits++}addFalsyHit(){this.archiveIfNeeded(),this.currentRecord.falsyHits++}addEmptyHit(){this.archiveIfNeeded(),this.currentRecord.emptyHits++}addMiss(){this.archiveIfNeeded(),this.currentRecord.misses++}addEviction(){this.archiveIfNeeded(),this.currentRecord.evictions++}setCacheSize(e){this.archiveIfNeeded(),this.currentRecord.cacheSize=e}addExpiration(){this.archiveIfNeeded(),this.currentRecord.expirations++}addSet(){this.archiveIfNeeded(),this.currentRecord.sets++}addInvalidateOne(){this.archiveIfNeeded(),this.currentRecord.invalidateOne++}addInvalidateAll(){this.archiveIfNeeded(),this.currentRecord.invalidateAll++}getStatistics(){return this.records.getStatistics()}archiveIfNeeded(){this.hoursPassed()>=this.statisticTtlInHours&&(this.collectionStart=new Date,this.currentTimeStamp=a(this.collectionStart),this.records.initForCache(this.cacheId,this.currentTimeStamp))}},s=class extends r{constructor(e,t,n,r,i){if(super(e||1e3,t||0),!n)throw Error(`Cache id is mandatory`);this.hitStatistics=new o(n,i===void 0?24:i,r)}getStatistics(){return this.hitStatistics.getStatistics()}set(e,t){super.set(e,t),this.hitStatistics.addSet(),this.hitStatistics.setCacheSize(this.size)}evict(){super.evict(),this.hitStatistics.addEviction(),this.hitStatistics.setCacheSize(this.size)}delete(e,t=!1){super.delete(e),t||this.hitStatistics.addInvalidateOne(),this.hitStatistics.setCacheSize(this.size)}clear(){super.clear(),this.hitStatistics.addInvalidateAll(),this.hitStatistics.setCacheSize(this.size)}get(e){if(Object.prototype.hasOwnProperty.call(this.items,e)){let t=this.items[e];if(this.ttl>0&&t.expiry<=Date.now()){this.delete(e,!0),this.hitStatistics.addExpiration();return}return this.bumpLru(t),t.value||this.hitStatistics.addFalsyHit(),(t.value===void 0||t.value===null||t.value===``)&&this.hitStatistics.addEmptyHit(),this.hitStatistics.addHit(),t.value}this.hitStatistics.addMiss()}},c=class{constructor(e=1e3,t=0){if(isNaN(e)||e<0)throw Error(`Invalid max value`);if(isNaN(t)||t<0)throw Error(`Invalid ttl value`);this.first=null,this.items=Object.create(null),this.last=null,this.size=0,this.max=e,this.ttl=t}clear(){this.items=Object.create(null),this.first=null,this.last=null,this.size=0}delete(e){if(Object.prototype.hasOwnProperty.call(this.items,e)){let t=this.items[e];delete this.items[e],this.size--,t.prev!==null&&(t.prev.next=t.next),t.next!==null&&(t.next.prev=t.prev),this.first===t&&(this.first=t.next),this.last===t&&(this.last=t.prev)}}deleteMany(e){for(var t=0;t<e.length;t++)this.delete(e[t])}evict(){if(this.size>0){let e=this.first;delete this.items[e.key],--this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}}expiresAt(e){if(Object.prototype.hasOwnProperty.call(this.items,e))return this.items[e].expiry}get(e){if(Object.prototype.hasOwnProperty.call(this.items,e)){let t=this.items[e];if(this.ttl>0&&t.expiry<=Date.now()){this.delete(e);return}return t.value}}getMany(e){let t=[];for(var n=0;n<e.length;n++)t.push(this.get(e[n]));return t}keys(){return Object.keys(this.items)}set(e,t){if(Object.prototype.hasOwnProperty.call(this.items,e)){let n=this.items[e];n.value=t,n.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl;return}this.max>0&&this.size===this.max&&this.evict();let n={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:t};this.items[e]=n,++this.size===1?this.first=n:this.last.next=n,this.last=n}};e.Fifo=c,e.FifoMap=t,e.FifoObject=c,e.HitStatisticsRecord=i,e.Lru=r,e.LruHitStatistics=s,e.LruMap=n,e.LruObject=r,e.LruObjectHitStatistics=s})),hd=o(((e,t)=>{let n=typeof Buffer<`u`,r=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,i=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function a(e,t,a){a==null&&typeof t==`object`&&t&&(a=t,t=void 0),n&&Buffer.isBuffer(e)&&(e=e.toString()),e&&e.charCodeAt(0)===65279&&(e=e.slice(1));let s=JSON.parse(e,t);if(typeof s!=`object`||!s)return s;let c=a&&a.protoAction||`error`,l=a&&a.constructorAction||`error`;if(c===`ignore`&&l===`ignore`)return s;if(c!==`ignore`&&l!==`ignore`){if(r.test(e)===!1&&i.test(e)===!1)return s}else if(c!==`ignore`&&l===`ignore`){if(r.test(e)===!1)return s}else if(i.test(e)===!1)return s;return o(s,{protoAction:c,constructorAction:l,safe:a&&a.safe})}function o(e,{protoAction:t=`error`,constructorAction:n=`error`,safe:r}={}){let i=[e];for(;i.length;){let e=i;i=[];for(let a of e){if(t!==`ignore`&&Object.prototype.hasOwnProperty.call(a,`__proto__`)){if(r===!0)return null;if(t===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete a.__proto__}if(n!==`ignore`&&Object.prototype.hasOwnProperty.call(a,`constructor`)&&a.constructor!==null&&typeof a.constructor==`object`&&Object.prototype.hasOwnProperty.call(a.constructor,`prototype`)){if(r===!0)return null;if(n===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete a.constructor}for(let e in a){let t=a[e];t&&typeof t==`object`&&i.push(t)}}}return e}function s(e,t,n){let{stackTraceLimit:r}=Error;Error.stackTraceLimit=0;try{return a(e,t,n)}finally{Error.stackTraceLimit=r}}function c(e,t){let{stackTraceLimit:n}=Error;Error.stackTraceLimit=0;try{return a(e,t,{safe:!0})}catch{return}finally{Error.stackTraceLimit=n}}t.exports=s,t.exports.default=s,t.exports.parse=s,t.exports.safeParse=c,t.exports.scan=o})),gd=o(((e,t)=>{let{AsyncResource:n}=require(`node:async_hooks`),{FifoMap:r}=md(),{parse:i}=hd(),a=yu(),{kDefaultJsonParse:o,kContentTypeParser:s,kBodyLimit:c,kRequestPayloadStream:l,kState:u,kTestInternals:d,kReplyIsError:f,kRouteContext:p}=du(),{FST_ERR_CTP_INVALID_TYPE:m,FST_ERR_CTP_EMPTY_TYPE:h,FST_ERR_CTP_ALREADY_PRESENT:g,FST_ERR_CTP_INVALID_HANDLER:_,FST_ERR_CTP_INVALID_PARSE_TYPE:v,FST_ERR_CTP_BODY_TOO_LARGE:y,FST_ERR_CTP_INVALID_MEDIA_TYPE:b,FST_ERR_CTP_INVALID_CONTENT_LENGTH:x,FST_ERR_CTP_EMPTY_JSON_BODY:S,FST_ERR_CTP_INSTANCE_ALREADY_STARTED:C,FST_ERR_CTP_INVALID_JSON_BODY:w}=mu(),{FSTSEC001:T}=pu();function E(e,t,n){this[o]=O(t,n),this.customParsers=new Map,this.customParsers.set(`application/json`,new A(!0,!1,e,this[o])),this.customParsers.set(`text/plain`,new A(!0,!1,e,k)),this.parserList=[`application/json`,`text/plain`],this.parserRegExpList=[],this.cache=new r(100)}E.prototype.add=function(e,t,n){let r=typeof e==`string`;if(r){if(e=e.trim().toLowerCase(),e.length===0)throw new h}else if(!(e instanceof RegExp))throw new m;if(typeof n!=`function`)throw new _;if(this.existingParser(e))throw new g(e);if(t.parseAs!==void 0&&t.parseAs!==`string`&&t.parseAs!==`buffer`)throw new v(t.parseAs);let i=new A(t.parseAs===`string`,t.parseAs===`buffer`,t.bodyLimit,n);if(e===`*`)this.customParsers.set(``,i);else if(r){let t=new a(e);if(t.isValid===!1)throw new m;let n=t.toString();this.parserList.unshift(n),this.customParsers.set(n,i)}else P(e),this.parserRegExpList.unshift(e),this.customParsers.set(e.toString(),i)},E.prototype.hasParser=function(e){if(typeof e==`string`)e=new a(e).toString();else{if(!(e instanceof RegExp))throw new m;e=e.toString()}return this.customParsers.has(e)},E.prototype.existingParser=function(e){if(typeof e==`string`){let t=new a(e).toString();if(e===`application/json`&&this.customParsers.has(e))return this.customParsers.get(t).fn!==this[o];if(e===`text/plain`&&this.customParsers.has(e))return this.customParsers.get(t).fn!==k}return this.hasParser(e)},E.prototype.getParser=function(e){typeof e==`string`&&(e=new a(e));let t=e.toString(),n=this.cache.get(t);if(n!==void 0)return n;if(n=this.customParsers.get(t),n!==void 0)return this.cache.set(t,n),n;if(n=this.customParsers.get(e.mediaType),n!==void 0)return n;for(let e=0;e!==this.parserRegExpList.length;++e){let r=this.parserRegExpList[e];if(r.test(t))return n=this.customParsers.get(r.toString()),this.cache.set(t,n),n}return this.customParsers.get(``)},E.prototype.removeAll=function(){this.customParsers=new Map,this.parserRegExpList=[],this.parserList=[],this.cache=new r(100)},E.prototype.remove=function(e){let t;if(typeof e==`string`)e=new a(e).toString(),t=this.parserList;else{if(!(e instanceof RegExp))throw new m;e=e.toString(),t=this.parserRegExpList}let n=this.customParsers.delete(e),r=t.findIndex(t=>t.toString()===e);return r>-1&&t.splice(r,1),n||r>-1},E.prototype.run=function(e,t,r,i){let a=this.getParser(e);if(a===void 0){if(r.is404===!0){t(r,i);return}i[f]=!0,i.send(new b(e||void 0));return}let o=new n(`content-type-parser:run`,r),s=o.bind(u);if(a.asString===!0||a.asBuffer===!0){D(r,i,i[p]._parserOptions,a,s);return}let c=a.fn(r,r[l],s);c&&typeof c.then==`function`&&c.then(e=>{s(null,e)},s);function u(e,n){if(o.emitDestroy(),e!=null){i.header(`connection`,`close`),i[f]=!0,i.send(e);return}r.body=n,t(r,i)}};function D(e,t,n,r,i){let a=r.asString===!0,o=n.limit===null?r.bodyLimit:n.limit,s=Number(e.headers[`content-length`]);if(s>o){i(new y,void 0);return}let c=0,u=a?``:[],d=e[l]||e.raw;a&&d.setEncoding(`utf8`),d.on(`data`,f),d.on(`end`,p),d.on(`error`,p),d.resume();function f(e){c+=a?Buffer.byteLength(e):e.length;let{receivedEncodedLength:t=0}=d;if(c>o||t>o){d.removeListener(`data`,f),d.removeListener(`end`,p),d.removeListener(`error`,p),i(new y,void 0);return}a?u+=e:u.push(e)}function p(t){if(d.removeListener(`data`,f),d.removeListener(`end`,p),d.removeListener(`error`,p),t!=null){typeof t.statusCode==`number`&&t.statusCode>=400||(t.statusCode=400),i(t,void 0);return}if(!Number.isNaN(s)&&(d.receivedEncodedLength||c)!==s){i(new x,void 0);return}a||(u=Buffer.concat(u));let n=r.fn(e,u,i);n&&typeof n.then==`function`&&n.then(e=>{i(null,e)},i)}}function O(e,t){let n={protoAction:e,constructorAction:t};return r;function r(e,t,r){if(t.length===0){r(new S,void 0);return}try{r(null,i(t,n))}catch{r(new w,void 0)}}}function k(e,t,n){n(null,t)}function A(e,t,n,r){this.asString=e,this.asBuffer=t,this.bodyLimit=n,this.fn=r}function j(e){let t=new E;return t[o]=e[o],t.customParsers=new Map(e.customParsers.entries()),t.parserList=e.parserList.slice(),t.parserRegExpList=e.parserRegExpList.slice(),t}function M(e,t,n){if(this[u].started)throw new C(`addContentTypeParser`);return typeof t==`function`&&(n=t,t={}),t||={},t.bodyLimit||=this[c],Array.isArray(e)?e.forEach(e=>this[s].add(e,t,n)):this[s].add(e,t,n),this}function ee(e){return this[s].hasParser(e)}function N(e){if(this[u].started)throw new C(`removeContentTypeParser`);if(Array.isArray(e))for(let t of e)this[s].remove(t);else this[s].remove(e)}function te(){if(this[u].started)throw new C(`removeAllContentTypeParsers`);this[s].removeAll()}function P(e){e.source[0]!==`^`&&e.source.includes(`;?`)===!1&&T(e.source)}t.exports=E,t.exports.helpers={buildContentTypeParser:j,addContentTypeParser:M,hasContentTypeParser:ee,removeContentTypeParser:N,removeAllContentTypeParsers:te},t.exports.defaultParsers={getDefaultJsonParser:O,defaultTextParser:k},t.exports[d]={rawBody:D}})),_d=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;let a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),vd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=_d();var n=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},r;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var i=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=i;var a=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=a;let o=(0,t._)`\n`;e.ValueScope=class extends i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=new Map;a.set(i,n);let o=this._scope[r]||(this._scope[r]=[]),s=o.length;return o[s]=t.ref,n.setValue(t,{property:r,itemIndex:s}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(i,a,o={},s){let c=t.nil;for(let l in i){let u=i[l];if(!u)continue;let d=o[l]=o[l]||new Map;u.forEach(i=>{if(d.has(i))return;d.set(i,r.Started);let o=a(i);if(o){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${i} = ${o};${this.opts._n}`}else if(o=s?.(i))c=(0,t._)`${c}${o}${this.opts._n}`;else throw new n(i);d.set(i,r.Completed)})}return c}}})),Z=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=_d(),n=vd();var r=_d();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,`strConcat`,{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,`getProperty`,{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,`regexpCode`,{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return r.Name}});var i=vd();Object.defineProperty(e,`Scope`,{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,`ValueScope`,{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,`ValueScopeName`,{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,`varKinds`,{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=k(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=k(this.rhs,e,n),this}get names(){return O(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=k(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(A(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>D(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(j(t),n instanceof e?[n]:n.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=k(this.condition,e,t),this}get names(){let e=super.names;return O(e,this.condition),this.else&&D(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=k(this.iteration,e,t),this}get names(){return D(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return O(O(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=k(this.iterable,e,t),this}get names(){return D(super.names,this.iterable.names)}},S=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};S.kind=`func`;var C=class extends p{render(e){return`return `+super.render(e)}};C.kind=`return`;var w=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&D(e,this.catch.names),this.finally&&D(e,this.finally.names),e}},T=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};T.kind=`catch`;var E=class extends m{render(e){return`finally`+super.render(e)}};E.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
|
|
129
|
-
`:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new b(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new x(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new x(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new C;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(C)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new w;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new T(e),t(e)}return n&&(this._currNode=r.finally=new E,this.code(n)),this._endBlockNode(T,E)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new S(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function D(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function O(e,n){return n instanceof t._CodeOrName?D(e,n.names):e}function k(e,n,r){if(e instanceof t.Name)return i(e);if(!a(e))return e;return new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[]));function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function A(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function j(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${ne(e)}`}e.not=j;let M=P(e.operators.AND);function ee(...e){return e.reduce(M)}e.and=ee;let N=P(e.operators.OR);function te(...e){return e.reduce(N)}e.or=te;function P(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${ne(n)} ${e} ${ne(r)}`}function ne(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),Q=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;let t=Z(),n=_d();function r(e){let t={};for(let n of e)t[n]=!0;return t}e.toHash=r;function i(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0?!0:(a(e,t),!o(t,e.self.RULES.all))}e.alwaysValidSchema=i;function a(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t==`boolean`)return;let i=r.RULES.keywords;for(let n in t)i[n]||x(e,`unknown keyword: "${n}"`)}e.checkUnknownRules=a;function o(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(t[n])return!0;return!1}e.schemaHasRules=o;function s(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(n!==`$ref`&&t.all[n])return!0;return!1}e.schemaHasRulesButRef=s;function c({topSchemaRef:e,schemaPath:n},r,i,a){if(!a){if(typeof r==`number`||typeof r==`boolean`)return r;if(typeof r==`string`)return(0,t._)`${r}`}return(0,t._)`${e}${n}${(0,t.getProperty)(i)}`}e.schemaRefOrVal=c;function l(e){return f(decodeURIComponent(e))}e.unescapeFragment=l;function u(e){return encodeURIComponent(d(e))}e.escapeFragment=u;function d(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=d;function f(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=f;function p(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}e.eachItem=p;function m({mergeNames:e,mergeToName:n,mergeValues:r,resultToName:i}){return(a,o,s,c)=>{let l=s===void 0?o:s instanceof t.Name?(o instanceof t.Name?e(a,o,s):n(a,o,s),s):o instanceof t.Name?(n(a,s,o),o):r(o,s);return c===t.Name&&!(l instanceof t.Name)?i(a,l):l}}e.mergeEvaluated={props:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>{e.if((0,t._)`${n} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,t._)`${r} || {}`).code((0,t._)`Object.assign(${r}, ${n})`))}),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>{n===!0?e.assign(r,!0):(e.assign(r,(0,t._)`${r} || {}`),g(e,r,n))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:h}),items:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>e.assign(r,(0,t._)`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>e.assign(r,n===!0?!0:(0,t._)`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function h(e,n){if(n===!0)return e.var(`props`,!0);let r=e.var(`props`,(0,t._)`{}`);return n!==void 0&&g(e,r,n),r}e.evaluatedPropsToName=h;function g(e,n,r){Object.keys(r).forEach(r=>e.assign((0,t._)`${n}${(0,t.getProperty)(r)}`,!0))}e.setEvaluated=g;let _={};function v(e,t){return e.scopeValue(`func`,{ref:t,code:_[t.code]||(_[t.code]=new n._Code(t.code))})}e.useFunc=v;var y;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(y||(e.Type=y={}));function b(e,n,r){if(e instanceof t.Name){let i=n===y.Num;return r?i?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:i?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,t.getProperty)(e).toString():`/`+d(e)}e.getErrorPath=b;function x(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=x})),yd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z();e.default={data:new t.Name(`data`),valCxt:new t.Name(`valCxt`),instancePath:new t.Name(`instancePath`),parentData:new t.Name(`parentData`),parentDataProperty:new t.Name(`parentDataProperty`),rootData:new t.Name(`rootData`),dynamicAnchors:new t.Name(`dynamicAnchors`),vErrors:new t.Name(`vErrors`),errors:new t.Name(`errors`),this:new t.Name(`this`),self:new t.Name(`self`),scope:new t.Name(`scope`),json:new t.Name(`json`),jsonPos:new t.Name(`jsonPos`),jsonLen:new t.Name(`jsonLen`),jsonPart:new t.Name(`jsonPart`)}})),bd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=Z(),n=Q(),r=yd();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?(0,t.str)`"${e}" keyword must be ${n} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function i(n,r=e.keywordError,i,a){let{it:o}=n,{gen:s,compositeRule:u,allErrors:f}=o,p=d(n,r,i);a??(u||f)?c(s,p):l(o,(0,t._)`[${p}]`)}e.reportError=i;function a(t,n=e.keywordError,i){let{it:a}=t,{gen:o,compositeRule:s,allErrors:u}=a;c(o,d(t,n,i)),s||u||l(a,r.default.vErrors)}e.reportExtraError=a;function o(e,n){e.assign(r.default.errors,n),e.if((0,t._)`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign((0,t._)`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))}e.resetErrorsCount=o;function s({gen:e,keyword:n,schemaValue:i,data:a,errsCount:o,it:s}){if(o===void 0)throw Error(`ajv implementation error`);let c=e.name(`err`);e.forRange(`i`,o,r.default.errors,o=>{e.const(c,(0,t._)`${r.default.vErrors}[${o}]`),e.if((0,t._)`${c}.instancePath === undefined`,()=>e.assign((0,t._)`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,s.errorPath))),e.assign((0,t._)`${c}.schemaPath`,(0,t.str)`${s.errSchemaPath}/${n}`),s.opts.verbose&&(e.assign((0,t._)`${c}.schema`,i),e.assign((0,t._)`${c}.data`,a))})}e.extendErrors=s;function c(e,n){let i=e.const(`err`,n);e.if((0,t._)`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,(0,t._)`[${i}]`),(0,t._)`${r.default.vErrors}.push(${i})`),e.code((0,t._)`${r.default.errors}++`)}function l(e,n){let{gen:r,validateName:i,schemaEnv:a}=e;a.$async?r.throw((0,t._)`new ${e.ValidationError}(${n})`):(r.assign((0,t._)`${i}.errors`,n),r.return(!1))}let u={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function d(e,n,r){let{createErrors:i}=e.it;return i===!1?(0,t._)`{}`:f(e,n,r)}function f(e,t,n={}){let{gen:r,it:i}=e,a=[p(i,n),m(e,n)];return h(e,t,a),r.object(...a)}function p({errorPath:e},{instancePath:i}){let a=i?(0,t.str)`${e}${(0,n.getErrorPath)(i,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function m({keyword:e,it:{errSchemaPath:r}},{schemaPath:i,parentSchema:a}){let o=a?r:(0,t.str)`${r}/${e}`;return i&&(o=(0,t.str)`${o}${(0,n.getErrorPath)(i,n.Type.Str)}`),[u.schemaPath,o]}function h(e,{params:n,message:i},a){let{keyword:o,data:s,schemaValue:c,it:l}=e,{opts:d,propertyName:f,topSchemaRef:p,schemaPath:m}=l;a.push([u.keyword,o],[u.params,typeof n==`function`?n(e):n||(0,t._)`{}`]),d.messages&&a.push([u.message,typeof i==`function`?i(e):i]),d.verbose&&a.push([u.schema,c],[u.parentSchema,(0,t._)`${p}${m}`],[r.default.data,s]),f&&a.push([u.propertyName,f])}})),xd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=bd(),n=Z(),r=yd(),i={message:`boolean schema is false`};function a(e){let{gen:t,schema:i,validateName:a}=e;i===!1?s(e,!1):typeof i==`object`&&i.$async===!0?t.return(r.default.data):(t.assign((0,n._)`${a}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=a;function o(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),s(e)):n.var(t,!0)}e.boolOrEmptySchema=o;function s(e,n){let{gen:r,data:a}=e,o={gen:r,keyword:`false schema`,data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(o,i,void 0,n)}})),Sd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getRules=e.isJSONType=void 0;let t=new Set([`string`,`number`,`integer`,`boolean`,`null`,`object`,`array`]);function n(e){return typeof e==`string`&&t.has(e)}e.isJSONType=n;function r(){let e={number:{type:`number`,rules:[]},string:{type:`string`,rules:[]},array:{type:`array`,rules:[]},object:{type:`object`,rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=r})),Cd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&n(e,i)}e.schemaHasRulesForType=t;function n(e,t){return t.rules.some(t=>r(e,t))}e.shouldUseGroup=n;function r(e,t){return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=r})),wd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;let t=Sd(),n=Cd(),r=bd(),i=Z(),a=Q();var o;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(o||(e.DataType=o={}));function s(e){let t=c(e.type);if(t.includes(`null`)){if(e.nullable===!1)throw Error(`type: null contradicts nullable: false`)}else{if(!t.length&&e.nullable!==void 0)throw Error(`"nullable" cannot be used without "type"`);e.nullable===!0&&t.push(`null`)}return t}e.getSchemaTypes=s;function c(e){let n=Array.isArray(e)?e:e?[e]:[];if(n.every(t.isJSONType))return n;throw Error(`type must be JSONType or JSONType[]: `+n.join(`,`))}e.getJSONTypes=c;function l(e,t){let{gen:r,data:i,opts:a}=e,s=d(t,a.coerceTypes),c=t.length>0&&!(s.length===0&&t.length===1&&(0,n.schemaHasRulesForType)(e,t[0]));if(c){let n=h(t,i,a.strictNumbers,o.Wrong);r.if(n,()=>{s.length?f(e,t,s):_(e)})}return c}e.coerceAndCheckDataType=l;let u=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function d(e,t){return t?e.filter(e=>u.has(e)||t===`array`&&e===`array`):[]}function f(e,t,n){let{gen:r,data:a,opts:o}=e,s=r.let(`dataType`,(0,i._)`typeof ${a}`),c=r.let(`coerced`,(0,i._)`undefined`);o.coerceTypes===`array`&&r.if((0,i._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,(0,i._)`${a}[0]`).assign(s,(0,i._)`typeof ${a}`).if(h(t,a,o.strictNumbers),()=>r.assign(c,a))),r.if((0,i._)`${c} !== undefined`);for(let e of n)(u.has(e)||e===`array`&&o.coerceTypes===`array`)&&l(e);r.else(),_(e),r.endIf(),r.if((0,i._)`${c} !== undefined`,()=>{r.assign(a,c),p(e,c)});function l(e){switch(e){case`string`:r.elseIf((0,i._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,i._)`"" + ${a}`).elseIf((0,i._)`${a} === null`).assign(c,(0,i._)`""`);return;case`number`:r.elseIf((0,i._)`${s} == "boolean" || ${a} === null
|
|
129
|
+
`:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new b(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new x(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new x(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new C;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(C)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new w;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new T(e),t(e)}return n&&(this._currNode=r.finally=new E,this.code(n)),this._endBlockNode(T,E)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new S(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function D(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function O(e,n){return n instanceof t._CodeOrName?D(e,n.names):e}function k(e,n,r){if(e instanceof t.Name)return i(e);if(!a(e))return e;return new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[]));function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function A(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function j(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${ne(e)}`}e.not=j;let M=P(e.operators.AND);function ee(...e){return e.reduce(M)}e.and=ee;let N=P(e.operators.OR);function te(...e){return e.reduce(N)}e.or=te;function P(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${ne(n)} ${e} ${ne(r)}`}function ne(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),yd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;let t=Z(),n=_d();function r(e){let t={};for(let n of e)t[n]=!0;return t}e.toHash=r;function i(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0?!0:(a(e,t),!o(t,e.self.RULES.all))}e.alwaysValidSchema=i;function a(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t==`boolean`)return;let i=r.RULES.keywords;for(let n in t)i[n]||x(e,`unknown keyword: "${n}"`)}e.checkUnknownRules=a;function o(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(t[n])return!0;return!1}e.schemaHasRules=o;function s(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(n!==`$ref`&&t.all[n])return!0;return!1}e.schemaHasRulesButRef=s;function c({topSchemaRef:e,schemaPath:n},r,i,a){if(!a){if(typeof r==`number`||typeof r==`boolean`)return r;if(typeof r==`string`)return(0,t._)`${r}`}return(0,t._)`${e}${n}${(0,t.getProperty)(i)}`}e.schemaRefOrVal=c;function l(e){return f(decodeURIComponent(e))}e.unescapeFragment=l;function u(e){return encodeURIComponent(d(e))}e.escapeFragment=u;function d(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=d;function f(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=f;function p(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}e.eachItem=p;function m({mergeNames:e,mergeToName:n,mergeValues:r,resultToName:i}){return(a,o,s,c)=>{let l=s===void 0?o:s instanceof t.Name?(o instanceof t.Name?e(a,o,s):n(a,o,s),s):o instanceof t.Name?(n(a,s,o),o):r(o,s);return c===t.Name&&!(l instanceof t.Name)?i(a,l):l}}e.mergeEvaluated={props:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>{e.if((0,t._)`${n} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,t._)`${r} || {}`).code((0,t._)`Object.assign(${r}, ${n})`))}),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>{n===!0?e.assign(r,!0):(e.assign(r,(0,t._)`${r} || {}`),g(e,r,n))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:h}),items:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>e.assign(r,(0,t._)`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>e.assign(r,n===!0?!0:(0,t._)`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function h(e,n){if(n===!0)return e.var(`props`,!0);let r=e.var(`props`,(0,t._)`{}`);return n!==void 0&&g(e,r,n),r}e.evaluatedPropsToName=h;function g(e,n,r){Object.keys(r).forEach(r=>e.assign((0,t._)`${n}${(0,t.getProperty)(r)}`,!0))}e.setEvaluated=g;let _={};function v(e,t){return e.scopeValue(`func`,{ref:t,code:_[t.code]||(_[t.code]=new n._Code(t.code))})}e.useFunc=v;var y;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(y||(e.Type=y={}));function b(e,n,r){if(e instanceof t.Name){let i=n===y.Num;return r?i?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:i?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,t.getProperty)(e).toString():`/`+d(e)}e.getErrorPath=b;function x(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=x})),bd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z();e.default={data:new t.Name(`data`),valCxt:new t.Name(`valCxt`),instancePath:new t.Name(`instancePath`),parentData:new t.Name(`parentData`),parentDataProperty:new t.Name(`parentDataProperty`),rootData:new t.Name(`rootData`),dynamicAnchors:new t.Name(`dynamicAnchors`),vErrors:new t.Name(`vErrors`),errors:new t.Name(`errors`),this:new t.Name(`this`),self:new t.Name(`self`),scope:new t.Name(`scope`),json:new t.Name(`json`),jsonPos:new t.Name(`jsonPos`),jsonLen:new t.Name(`jsonLen`),jsonPart:new t.Name(`jsonPart`)}})),xd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=Z(),n=yd(),r=bd();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?(0,t.str)`"${e}" keyword must be ${n} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function i(n,r=e.keywordError,i,a){let{it:o}=n,{gen:s,compositeRule:u,allErrors:f}=o,p=d(n,r,i);a??(u||f)?c(s,p):l(o,(0,t._)`[${p}]`)}e.reportError=i;function a(t,n=e.keywordError,i){let{it:a}=t,{gen:o,compositeRule:s,allErrors:u}=a;c(o,d(t,n,i)),s||u||l(a,r.default.vErrors)}e.reportExtraError=a;function o(e,n){e.assign(r.default.errors,n),e.if((0,t._)`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign((0,t._)`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))}e.resetErrorsCount=o;function s({gen:e,keyword:n,schemaValue:i,data:a,errsCount:o,it:s}){if(o===void 0)throw Error(`ajv implementation error`);let c=e.name(`err`);e.forRange(`i`,o,r.default.errors,o=>{e.const(c,(0,t._)`${r.default.vErrors}[${o}]`),e.if((0,t._)`${c}.instancePath === undefined`,()=>e.assign((0,t._)`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,s.errorPath))),e.assign((0,t._)`${c}.schemaPath`,(0,t.str)`${s.errSchemaPath}/${n}`),s.opts.verbose&&(e.assign((0,t._)`${c}.schema`,i),e.assign((0,t._)`${c}.data`,a))})}e.extendErrors=s;function c(e,n){let i=e.const(`err`,n);e.if((0,t._)`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,(0,t._)`[${i}]`),(0,t._)`${r.default.vErrors}.push(${i})`),e.code((0,t._)`${r.default.errors}++`)}function l(e,n){let{gen:r,validateName:i,schemaEnv:a}=e;a.$async?r.throw((0,t._)`new ${e.ValidationError}(${n})`):(r.assign((0,t._)`${i}.errors`,n),r.return(!1))}let u={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function d(e,n,r){let{createErrors:i}=e.it;return i===!1?(0,t._)`{}`:f(e,n,r)}function f(e,t,n={}){let{gen:r,it:i}=e,a=[p(i,n),m(e,n)];return h(e,t,a),r.object(...a)}function p({errorPath:e},{instancePath:i}){let a=i?(0,t.str)`${e}${(0,n.getErrorPath)(i,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function m({keyword:e,it:{errSchemaPath:r}},{schemaPath:i,parentSchema:a}){let o=a?r:(0,t.str)`${r}/${e}`;return i&&(o=(0,t.str)`${o}${(0,n.getErrorPath)(i,n.Type.Str)}`),[u.schemaPath,o]}function h(e,{params:n,message:i},a){let{keyword:o,data:s,schemaValue:c,it:l}=e,{opts:d,propertyName:f,topSchemaRef:p,schemaPath:m}=l;a.push([u.keyword,o],[u.params,typeof n==`function`?n(e):n||(0,t._)`{}`]),d.messages&&a.push([u.message,typeof i==`function`?i(e):i]),d.verbose&&a.push([u.schema,c],[u.parentSchema,(0,t._)`${p}${m}`],[r.default.data,s]),f&&a.push([u.propertyName,f])}})),Sd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=xd(),n=Z(),r=bd(),i={message:`boolean schema is false`};function a(e){let{gen:t,schema:i,validateName:a}=e;i===!1?s(e,!1):typeof i==`object`&&i.$async===!0?t.return(r.default.data):(t.assign((0,n._)`${a}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=a;function o(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),s(e)):n.var(t,!0)}e.boolOrEmptySchema=o;function s(e,n){let{gen:r,data:a}=e,o={gen:r,keyword:`false schema`,data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(o,i,void 0,n)}})),Cd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getRules=e.isJSONType=void 0;let t=new Set([`string`,`number`,`integer`,`boolean`,`null`,`object`,`array`]);function n(e){return typeof e==`string`&&t.has(e)}e.isJSONType=n;function r(){let e={number:{type:`number`,rules:[]},string:{type:`string`,rules:[]},array:{type:`array`,rules:[]},object:{type:`object`,rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=r})),wd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&n(e,i)}e.schemaHasRulesForType=t;function n(e,t){return t.rules.some(t=>r(e,t))}e.shouldUseGroup=n;function r(e,t){return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=r})),Td=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;let t=Cd(),n=wd(),r=xd(),i=Z(),a=yd();var o;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(o||(e.DataType=o={}));function s(e){let t=c(e.type);if(t.includes(`null`)){if(e.nullable===!1)throw Error(`type: null contradicts nullable: false`)}else{if(!t.length&&e.nullable!==void 0)throw Error(`"nullable" cannot be used without "type"`);e.nullable===!0&&t.push(`null`)}return t}e.getSchemaTypes=s;function c(e){let n=Array.isArray(e)?e:e?[e]:[];if(n.every(t.isJSONType))return n;throw Error(`type must be JSONType or JSONType[]: `+n.join(`,`))}e.getJSONTypes=c;function l(e,t){let{gen:r,data:i,opts:a}=e,s=d(t,a.coerceTypes),c=t.length>0&&!(s.length===0&&t.length===1&&(0,n.schemaHasRulesForType)(e,t[0]));if(c){let n=h(t,i,a.strictNumbers,o.Wrong);r.if(n,()=>{s.length?f(e,t,s):_(e)})}return c}e.coerceAndCheckDataType=l;let u=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function d(e,t){return t?e.filter(e=>u.has(e)||t===`array`&&e===`array`):[]}function f(e,t,n){let{gen:r,data:a,opts:o}=e,s=r.let(`dataType`,(0,i._)`typeof ${a}`),c=r.let(`coerced`,(0,i._)`undefined`);o.coerceTypes===`array`&&r.if((0,i._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,(0,i._)`${a}[0]`).assign(s,(0,i._)`typeof ${a}`).if(h(t,a,o.strictNumbers),()=>r.assign(c,a))),r.if((0,i._)`${c} !== undefined`);for(let e of n)(u.has(e)||e===`array`&&o.coerceTypes===`array`)&&l(e);r.else(),_(e),r.endIf(),r.if((0,i._)`${c} !== undefined`,()=>{r.assign(a,c),p(e,c)});function l(e){switch(e){case`string`:r.elseIf((0,i._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,i._)`"" + ${a}`).elseIf((0,i._)`${a} === null`).assign(c,(0,i._)`""`);return;case`number`:r.elseIf((0,i._)`${s} == "boolean" || ${a} === null
|
|
130
130
|
|| (${s} == "string" && ${a} && ${a} == +${a})`).assign(c,(0,i._)`+${a}`);return;case`integer`:r.elseIf((0,i._)`${s} === "boolean" || ${a} === null
|
|
131
131
|
|| (${s} === "string" && ${a} && ${a} == +${a} && !(${a} % 1))`).assign(c,(0,i._)`+${a}`);return;case`boolean`:r.elseIf((0,i._)`${a} === "false" || ${a} === 0 || ${a} === null`).assign(c,!1).elseIf((0,i._)`${a} === "true" || ${a} === 1`).assign(c,!0);return;case`null`:r.elseIf((0,i._)`${a} === "" || ${a} === 0 || ${a} === false`),r.assign(c,null);return;case`array`:r.elseIf((0,i._)`${s} === "string" || ${s} === "number"
|
|
132
|
-
|| ${s} === "boolean" || ${a} === null`).assign(c,(0,i._)`[${a}]`)}}}function p({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,i._)`${t} !== undefined`,()=>e.assign((0,i._)`${t}[${n}]`,r))}function m(e,t,n,r=o.Correct){let a=r===o.Correct?i.operators.EQ:i.operators.NEQ,s;switch(e){case`null`:return(0,i._)`${t} ${a} null`;case`array`:s=(0,i._)`Array.isArray(${t})`;break;case`object`:s=(0,i._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case`integer`:s=c((0,i._)`!(${t} % 1) && !isNaN(${t})`);break;case`number`:s=c();break;default:return(0,i._)`typeof ${t} ${a} ${e}`}return r===o.Correct?s:(0,i.not)(s);function c(e=i.nil){return(0,i.and)((0,i._)`typeof ${t} == "number"`,e,n?(0,i._)`isFinite(${t})`:i.nil)}}e.checkDataType=m;function h(e,t,n,r){if(e.length===1)return m(e[0],t,n,r);let o,s=(0,a.toHash)(e);if(s.array&&s.object){let e=(0,i._)`typeof ${t} != "object"`;o=s.null?e:(0,i._)`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else o=i.nil;s.number&&delete s.integer;for(let e in s)o=(0,i.and)(o,m(e,t,n,r));return o}e.checkDataTypes=h;let g={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e==`string`?(0,i._)`{type: ${e}}`:(0,i._)`{type: ${t}}`};function _(e){let t=v(e);(0,r.reportError)(t,g)}e.reportTypeError=_;function v(e){let{gen:t,data:n,schema:r}=e,i=(0,a.schemaRefOrVal)(e,r,`type`);return{gen:t,keyword:`type`,data:n,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:e}}})),Td=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.assignDefaults=void 0;let t=Z(),n=Q();function r(e,t){let{properties:n,items:r}=e.schema;if(t===`object`&&n)for(let t in n)i(e,t,n[t].default);else t===`array`&&Array.isArray(r)&&r.forEach((t,n)=>i(e,n,t.default))}e.assignDefaults=r;function i(e,r,i){let{gen:a,compositeRule:o,data:s,opts:c}=e;if(i===void 0)return;let l=(0,t._)`${s}${(0,t.getProperty)(r)}`;if(o){(0,n.checkStrictMode)(e,`default is ignored for: ${l}`);return}let u=(0,t._)`${l} === undefined`;c.useDefaults===`empty`&&(u=(0,t._)`${u} || ${l} === null || ${l} === ""`),a.if(u,(0,t._)`${l} = ${(0,t.stringify)(i)}`)}})),Ed=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;let t=Z(),n=Q(),r=yd(),i=Q();function a(e,n){let{gen:r,data:i,it:a}=e;r.if(d(r,i,n,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,t._)`${n}`},!0),e.error()})}e.checkReportMissingProp=a;function o({gen:e,data:n,it:{opts:r}},i,a){return(0,t.or)(...i.map(i=>(0,t.and)(d(e,n,i,r.ownProperties),(0,t._)`${a} = ${i}`)))}e.checkMissingProp=o;function s(e,t){e.setParams({missingProperty:t},!0),e.error()}e.reportMissingProp=s;function c(e){return e.scopeValue(`func`,{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=c;function l(e,n,r){return(0,t._)`${c(e)}.call(${n}, ${r})`}e.isOwnProperty=l;function u(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} !== undefined`;return i?(0,t._)`${a} && ${l(e,n,r)}`:a}e.propertyInData=u;function d(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} === undefined`;return i?(0,t.or)(a,(0,t.not)(l(e,n,r))):a}e.noPropertyInData=d;function f(e){return e?Object.keys(e).filter(e=>e!==`__proto__`):[]}e.allSchemaProperties=f;function p(e,t){return f(t).filter(r=>!(0,n.alwaysValidSchema)(e,t[r]))}e.schemaProperties=p;function m({schemaCode:e,data:n,it:{gen:i,topSchemaRef:a,schemaPath:o,errorPath:s},it:c},l,u,d){let f=d?(0,t._)`${e}, ${n}, ${a}${o}`:n,p=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,s)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&p.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);let m=(0,t._)`${f}, ${i.object(...p)}`;return u===t.nil?(0,t._)`${l}(${m})`:(0,t._)`${l}.call(${u}, ${m})`}e.callValidateCode=m;let h=(0,t._)`new RegExp`;function g({gen:e,it:{opts:n}},r){let a=n.unicodeRegExp?`u`:``,{regExp:o}=n.code,s=o(r,a);return e.scopeValue(`pattern`,{key:s.toString(),ref:s,code:(0,t._)`${o.code===`new RegExp`?h:(0,i.useFunc)(e,o)}(${r}, ${a})`})}e.usePattern=g;function _(e){let{gen:r,data:i,keyword:a,it:o}=e,s=r.name(`valid`);if(o.allErrors){let e=r.let(`valid`,!0);return c(()=>r.assign(e,!1)),e}return r.var(s,!0),c(()=>r.break()),s;function c(o){let c=r.const(`len`,(0,t._)`${i}.length`);r.forRange(`i`,0,c,i=>{e.subschema({keyword:a,dataProp:i,dataPropType:n.Type.Num},s),r.if((0,t.not)(s),o)})}}e.validateArray=_;function v(e){let{gen:r,schema:i,keyword:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(i.some(e=>(0,n.alwaysValidSchema)(o,e))&&!o.opts.unevaluated)return;let s=r.let(`valid`,!1),c=r.name(`_valid`);r.block(()=>i.forEach((n,i)=>{let o=e.subschema({keyword:a,schemaProp:i,compositeRule:!0},c);r.assign(s,(0,t._)`${s} || ${c}`),e.mergeValidEvaluated(o,c)||r.if((0,t.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}e.validateUnion=v})),Dd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=Z(),n=yd(),r=Ed(),i=bd();function a(e,n){let{gen:r,keyword:i,schema:a,parentSchema:o,it:s}=e,c=n.macro.call(s.self,a,o,s),l=u(r,i,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let d=r.name(`valid`);e.subschema({schema:c,schemaPath:t.nil,errSchemaPath:`${s.errSchemaPath}/${i}`,topSchemaRef:l,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}e.macroKeywordCode=a;function o(e,i){let{gen:a,keyword:o,schema:d,parentSchema:f,$data:p,it:m}=e;l(m,i);let h=u(a,o,!p&&i.compile?i.compile.call(m.self,d,f,m):i.validate),g=a.let(`valid`);e.block$data(g,_),e.ok(i.valid??g);function _(){if(i.errors===!1)b(),i.modifying&&s(e),x(()=>e.error());else{let t=i.async?v():y();i.modifying&&s(e),x(()=>c(e,t))}}function v(){let e=a.let(`ruleErrs`,null);return a.try(()=>b((0,t._)`await `),n=>a.assign(g,!1).if((0,t._)`${n} instanceof ${m.ValidationError}`,()=>a.assign(e,(0,t._)`${n}.errors`),()=>a.throw(n))),e}function y(){let e=(0,t._)`${h}.errors`;return a.assign(e,null),b(t.nil),e}function b(o=i.async?(0,t._)`await `:t.nil){let s=m.opts.passContext?n.default.this:n.default.self,c=!(`compile`in i&&!p||i.schema===!1);a.assign(g,(0,t._)`${o}${(0,r.callValidateCode)(e,h,s,c)}`,i.modifying)}function x(e){a.if((0,t.not)(i.valid??g),e)}}e.funcKeywordCode=o;function s(e){let{gen:n,data:r,it:i}=e;n.if(i.parentData,()=>n.assign(r,(0,t._)`${i.parentData}[${i.parentDataProperty}]`))}function c(e,r){let{gen:a}=e;a.if((0,t._)`Array.isArray(${r})`,()=>{a.assign(n.default.vErrors,(0,t._)`${n.default.vErrors} === null ? ${r} : ${n.default.vErrors}.concat(${r})`).assign(n.default.errors,(0,t._)`${n.default.vErrors}.length`),(0,i.extendErrors)(e)},()=>e.error())}function l({schemaEnv:e},t){if(t.async&&!e.$async)throw Error(`async keyword in sync schema`)}function u(e,n,r){if(r===void 0)throw Error(`keyword "${n}" failed to compile`);return e.scopeValue(`keyword`,typeof r==`function`?{ref:r}:{ref:r,code:(0,t.stringify)(r)})}function d(e,t,n=!1){return!t.length||t.some(t=>t===`array`?Array.isArray(e):t===`object`?e&&typeof e==`object`&&!Array.isArray(e):typeof e==t||n&&e===void 0)}e.validSchemaType=d;function f({schema:e,opts:t,self:n,errSchemaPath:r},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw Error(`ajv implementation error`);let o=i.dependencies;if(o?.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${a}: ${o.join(`,`)}`);if(i.validateSchema&&!i.validateSchema(e[a])){let e=`keyword "${a}" value is invalid at path "${r}": `+n.errorsText(i.validateSchema.errors);if(t.validateSchema===`log`)n.logger.error(e);else throw Error(e)}}e.validateKeywordUsage=f})),Od=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=Z(),n=Q();function r(e,{keyword:r,schemaProp:i,schema:a,schemaPath:o,errSchemaPath:s,topSchemaRef:c}){if(r!==void 0&&a!==void 0)throw Error(`both "keyword" and "schema" passed, only one allowed`);if(r!==void 0){let a=e.schema[r];return i===void 0?{schema:a,schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${r}`}:{schema:a[i],schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}${(0,t.getProperty)(i)}`,errSchemaPath:`${e.errSchemaPath}/${r}/${(0,n.escapeFragment)(i)}`}}if(a!==void 0){if(o===void 0||s===void 0||c===void 0)throw Error(`"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"`);return{schema:a,schemaPath:o,topSchemaRef:c,errSchemaPath:s}}throw Error(`either "keyword" or "schema" must be passed`)}e.getSubschema=r;function i(e,r,{dataProp:i,dataPropType:a,data:o,dataTypes:s,propertyName:c}){if(o!==void 0&&i!==void 0)throw Error(`both "data" and "dataProp" passed, only one allowed`);let{gen:l}=r;if(i!==void 0){let{errorPath:o,dataPathArr:s,opts:c}=r;u(l.let(`data`,(0,t._)`${r.data}${(0,t.getProperty)(i)}`,!0)),e.errorPath=(0,t.str)`${o}${(0,n.getErrorPath)(i,a,c.jsPropertySyntax)}`,e.parentDataProperty=(0,t._)`${i}`,e.dataPathArr=[...s,e.parentDataProperty]}o!==void 0&&(u(o instanceof t.Name?o:l.let(`data`,o,!0)),c!==void 0&&(e.propertyName=c)),s&&(e.dataTypes=s);function u(t){e.data=t,e.dataLevel=r.dataLevel+1,e.dataTypes=[],r.definedProperties=new Set,e.parentData=r.data,e.dataNames=[...r.dataNames,t]}}e.extendSubschemaData=i;function a(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:i,allErrors:a}){r!==void 0&&(e.compositeRule=r),i!==void 0&&(e.createErrors=i),a!==void 0&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=n}e.extendSubschemaMode=a})),kd=o(((e,t)=>{t.exports=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t==`object`&&typeof n==`object`){if(t.constructor!==n.constructor)return!1;var r,i,a;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(i=r;i--!==0;)if(!e(t[i],n[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(a=Object.keys(t),r=a.length,r!==Object.keys(n).length)return!1;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(n,a[i]))return!1;for(i=r;i--!==0;){var o=a[i];if(!e(t[o],n[o]))return!1}return!0}return t!==t&&n!==n}})),Ad=o(((e,t)=>{var n=t.exports=function(e,t,n){typeof t==`function`&&(n=t,t={}),n=t.cb||n;var i=typeof n==`function`?n:n.pre||function(){},a=n.post||function(){};r(t,i,a,e,``,e)};n.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},n.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},n.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},n.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function r(e,t,a,o,s,c,l,u,d,f){if(o&&typeof o==`object`&&!Array.isArray(o)){for(var p in t(o,s,c,l,u,d,f),o){var m=o[p];if(Array.isArray(m)){if(p in n.arrayKeywords)for(var h=0;h<m.length;h++)r(e,t,a,m[h],s+`/`+p+`/`+h,c,s,p,o,h)}else if(p in n.propsKeywords){if(m&&typeof m==`object`)for(var g in m)r(e,t,a,m[g],s+`/`+p+`/`+i(g),c,s,p,o,g)}else (p in n.keywords||e.allKeys&&!(p in n.skipKeywords))&&r(e,t,a,m,s+`/`+p,c,s,p,o)}a(o,s,c,l,u,d,f)}}function i(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}})),jd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=Q(),n=kd(),r=Ad(),i=new Set([`type`,`format`,`pattern`,`maxLength`,`minLength`,`maxProperties`,`minProperties`,`maxItems`,`minItems`,`maximum`,`minimum`,`uniqueItems`,`multipleOf`,`required`,`enum`,`const`]);function a(e,t=!0){return typeof e==`boolean`?!0:t===!0?!s(e):t?c(e)<=t:!1}e.inlineRef=a;let o=new Set([`$ref`,`$recursiveRef`,`$recursiveAnchor`,`$dynamicRef`,`$dynamicAnchor`]);function s(e){for(let t in e){if(o.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(s)||typeof n==`object`&&s(n))return!0}return!1}function c(e){let n=0;for(let r in e)if(r===`$ref`||(n++,!i.has(r)&&(typeof e[r]==`object`&&(0,t.eachItem)(e[r],e=>n+=c(e)),n===1/0)))return 1/0;return n}function l(e,t=``,n){return n!==!1&&(t=f(t)),u(e,e.parse(t))}e.getFullPath=l;function u(e,t){return e.serialize(t).split(`#`)[0]+`#`}e._getFullPath=u;let d=/#\/?$/;function f(e){return e?e.replace(d,``):``}e.normalizeId=f;function p(e,t,n){return n=f(n),e.resolve(t,n)}e.resolveUrl=p;let m=/^[a-z_][-a-z0-9._]*$/i;function h(e,t){if(typeof e==`boolean`)return{};let{schemaId:i,uriResolver:a}=this.opts,o=f(e[i]||t),s={"":o},c=l(a,o,!1),u={},d=new Set;return r(e,{allKeys:!0},(e,t,n,r)=>{if(r===void 0)return;let a=c+t,o=s[r];typeof e[i]==`string`&&(o=l.call(this,e[i])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),s[t]=o;function l(t){let n=this.opts.uriResolver.resolve;if(t=f(o?n(o,t):t),d.has(t))throw h(t);d.add(t);let r=this.refs[t];return typeof r==`string`&&(r=this.refs[r]),typeof r==`object`?p(e,r.schema,t):t!==f(a)&&(t[0]===`#`?(p(e,u[t],t),u[t]=e):this.refs[t]=a),t}function g(e){if(typeof e==`string`){if(!m.test(e))throw Error(`invalid anchor "${e}"`);l.call(this,`#${e}`)}}}),u;function p(e,t,r){if(t!==void 0&&!n(e,t))throw h(r)}function h(e){return Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=h})),Md=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=xd(),n=wd(),r=Cd(),i=wd(),a=Td(),o=Dd(),s=Od(),c=Z(),l=yd(),u=jd(),d=Q(),f=bd();function p(e){if(S(e)&&(w(e),x(e))){_(e);return}m(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=p;function m({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},a){i.code.es5?e.func(t,(0,c._)`${l.default.data}, ${l.default.valCxt}`,r.$async,()=>{e.code((0,c._)`"use strict"; ${y(n,i)}`),g(e,i),e.code(a)}):e.func(t,(0,c._)`${l.default.data}, ${h(i)}`,r.$async,()=>e.code(y(n,i)).code(a))}function h(e){return(0,c._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${e.dynamicRef?(0,c._)`, ${l.default.dynamicAnchors}={}`:c.nil}}={}`}function g(e,t){e.if(l.default.valCxt,()=>{e.var(l.default.instancePath,(0,c._)`${l.default.valCxt}.${l.default.instancePath}`),e.var(l.default.parentData,(0,c._)`${l.default.valCxt}.${l.default.parentData}`),e.var(l.default.parentDataProperty,(0,c._)`${l.default.valCxt}.${l.default.parentDataProperty}`),e.var(l.default.rootData,(0,c._)`${l.default.valCxt}.${l.default.rootData}`),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{e.var(l.default.instancePath,(0,c._)`""`),e.var(l.default.parentData,(0,c._)`undefined`),e.var(l.default.parentDataProperty,(0,c._)`undefined`),e.var(l.default.rootData,l.default.data),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`{}`)})}function _(e){let{schema:t,opts:n,gen:r}=e;m(e,()=>{n.$comment&&t.$comment&&A(e),D(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),T(e),j(e)})}function v(e){let{gen:t,validateName:n}=e;e.evaluated=t.const(`evaluated`,(0,c._)`${n}.evaluated`),t.if((0,c._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,c._)`${e.evaluated}.props`,(0,c._)`undefined`)),t.if((0,c._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,c._)`${e.evaluated}.items`,(0,c._)`undefined`))}function y(e,t){let n=typeof e==`object`&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,c._)`/*# sourceURL=${n} */`:c.nil}function b(e,n){if(S(e)&&(w(e),x(e))){C(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function x({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function S(e){return typeof e.schema!=`boolean`}function C(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&A(e),O(e),k(e);let a=r.const(`_errs`,l.default.errors);T(e,a),r.var(t,(0,c._)`${a} === ${l.default.errors}`)}function w(e){(0,d.checkUnknownRules)(e),E(e)}function T(e,t){if(e.opts.jtd)return ee(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);ee(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function E(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function D(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,d.checkStrictMode)(e,`default is ignored in the schema root`)}function O(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function k(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function A({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let a=n.$comment;if(i.$comment===!0)e.code((0,c._)`${l.default.self}.logger.log(${a})`);else if(typeof i.$comment==`function`){let n=(0,c.str)`${r}/$comment`,i=e.scopeValue(`root`,{ref:t.root});e.code((0,c._)`${l.default.self}.opts.$comment(${a}, ${n}, ${i}.schema)`)}}function j(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:a}=e;n.$async?t.if((0,c._)`${l.default.errors} === 0`,()=>t.return(l.default.data),()=>t.throw((0,c._)`new ${i}(${l.default.vErrors})`)):(t.assign((0,c._)`${r}.errors`,l.default.vErrors),a.unevaluated&&M(e),t.return((0,c._)`${l.default.errors} === 0`))}function M({gen:e,evaluated:t,props:n,items:r}){n instanceof c.Name&&e.assign((0,c._)`${t}.props`,n),r instanceof c.Name&&e.assign((0,c._)`${t}.items`,r)}function ee(e,t,n,a){let{gen:o,schema:s,data:u,allErrors:f,opts:p,self:m}=e,{RULES:h}=m;if(s.$ref&&(p.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(s,h))){o.block(()=>R(e,`$ref`,h.all.$ref.definition));return}p.jtd||te(e,t),o.block(()=>{for(let e of h.rules)g(e);g(h.post)});function g(d){(0,r.shouldUseGroup)(s,d)&&(d.type?(o.if((0,i.checkDataType)(d.type,u,p.strictNumbers)),N(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):N(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function N(e,t){let{gen:n,schema:i,opts:{useDefaults:o}}=e;o&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(let n of t.rules)(0,r.shouldUseRule)(i,n)&&R(e,n.keyword,n.definition,t.type)})}function te(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(P(e,t),e.opts.allowUnionTypes||ne(e,t),F(e,e.dataTypes))}function P(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{re(e.dataTypes,t)||ie(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),L(e,t)}}function ne(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&ie(e,`use allowUnionTypes to allow union type keyword`)}function F(e,t){let n=e.self.RULES.all;for(let i in n){let a=n[i];if(typeof a==`object`&&(0,r.shouldUseRule)(e.schema,a)){let{type:n}=a.definition;n.length&&!n.some(e=>I(t,e))&&ie(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function I(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function re(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function L(e,t){let n=[];for(let r of e.dataTypes)re(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function ie(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var ae=class{constructor(e,t,n){if((0,o.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,ce(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,l.default.errors))}result(e,t,n){this.failResult((0,c.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,c.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,c._)`${t} !== undefined && (${(0,c.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?f.reportExtraError:f.reportError)(this,this.def.error,t)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=c.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=c.nil,t=c.nil){if(!this.$data)return;let{gen:n,schemaCode:r,schemaType:i,def:a}=this;n.if((0,c.or)((0,c._)`${r} === undefined`,t)),e!==c.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==c.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:r,it:a}=this;return(0,c.or)(o(),s());function o(){if(n.length){if(!(t instanceof c.Name))throw Error(`ajv implementation error`);let e=Array.isArray(n)?n:[n];return(0,c._)`${(0,i.checkDataTypes)(e,t,a.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function s(){if(r.validateSchema){let n=e.scopeValue(`validate$data`,{ref:r.validateSchema});return(0,c._)`!${n}(${t})`}return c.nil}}subschema(e,t){let n=(0,s.getSubschema)(this.it,e);(0,s.extendSubschemaData)(n,this.it,e),(0,s.extendSubschemaMode)(n,e);let r={...this.it,...n,items:void 0,props:void 0};return b(r,t),r}mergeEvaluated(e,t){let{it:n,gen:r}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=d.mergeEvaluated.props(r,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=d.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:r}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return r.if(t,()=>this.mergeEvaluated(e,c.Name)),!0}};e.KeywordCxt=ae;function R(e,t,n,r){let i=new ae(e,n,t);`code`in n?n.code(i,r):i.$data&&n.validate?(0,o.funcKeywordCode)(i,n):`macro`in n?(0,o.macroKeywordCode)(i,n):(n.compile||n.validate)&&(0,o.funcKeywordCode)(i,n)}let oe=/^\/(?:[^~]|~0|~1)*$/,se=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ce(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!oe.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=se.exec(e);if(!o)throw Error(`Invalid JSON-pointer: ${e}`);let s=+o[1];if(i=o[2],i===`#`){if(s>=t)throw Error(u(`property/index`,s));return r[t-s]}if(s>t)throw Error(u(`data`,s));if(a=n[t-s],!i)return a}let o=a,s=i.split(`/`);for(let e of s)e&&(a=(0,c._)`${a}${(0,c.getProperty)((0,d.unescapeJsonPointer)(e))}`,o=(0,c._)`${o} && ${a}`);return o;function u(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}e.getData=ce})),Nd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=class extends Error{constructor(e){super(`validation failed`),this.errors=e,this.ajv=this.validation=!0}}})),Pd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=jd();e.default=class extends Error{constructor(e,n,r,i){super(i||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,t.resolveUrl)(e,n,r),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(e,this.missingRef))}}})),Fd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=Z(),n=Nd(),r=yd(),i=jd(),a=Q(),o=Md();var s=class{constructor(e){this.refs={},this.dynamicAnchors={};let t;typeof e.schema==`object`&&(t=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=e.baseId??(0,i.normalizeId)(t?.[e.schemaId||`$id`]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=t?.$async,this.refs={}}};e.SchemaEnv=s;function c(e){let a=d.call(this,e);if(a)return a;let s=(0,i.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:c,lines:l}=this.opts.code,{ownProperties:u}=this.opts,f=new t.CodeGen(this.scope,{es5:c,lines:l,ownProperties:u}),p;e.$async&&(p=f.scopeValue(`Error`,{ref:n.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let m=f.scopeName(`validate`);e.validateName=m;let h={gen:f,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:f.scopeValue(`schema`,this.opts.code.source===!0?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:m,ValidationError:p,schema:e.schema,schemaEnv:e,rootId:s,baseId:e.baseId||s,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?``:`#`),errorPath:(0,t._)`""`,opts:this.opts,self:this},g;try{this._compilations.add(e),(0,o.validateFunctionCode)(h),f.optimize(this.opts.code.optimize);let n=f.toString();g=`${f.scopeRefs(r.default.scope)}return ${n}`,this.opts.code.process&&(g=this.opts.code.process(g,e));let i=Function(`${r.default.self}`,`${r.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:i}),i.errors=null,i.schema=e.schema,i.schemaEnv=e,e.$async&&(i.$async=!0),this.opts.code.source===!0&&(i.source={validateName:m,validateCode:n,scopeValues:f._values}),this.opts.unevaluated){let{props:e,items:n}=h;i.evaluated={props:e instanceof t.Name?void 0:e,items:n instanceof t.Name?void 0:n,dynamicProps:e instanceof t.Name,dynamicItems:n instanceof t.Name},i.source&&(i.source.evaluated=(0,t.stringify)(i.evaluated))}return e.validate=i,e}catch(t){throw delete e.validate,delete e.validateName,g&&this.logger.error(`Error compiling schema, function code:`,g),t}finally{this._compilations.delete(e)}}e.compileSchema=c;function l(e,t,n){n=(0,i.resolveUrl)(this.opts.uriResolver,t,n);let r=e.refs[n];if(r)return r;let a=p.call(this,e,n);if(a===void 0){let r=e.localRefs?.[n],{schemaId:i}=this.opts;r&&(a=new s({schema:r,schemaId:i,root:e,baseId:t}))}if(a!==void 0)return e.refs[n]=u.call(this,a)}e.resolveRef=l;function u(e){return(0,i.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:c.call(this,e)}function d(e){for(let t of this._compilations)if(f(t,e))return t}e.getCompilingSchema=d;function f(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function p(e,t){let n;for(;typeof(n=this.refs[t])==`string`;)t=n;return n||this.schemas[t]||m.call(this,e,t)}function m(e,t){let n=this.opts.uriResolver.parse(t),r=(0,i._getFullPath)(this.opts.uriResolver,n),a=(0,i.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===a)return g.call(this,n,e);let o=(0,i.normalizeId)(r),l=this.refs[o]||this.schemas[o];if(typeof l==`string`){let t=m.call(this,e,l);return typeof t?.schema==`object`?g.call(this,n,t):void 0}if(typeof l?.schema==`object`){if(l.validate||c.call(this,l),o===(0,i.normalizeId)(t)){let{schema:t}=l,{schemaId:n}=this.opts,r=t[n];return r&&(a=(0,i.resolveUrl)(this.opts.uriResolver,a,r)),new s({schema:t,schemaId:n,root:e,baseId:a})}return g.call(this,n,l)}}e.resolveSchema=m;let h=new Set([`properties`,`patternProperties`,`enum`,`dependencies`,`definitions`]);function g(e,{baseId:t,schema:n,root:r}){if(e.fragment?.[0]!==`/`)return;for(let r of e.fragment.slice(1).split(`/`)){if(typeof n==`boolean`)return;let e=n[(0,a.unescapeFragment)(r)];if(e===void 0)return;n=e;let o=typeof n==`object`&&n[this.opts.schemaId];!h.has(r)&&o&&(t=(0,i.resolveUrl)(this.opts.uriResolver,t,o))}let o;if(typeof n!=`boolean`&&n.$ref&&!(0,a.schemaHasRulesButRef)(n,this.RULES)){let e=(0,i.resolveUrl)(this.opts.uriResolver,t,n.$ref);o=m.call(this,r,e)}let{schemaId:c}=this.opts;if(o||=new s({schema:n,schemaId:c,root:r,baseId:t}),o.schema!==o.root.schema)return o}})),Id=o(((e,t)=>{t.exports={$id:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`,description:`Meta-schema for $data reference (JSON AnySchema extension proposal)`,type:`object`,required:[`$data`],properties:{$data:{type:`string`,anyOf:[{format:`relative-json-pointer`},{format:`json-pointer`}]}},additionalProperties:!1}})),Ld=o(((e,t)=>{let n=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function i(e){let t=``,n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r]}return t}let a=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function o(e){return e.length=0,!0}function s(e,t,n){if(e.length){let r=i(e);if(r!==``)t.push(r);else return n.error=!0,!1;e.length=0}return!0}function c(e){let t=0,n={error:!1,address:``,zone:``},r=[],a=[],c=!1,l=!1,u=s;for(let i=0;i<e.length;i++){let s=e[i];if(!(s===`[`||s===`]`))if(s===`:`){if(c===!0&&(l=!0),!u(a,r,n))break;if(++t>7){n.error=!0;break}i>0&&e[i-1]===`:`&&(c=!0),r.push(`:`);continue}else if(s===`%`){if(!u(a,r,n))break;u=o}else{a.push(s);continue}}return a.length&&(u===o?n.zone=a.join(``):l?r.push(a.join(``)):r.push(i(a))),n.address=r.join(``),n}function l(e){if(u(e,`:`)<2)return{host:e,isIPV6:!1};let t=c(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,n=t.address;return t.zone&&(e+=`%`+t.zone,n+=`%25`+t.zone),{host:e,isIPV6:!0,escapedHost:n}}}function u(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function d(e){let t=e,n=[],r=-1,i=0;for(;i=t.length;){if(i===1){if(t===`.`)break;if(t===`/`){n.push(`/`);break}else{n.push(t);break}}else if(i===2){if(t[0]===`.`){if(t[1]===`.`)break;if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&(t[1]===`.`||t[1]===`/`)){n.push(`/`);break}}else if(i===3&&t===`/..`){n.length!==0&&n.pop(),n.push(`/`);break}if(t[0]===`.`){if(t[1]===`.`){if(t[2]===`/`){t=t.slice(3);continue}}else if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&t[1]===`.`){if(t[2]===`/`){t=t.slice(2);continue}else if(t[2]===`.`&&t[3]===`/`){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf(`/`,1))===-1){n.push(t);break}else n.push(t.slice(0,r)),t=t.slice(r)}return n.join(``)}function f(e,t){let n=t===!0?unescape:escape;return e.scheme!==void 0&&(e.scheme=n(e.scheme)),e.userinfo!==void 0&&(e.userinfo=n(e.userinfo)),e.host!==void 0&&(e.host=n(e.host)),e.path!==void 0&&(e.path=n(e.path)),e.query!==void 0&&(e.query=n(e.query)),e.fragment!==void 0&&(e.fragment=n(e.fragment)),e}function p(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push(`@`)),e.host!==void 0){let n=unescape(e.host);if(!r(n)){let t=l(n);n=t.isIPV6===!0?`[${t.escapedHost}]`:e.host}t.push(n)}return(typeof e.port==`number`||typeof e.port==`string`)&&(t.push(`:`),t.push(String(e.port))),t.length?t.join(``):void 0}t.exports={nonSimpleDomain:a,recomposeAuthority:p,normalizeComponentEncoding:f,removeDotSegments:d,isIPv4:r,isUUID:n,normalizeIPv6:l,stringArrayToHexStripped:i}})),Rd=o(((e,t)=>{let{isUUID:n}=Ld(),r=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,i=[`http`,`https`,`ws`,`wss`,`urn`,`urn:uuid`];function a(e){return i.indexOf(e)!==-1}function o(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]===`w`||e.scheme[0]===`W`)&&(e.scheme[1]===`s`||e.scheme[1]===`S`)&&(e.scheme[2]===`s`||e.scheme[2]===`S`):!1}function s(e){return e.host||(e.error=e.error||`HTTP URIs must have a host.`),e}function c(e){let t=String(e.scheme).toLowerCase()===`https`;return(e.port===(t?443:80)||e.port===``)&&(e.port=void 0),e.path||=`/`,e}function l(e){return e.secure=o(e),e.resourceName=(e.path||`/`)+(e.query?`?`+e.query:``),e.path=void 0,e.query=void 0,e}function u(e){if((e.port===(o(e)?443:80)||e.port===``)&&(e.port=void 0),typeof e.secure==`boolean`&&(e.scheme=e.secure?`wss`:`ws`,e.secure=void 0),e.resourceName){let[t,n]=e.resourceName.split(`?`);e.path=t&&t!==`/`?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}function d(e,t){if(!e.path)return e.error=`URN can not be parsed`,e;let n=e.path.match(r);if(n){let r=t.scheme||e.scheme||`urn`;e.nid=n[1].toLowerCase(),e.nss=n[2];let i=S(`${r}:${t.nid||e.nid}`);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||`URN can not be parsed.`;return e}function f(e,t){if(e.nid===void 0)throw Error(`URN without nid cannot be serialized`);let n=t.scheme||e.scheme||`urn`,r=e.nid.toLowerCase(),i=S(`${n}:${t.nid||r}`);i&&(e=i.serialize(e,t));let a=e,o=e.nss;return a.path=`${r||t.nid}:${o}`,t.skipEscape=!0,a}function p(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!n(r.uuid))&&(r.error=r.error||`UUID is not valid.`),r}function m(e){let t=e;return t.nss=(e.uuid||``).toLowerCase(),t}let h={scheme:`http`,domainHost:!0,parse:s,serialize:c},g={scheme:`https`,domainHost:h.domainHost,parse:s,serialize:c},_={scheme:`ws`,domainHost:!0,parse:l,serialize:u},v={scheme:`wss`,domainHost:_.domainHost,parse:_.parse,serialize:_.serialize},y={scheme:`urn`,parse:d,serialize:f,skipNormalize:!0},b={scheme:`urn:uuid`,parse:p,serialize:m,skipNormalize:!0},x={http:h,https:g,ws:_,wss:v,urn:y,"urn:uuid":b};Object.setPrototypeOf(x,null);function S(e){return e&&(x[e]||x[e.toLowerCase()])||void 0}t.exports={wsIsSecure:o,SCHEMES:x,isValidSchemeName:a,getSchemeHandler:S}})),zd=o(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizeComponentEncoding:a,isIPv4:o,nonSimpleDomain:s}=Ld(),{SCHEMES:c,getSchemeHandler:l}=Rd();function u(e,t){return typeof e==`string`?e=m(g(e,t),t):typeof e==`object`&&(e=g(m(e,t),t)),e}function d(e,t,n){let r=n?Object.assign({scheme:`null`},n):{scheme:`null`},i=f(g(e,r),g(t,r),r,!0);return r.skipEscape=!0,m(i,r)}function f(e,t,n,i){let a={};return i||(e=g(m(e,n),n),t=g(m(t,n),n)),n||={},!n.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.path?(t.path[0]===`/`?a.path=r(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?a.path=`/`+t.path:e.path?a.path=e.path.slice(0,e.path.lastIndexOf(`/`)+1)+t.path:a.path=t.path,a.path=r(a.path)),a.query=t.query):(a.path=e.path,t.query===void 0?a.query=e.query:a.query=t.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function p(e,t,n){return typeof e==`string`?(e=unescape(e),e=m(a(g(e,n),!0),{...n,skipEscape:!0})):typeof e==`object`&&(e=m(a(e,!0),{...n,skipEscape:!0})),typeof t==`string`?(t=unescape(t),t=m(a(g(t,n),!0),{...n,skipEscape:!0})):typeof t==`object`&&(t=m(a(t,!0),{...n,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}function m(e,t){let n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:``},a=Object.assign({},t),o=[],s=l(a.scheme||n.scheme);s&&s.serialize&&s.serialize(n,a),n.path!==void 0&&(a.skipEscape?n.path=unescape(n.path):(n.path=escape(n.path),n.scheme!==void 0&&(n.path=n.path.split(`%3A`).join(`:`)))),a.reference!==`suffix`&&n.scheme&&o.push(n.scheme,`:`);let c=i(n);if(c!==void 0&&(a.reference!==`suffix`&&o.push(`//`),o.push(c),n.path&&n.path[0]!==`/`&&o.push(`/`)),n.path!==void 0){let e=n.path;!a.absolutePath&&(!s||!s.absolutePath)&&(e=r(e)),c===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),o.push(e)}return n.query!==void 0&&o.push(`?`,n.query),n.fragment!==void 0&&o.push(`#`,n.fragment),o.join(``)}let h=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function g(e,t){let r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:``,port:void 0,path:``,query:void 0,fragment:void 0},a=!1;r.reference===`suffix`&&(e=r.scheme?r.scheme+`:`+e:`//`+e);let c=e.match(h);if(c){if(i.scheme=c[1],i.userinfo=c[3],i.host=c[4],i.port=parseInt(c[5],10),i.path=c[6]||``,i.query=c[7],i.fragment=c[8],isNaN(i.port)&&(i.port=c[5]),i.host)if(o(i.host)===!1){let e=n(i.host);i.host=e.host.toLowerCase(),a=e.isIPV6}else a=!0;i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path?i.reference=`same-document`:i.scheme===void 0?i.reference=`relative`:i.fragment===void 0?i.reference=`absolute`:i.reference=`uri`,r.reference&&r.reference!==`suffix`&&r.reference!==i.reference&&(i.error=i.error||`URI is not a `+r.reference+` reference.`);let t=l(r.scheme||i.scheme);if(!r.unicodeSupport&&(!t||!t.unicodeSupport)&&i.host&&(r.domainHost||t&&t.domainHost)&&a===!1&&s(i.host))try{i.host=URL.domainToASCII(i.host.toLowerCase())}catch(e){i.error=i.error||`Host's domain name can not be converted to ASCII: `+e}(!t||t&&!t.skipNormalize)&&(e.indexOf(`%`)!==-1&&(i.scheme!==void 0&&(i.scheme=unescape(i.scheme)),i.host!==void 0&&(i.host=unescape(i.host))),i.path&&=escape(unescape(i.path)),i.fragment&&=encodeURI(decodeURIComponent(i.fragment))),t&&t.parse&&t.parse(i,r)}else i.error=i.error||`URI can not be parsed.`;return i}let _={SCHEMES:c,normalize:u,resolve:d,resolveComponent:f,equal:p,serialize:m,parse:g};t.exports=_,t.exports.default=_,t.exports.fastUri=_})),Bd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=zd();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),Vd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Md();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return t.KeywordCxt}});var n=Z();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return n.CodeGen}});let r=Nd(),i=Pd(),a=Sd(),o=Fd(),s=Z(),c=jd(),l=wd(),u=Q(),d=Id(),f=Bd(),p=(e,t)=>new RegExp(e,t);p.code=`new RegExp`;let m=[`removeAdditional`,`useDefaults`,`coerceTypes`],h=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),g={errorDataPath:``,format:"`validateFormats: false` can be used instead.",nullable:`"nullable" keyword is supported by default.`,jsonPointers:`Deprecated jsPropertySyntax can be used instead.`,extendRefs:`Deprecated ignoreKeywordsWithRef can be used instead.`,missingRefs:`Pass empty schema with $id that should be ignored to ajv.addSchema.`,processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:`"uniqueItems" keyword is always validated.`,unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:`Map is used as cache, schema object as key.`,serialize:`Map is used as cache, schema object as key.`,ajvErrors:`It is default now.`},_={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`};function v(e){let t=e.strict,n=e.code?.optimize,r=n===!0||n===void 0?1:n||0,i=e.code?.regExp??p,a=e.uriResolver??f.default;return{strictSchema:e.strictSchema??t??!0,strictNumbers:e.strictNumbers??t??!0,strictTypes:e.strictTypes??t??`log`,strictTuples:e.strictTuples??t??`log`,strictRequired:e.strictRequired??t??!1,code:e.code?{...e.code,optimize:r,regExp:i}:{optimize:r,regExp:i},loopRequired:e.loopRequired??200,loopEnum:e.loopEnum??200,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:a}}var y=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...v(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:h,es5:t,lines:n}),this.logger=D(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),b.call(this,g,e,`NOT SUPPORTED`),b.call(this,_,e,`DEPRECATED`,`warn`),this._metaOpts=T.call(this),e.formats&&C.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&w.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),S.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,r=d;n===`id`&&(r={...d},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let n;if(typeof e==`string`){if(n=this.getSchema(e),!n)throw Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let r=n(t);return`$async`in n||(this.errors=n.errors),r}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await a.call(this,e.$schema);let n=this._addSchema(e,t);return n.validate||o.call(this,n)}async function a(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return s.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function s({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){let n=await l.call(this,e);this.refs[e]||await a.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function l(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,n,r);return this}let i;if(typeof e==`object`){let{schemaId:t}=this.opts;if(i=e[t],i!==void 0&&typeof i!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!=`string`)throw Error(`$schema must be a string`);if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn(`meta-schema not available`),this.errors=null,!0;let r=this.validate(n,e);if(!r&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return r}getSchema(e){let t;for(;typeof(t=x.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:n}=this.opts,r=new o.SchemaEnv({schema:{},schemaId:n});if(t=o.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=x.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e==`string`)n=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=n);else if(typeof e==`object`&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(k.call(this,n,t),!t)return(0,u.eachItem)(n,e=>A.call(this,e)),this;M.call(this,t);let r={...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)};return(0,u.eachItem)(n,r.type.length===0?e=>A.call(this,e,r):e=>r.type.forEach(t=>A.call(this,e,r,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:n=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of t){let t=r.split(`/`).slice(1),i=e;for(let e of t)i=i[e];for(let e in n){let t=n[e];if(typeof t!=`object`)continue;let{$data:r}=t.definition,a=i[e];r&&a&&(i[e]=N(a))}}return e}_removeAllSchemas(e,t){for(let n in e){let r=e[n];(!t||t.test(n))&&(typeof r==`string`?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof e==`object`)a=e[s];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let l=this._cache.get(e);if(l!==void 0)return l;n=(0,c.normalizeId)(a||n);let u=c.getSchemaRefs.call(this,e,n);return l=new o.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:n,localRefs:u}),this._cache.set(l.schema,l),i&&!n.startsWith(`#`)&&(n&&this._checkUnique(n),this.refs[n]=l),r&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):o.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,e)}finally{this.opts=t}}};y.ValidationError=r.default,y.MissingRefError=i.default,e.default=y;function b(e,t,n,r=`error`){for(let i in e){let a=i;a in t&&this.logger[r](`${n}: option ${i}. ${e[a]}`)}}function x(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function S(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function C(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function w(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let n=e[t];n.keyword||=t,this.addKeyword(n)}}function T(){let e={...this.opts};for(let t of m)delete e[t];return e}let E={log(){},warn(){},error(){}};function D(e){if(e===!1)return E;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}let O=/^[a-z_$][a-z0-9_$:-]*$/i;function k(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!O.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function A(e,t,n){var r;let i=t?.post;if(n&&i)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:a}=this,o=i?a.post:a.rules.find(({type:e})=>e===n);if(o||(o={type:n,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?j.call(this,o,s,t.before):o.rules.push(s),a.all[e]=s,(r=t.implements)==null||r.forEach(e=>this.addKeyword(e))}function j(e,t,n){let r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function M(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=N(t)),e.validateSchema=this.compile(t,!0))}let ee={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function N(e){return{anyOf:[e,ee]}}})),Hd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),Ud=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.callRef=e.getValidate=void 0;let t=Pd(),n=Ed(),r=Z(),i=yd(),a=Fd(),o=Q(),s={keyword:`$ref`,schemaType:`string`,code(e){let{gen:n,schema:i,it:o}=e,{baseId:s,schemaEnv:u,validateName:d,opts:f,self:p}=o,{root:m}=u;if((i===`#`||i===`#/`)&&s===m.baseId)return g();let h=a.resolveRef.call(p,m,s,i);if(h===void 0)throw new t.default(o.opts.uriResolver,s,i);if(h instanceof a.SchemaEnv)return _(h);return v(h);function g(){if(u===m)return l(e,d,u,u.$async);let t=n.scopeValue(`root`,{ref:m});return l(e,(0,r._)`${t}.validate`,m,m.$async)}function _(t){l(e,c(e,t),t,t.$async)}function v(t){let a=n.scopeValue(`schema`,f.code.source===!0?{ref:t,code:(0,r.stringify)(t)}:{ref:t}),o=n.name(`valid`),s=e.subschema({schema:t,dataTypes:[],schemaPath:r.nil,topSchemaRef:a,errSchemaPath:i},o);e.mergeEvaluated(s),e.ok(o)}}};function c(e,t){let{gen:n}=e;return t.validate?n.scopeValue(`validate`,{ref:t.validate}):(0,r._)`${n.scopeValue(`wrapper`,{ref:t})}.validate`}e.getValidate=c;function l(e,t,a,s){let{gen:c,it:l}=e,{allErrors:u,schemaEnv:d,opts:f}=l,p=f.passContext?i.default.this:r.nil;s?m():h();function m(){if(!d.$async)throw Error(`async schema referenced by sync schema`);let i=c.let(`valid`);c.try(()=>{c.code((0,r._)`await ${(0,n.callValidateCode)(e,t,p)}`),_(t),u||c.assign(i,!0)},e=>{c.if((0,r._)`!(${e} instanceof ${l.ValidationError})`,()=>c.throw(e)),g(e),u||c.assign(i,!1)}),e.ok(i)}function h(){e.result((0,n.callValidateCode)(e,t,p),()=>_(t),()=>g(t))}function g(e){let t=(0,r._)`${e}.errors`;c.assign(i.default.vErrors,(0,r._)`${i.default.vErrors} === null ? ${t} : ${i.default.vErrors}.concat(${t})`),c.assign(i.default.errors,(0,r._)`${i.default.vErrors}.length`)}function _(e){if(!l.opts.unevaluated)return;let t=a?.validate?.evaluated;if(l.props!==!0)if(t&&!t.dynamicProps)t.props!==void 0&&(l.props=o.mergeEvaluated.props(c,t.props,l.props));else{let t=c.var(`props`,(0,r._)`${e}.evaluated.props`);l.props=o.mergeEvaluated.props(c,t,l.props,r.Name)}if(l.items!==!0)if(t&&!t.dynamicItems)t.items!==void 0&&(l.items=o.mergeEvaluated.items(c,t.items,l.items));else{let t=c.var(`items`,(0,r._)`${e}.evaluated.items`);l.items=o.mergeEvaluated.items(c,t,l.items,r.Name)}}}e.callRef=l,e.default=s})),Wd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Hd(),n=Ud();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),Gd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z(),n=t.operators,r={maximum:{okStr:`<=`,ok:n.LTE,fail:n.GT},minimum:{okStr:`>=`,ok:n.GTE,fail:n.LT},exclusiveMaximum:{okStr:`<`,ok:n.LT,fail:n.GTE},exclusiveMinimum:{okStr:`>`,ok:n.GT,fail:n.LTE}};e.default={keyword:Object.keys(r),type:`number`,schemaType:`number`,$data:!0,error:{message:({keyword:e,schemaCode:n})=>(0,t.str)`must be ${r[e].okStr} ${n}`,params:({keyword:e,schemaCode:n})=>(0,t._)`{comparison: ${r[e].okStr}, limit: ${n}}`},code(e){let{keyword:n,data:i,schemaCode:a}=e;e.fail$data((0,t._)`${i} ${r[n].fail} ${a} || isNaN(${i})`)}}})),Kd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z();e.default={keyword:`multipleOf`,type:`number`,schemaType:`number`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,t._)`{multipleOf: ${e}}`},code(e){let{gen:n,data:r,schemaCode:i,it:a}=e,o=a.opts.multipleOfPrecision,s=n.let(`res`),c=o?(0,t._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,t._)`${s} !== parseInt(${s})`;e.fail$data((0,t._)`(${i} === 0 || (${s} = ${r}/${i}, ${c}))`)}}})),qd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});function t(e){let t=e.length,n=0,r=0,i;for(;r<t;)n++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<t&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return n}e.default=t,t.code=`require("ajv/dist/runtime/ucs2length").default`})),Jd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z(),n=Q(),r=qd();e.default={keyword:[`maxLength`,`minLength`],type:`string`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxLength`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} characters`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:i,data:a,schemaCode:o,it:s}=e,c=i===`maxLength`?t.operators.GT:t.operators.LT,l=s.opts.unicode===!1?(0,t._)`${a}.length`:(0,t._)`${(0,n.useFunc)(e.gen,r.default)}(${a})`;e.fail$data((0,t._)`${l} ${c} ${o}`)}}})),Yd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Ed(),n=Q(),r=Z();e.default={keyword:`pattern`,type:`string`,schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,r._)`{pattern: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e,u=l.opts.unicodeRegExp?`u`:``;if(o){let{regExp:t}=l.opts.code,o=t.code===`new RegExp`?(0,r._)`new RegExp`:(0,n.useFunc)(i,t),s=i.let(`valid`);i.try(()=>i.assign(s,(0,r._)`${o}(${c}, ${u}).test(${a})`),()=>i.assign(s,!1)),e.fail$data((0,r._)`!${s}`)}else{let n=(0,t.usePattern)(e,s);e.fail$data((0,r._)`!${n}.test(${a})`)}}}})),Xd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z();e.default={keyword:[`maxProperties`,`minProperties`],type:`object`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxProperties`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} properties`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxProperties`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`Object.keys(${r}).length ${a} ${i}`)}}})),Zd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Ed(),n=Z(),r=Q();e.default={keyword:`required`,type:`object`,schemaType:`array`,$data:!0,error:{message:({params:{missingProperty:e}})=>(0,n.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,n._)`{missingProperty: ${e}}`},code(e){let{gen:i,schema:a,schemaCode:o,data:s,$data:c,it:l}=e,{opts:u}=l;if(!c&&a.length===0)return;let d=a.length>=u.loopRequired;if(l.allErrors?f():p(),u.strictRequired){let t=e.parentSchema.properties,{definedProperties:n}=e.it;for(let e of a)if(t?.[e]===void 0&&!n.has(e)){let t=`required property "${e}" is not defined at "${l.schemaEnv.baseId+l.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(l,t,l.opts.strictRequired)}}function f(){if(d||c)e.block$data(n.nil,m);else for(let n of a)(0,t.checkReportMissingProp)(e,n)}function p(){let n=i.let(`missing`);if(d||c){let t=i.let(`valid`,!0);e.block$data(t,()=>h(n,t)),e.ok(t)}else i.if((0,t.checkMissingProp)(e,a,n)),(0,t.reportMissingProp)(e,n),i.else()}function m(){i.forOf(`prop`,o,n=>{e.setParams({missingProperty:n}),i.if((0,t.noPropertyInData)(i,s,n,u.ownProperties),()=>e.error())})}function h(r,a){e.setParams({missingProperty:r}),i.forOf(r,o,()=>{i.assign(a,(0,t.propertyInData)(i,s,r,u.ownProperties)),i.if((0,n.not)(a),()=>{e.error(),i.break()})},n.nil)}}}})),Qd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z();e.default={keyword:[`maxItems`,`minItems`],type:`array`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxItems`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} items`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxItems`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`${r}.length ${a} ${i}`)}}})),$d=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=kd();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),ef=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=wd(),n=Z(),r=Q(),i=$d();e.default={keyword:`uniqueItems`,type:`array`,schemaType:`boolean`,$data:!0,error:{message:({params:{i:e,j:t}})=>(0,n.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,n._)`{i: ${e}, j: ${t}}`},code(e){let{gen:a,data:o,$data:s,schema:c,parentSchema:l,schemaCode:u,it:d}=e;if(!s&&!c)return;let f=a.let(`valid`),p=l.items?(0,t.getSchemaTypes)(l.items):[];e.block$data(f,m,(0,n._)`${u} === false`),e.ok(f);function m(){let t=a.let(`i`,(0,n._)`${o}.length`),r=a.let(`j`);e.setParams({i:t,j:r}),a.assign(f,!0),a.if((0,n._)`${t} > 1`,()=>(h()?g:_)(t,r))}function h(){return p.length>0&&!p.some(e=>e===`object`||e===`array`)}function g(r,i){let s=a.name(`item`),c=(0,t.checkDataTypes)(p,s,d.opts.strictNumbers,t.DataType.Wrong),l=a.const(`indices`,(0,n._)`{}`);a.for((0,n._)`;${r}--;`,()=>{a.let(s,(0,n._)`${o}[${r}]`),a.if(c,(0,n._)`continue`),p.length>1&&a.if((0,n._)`typeof ${s} == "string"`,(0,n._)`${s} += "_"`),a.if((0,n._)`typeof ${l}[${s}] == "number"`,()=>{a.assign(i,(0,n._)`${l}[${s}]`),e.error(),a.assign(f,!1).break()}).code((0,n._)`${l}[${s}] = ${r}`)})}function _(t,s){let c=(0,r.useFunc)(a,i.default),l=a.name(`outer`);a.label(l).for((0,n._)`;${t}--;`,()=>a.for((0,n._)`${s} = ${t}; ${s}--;`,()=>a.if((0,n._)`${c}(${o}[${t}], ${o}[${s}])`,()=>{e.error(),a.assign(f,!1).break(l)})))}}}})),tf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z(),n=Q(),r=$d();e.default={keyword:`const`,$data:!0,error:{message:`must be equal to constant`,params:({schemaCode:e})=>(0,t._)`{allowedValue: ${e}}`},code(e){let{gen:i,data:a,$data:o,schemaCode:s,schema:c}=e;o||c&&typeof c==`object`?e.fail$data((0,t._)`!${(0,n.useFunc)(i,r.default)}(${a}, ${s})`):e.fail((0,t._)`${c} !== ${a}`)}}})),nf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z(),n=Q(),r=$d();e.default={keyword:`enum`,schemaType:`array`,$data:!0,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e;if(!o&&s.length===0)throw Error(`enum must have non-empty array`);let u=s.length>=l.opts.loopEnum,d,f=()=>d??=(0,n.useFunc)(i,r.default),p;if(u||o)p=i.let(`valid`),e.block$data(p,m);else{if(!Array.isArray(s))throw Error(`ajv implementation error`);let e=i.const(`vSchema`,c);p=(0,t.or)(...s.map((t,n)=>h(e,n)))}e.pass(p);function m(){i.assign(p,!1),i.forOf(`v`,c,e=>i.if((0,t._)`${f()}(${a}, ${e})`,()=>i.assign(p,!0).break()))}function h(e,n){let r=s[n];return typeof r==`object`&&r?(0,t._)`${f()}(${a}, ${e}[${n}])`:(0,t._)`${a} === ${r}`}}}})),rf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Gd(),n=Kd(),r=Jd(),i=Yd(),a=Xd(),o=Zd(),s=Qd(),c=ef(),l=tf(),u=nf();e.default=[t.default,n.default,r.default,i.default,a.default,o.default,s.default,c.default,{keyword:`type`,schemaType:[`string`,`array`]},{keyword:`nullable`,schemaType:`boolean`},l.default,u.default]})),af=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateAdditionalItems=void 0;let t=Z(),n=Q(),r={keyword:`additionalItems`,type:`array`,schemaType:[`boolean`,`object`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{parentSchema:t,it:r}=e,{items:a}=t;if(!Array.isArray(a)){(0,n.checkStrictMode)(r,`"additionalItems" is ignored when "items" is not an array of schemas`);return}i(e,a)}};function i(e,r){let{gen:i,schema:a,data:o,keyword:s,it:c}=e;c.items=!0;let l=i.const(`len`,(0,t._)`${o}.length`);if(a===!1)e.setParams({len:r.length}),e.pass((0,t._)`${l} <= ${r.length}`);else if(typeof a==`object`&&!(0,n.alwaysValidSchema)(c,a)){let n=i.var(`valid`,(0,t._)`${l} <= ${r.length}`);i.if((0,t.not)(n),()=>u(n)),e.ok(n)}function u(a){i.forRange(`i`,r.length,l,r=>{e.subschema({keyword:s,dataProp:r,dataPropType:n.Type.Num},a),c.allErrors||i.if((0,t.not)(a),()=>i.break())})}}e.validateAdditionalItems=i,e.default=r})),of=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateTuple=void 0;let t=Z(),n=Q(),r=Ed(),i={keyword:`items`,type:`array`,schemaType:[`object`,`array`,`boolean`],before:`uniqueItems`,code(e){let{schema:t,it:i}=e;if(Array.isArray(t))return a(e,`additionalItems`,t);i.items=!0,!(0,n.alwaysValidSchema)(i,t)&&e.ok((0,r.validateArray)(e))}};function a(e,r,i=e.schema){let{gen:a,parentSchema:o,data:s,keyword:c,it:l}=e;f(o),l.opts.unevaluated&&i.length&&l.items!==!0&&(l.items=n.mergeEvaluated.items(a,i.length,l.items));let u=a.name(`valid`),d=a.const(`len`,(0,t._)`${s}.length`);i.forEach((r,i)=>{(0,n.alwaysValidSchema)(l,r)||(a.if((0,t._)`${d} > ${i}`,()=>e.subschema({keyword:c,schemaProp:i,dataProp:i},u)),e.ok(u))});function f(e){let{opts:t,errSchemaPath:a}=l,o=i.length,s=o===e.minItems&&(o===e.maxItems||e[r]===!1);if(t.strictTuples&&!s){let e=`"${c}" is ${o}-tuple, but minItems or maxItems/${r} are not specified or different at path "${a}"`;(0,n.checkStrictMode)(l,e,t.strictTuples)}}}e.validateTuple=a,e.default=i})),sf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=of();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),cf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z(),n=Q(),r=Ed(),i=af();e.default={keyword:`items`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{schema:t,parentSchema:a,it:o}=e,{prefixItems:s}=a;o.items=!0,!(0,n.alwaysValidSchema)(o,t)&&(s?(0,i.validateAdditionalItems)(e,s):e.ok((0,r.validateArray)(e)))}}})),lf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z(),n=Q();e.default={keyword:`contains`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,trackErrors:!0,error:{message:({params:{min:e,max:n}})=>n===void 0?(0,t.str)`must contain at least ${e} valid item(s)`:(0,t.str)`must contain at least ${e} and no more than ${n} valid item(s)`,params:({params:{min:e,max:n}})=>n===void 0?(0,t._)`{minContains: ${e}}`:(0,t._)`{minContains: ${e}, maxContains: ${n}}`},code(e){let{gen:r,schema:i,parentSchema:a,data:o,it:s}=e,c,l,{minContains:u,maxContains:d}=a;s.opts.next?(c=u===void 0?1:u,l=d):c=1;let f=r.const(`len`,(0,t._)`${o}.length`);if(e.setParams({min:c,max:l}),l===void 0&&c===0){(0,n.checkStrictMode)(s,`"minContains" == 0 without "maxContains": "contains" keyword ignored`);return}if(l!==void 0&&c>l){(0,n.checkStrictMode)(s,`"minContains" > "maxContains" is always invalid`),e.fail();return}if((0,n.alwaysValidSchema)(s,i)){let n=(0,t._)`${f} >= ${c}`;l!==void 0&&(n=(0,t._)`${n} && ${f} <= ${l}`),e.pass(n);return}s.items=!0;let p=r.name(`valid`);l===void 0&&c===1?h(p,()=>r.if(p,()=>r.break())):c===0?(r.let(p,!0),l!==void 0&&r.if((0,t._)`${o}.length > 0`,m)):(r.let(p,!1),m()),e.result(p,()=>e.reset());function m(){let e=r.name(`_valid`),t=r.let(`count`,0);h(e,()=>r.if(e,()=>g(t)))}function h(t,i){r.forRange(`i`,0,f,r=>{e.subschema({keyword:`contains`,dataProp:r,dataPropType:n.Type.Num,compositeRule:!0},t),i()})}function g(e){r.code((0,t._)`${e}++`),l===void 0?r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0).break()):(r.if((0,t._)`${e} > ${l}`,()=>r.assign(p,!1).break()),c===1?r.assign(p,!0):r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0)))}}}})),uf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=Z(),n=Q(),r=Ed();e.error={message:({params:{property:e,depsCount:n,deps:r}})=>{let i=n===1?`property`:`properties`;return(0,t.str)`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:n,deps:r,missingProperty:i}})=>(0,t._)`{property: ${e},
|
|
132
|
+
|| ${s} === "boolean" || ${a} === null`).assign(c,(0,i._)`[${a}]`)}}}function p({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,i._)`${t} !== undefined`,()=>e.assign((0,i._)`${t}[${n}]`,r))}function m(e,t,n,r=o.Correct){let a=r===o.Correct?i.operators.EQ:i.operators.NEQ,s;switch(e){case`null`:return(0,i._)`${t} ${a} null`;case`array`:s=(0,i._)`Array.isArray(${t})`;break;case`object`:s=(0,i._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case`integer`:s=c((0,i._)`!(${t} % 1) && !isNaN(${t})`);break;case`number`:s=c();break;default:return(0,i._)`typeof ${t} ${a} ${e}`}return r===o.Correct?s:(0,i.not)(s);function c(e=i.nil){return(0,i.and)((0,i._)`typeof ${t} == "number"`,e,n?(0,i._)`isFinite(${t})`:i.nil)}}e.checkDataType=m;function h(e,t,n,r){if(e.length===1)return m(e[0],t,n,r);let o,s=(0,a.toHash)(e);if(s.array&&s.object){let e=(0,i._)`typeof ${t} != "object"`;o=s.null?e:(0,i._)`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else o=i.nil;s.number&&delete s.integer;for(let e in s)o=(0,i.and)(o,m(e,t,n,r));return o}e.checkDataTypes=h;let g={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e==`string`?(0,i._)`{type: ${e}}`:(0,i._)`{type: ${t}}`};function _(e){let t=v(e);(0,r.reportError)(t,g)}e.reportTypeError=_;function v(e){let{gen:t,data:n,schema:r}=e,i=(0,a.schemaRefOrVal)(e,r,`type`);return{gen:t,keyword:`type`,data:n,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:e}}})),Ed=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.assignDefaults=void 0;let t=Z(),n=yd();function r(e,t){let{properties:n,items:r}=e.schema;if(t===`object`&&n)for(let t in n)i(e,t,n[t].default);else t===`array`&&Array.isArray(r)&&r.forEach((t,n)=>i(e,n,t.default))}e.assignDefaults=r;function i(e,r,i){let{gen:a,compositeRule:o,data:s,opts:c}=e;if(i===void 0)return;let l=(0,t._)`${s}${(0,t.getProperty)(r)}`;if(o){(0,n.checkStrictMode)(e,`default is ignored for: ${l}`);return}let u=(0,t._)`${l} === undefined`;c.useDefaults===`empty`&&(u=(0,t._)`${u} || ${l} === null || ${l} === ""`),a.if(u,(0,t._)`${l} = ${(0,t.stringify)(i)}`)}})),Dd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;let t=Z(),n=yd(),r=bd(),i=yd();function a(e,n){let{gen:r,data:i,it:a}=e;r.if(d(r,i,n,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,t._)`${n}`},!0),e.error()})}e.checkReportMissingProp=a;function o({gen:e,data:n,it:{opts:r}},i,a){return(0,t.or)(...i.map(i=>(0,t.and)(d(e,n,i,r.ownProperties),(0,t._)`${a} = ${i}`)))}e.checkMissingProp=o;function s(e,t){e.setParams({missingProperty:t},!0),e.error()}e.reportMissingProp=s;function c(e){return e.scopeValue(`func`,{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=c;function l(e,n,r){return(0,t._)`${c(e)}.call(${n}, ${r})`}e.isOwnProperty=l;function u(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} !== undefined`;return i?(0,t._)`${a} && ${l(e,n,r)}`:a}e.propertyInData=u;function d(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} === undefined`;return i?(0,t.or)(a,(0,t.not)(l(e,n,r))):a}e.noPropertyInData=d;function f(e){return e?Object.keys(e).filter(e=>e!==`__proto__`):[]}e.allSchemaProperties=f;function p(e,t){return f(t).filter(r=>!(0,n.alwaysValidSchema)(e,t[r]))}e.schemaProperties=p;function m({schemaCode:e,data:n,it:{gen:i,topSchemaRef:a,schemaPath:o,errorPath:s},it:c},l,u,d){let f=d?(0,t._)`${e}, ${n}, ${a}${o}`:n,p=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,s)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&p.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);let m=(0,t._)`${f}, ${i.object(...p)}`;return u===t.nil?(0,t._)`${l}(${m})`:(0,t._)`${l}.call(${u}, ${m})`}e.callValidateCode=m;let h=(0,t._)`new RegExp`;function g({gen:e,it:{opts:n}},r){let a=n.unicodeRegExp?`u`:``,{regExp:o}=n.code,s=o(r,a);return e.scopeValue(`pattern`,{key:s.toString(),ref:s,code:(0,t._)`${o.code===`new RegExp`?h:(0,i.useFunc)(e,o)}(${r}, ${a})`})}e.usePattern=g;function _(e){let{gen:r,data:i,keyword:a,it:o}=e,s=r.name(`valid`);if(o.allErrors){let e=r.let(`valid`,!0);return c(()=>r.assign(e,!1)),e}return r.var(s,!0),c(()=>r.break()),s;function c(o){let c=r.const(`len`,(0,t._)`${i}.length`);r.forRange(`i`,0,c,i=>{e.subschema({keyword:a,dataProp:i,dataPropType:n.Type.Num},s),r.if((0,t.not)(s),o)})}}e.validateArray=_;function v(e){let{gen:r,schema:i,keyword:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(i.some(e=>(0,n.alwaysValidSchema)(o,e))&&!o.opts.unevaluated)return;let s=r.let(`valid`,!1),c=r.name(`_valid`);r.block(()=>i.forEach((n,i)=>{let o=e.subschema({keyword:a,schemaProp:i,compositeRule:!0},c);r.assign(s,(0,t._)`${s} || ${c}`),e.mergeValidEvaluated(o,c)||r.if((0,t.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}e.validateUnion=v})),Od=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=Z(),n=bd(),r=Dd(),i=xd();function a(e,n){let{gen:r,keyword:i,schema:a,parentSchema:o,it:s}=e,c=n.macro.call(s.self,a,o,s),l=u(r,i,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let d=r.name(`valid`);e.subschema({schema:c,schemaPath:t.nil,errSchemaPath:`${s.errSchemaPath}/${i}`,topSchemaRef:l,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}e.macroKeywordCode=a;function o(e,i){let{gen:a,keyword:o,schema:d,parentSchema:f,$data:p,it:m}=e;l(m,i);let h=u(a,o,!p&&i.compile?i.compile.call(m.self,d,f,m):i.validate),g=a.let(`valid`);e.block$data(g,_),e.ok(i.valid??g);function _(){if(i.errors===!1)b(),i.modifying&&s(e),x(()=>e.error());else{let t=i.async?v():y();i.modifying&&s(e),x(()=>c(e,t))}}function v(){let e=a.let(`ruleErrs`,null);return a.try(()=>b((0,t._)`await `),n=>a.assign(g,!1).if((0,t._)`${n} instanceof ${m.ValidationError}`,()=>a.assign(e,(0,t._)`${n}.errors`),()=>a.throw(n))),e}function y(){let e=(0,t._)`${h}.errors`;return a.assign(e,null),b(t.nil),e}function b(o=i.async?(0,t._)`await `:t.nil){let s=m.opts.passContext?n.default.this:n.default.self,c=!(`compile`in i&&!p||i.schema===!1);a.assign(g,(0,t._)`${o}${(0,r.callValidateCode)(e,h,s,c)}`,i.modifying)}function x(e){a.if((0,t.not)(i.valid??g),e)}}e.funcKeywordCode=o;function s(e){let{gen:n,data:r,it:i}=e;n.if(i.parentData,()=>n.assign(r,(0,t._)`${i.parentData}[${i.parentDataProperty}]`))}function c(e,r){let{gen:a}=e;a.if((0,t._)`Array.isArray(${r})`,()=>{a.assign(n.default.vErrors,(0,t._)`${n.default.vErrors} === null ? ${r} : ${n.default.vErrors}.concat(${r})`).assign(n.default.errors,(0,t._)`${n.default.vErrors}.length`),(0,i.extendErrors)(e)},()=>e.error())}function l({schemaEnv:e},t){if(t.async&&!e.$async)throw Error(`async keyword in sync schema`)}function u(e,n,r){if(r===void 0)throw Error(`keyword "${n}" failed to compile`);return e.scopeValue(`keyword`,typeof r==`function`?{ref:r}:{ref:r,code:(0,t.stringify)(r)})}function d(e,t,n=!1){return!t.length||t.some(t=>t===`array`?Array.isArray(e):t===`object`?e&&typeof e==`object`&&!Array.isArray(e):typeof e==t||n&&e===void 0)}e.validSchemaType=d;function f({schema:e,opts:t,self:n,errSchemaPath:r},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw Error(`ajv implementation error`);let o=i.dependencies;if(o?.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${a}: ${o.join(`,`)}`);if(i.validateSchema&&!i.validateSchema(e[a])){let e=`keyword "${a}" value is invalid at path "${r}": `+n.errorsText(i.validateSchema.errors);if(t.validateSchema===`log`)n.logger.error(e);else throw Error(e)}}e.validateKeywordUsage=f})),kd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=Z(),n=yd();function r(e,{keyword:r,schemaProp:i,schema:a,schemaPath:o,errSchemaPath:s,topSchemaRef:c}){if(r!==void 0&&a!==void 0)throw Error(`both "keyword" and "schema" passed, only one allowed`);if(r!==void 0){let a=e.schema[r];return i===void 0?{schema:a,schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${r}`}:{schema:a[i],schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}${(0,t.getProperty)(i)}`,errSchemaPath:`${e.errSchemaPath}/${r}/${(0,n.escapeFragment)(i)}`}}if(a!==void 0){if(o===void 0||s===void 0||c===void 0)throw Error(`"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"`);return{schema:a,schemaPath:o,topSchemaRef:c,errSchemaPath:s}}throw Error(`either "keyword" or "schema" must be passed`)}e.getSubschema=r;function i(e,r,{dataProp:i,dataPropType:a,data:o,dataTypes:s,propertyName:c}){if(o!==void 0&&i!==void 0)throw Error(`both "data" and "dataProp" passed, only one allowed`);let{gen:l}=r;if(i!==void 0){let{errorPath:o,dataPathArr:s,opts:c}=r;u(l.let(`data`,(0,t._)`${r.data}${(0,t.getProperty)(i)}`,!0)),e.errorPath=(0,t.str)`${o}${(0,n.getErrorPath)(i,a,c.jsPropertySyntax)}`,e.parentDataProperty=(0,t._)`${i}`,e.dataPathArr=[...s,e.parentDataProperty]}o!==void 0&&(u(o instanceof t.Name?o:l.let(`data`,o,!0)),c!==void 0&&(e.propertyName=c)),s&&(e.dataTypes=s);function u(t){e.data=t,e.dataLevel=r.dataLevel+1,e.dataTypes=[],r.definedProperties=new Set,e.parentData=r.data,e.dataNames=[...r.dataNames,t]}}e.extendSubschemaData=i;function a(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:i,allErrors:a}){r!==void 0&&(e.compositeRule=r),i!==void 0&&(e.createErrors=i),a!==void 0&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=n}e.extendSubschemaMode=a})),Ad=o(((e,t)=>{t.exports=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t==`object`&&typeof n==`object`){if(t.constructor!==n.constructor)return!1;var r,i,a;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(i=r;i--!==0;)if(!e(t[i],n[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(a=Object.keys(t),r=a.length,r!==Object.keys(n).length)return!1;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(n,a[i]))return!1;for(i=r;i--!==0;){var o=a[i];if(!e(t[o],n[o]))return!1}return!0}return t!==t&&n!==n}})),jd=o(((e,t)=>{var n=t.exports=function(e,t,n){typeof t==`function`&&(n=t,t={}),n=t.cb||n;var i=typeof n==`function`?n:n.pre||function(){},a=n.post||function(){};r(t,i,a,e,``,e)};n.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},n.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},n.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},n.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function r(e,t,a,o,s,c,l,u,d,f){if(o&&typeof o==`object`&&!Array.isArray(o)){for(var p in t(o,s,c,l,u,d,f),o){var m=o[p];if(Array.isArray(m)){if(p in n.arrayKeywords)for(var h=0;h<m.length;h++)r(e,t,a,m[h],s+`/`+p+`/`+h,c,s,p,o,h)}else if(p in n.propsKeywords){if(m&&typeof m==`object`)for(var g in m)r(e,t,a,m[g],s+`/`+p+`/`+i(g),c,s,p,o,g)}else (p in n.keywords||e.allKeys&&!(p in n.skipKeywords))&&r(e,t,a,m,s+`/`+p,c,s,p,o)}a(o,s,c,l,u,d,f)}}function i(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}})),Md=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=yd(),n=Ad(),r=jd(),i=new Set([`type`,`format`,`pattern`,`maxLength`,`minLength`,`maxProperties`,`minProperties`,`maxItems`,`minItems`,`maximum`,`minimum`,`uniqueItems`,`multipleOf`,`required`,`enum`,`const`]);function a(e,t=!0){return typeof e==`boolean`?!0:t===!0?!s(e):t?c(e)<=t:!1}e.inlineRef=a;let o=new Set([`$ref`,`$recursiveRef`,`$recursiveAnchor`,`$dynamicRef`,`$dynamicAnchor`]);function s(e){for(let t in e){if(o.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(s)||typeof n==`object`&&s(n))return!0}return!1}function c(e){let n=0;for(let r in e)if(r===`$ref`||(n++,!i.has(r)&&(typeof e[r]==`object`&&(0,t.eachItem)(e[r],e=>n+=c(e)),n===1/0)))return 1/0;return n}function l(e,t=``,n){return n!==!1&&(t=f(t)),u(e,e.parse(t))}e.getFullPath=l;function u(e,t){return e.serialize(t).split(`#`)[0]+`#`}e._getFullPath=u;let d=/#\/?$/;function f(e){return e?e.replace(d,``):``}e.normalizeId=f;function p(e,t,n){return n=f(n),e.resolve(t,n)}e.resolveUrl=p;let m=/^[a-z_][-a-z0-9._]*$/i;function h(e,t){if(typeof e==`boolean`)return{};let{schemaId:i,uriResolver:a}=this.opts,o=f(e[i]||t),s={"":o},c=l(a,o,!1),u={},d=new Set;return r(e,{allKeys:!0},(e,t,n,r)=>{if(r===void 0)return;let a=c+t,o=s[r];typeof e[i]==`string`&&(o=l.call(this,e[i])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),s[t]=o;function l(t){let n=this.opts.uriResolver.resolve;if(t=f(o?n(o,t):t),d.has(t))throw h(t);d.add(t);let r=this.refs[t];return typeof r==`string`&&(r=this.refs[r]),typeof r==`object`?p(e,r.schema,t):t!==f(a)&&(t[0]===`#`?(p(e,u[t],t),u[t]=e):this.refs[t]=a),t}function g(e){if(typeof e==`string`){if(!m.test(e))throw Error(`invalid anchor "${e}"`);l.call(this,`#${e}`)}}}),u;function p(e,t,r){if(t!==void 0&&!n(e,t))throw h(r)}function h(e){return Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=h})),Nd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=Sd(),n=Td(),r=wd(),i=Td(),a=Ed(),o=Od(),s=kd(),c=Z(),l=bd(),u=Md(),d=yd(),f=xd();function p(e){if(S(e)&&(w(e),x(e))){_(e);return}m(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=p;function m({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},a){i.code.es5?e.func(t,(0,c._)`${l.default.data}, ${l.default.valCxt}`,r.$async,()=>{e.code((0,c._)`"use strict"; ${y(n,i)}`),g(e,i),e.code(a)}):e.func(t,(0,c._)`${l.default.data}, ${h(i)}`,r.$async,()=>e.code(y(n,i)).code(a))}function h(e){return(0,c._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${e.dynamicRef?(0,c._)`, ${l.default.dynamicAnchors}={}`:c.nil}}={}`}function g(e,t){e.if(l.default.valCxt,()=>{e.var(l.default.instancePath,(0,c._)`${l.default.valCxt}.${l.default.instancePath}`),e.var(l.default.parentData,(0,c._)`${l.default.valCxt}.${l.default.parentData}`),e.var(l.default.parentDataProperty,(0,c._)`${l.default.valCxt}.${l.default.parentDataProperty}`),e.var(l.default.rootData,(0,c._)`${l.default.valCxt}.${l.default.rootData}`),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{e.var(l.default.instancePath,(0,c._)`""`),e.var(l.default.parentData,(0,c._)`undefined`),e.var(l.default.parentDataProperty,(0,c._)`undefined`),e.var(l.default.rootData,l.default.data),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`{}`)})}function _(e){let{schema:t,opts:n,gen:r}=e;m(e,()=>{n.$comment&&t.$comment&&A(e),D(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),T(e),j(e)})}function v(e){let{gen:t,validateName:n}=e;e.evaluated=t.const(`evaluated`,(0,c._)`${n}.evaluated`),t.if((0,c._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,c._)`${e.evaluated}.props`,(0,c._)`undefined`)),t.if((0,c._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,c._)`${e.evaluated}.items`,(0,c._)`undefined`))}function y(e,t){let n=typeof e==`object`&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,c._)`/*# sourceURL=${n} */`:c.nil}function b(e,n){if(S(e)&&(w(e),x(e))){C(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function x({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function S(e){return typeof e.schema!=`boolean`}function C(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&A(e),O(e),k(e);let a=r.const(`_errs`,l.default.errors);T(e,a),r.var(t,(0,c._)`${a} === ${l.default.errors}`)}function w(e){(0,d.checkUnknownRules)(e),E(e)}function T(e,t){if(e.opts.jtd)return ee(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);ee(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function E(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function D(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,d.checkStrictMode)(e,`default is ignored in the schema root`)}function O(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function k(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function A({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let a=n.$comment;if(i.$comment===!0)e.code((0,c._)`${l.default.self}.logger.log(${a})`);else if(typeof i.$comment==`function`){let n=(0,c.str)`${r}/$comment`,i=e.scopeValue(`root`,{ref:t.root});e.code((0,c._)`${l.default.self}.opts.$comment(${a}, ${n}, ${i}.schema)`)}}function j(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:a}=e;n.$async?t.if((0,c._)`${l.default.errors} === 0`,()=>t.return(l.default.data),()=>t.throw((0,c._)`new ${i}(${l.default.vErrors})`)):(t.assign((0,c._)`${r}.errors`,l.default.vErrors),a.unevaluated&&M(e),t.return((0,c._)`${l.default.errors} === 0`))}function M({gen:e,evaluated:t,props:n,items:r}){n instanceof c.Name&&e.assign((0,c._)`${t}.props`,n),r instanceof c.Name&&e.assign((0,c._)`${t}.items`,r)}function ee(e,t,n,a){let{gen:o,schema:s,data:u,allErrors:f,opts:p,self:m}=e,{RULES:h}=m;if(s.$ref&&(p.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(s,h))){o.block(()=>R(e,`$ref`,h.all.$ref.definition));return}p.jtd||te(e,t),o.block(()=>{for(let e of h.rules)g(e);g(h.post)});function g(d){(0,r.shouldUseGroup)(s,d)&&(d.type?(o.if((0,i.checkDataType)(d.type,u,p.strictNumbers)),N(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):N(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function N(e,t){let{gen:n,schema:i,opts:{useDefaults:o}}=e;o&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(let n of t.rules)(0,r.shouldUseRule)(i,n)&&R(e,n.keyword,n.definition,t.type)})}function te(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(P(e,t),e.opts.allowUnionTypes||ne(e,t),F(e,e.dataTypes))}function P(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{re(e.dataTypes,t)||ie(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),L(e,t)}}function ne(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&ie(e,`use allowUnionTypes to allow union type keyword`)}function F(e,t){let n=e.self.RULES.all;for(let i in n){let a=n[i];if(typeof a==`object`&&(0,r.shouldUseRule)(e.schema,a)){let{type:n}=a.definition;n.length&&!n.some(e=>I(t,e))&&ie(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function I(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function re(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function L(e,t){let n=[];for(let r of e.dataTypes)re(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function ie(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var ae=class{constructor(e,t,n){if((0,o.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,ce(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,l.default.errors))}result(e,t,n){this.failResult((0,c.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,c.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,c._)`${t} !== undefined && (${(0,c.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?f.reportExtraError:f.reportError)(this,this.def.error,t)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=c.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=c.nil,t=c.nil){if(!this.$data)return;let{gen:n,schemaCode:r,schemaType:i,def:a}=this;n.if((0,c.or)((0,c._)`${r} === undefined`,t)),e!==c.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==c.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:r,it:a}=this;return(0,c.or)(o(),s());function o(){if(n.length){if(!(t instanceof c.Name))throw Error(`ajv implementation error`);let e=Array.isArray(n)?n:[n];return(0,c._)`${(0,i.checkDataTypes)(e,t,a.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function s(){if(r.validateSchema){let n=e.scopeValue(`validate$data`,{ref:r.validateSchema});return(0,c._)`!${n}(${t})`}return c.nil}}subschema(e,t){let n=(0,s.getSubschema)(this.it,e);(0,s.extendSubschemaData)(n,this.it,e),(0,s.extendSubschemaMode)(n,e);let r={...this.it,...n,items:void 0,props:void 0};return b(r,t),r}mergeEvaluated(e,t){let{it:n,gen:r}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=d.mergeEvaluated.props(r,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=d.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:r}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return r.if(t,()=>this.mergeEvaluated(e,c.Name)),!0}};e.KeywordCxt=ae;function R(e,t,n,r){let i=new ae(e,n,t);`code`in n?n.code(i,r):i.$data&&n.validate?(0,o.funcKeywordCode)(i,n):`macro`in n?(0,o.macroKeywordCode)(i,n):(n.compile||n.validate)&&(0,o.funcKeywordCode)(i,n)}let oe=/^\/(?:[^~]|~0|~1)*$/,se=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ce(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!oe.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=se.exec(e);if(!o)throw Error(`Invalid JSON-pointer: ${e}`);let s=+o[1];if(i=o[2],i===`#`){if(s>=t)throw Error(u(`property/index`,s));return r[t-s]}if(s>t)throw Error(u(`data`,s));if(a=n[t-s],!i)return a}let o=a,s=i.split(`/`);for(let e of s)e&&(a=(0,c._)`${a}${(0,c.getProperty)((0,d.unescapeJsonPointer)(e))}`,o=(0,c._)`${o} && ${a}`);return o;function u(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}e.getData=ce})),Pd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=class extends Error{constructor(e){super(`validation failed`),this.errors=e,this.ajv=this.validation=!0}}})),Fd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Md();e.default=class extends Error{constructor(e,n,r,i){super(i||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,t.resolveUrl)(e,n,r),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(e,this.missingRef))}}})),Id=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=Z(),n=Pd(),r=bd(),i=Md(),a=yd(),o=Nd();var s=class{constructor(e){this.refs={},this.dynamicAnchors={};let t;typeof e.schema==`object`&&(t=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=e.baseId??(0,i.normalizeId)(t?.[e.schemaId||`$id`]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=t?.$async,this.refs={}}};e.SchemaEnv=s;function c(e){let a=d.call(this,e);if(a)return a;let s=(0,i.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:c,lines:l}=this.opts.code,{ownProperties:u}=this.opts,f=new t.CodeGen(this.scope,{es5:c,lines:l,ownProperties:u}),p;e.$async&&(p=f.scopeValue(`Error`,{ref:n.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let m=f.scopeName(`validate`);e.validateName=m;let h={gen:f,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:f.scopeValue(`schema`,this.opts.code.source===!0?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:m,ValidationError:p,schema:e.schema,schemaEnv:e,rootId:s,baseId:e.baseId||s,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?``:`#`),errorPath:(0,t._)`""`,opts:this.opts,self:this},g;try{this._compilations.add(e),(0,o.validateFunctionCode)(h),f.optimize(this.opts.code.optimize);let n=f.toString();g=`${f.scopeRefs(r.default.scope)}return ${n}`,this.opts.code.process&&(g=this.opts.code.process(g,e));let i=Function(`${r.default.self}`,`${r.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:i}),i.errors=null,i.schema=e.schema,i.schemaEnv=e,e.$async&&(i.$async=!0),this.opts.code.source===!0&&(i.source={validateName:m,validateCode:n,scopeValues:f._values}),this.opts.unevaluated){let{props:e,items:n}=h;i.evaluated={props:e instanceof t.Name?void 0:e,items:n instanceof t.Name?void 0:n,dynamicProps:e instanceof t.Name,dynamicItems:n instanceof t.Name},i.source&&(i.source.evaluated=(0,t.stringify)(i.evaluated))}return e.validate=i,e}catch(t){throw delete e.validate,delete e.validateName,g&&this.logger.error(`Error compiling schema, function code:`,g),t}finally{this._compilations.delete(e)}}e.compileSchema=c;function l(e,t,n){n=(0,i.resolveUrl)(this.opts.uriResolver,t,n);let r=e.refs[n];if(r)return r;let a=p.call(this,e,n);if(a===void 0){let r=e.localRefs?.[n],{schemaId:i}=this.opts;r&&(a=new s({schema:r,schemaId:i,root:e,baseId:t}))}if(a!==void 0)return e.refs[n]=u.call(this,a)}e.resolveRef=l;function u(e){return(0,i.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:c.call(this,e)}function d(e){for(let t of this._compilations)if(f(t,e))return t}e.getCompilingSchema=d;function f(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function p(e,t){let n;for(;typeof(n=this.refs[t])==`string`;)t=n;return n||this.schemas[t]||m.call(this,e,t)}function m(e,t){let n=this.opts.uriResolver.parse(t),r=(0,i._getFullPath)(this.opts.uriResolver,n),a=(0,i.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===a)return g.call(this,n,e);let o=(0,i.normalizeId)(r),l=this.refs[o]||this.schemas[o];if(typeof l==`string`){let t=m.call(this,e,l);return typeof t?.schema==`object`?g.call(this,n,t):void 0}if(typeof l?.schema==`object`){if(l.validate||c.call(this,l),o===(0,i.normalizeId)(t)){let{schema:t}=l,{schemaId:n}=this.opts,r=t[n];return r&&(a=(0,i.resolveUrl)(this.opts.uriResolver,a,r)),new s({schema:t,schemaId:n,root:e,baseId:a})}return g.call(this,n,l)}}e.resolveSchema=m;let h=new Set([`properties`,`patternProperties`,`enum`,`dependencies`,`definitions`]);function g(e,{baseId:t,schema:n,root:r}){if(e.fragment?.[0]!==`/`)return;for(let r of e.fragment.slice(1).split(`/`)){if(typeof n==`boolean`)return;let e=n[(0,a.unescapeFragment)(r)];if(e===void 0)return;n=e;let o=typeof n==`object`&&n[this.opts.schemaId];!h.has(r)&&o&&(t=(0,i.resolveUrl)(this.opts.uriResolver,t,o))}let o;if(typeof n!=`boolean`&&n.$ref&&!(0,a.schemaHasRulesButRef)(n,this.RULES)){let e=(0,i.resolveUrl)(this.opts.uriResolver,t,n.$ref);o=m.call(this,r,e)}let{schemaId:c}=this.opts;if(o||=new s({schema:n,schemaId:c,root:r,baseId:t}),o.schema!==o.root.schema)return o}})),Ld=o(((e,t)=>{t.exports={$id:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`,description:`Meta-schema for $data reference (JSON AnySchema extension proposal)`,type:`object`,required:[`$data`],properties:{$data:{type:`string`,anyOf:[{format:`relative-json-pointer`},{format:`json-pointer`}]}},additionalProperties:!1}})),Rd=o(((e,t)=>{let n=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function i(e){let t=``,n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r]}return t}let a=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function o(e){return e.length=0,!0}function s(e,t,n){if(e.length){let r=i(e);if(r!==``)t.push(r);else return n.error=!0,!1;e.length=0}return!0}function c(e){let t=0,n={error:!1,address:``,zone:``},r=[],a=[],c=!1,l=!1,u=s;for(let i=0;i<e.length;i++){let s=e[i];if(!(s===`[`||s===`]`))if(s===`:`){if(c===!0&&(l=!0),!u(a,r,n))break;if(++t>7){n.error=!0;break}i>0&&e[i-1]===`:`&&(c=!0),r.push(`:`);continue}else if(s===`%`){if(!u(a,r,n))break;u=o}else{a.push(s);continue}}return a.length&&(u===o?n.zone=a.join(``):l?r.push(a.join(``)):r.push(i(a))),n.address=r.join(``),n}function l(e){if(u(e,`:`)<2)return{host:e,isIPV6:!1};let t=c(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,n=t.address;return t.zone&&(e+=`%`+t.zone,n+=`%25`+t.zone),{host:e,isIPV6:!0,escapedHost:n}}}function u(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function d(e){let t=e,n=[],r=-1,i=0;for(;i=t.length;){if(i===1){if(t===`.`)break;if(t===`/`){n.push(`/`);break}else{n.push(t);break}}else if(i===2){if(t[0]===`.`){if(t[1]===`.`)break;if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&(t[1]===`.`||t[1]===`/`)){n.push(`/`);break}}else if(i===3&&t===`/..`){n.length!==0&&n.pop(),n.push(`/`);break}if(t[0]===`.`){if(t[1]===`.`){if(t[2]===`/`){t=t.slice(3);continue}}else if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&t[1]===`.`){if(t[2]===`/`){t=t.slice(2);continue}else if(t[2]===`.`&&t[3]===`/`){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf(`/`,1))===-1){n.push(t);break}else n.push(t.slice(0,r)),t=t.slice(r)}return n.join(``)}function f(e,t){let n=t===!0?unescape:escape;return e.scheme!==void 0&&(e.scheme=n(e.scheme)),e.userinfo!==void 0&&(e.userinfo=n(e.userinfo)),e.host!==void 0&&(e.host=n(e.host)),e.path!==void 0&&(e.path=n(e.path)),e.query!==void 0&&(e.query=n(e.query)),e.fragment!==void 0&&(e.fragment=n(e.fragment)),e}function p(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push(`@`)),e.host!==void 0){let n=unescape(e.host);if(!r(n)){let t=l(n);n=t.isIPV6===!0?`[${t.escapedHost}]`:e.host}t.push(n)}return(typeof e.port==`number`||typeof e.port==`string`)&&(t.push(`:`),t.push(String(e.port))),t.length?t.join(``):void 0}t.exports={nonSimpleDomain:a,recomposeAuthority:p,normalizeComponentEncoding:f,removeDotSegments:d,isIPv4:r,isUUID:n,normalizeIPv6:l,stringArrayToHexStripped:i}})),zd=o(((e,t)=>{let{isUUID:n}=Rd(),r=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,i=[`http`,`https`,`ws`,`wss`,`urn`,`urn:uuid`];function a(e){return i.indexOf(e)!==-1}function o(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]===`w`||e.scheme[0]===`W`)&&(e.scheme[1]===`s`||e.scheme[1]===`S`)&&(e.scheme[2]===`s`||e.scheme[2]===`S`):!1}function s(e){return e.host||(e.error=e.error||`HTTP URIs must have a host.`),e}function c(e){let t=String(e.scheme).toLowerCase()===`https`;return(e.port===(t?443:80)||e.port===``)&&(e.port=void 0),e.path||=`/`,e}function l(e){return e.secure=o(e),e.resourceName=(e.path||`/`)+(e.query?`?`+e.query:``),e.path=void 0,e.query=void 0,e}function u(e){if((e.port===(o(e)?443:80)||e.port===``)&&(e.port=void 0),typeof e.secure==`boolean`&&(e.scheme=e.secure?`wss`:`ws`,e.secure=void 0),e.resourceName){let[t,n]=e.resourceName.split(`?`);e.path=t&&t!==`/`?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}function d(e,t){if(!e.path)return e.error=`URN can not be parsed`,e;let n=e.path.match(r);if(n){let r=t.scheme||e.scheme||`urn`;e.nid=n[1].toLowerCase(),e.nss=n[2];let i=S(`${r}:${t.nid||e.nid}`);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||`URN can not be parsed.`;return e}function f(e,t){if(e.nid===void 0)throw Error(`URN without nid cannot be serialized`);let n=t.scheme||e.scheme||`urn`,r=e.nid.toLowerCase(),i=S(`${n}:${t.nid||r}`);i&&(e=i.serialize(e,t));let a=e,o=e.nss;return a.path=`${r||t.nid}:${o}`,t.skipEscape=!0,a}function p(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!n(r.uuid))&&(r.error=r.error||`UUID is not valid.`),r}function m(e){let t=e;return t.nss=(e.uuid||``).toLowerCase(),t}let h={scheme:`http`,domainHost:!0,parse:s,serialize:c},g={scheme:`https`,domainHost:h.domainHost,parse:s,serialize:c},_={scheme:`ws`,domainHost:!0,parse:l,serialize:u},v={scheme:`wss`,domainHost:_.domainHost,parse:_.parse,serialize:_.serialize},y={scheme:`urn`,parse:d,serialize:f,skipNormalize:!0},b={scheme:`urn:uuid`,parse:p,serialize:m,skipNormalize:!0},x={http:h,https:g,ws:_,wss:v,urn:y,"urn:uuid":b};Object.setPrototypeOf(x,null);function S(e){return e&&(x[e]||x[e.toLowerCase()])||void 0}t.exports={wsIsSecure:o,SCHEMES:x,isValidSchemeName:a,getSchemeHandler:S}})),Bd=o(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizeComponentEncoding:a,isIPv4:o,nonSimpleDomain:s}=Rd(),{SCHEMES:c,getSchemeHandler:l}=zd();function u(e,t){return typeof e==`string`?e=m(g(e,t),t):typeof e==`object`&&(e=g(m(e,t),t)),e}function d(e,t,n){let r=n?Object.assign({scheme:`null`},n):{scheme:`null`},i=f(g(e,r),g(t,r),r,!0);return r.skipEscape=!0,m(i,r)}function f(e,t,n,i){let a={};return i||(e=g(m(e,n),n),t=g(m(t,n),n)),n||={},!n.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.path?(t.path[0]===`/`?a.path=r(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?a.path=`/`+t.path:e.path?a.path=e.path.slice(0,e.path.lastIndexOf(`/`)+1)+t.path:a.path=t.path,a.path=r(a.path)),a.query=t.query):(a.path=e.path,t.query===void 0?a.query=e.query:a.query=t.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function p(e,t,n){return typeof e==`string`?(e=unescape(e),e=m(a(g(e,n),!0),{...n,skipEscape:!0})):typeof e==`object`&&(e=m(a(e,!0),{...n,skipEscape:!0})),typeof t==`string`?(t=unescape(t),t=m(a(g(t,n),!0),{...n,skipEscape:!0})):typeof t==`object`&&(t=m(a(t,!0),{...n,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}function m(e,t){let n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:``},a=Object.assign({},t),o=[],s=l(a.scheme||n.scheme);s&&s.serialize&&s.serialize(n,a),n.path!==void 0&&(a.skipEscape?n.path=unescape(n.path):(n.path=escape(n.path),n.scheme!==void 0&&(n.path=n.path.split(`%3A`).join(`:`)))),a.reference!==`suffix`&&n.scheme&&o.push(n.scheme,`:`);let c=i(n);if(c!==void 0&&(a.reference!==`suffix`&&o.push(`//`),o.push(c),n.path&&n.path[0]!==`/`&&o.push(`/`)),n.path!==void 0){let e=n.path;!a.absolutePath&&(!s||!s.absolutePath)&&(e=r(e)),c===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),o.push(e)}return n.query!==void 0&&o.push(`?`,n.query),n.fragment!==void 0&&o.push(`#`,n.fragment),o.join(``)}let h=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function g(e,t){let r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:``,port:void 0,path:``,query:void 0,fragment:void 0},a=!1;r.reference===`suffix`&&(e=r.scheme?r.scheme+`:`+e:`//`+e);let c=e.match(h);if(c){if(i.scheme=c[1],i.userinfo=c[3],i.host=c[4],i.port=parseInt(c[5],10),i.path=c[6]||``,i.query=c[7],i.fragment=c[8],isNaN(i.port)&&(i.port=c[5]),i.host)if(o(i.host)===!1){let e=n(i.host);i.host=e.host.toLowerCase(),a=e.isIPV6}else a=!0;i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path?i.reference=`same-document`:i.scheme===void 0?i.reference=`relative`:i.fragment===void 0?i.reference=`absolute`:i.reference=`uri`,r.reference&&r.reference!==`suffix`&&r.reference!==i.reference&&(i.error=i.error||`URI is not a `+r.reference+` reference.`);let t=l(r.scheme||i.scheme);if(!r.unicodeSupport&&(!t||!t.unicodeSupport)&&i.host&&(r.domainHost||t&&t.domainHost)&&a===!1&&s(i.host))try{i.host=URL.domainToASCII(i.host.toLowerCase())}catch(e){i.error=i.error||`Host's domain name can not be converted to ASCII: `+e}(!t||t&&!t.skipNormalize)&&(e.indexOf(`%`)!==-1&&(i.scheme!==void 0&&(i.scheme=unescape(i.scheme)),i.host!==void 0&&(i.host=unescape(i.host))),i.path&&=escape(unescape(i.path)),i.fragment&&=encodeURI(decodeURIComponent(i.fragment))),t&&t.parse&&t.parse(i,r)}else i.error=i.error||`URI can not be parsed.`;return i}let _={SCHEMES:c,normalize:u,resolve:d,resolveComponent:f,equal:p,serialize:m,parse:g};t.exports=_,t.exports.default=_,t.exports.fastUri=_})),Vd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Bd();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),Hd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Nd();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return t.KeywordCxt}});var n=Z();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return n.CodeGen}});let r=Pd(),i=Fd(),a=Cd(),o=Id(),s=Z(),c=Md(),l=Td(),u=yd(),d=Ld(),f=Vd(),p=(e,t)=>new RegExp(e,t);p.code=`new RegExp`;let m=[`removeAdditional`,`useDefaults`,`coerceTypes`],h=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),g={errorDataPath:``,format:"`validateFormats: false` can be used instead.",nullable:`"nullable" keyword is supported by default.`,jsonPointers:`Deprecated jsPropertySyntax can be used instead.`,extendRefs:`Deprecated ignoreKeywordsWithRef can be used instead.`,missingRefs:`Pass empty schema with $id that should be ignored to ajv.addSchema.`,processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:`"uniqueItems" keyword is always validated.`,unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:`Map is used as cache, schema object as key.`,serialize:`Map is used as cache, schema object as key.`,ajvErrors:`It is default now.`},_={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`};function v(e){let t=e.strict,n=e.code?.optimize,r=n===!0||n===void 0?1:n||0,i=e.code?.regExp??p,a=e.uriResolver??f.default;return{strictSchema:e.strictSchema??t??!0,strictNumbers:e.strictNumbers??t??!0,strictTypes:e.strictTypes??t??`log`,strictTuples:e.strictTuples??t??`log`,strictRequired:e.strictRequired??t??!1,code:e.code?{...e.code,optimize:r,regExp:i}:{optimize:r,regExp:i},loopRequired:e.loopRequired??200,loopEnum:e.loopEnum??200,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:a}}var y=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...v(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:h,es5:t,lines:n}),this.logger=D(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),b.call(this,g,e,`NOT SUPPORTED`),b.call(this,_,e,`DEPRECATED`,`warn`),this._metaOpts=T.call(this),e.formats&&C.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&w.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),S.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,r=d;n===`id`&&(r={...d},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let n;if(typeof e==`string`){if(n=this.getSchema(e),!n)throw Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let r=n(t);return`$async`in n||(this.errors=n.errors),r}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await a.call(this,e.$schema);let n=this._addSchema(e,t);return n.validate||o.call(this,n)}async function a(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return s.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function s({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){let n=await l.call(this,e);this.refs[e]||await a.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function l(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,n,r);return this}let i;if(typeof e==`object`){let{schemaId:t}=this.opts;if(i=e[t],i!==void 0&&typeof i!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!=`string`)throw Error(`$schema must be a string`);if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn(`meta-schema not available`),this.errors=null,!0;let r=this.validate(n,e);if(!r&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return r}getSchema(e){let t;for(;typeof(t=x.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:n}=this.opts,r=new o.SchemaEnv({schema:{},schemaId:n});if(t=o.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=x.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e==`string`)n=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=n);else if(typeof e==`object`&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(k.call(this,n,t),!t)return(0,u.eachItem)(n,e=>A.call(this,e)),this;M.call(this,t);let r={...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)};return(0,u.eachItem)(n,r.type.length===0?e=>A.call(this,e,r):e=>r.type.forEach(t=>A.call(this,e,r,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:n=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of t){let t=r.split(`/`).slice(1),i=e;for(let e of t)i=i[e];for(let e in n){let t=n[e];if(typeof t!=`object`)continue;let{$data:r}=t.definition,a=i[e];r&&a&&(i[e]=N(a))}}return e}_removeAllSchemas(e,t){for(let n in e){let r=e[n];(!t||t.test(n))&&(typeof r==`string`?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof e==`object`)a=e[s];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let l=this._cache.get(e);if(l!==void 0)return l;n=(0,c.normalizeId)(a||n);let u=c.getSchemaRefs.call(this,e,n);return l=new o.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:n,localRefs:u}),this._cache.set(l.schema,l),i&&!n.startsWith(`#`)&&(n&&this._checkUnique(n),this.refs[n]=l),r&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):o.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,e)}finally{this.opts=t}}};y.ValidationError=r.default,y.MissingRefError=i.default,e.default=y;function b(e,t,n,r=`error`){for(let i in e){let a=i;a in t&&this.logger[r](`${n}: option ${i}. ${e[a]}`)}}function x(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function S(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function C(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function w(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let n=e[t];n.keyword||=t,this.addKeyword(n)}}function T(){let e={...this.opts};for(let t of m)delete e[t];return e}let E={log(){},warn(){},error(){}};function D(e){if(e===!1)return E;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}let O=/^[a-z_$][a-z0-9_$:-]*$/i;function k(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!O.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function A(e,t,n){var r;let i=t?.post;if(n&&i)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:a}=this,o=i?a.post:a.rules.find(({type:e})=>e===n);if(o||(o={type:n,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?j.call(this,o,s,t.before):o.rules.push(s),a.all[e]=s,(r=t.implements)==null||r.forEach(e=>this.addKeyword(e))}function j(e,t,n){let r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function M(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=N(t)),e.validateSchema=this.compile(t,!0))}let ee={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function N(e){return{anyOf:[e,ee]}}})),Ud=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),Wd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.callRef=e.getValidate=void 0;let t=Fd(),n=Dd(),r=Z(),i=bd(),a=Id(),o=yd(),s={keyword:`$ref`,schemaType:`string`,code(e){let{gen:n,schema:i,it:o}=e,{baseId:s,schemaEnv:u,validateName:d,opts:f,self:p}=o,{root:m}=u;if((i===`#`||i===`#/`)&&s===m.baseId)return g();let h=a.resolveRef.call(p,m,s,i);if(h===void 0)throw new t.default(o.opts.uriResolver,s,i);if(h instanceof a.SchemaEnv)return _(h);return v(h);function g(){if(u===m)return l(e,d,u,u.$async);let t=n.scopeValue(`root`,{ref:m});return l(e,(0,r._)`${t}.validate`,m,m.$async)}function _(t){l(e,c(e,t),t,t.$async)}function v(t){let a=n.scopeValue(`schema`,f.code.source===!0?{ref:t,code:(0,r.stringify)(t)}:{ref:t}),o=n.name(`valid`),s=e.subschema({schema:t,dataTypes:[],schemaPath:r.nil,topSchemaRef:a,errSchemaPath:i},o);e.mergeEvaluated(s),e.ok(o)}}};function c(e,t){let{gen:n}=e;return t.validate?n.scopeValue(`validate`,{ref:t.validate}):(0,r._)`${n.scopeValue(`wrapper`,{ref:t})}.validate`}e.getValidate=c;function l(e,t,a,s){let{gen:c,it:l}=e,{allErrors:u,schemaEnv:d,opts:f}=l,p=f.passContext?i.default.this:r.nil;s?m():h();function m(){if(!d.$async)throw Error(`async schema referenced by sync schema`);let i=c.let(`valid`);c.try(()=>{c.code((0,r._)`await ${(0,n.callValidateCode)(e,t,p)}`),_(t),u||c.assign(i,!0)},e=>{c.if((0,r._)`!(${e} instanceof ${l.ValidationError})`,()=>c.throw(e)),g(e),u||c.assign(i,!1)}),e.ok(i)}function h(){e.result((0,n.callValidateCode)(e,t,p),()=>_(t),()=>g(t))}function g(e){let t=(0,r._)`${e}.errors`;c.assign(i.default.vErrors,(0,r._)`${i.default.vErrors} === null ? ${t} : ${i.default.vErrors}.concat(${t})`),c.assign(i.default.errors,(0,r._)`${i.default.vErrors}.length`)}function _(e){if(!l.opts.unevaluated)return;let t=a?.validate?.evaluated;if(l.props!==!0)if(t&&!t.dynamicProps)t.props!==void 0&&(l.props=o.mergeEvaluated.props(c,t.props,l.props));else{let t=c.var(`props`,(0,r._)`${e}.evaluated.props`);l.props=o.mergeEvaluated.props(c,t,l.props,r.Name)}if(l.items!==!0)if(t&&!t.dynamicItems)t.items!==void 0&&(l.items=o.mergeEvaluated.items(c,t.items,l.items));else{let t=c.var(`items`,(0,r._)`${e}.evaluated.items`);l.items=o.mergeEvaluated.items(c,t,l.items,r.Name)}}}e.callRef=l,e.default=s})),Gd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Ud(),n=Wd();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),Kd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z(),n=t.operators,r={maximum:{okStr:`<=`,ok:n.LTE,fail:n.GT},minimum:{okStr:`>=`,ok:n.GTE,fail:n.LT},exclusiveMaximum:{okStr:`<`,ok:n.LT,fail:n.GTE},exclusiveMinimum:{okStr:`>`,ok:n.GT,fail:n.LTE}};e.default={keyword:Object.keys(r),type:`number`,schemaType:`number`,$data:!0,error:{message:({keyword:e,schemaCode:n})=>(0,t.str)`must be ${r[e].okStr} ${n}`,params:({keyword:e,schemaCode:n})=>(0,t._)`{comparison: ${r[e].okStr}, limit: ${n}}`},code(e){let{keyword:n,data:i,schemaCode:a}=e;e.fail$data((0,t._)`${i} ${r[n].fail} ${a} || isNaN(${i})`)}}})),qd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z();e.default={keyword:`multipleOf`,type:`number`,schemaType:`number`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,t._)`{multipleOf: ${e}}`},code(e){let{gen:n,data:r,schemaCode:i,it:a}=e,o=a.opts.multipleOfPrecision,s=n.let(`res`),c=o?(0,t._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,t._)`${s} !== parseInt(${s})`;e.fail$data((0,t._)`(${i} === 0 || (${s} = ${r}/${i}, ${c}))`)}}})),Jd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});function t(e){let t=e.length,n=0,r=0,i;for(;r<t;)n++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<t&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return n}e.default=t,t.code=`require("ajv/dist/runtime/ucs2length").default`})),Yd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z(),n=yd(),r=Jd();e.default={keyword:[`maxLength`,`minLength`],type:`string`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxLength`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} characters`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:i,data:a,schemaCode:o,it:s}=e,c=i===`maxLength`?t.operators.GT:t.operators.LT,l=s.opts.unicode===!1?(0,t._)`${a}.length`:(0,t._)`${(0,n.useFunc)(e.gen,r.default)}(${a})`;e.fail$data((0,t._)`${l} ${c} ${o}`)}}})),Xd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Dd(),n=yd(),r=Z();e.default={keyword:`pattern`,type:`string`,schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,r._)`{pattern: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e,u=l.opts.unicodeRegExp?`u`:``;if(o){let{regExp:t}=l.opts.code,o=t.code===`new RegExp`?(0,r._)`new RegExp`:(0,n.useFunc)(i,t),s=i.let(`valid`);i.try(()=>i.assign(s,(0,r._)`${o}(${c}, ${u}).test(${a})`),()=>i.assign(s,!1)),e.fail$data((0,r._)`!${s}`)}else{let n=(0,t.usePattern)(e,s);e.fail$data((0,r._)`!${n}.test(${a})`)}}}})),Zd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z();e.default={keyword:[`maxProperties`,`minProperties`],type:`object`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxProperties`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} properties`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxProperties`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`Object.keys(${r}).length ${a} ${i}`)}}})),Qd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Dd(),n=Z(),r=yd();e.default={keyword:`required`,type:`object`,schemaType:`array`,$data:!0,error:{message:({params:{missingProperty:e}})=>(0,n.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,n._)`{missingProperty: ${e}}`},code(e){let{gen:i,schema:a,schemaCode:o,data:s,$data:c,it:l}=e,{opts:u}=l;if(!c&&a.length===0)return;let d=a.length>=u.loopRequired;if(l.allErrors?f():p(),u.strictRequired){let t=e.parentSchema.properties,{definedProperties:n}=e.it;for(let e of a)if(t?.[e]===void 0&&!n.has(e)){let t=`required property "${e}" is not defined at "${l.schemaEnv.baseId+l.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(l,t,l.opts.strictRequired)}}function f(){if(d||c)e.block$data(n.nil,m);else for(let n of a)(0,t.checkReportMissingProp)(e,n)}function p(){let n=i.let(`missing`);if(d||c){let t=i.let(`valid`,!0);e.block$data(t,()=>h(n,t)),e.ok(t)}else i.if((0,t.checkMissingProp)(e,a,n)),(0,t.reportMissingProp)(e,n),i.else()}function m(){i.forOf(`prop`,o,n=>{e.setParams({missingProperty:n}),i.if((0,t.noPropertyInData)(i,s,n,u.ownProperties),()=>e.error())})}function h(r,a){e.setParams({missingProperty:r}),i.forOf(r,o,()=>{i.assign(a,(0,t.propertyInData)(i,s,r,u.ownProperties)),i.if((0,n.not)(a),()=>{e.error(),i.break()})},n.nil)}}}})),$d=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z();e.default={keyword:[`maxItems`,`minItems`],type:`array`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxItems`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} items`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxItems`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`${r}.length ${a} ${i}`)}}})),ef=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Ad();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),tf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Td(),n=Z(),r=yd(),i=ef();e.default={keyword:`uniqueItems`,type:`array`,schemaType:`boolean`,$data:!0,error:{message:({params:{i:e,j:t}})=>(0,n.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,n._)`{i: ${e}, j: ${t}}`},code(e){let{gen:a,data:o,$data:s,schema:c,parentSchema:l,schemaCode:u,it:d}=e;if(!s&&!c)return;let f=a.let(`valid`),p=l.items?(0,t.getSchemaTypes)(l.items):[];e.block$data(f,m,(0,n._)`${u} === false`),e.ok(f);function m(){let t=a.let(`i`,(0,n._)`${o}.length`),r=a.let(`j`);e.setParams({i:t,j:r}),a.assign(f,!0),a.if((0,n._)`${t} > 1`,()=>(h()?g:_)(t,r))}function h(){return p.length>0&&!p.some(e=>e===`object`||e===`array`)}function g(r,i){let s=a.name(`item`),c=(0,t.checkDataTypes)(p,s,d.opts.strictNumbers,t.DataType.Wrong),l=a.const(`indices`,(0,n._)`{}`);a.for((0,n._)`;${r}--;`,()=>{a.let(s,(0,n._)`${o}[${r}]`),a.if(c,(0,n._)`continue`),p.length>1&&a.if((0,n._)`typeof ${s} == "string"`,(0,n._)`${s} += "_"`),a.if((0,n._)`typeof ${l}[${s}] == "number"`,()=>{a.assign(i,(0,n._)`${l}[${s}]`),e.error(),a.assign(f,!1).break()}).code((0,n._)`${l}[${s}] = ${r}`)})}function _(t,s){let c=(0,r.useFunc)(a,i.default),l=a.name(`outer`);a.label(l).for((0,n._)`;${t}--;`,()=>a.for((0,n._)`${s} = ${t}; ${s}--;`,()=>a.if((0,n._)`${c}(${o}[${t}], ${o}[${s}])`,()=>{e.error(),a.assign(f,!1).break(l)})))}}}})),nf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z(),n=yd(),r=ef();e.default={keyword:`const`,$data:!0,error:{message:`must be equal to constant`,params:({schemaCode:e})=>(0,t._)`{allowedValue: ${e}}`},code(e){let{gen:i,data:a,$data:o,schemaCode:s,schema:c}=e;o||c&&typeof c==`object`?e.fail$data((0,t._)`!${(0,n.useFunc)(i,r.default)}(${a}, ${s})`):e.fail((0,t._)`${c} !== ${a}`)}}})),rf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z(),n=yd(),r=ef();e.default={keyword:`enum`,schemaType:`array`,$data:!0,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e;if(!o&&s.length===0)throw Error(`enum must have non-empty array`);let u=s.length>=l.opts.loopEnum,d,f=()=>d??=(0,n.useFunc)(i,r.default),p;if(u||o)p=i.let(`valid`),e.block$data(p,m);else{if(!Array.isArray(s))throw Error(`ajv implementation error`);let e=i.const(`vSchema`,c);p=(0,t.or)(...s.map((t,n)=>h(e,n)))}e.pass(p);function m(){i.assign(p,!1),i.forOf(`v`,c,e=>i.if((0,t._)`${f()}(${a}, ${e})`,()=>i.assign(p,!0).break()))}function h(e,n){let r=s[n];return typeof r==`object`&&r?(0,t._)`${f()}(${a}, ${e}[${n}])`:(0,t._)`${a} === ${r}`}}}})),af=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Kd(),n=qd(),r=Yd(),i=Xd(),a=Zd(),o=Qd(),s=$d(),c=tf(),l=nf(),u=rf();e.default=[t.default,n.default,r.default,i.default,a.default,o.default,s.default,c.default,{keyword:`type`,schemaType:[`string`,`array`]},{keyword:`nullable`,schemaType:`boolean`},l.default,u.default]})),of=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateAdditionalItems=void 0;let t=Z(),n=yd(),r={keyword:`additionalItems`,type:`array`,schemaType:[`boolean`,`object`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{parentSchema:t,it:r}=e,{items:a}=t;if(!Array.isArray(a)){(0,n.checkStrictMode)(r,`"additionalItems" is ignored when "items" is not an array of schemas`);return}i(e,a)}};function i(e,r){let{gen:i,schema:a,data:o,keyword:s,it:c}=e;c.items=!0;let l=i.const(`len`,(0,t._)`${o}.length`);if(a===!1)e.setParams({len:r.length}),e.pass((0,t._)`${l} <= ${r.length}`);else if(typeof a==`object`&&!(0,n.alwaysValidSchema)(c,a)){let n=i.var(`valid`,(0,t._)`${l} <= ${r.length}`);i.if((0,t.not)(n),()=>u(n)),e.ok(n)}function u(a){i.forRange(`i`,r.length,l,r=>{e.subschema({keyword:s,dataProp:r,dataPropType:n.Type.Num},a),c.allErrors||i.if((0,t.not)(a),()=>i.break())})}}e.validateAdditionalItems=i,e.default=r})),sf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateTuple=void 0;let t=Z(),n=yd(),r=Dd(),i={keyword:`items`,type:`array`,schemaType:[`object`,`array`,`boolean`],before:`uniqueItems`,code(e){let{schema:t,it:i}=e;if(Array.isArray(t))return a(e,`additionalItems`,t);i.items=!0,!(0,n.alwaysValidSchema)(i,t)&&e.ok((0,r.validateArray)(e))}};function a(e,r,i=e.schema){let{gen:a,parentSchema:o,data:s,keyword:c,it:l}=e;f(o),l.opts.unevaluated&&i.length&&l.items!==!0&&(l.items=n.mergeEvaluated.items(a,i.length,l.items));let u=a.name(`valid`),d=a.const(`len`,(0,t._)`${s}.length`);i.forEach((r,i)=>{(0,n.alwaysValidSchema)(l,r)||(a.if((0,t._)`${d} > ${i}`,()=>e.subschema({keyword:c,schemaProp:i,dataProp:i},u)),e.ok(u))});function f(e){let{opts:t,errSchemaPath:a}=l,o=i.length,s=o===e.minItems&&(o===e.maxItems||e[r]===!1);if(t.strictTuples&&!s){let e=`"${c}" is ${o}-tuple, but minItems or maxItems/${r} are not specified or different at path "${a}"`;(0,n.checkStrictMode)(l,e,t.strictTuples)}}}e.validateTuple=a,e.default=i})),cf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=sf();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),lf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z(),n=yd(),r=Dd(),i=of();e.default={keyword:`items`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{schema:t,parentSchema:a,it:o}=e,{prefixItems:s}=a;o.items=!0,!(0,n.alwaysValidSchema)(o,t)&&(s?(0,i.validateAdditionalItems)(e,s):e.ok((0,r.validateArray)(e)))}}})),uf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z(),n=yd();e.default={keyword:`contains`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,trackErrors:!0,error:{message:({params:{min:e,max:n}})=>n===void 0?(0,t.str)`must contain at least ${e} valid item(s)`:(0,t.str)`must contain at least ${e} and no more than ${n} valid item(s)`,params:({params:{min:e,max:n}})=>n===void 0?(0,t._)`{minContains: ${e}}`:(0,t._)`{minContains: ${e}, maxContains: ${n}}`},code(e){let{gen:r,schema:i,parentSchema:a,data:o,it:s}=e,c,l,{minContains:u,maxContains:d}=a;s.opts.next?(c=u===void 0?1:u,l=d):c=1;let f=r.const(`len`,(0,t._)`${o}.length`);if(e.setParams({min:c,max:l}),l===void 0&&c===0){(0,n.checkStrictMode)(s,`"minContains" == 0 without "maxContains": "contains" keyword ignored`);return}if(l!==void 0&&c>l){(0,n.checkStrictMode)(s,`"minContains" > "maxContains" is always invalid`),e.fail();return}if((0,n.alwaysValidSchema)(s,i)){let n=(0,t._)`${f} >= ${c}`;l!==void 0&&(n=(0,t._)`${n} && ${f} <= ${l}`),e.pass(n);return}s.items=!0;let p=r.name(`valid`);l===void 0&&c===1?h(p,()=>r.if(p,()=>r.break())):c===0?(r.let(p,!0),l!==void 0&&r.if((0,t._)`${o}.length > 0`,m)):(r.let(p,!1),m()),e.result(p,()=>e.reset());function m(){let e=r.name(`_valid`),t=r.let(`count`,0);h(e,()=>r.if(e,()=>g(t)))}function h(t,i){r.forRange(`i`,0,f,r=>{e.subschema({keyword:`contains`,dataProp:r,dataPropType:n.Type.Num,compositeRule:!0},t),i()})}function g(e){r.code((0,t._)`${e}++`),l===void 0?r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0).break()):(r.if((0,t._)`${e} > ${l}`,()=>r.assign(p,!1).break()),c===1?r.assign(p,!0):r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0)))}}}})),df=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=Z(),n=yd(),r=Dd();e.error={message:({params:{property:e,depsCount:n,deps:r}})=>{let i=n===1?`property`:`properties`;return(0,t.str)`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:n,deps:r,missingProperty:i}})=>(0,t._)`{property: ${e},
|
|
133
133
|
missingProperty: ${i},
|
|
134
134
|
depsCount: ${n},
|
|
135
|
-
deps: ${r}}`};let i={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,n]=a(e);o(e,t),s(e,n)}};function a({schema:e}){let t={},n={};for(let r in e){if(r===`__proto__`)continue;let i=Array.isArray(e[r])?t:n;i[r]=e[r]}return[t,n]}function o(e,n=e.schema){let{gen:i,data:a,it:o}=e;if(Object.keys(n).length===0)return;let s=i.let(`missing`);for(let c in n){let l=n[c];if(l.length===0)continue;let u=(0,r.propertyInData)(i,a,c,o.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(`, `)}),o.allErrors?i.if(u,()=>{for(let t of l)(0,r.checkReportMissingProp)(e,t)}):(i.if((0,t._)`${u} && (${(0,r.checkMissingProp)(e,l,s)})`),(0,r.reportMissingProp)(e,s),i.else())}}e.validatePropertyDeps=o;function s(e,t=e.schema){let{gen:i,data:a,keyword:o,it:s}=e,c=i.name(`valid`);for(let l in t)(0,n.alwaysValidSchema)(s,t[l])||(i.if((0,r.propertyInData)(i,a,l,s.opts.ownProperties),()=>{let t=e.subschema({keyword:o,schemaProp:l},c);e.mergeValidEvaluated(t,c)},()=>i.var(c,!0)),e.ok(c))}e.validateSchemaDeps=s,e.default=i})),df=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z(),n=Q();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:r,schema:i,data:a,it:o}=e;if((0,n.alwaysValidSchema)(o,i))return;let s=r.name(`valid`);r.forIn(`key`,a,n=>{e.setParams({propertyName:n}),e.subschema({keyword:`propertyNames`,data:n,dataTypes:[`string`],propertyName:n,compositeRule:!0},s),r.if((0,t.not)(s),()=>{e.error(!0),o.allErrors||r.break()})}),e.ok(s)}}})),ff=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Ed(),n=Z(),r=yd(),i=Q();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,n._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:a,schema:o,parentSchema:s,data:c,errsCount:l,it:u}=e;if(!l)throw Error(`ajv implementation error`);let{allErrors:d,opts:f}=u;if(u.props=!0,f.removeAdditional!==`all`&&(0,i.alwaysValidSchema)(u,o))return;let p=(0,t.allSchemaProperties)(s.properties),m=(0,t.allSchemaProperties)(s.patternProperties);h(),e.ok((0,n._)`${l} === ${r.default.errors}`);function h(){a.forIn(`key`,c,e=>{!p.length&&!m.length?v(e):a.if(g(e),()=>v(e))})}function g(r){let o;if(p.length>8){let e=(0,i.schemaRefOrVal)(u,s.properties,`properties`);o=(0,t.isOwnProperty)(a,e,r)}else o=p.length?(0,n.or)(...p.map(e=>(0,n._)`${r} === ${e}`)):n.nil;return m.length&&(o=(0,n.or)(o,...m.map(i=>(0,n._)`${(0,t.usePattern)(e,i)}.test(${r})`))),(0,n.not)(o)}function _(e){a.code((0,n._)`delete ${c}[${e}]`)}function v(t){if(f.removeAdditional===`all`||f.removeAdditional&&o===!1){_(t);return}if(o===!1){e.setParams({additionalProperty:t}),e.error(),d||a.break();return}if(typeof o==`object`&&!(0,i.alwaysValidSchema)(u,o)){let r=a.name(`valid`);f.removeAdditional===`failing`?(y(t,r,!1),a.if((0,n.not)(r),()=>{e.reset(),_(t)})):(y(t,r),d||a.if((0,n.not)(r),()=>a.break()))}}function y(t,n,r){let a={keyword:`additionalProperties`,dataProp:t,dataPropType:i.Type.Str};r===!1&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(a,n)}}}})),pf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Md(),n=Ed(),r=Q(),i=ff();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,parentSchema:s,data:c,it:l}=e;l.opts.removeAdditional===`all`&&s.additionalProperties===void 0&&i.default.code(new t.KeywordCxt(l,i.default,`additionalProperties`));let u=(0,n.allSchemaProperties)(o);for(let e of u)l.definedProperties.add(e);l.opts.unevaluated&&u.length&&l.props!==!0&&(l.props=r.mergeEvaluated.props(a,(0,r.toHash)(u),l.props));let d=u.filter(e=>!(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0)return;let f=a.name(`valid`);for(let t of d)p(t)?m(t):(a.if((0,n.propertyInData)(a,c,t,l.opts.ownProperties)),m(t),l.allErrors||a.else().var(f,!0),a.endIf()),e.it.definedProperties.add(t),e.ok(f);function p(e){return l.opts.useDefaults&&!l.compositeRule&&o[e].default!==void 0}function m(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},f)}}}})),mf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Ed(),n=Z(),r=Q(),i=Q();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,data:s,parentSchema:c,it:l}=e,{opts:u}=l,d=(0,t.allSchemaProperties)(o),f=d.filter(e=>(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0||f.length===d.length&&(!l.opts.unevaluated||l.props===!0))return;let p=u.strictSchema&&!u.allowMatchingProperties&&c.properties,m=a.name(`valid`);l.props!==!0&&!(l.props instanceof n.Name)&&(l.props=(0,i.evaluatedPropsToName)(a,l.props));let{props:h}=l;g();function g(){for(let e of d)p&&_(e),l.allErrors?v(e):(a.var(m,!0),v(e),a.if(m))}function _(e){for(let t in p)new RegExp(e).test(t)&&(0,r.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function v(r){a.forIn(`key`,s,o=>{a.if((0,n._)`${(0,t.usePattern)(e,r)}.test(${o})`,()=>{let t=f.includes(r);t||e.subschema({keyword:`patternProperties`,schemaProp:r,dataProp:o,dataPropType:i.Type.Str},m),l.opts.unevaluated&&h!==!0?a.assign((0,n._)`${h}[${o}]`,!0):!t&&!l.allErrors&&a.if((0,n.not)(m),()=>a.break())})})}}}})),hf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:n,schema:r,it:i}=e;if((0,t.alwaysValidSchema)(i,r)){e.fail();return}let a=n.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),gf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:Ed().validateUnion,error:{message:`must match a schema in anyOf`}}})),_f=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z(),n=Q();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:r,schema:i,parentSchema:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(o.opts.discriminator&&a.discriminator)return;let s=i,c=r.let(`valid`,!1),l=r.let(`passing`,null),u=r.name(`_valid`);e.setParams({passing:l}),r.block(d),e.result(c,()=>e.reset(),()=>e.error(!0));function d(){s.forEach((i,a)=>{let s;(0,n.alwaysValidSchema)(o,i)?r.var(u,!0):s=e.subschema({keyword:`oneOf`,schemaProp:a,compositeRule:!0},u),a>0&&r.if((0,t._)`${u} && ${c}`).assign(c,!1).assign(l,(0,t._)`[${l}, ${a}]`).else(),r.if(u,()=>{r.assign(c,!0),r.assign(l,a),s&&e.mergeEvaluated(s,t.Name)})})}}}})),vf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid`);r.forEach((n,r)=>{if((0,t.alwaysValidSchema)(i,n))return;let o=e.subschema({keyword:`allOf`,schemaProp:r},a);e.ok(a),e.mergeEvaluated(o)})}}})),yf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z(),n=Q(),r={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:r,parentSchema:a,it:o}=e;a.then===void 0&&a.else===void 0&&(0,n.checkStrictMode)(o,`"if" without "then" and "else" is ignored`);let s=i(o,`then`),c=i(o,`else`);if(!s&&!c)return;let l=r.let(`valid`,!0),u=r.name(`_valid`);if(d(),e.reset(),s&&c){let t=r.let(`ifClause`);e.setParams({ifClause:t}),r.if(u,f(`then`,t),f(`else`,t))}else s?r.if(u,f(`then`)):r.if((0,t.not)(u),f(`else`));e.pass(l,()=>e.error(!0));function d(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}function f(n,i){return()=>{let a=e.subschema({keyword:n},u);r.assign(l,u),e.mergeValidEvaluated(a,l),i?r.assign(i,(0,t._)`${n}`):e.setParams({ifClause:n})}}}};function i(e,t){let r=e.schema[t];return r!==void 0&&!(0,n.alwaysValidSchema)(e,r)}e.default=r})),bf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:n,it:r}){n.if===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "if" is ignored`)}}})),xf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=af(),n=sf(),r=of(),i=cf(),a=lf(),o=uf(),s=df(),c=ff(),l=pf(),u=mf(),d=hf(),f=gf(),p=_f(),m=vf(),h=yf(),g=bf();function _(e=!1){let _=[d.default,f.default,p.default,m.default,h.default,g.default,s.default,c.default,o.default,l.default,u.default];return e?_.push(n.default,i.default):_.push(t.default,r.default),_.push(a.default),_}e.default=_})),Sf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,n){let{gen:r,data:i,$data:a,schema:o,schemaCode:s,it:c}=e,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;a?p():m();function p(){let a=r.scopeValue(`formats`,{ref:f.formats,code:l.code.formats}),o=r.const(`fDef`,(0,t._)`${a}[${s}]`),c=r.let(`fType`),u=r.let(`format`);r.if((0,t._)`typeof ${o} == "object" && !(${o} instanceof RegExp)`,()=>r.assign(c,(0,t._)`${o}.type || "string"`).assign(u,(0,t._)`${o}.validate`),()=>r.assign(c,(0,t._)`"string"`).assign(u,o)),e.fail$data((0,t.or)(p(),m()));function p(){return l.strictSchema===!1?t.nil:(0,t._)`${s} && !${u}`}function m(){let e=d.$async?(0,t._)`(${o}.async ? await ${u}(${i}) : ${u}(${i}))`:(0,t._)`${u}(${i})`,r=(0,t._)`(typeof ${u} == "function" ? ${e} : ${u}.test(${i}))`;return(0,t._)`${u} && ${u} !== true && ${c} === ${n} && !${r}`}}function m(){let a=f.formats[o];if(!a){m();return}if(a===!0)return;let[s,c,p]=h(a);s===n&&e.pass(g());function m(){if(l.strictSchema===!1){f.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function h(e){let n=e instanceof RegExp?(0,t.regexpCode)(e):l.code.formats?(0,t._)`${l.code.formats}${(0,t.getProperty)(o)}`:void 0,i=r.scopeValue(`formats`,{key:o,ref:e,code:n});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${i}.validate`]:[`string`,e,i]}function g(){if(typeof a==`object`&&!(a instanceof RegExp)&&a.async){if(!d.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${p}(${i})`}return typeof c==`function`?(0,t._)`${p}(${i})`:(0,t._)`${p}.test(${i})`}}}}})),Cf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=[Sf().default]})),wf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),Tf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Wd(),n=rf(),r=xf(),i=Cf(),a=wf();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),Ef=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),Df=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z(),n=Ef(),r=Fd(),i=Pd(),a=Q();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:n,tagName:r}})=>(0,t._)`{error: ${e}, tag: ${r}, tagValue: ${n}}`},code(e){let{gen:o,data:s,schema:c,parentSchema:l,it:u}=e,{oneOf:d}=l;if(!u.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let f=c.propertyName;if(typeof f!=`string`)throw Error(`discriminator: requires propertyName`);if(c.mapping)throw Error(`discriminator: mapping is not supported`);if(!d)throw Error(`discriminator: requires oneOf keyword`);let p=o.let(`valid`,!1),m=o.const(`tag`,(0,t._)`${s}${(0,t.getProperty)(f)}`);o.if((0,t._)`typeof ${m} == "string"`,()=>h(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:m,tagName:f})),e.ok(p);function h(){let r=_();o.if(!1);for(let e in r)o.elseIf((0,t._)`${m} === ${e}`),o.assign(p,g(r[e]));o.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:m,tagName:f}),o.endIf()}function g(n){let r=o.name(`valid`),i=e.subschema({keyword:`oneOf`,schemaProp:n},r);return e.mergeEvaluated(i,t.Name),r}function _(){let e={},t=o(l),n=!0;for(let e=0;e<d.length;e++){let c=d[e];if(c?.$ref&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){let e=c.$ref;if(c=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof r.SchemaEnv&&(c=c.schema),c===void 0)throw new i.default(u.opts.uriResolver,u.baseId,e)}let l=c?.properties?.[f];if(typeof l!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);n&&=t||o(c),s(l,e)}if(!n)throw Error(`discriminator: "${f}" must be required`);return e;function o({required:e}){return Array.isArray(e)&&e.includes(f)}function s(e,t){if(e.const)c(e.const,t);else if(e.enum)for(let n of e.enum)c(n,t);else throw Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function c(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${f}" values must be unique strings`);e[t]=n}}}}})),Of=o(((e,t)=>{t.exports={$schema:`http://json-schema.org/draft-07/schema#`,$id:`http://json-schema.org/draft-07/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:!0}})),kf=o(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let n=Vd(),r=Tf(),i=Df(),a=Of(),o=[`/properties`],s=`http://json-schema.org/draft-07/schema`;var c=class extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,s,!1),this.refs[`http://json-schema.org/schema`]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=c;var l=Md();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return l.KeywordCxt}});var u=Z();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return u.CodeGen}});var d=Nd();Object.defineProperty(e,`ValidationError`,{enumerable:!0,get:function(){return d.default}});var f=Pd();Object.defineProperty(e,`MissingRefError`,{enumerable:!0,get:function(){return f.default}})})),Af=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.checkMetadata=void 0;let t=Q(),n={keyword:`metadata`,schemaType:`object`,code(e){r(e);let{gen:n,schema:i,it:a}=e;if((0,t.alwaysValidSchema)(a,i))return;let o=n.name(`valid`);e.subschema({keyword:`metadata`,jtdMetadata:!0},o),e.ok(o)}};function r({it:e,keyword:t},n){if(e.jtdMetadata!==n)throw Error(`JTD: "${t}" cannot be used in this schema location`)}e.checkMetadata=r,e.default=n})),jf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.hasRef=void 0;let t=Fd(),n=Z(),r=Pd(),i=yd(),a=Ud(),o=Af(),s={keyword:`ref`,schemaType:`string`,code(e){(0,o.checkMetadata)(e);let{gen:s,data:l,schema:u,parentSchema:d,it:f}=e,{schemaEnv:{root:p}}=f,m=s.name(`valid`);d.nullable?(s.var(m,(0,n._)`${l} === null`),s.if((0,n.not)(m),h)):(s.var(m,!1),h()),e.ok(m);function h(){let e=p.schema.definitions?.[u];if(!e)throw new r.default(f.opts.uriResolver,``,u,`No definition ${u}`);c(e)||!f.opts.inlineRefs?g(e):_(e)}function g(r){let o=t.compileSchema.call(f.self,new t.SchemaEnv({schema:r,root:p,schemaPath:`/definitions/${u}`})),c=(0,a.getValidate)(e,o),l=s.const(`_errs`,i.default.errors);(0,a.callRef)(e,c,o,o.$async),s.assign(m,(0,n._)`${l} === ${i.default.errors}`)}function _(t){let r=s.scopeValue(`schema`,f.opts.code.source===!0?{ref:t,code:(0,n.stringify)(t)}:{ref:t});e.subschema({schema:t,dataTypes:[],schemaPath:n.nil,topSchemaRef:r,errSchemaPath:`/definitions/${u}`},m)}}};function c(e){for(let t in e){let n;if(t===`ref`||typeof(n=e[t])==`object`&&c(n))return!0}return!1}e.hasRef=c,e.default=s})),Mf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=/t|\s/i,n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,r=/^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:z|([+-]\d\d)(?::?(\d\d))?)$/i,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e,n){let r=e.split(t);return r.length===2&&o(r[0])&&s(r[1])||n&&r.length===1&&o(r[0])}e.default=a;function o(e){let t=n.exec(e);if(!t)return!1;let r=+t[1],a=+t[2],o=+t[3];return a>=1&&a<=12&&o>=1&&(o<=i[a]||a===2&&o===29&&(r%100==0?r%400==0:r%4==0))}function s(e){let t=r.exec(e);if(!t)return!1;let n=+t[1],i=+t[2],a=+t[3],o=+(t[4]||0),s=+(t[5]||0);return n<=23&&i<=59&&a<=59||n-o===23&&i-s===59&&a===60}a.code=`require("ajv/dist/runtime/timestamp").default`})),Nf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.typeErrorParams=e.typeErrorMessage=e.typeError=void 0;let t=Z();function n(e){return{message:t=>r(t,e),params:t=>i(t,e)}}e.typeError=n;function r({parentSchema:e},t){return e?.nullable?`must be ${t} or null`:`must be ${t}`}e.typeErrorMessage=r;function i({parentSchema:e},n){return(0,t._)`{type: ${n}, nullable: ${!!e?.nullable}}`}e.typeErrorParams=i})),Pf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.intRange=void 0;let t=Z(),n=Mf(),r=Q(),i=Af(),a=Nf();e.intRange={int8:[-128,127,3],uint8:[0,255,3],int16:[-32768,32767,5],uint16:[0,65535,5],int32:[-2147483648,2147483647,10],uint32:[0,4294967295,10]};let o={message:e=>(0,a.typeErrorMessage)(e,e.schema),params:e=>(0,a.typeErrorParams)(e,e.schema)};function s(e){let{gen:i,data:a,it:o}=e,{timestamp:s,allowDate:c}=o.opts;if(s===`date`)return(0,t._)`${a} instanceof Date `;let l=(0,r.useFunc)(i,n.default),u=c?(0,t._)`, true`:t.nil,d=(0,t._)`typeof ${a} == "string" && ${l}(${a}${u})`;return s===`string`?d:(0,t.or)((0,t._)`${a} instanceof Date`,d)}e.default={keyword:`type`,schemaType:`string`,error:o,code(n){(0,i.checkMetadata)(n);let{data:r,schema:a,parentSchema:o,it:c}=n,l;switch(a){case`boolean`:case`string`:l=(0,t._)`typeof ${r} == ${a}`;break;case`timestamp`:l=s(n);break;case`float32`:case`float64`:l=(0,t._)`typeof ${r} == "number"`;break;default:{let n=a;if(l=(0,t._)`typeof ${r} == "number" && isFinite(${r}) && !(${r} % 1)`,!c.opts.int32range&&(n===`int32`||n===`uint32`))n===`uint32`&&(l=(0,t._)`${l} && ${r} >= 0`);else{let[i,a]=e.intRange[n];l=(0,t._)`${l} && ${r} >= ${i} && ${r} <= ${a}`}}}n.pass(o.nullable?(0,t.or)((0,t._)`${r} === null`,l):l)}}})),Ff=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.checkNullableObject=e.checkNullable=void 0;let t=Z();function n({gen:e,data:n,parentSchema:r},i=t.nil){let a=e.name(`valid`);return r.nullable?(e.let(a,(0,t._)`${n} === null`),i=(0,t.not)(a)):e.let(a,!1),[a,i]}e.checkNullable=n;function r(e,r){let[i,a]=n(e,r);return[i,(0,t._)`${a} && typeof ${e.data} == "object" && !Array.isArray(${e.data})`]}e.checkNullableObject=r})),If=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z(),n=Af(),r=Ff();e.default={keyword:`enum`,schemaType:`array`,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){(0,n.checkMetadata)(e);let{gen:i,data:a,schema:o,schemaValue:s,parentSchema:c,it:l}=e;if(o.length===0)throw Error(`enum must have non-empty array`);if(o.length!==new Set(o).size)throw Error(`enum items must be unique`);let u,d=(0,t._)`typeof ${a} == "string"`;if(o.length>=l.opts.loopEnum){let t;[u,t]=(0,r.checkNullable)(e,d),i.if(t,f)}else{if(!Array.isArray(o))throw Error(`ajv implementation error`);u=(0,t.and)(d,(0,t.or)(...o.map(e=>(0,t._)`${a} === ${e}`))),c.nullable&&(u=(0,t.or)((0,t._)`${a} === null`,u))}e.pass(u);function f(){i.forOf(`v`,s,e=>i.if((0,t._)`${u} = ${a} === ${e}`,()=>i.break()))}}}})),Lf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q(),n=Ed(),r=Z(),i=Af(),a=Ff();e.default={keyword:`elements`,schemaType:`object`,error:(0,Nf().typeError)(`array`),code(e){(0,i.checkMetadata)(e);let{gen:o,data:s,schema:c,it:l}=e;if((0,t.alwaysValidSchema)(l,c))return;let[u]=(0,a.checkNullable)(e);o.if((0,r.not)(u),()=>o.if((0,r._)`Array.isArray(${s})`,()=>o.assign(u,(0,n.validateArray)(e)),()=>e.error())),e.ok(u)}}})),Rf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateProperties=e.error=void 0;let t=Ed(),n=Q(),r=Z(),i=Af(),a=Ff(),o=Nf();var s;(function(e){e.Additional=`additional`,e.Missing=`missing`})(s||={}),e.error={message:e=>{let{params:t}=e;return t.propError?t.propError===s.Additional?`must NOT have additional properties`:`must have property '${t.missingProperty}'`:(0,o.typeErrorMessage)(e,`object`)},params:e=>{let{params:t}=e;return t.propError?t.propError===s.Additional?(0,r._)`{error: ${t.propError}, additionalProperty: ${t.additionalProperty}}`:(0,r._)`{error: ${t.propError}, missingProperty: ${t.missingProperty}}`:(0,o.typeErrorParams)(e,`object`)}};let c={keyword:`properties`,schemaType:`object`,error:e.error,code:l};function l(e){(0,i.checkMetadata)(e);let{gen:o,data:c,parentSchema:l,it:u}=e,{additionalProperties:d,nullable:f}=l;if(u.jtdDiscriminator&&f)throw Error(`JTD: nullable inside discriminator mapping`);if(y())throw Error(`JTD: properties and optionalProperties have common members`);let[p,m]=b(`properties`),[h,g]=b(`optionalProperties`);if(m.length===0&&g.length===0&&d)return;let[_,v]=u.jtdDiscriminator===void 0?(0,a.checkNullableObject)(e,c):[o.let(`valid`,!1),!0];o.if(v,()=>o.assign(_,!0).block(()=>{x(m,`properties`,!0),x(g,`optionalProperties`),d||C()})),e.pass(_);function y(){let e=l.properties,t=l.optionalProperties;if(!(e&&t))return!1;for(let n in e)if(Object.prototype.hasOwnProperty.call(t,n))return!0;return!1}function b(e){let r=l[e],i=r?(0,t.allSchemaProperties)(r):[];if(u.jtdDiscriminator&&i.some(e=>e===u.jtdDiscriminator))throw Error(`JTD: discriminator tag used in ${e}`);return[i,i.filter(e=>!(0,n.alwaysValidSchema)(u,r[e]))]}function x(n,r,i){let a=o.var(`valid`);for(let i of n)o.if((0,t.propertyInData)(o,c,i,u.opts.ownProperties),()=>S(i,r,a),()=>l(i)),e.ok(a);function l(t){i?(o.assign(a,!1),e.error(!1,{propError:s.Missing,missingProperty:t},{schemaPath:t})):o.assign(a,!0)}}function S(t,n,r){e.subschema({keyword:n,schemaProp:t,dataProp:t},r)}function C(){o.forIn(`key`,c,t=>{let n=w(t,p,`properties`,u.jtdDiscriminator),i=w(t,h,`optionalProperties`),a=n===!0?i:i===!0?n:(0,r.and)(n,i);o.if(a,()=>{u.opts.removeAdditional?o.code((0,r._)`delete ${c}[${t}]`):(e.error(!1,{propError:s.Additional,additionalProperty:t},{instancePath:t,parentSchema:!0}),u.opts.allErrors||o.break())})})}function w(e,i,a,s){let c;if(i.length>8){let i=(0,n.schemaRefOrVal)(u,l[a],a);c=(0,r.not)((0,t.isOwnProperty)(o,i,e)),s!==void 0&&(c=(0,r.and)(c,(0,r._)`${e} !== ${s}`))}else if(i.length||s!==void 0){let t=s===void 0?i:[s].concat(i);c=(0,r.and)(...t.map(t=>(0,r._)`${e} !== ${t}`))}else c=!0;return c}}e.validateProperties=l,e.default=c})),zf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Rf();e.default={keyword:`optionalProperties`,schemaType:`object`,error:t.error,code(e){e.parentSchema.properties||(0,t.validateProperties)(e)}}})),Bf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z(),n=Af(),r=Ff(),i=Nf(),a=Ef();e.default={keyword:`discriminator`,schemaType:`string`,implements:[`mapping`],error:{message:e=>{let{schema:t,params:n}=e;return n.discrError?n.discrError===a.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in mapping`:(0,i.typeErrorMessage)(e,`object`)},params:e=>{let{schema:n,params:r}=e;return r.discrError?(0,t._)`{error: ${r.discrError}, tag: ${n}, tagValue: ${r.tag}}`:(0,i.typeErrorParams)(e,`object`)}},code(e){(0,n.checkMetadata)(e);let{gen:i,data:o,schema:s,parentSchema:c}=e,[l,u]=(0,r.checkNullableObject)(e,o);i.if(u),d(),i.elseIf((0,t.not)(l)),e.error(),i.endIf(),e.ok(l);function d(){let n=i.const(`tag`,(0,t._)`${o}${(0,t.getProperty)(s)}`);i.if((0,t._)`${n} === undefined`),e.error(!1,{discrError:a.DiscrError.Tag,tag:n}),i.elseIf((0,t._)`typeof ${n} == "string"`),f(n),i.else(),e.error(!1,{discrError:a.DiscrError.Tag,tag:n},{instancePath:s}),i.endIf()}function f(n){i.if(!1);for(let e in c.mapping)i.elseIf((0,t._)`${n} === ${e}`),i.assign(l,p(e));i.else(),e.error(!1,{discrError:a.DiscrError.Mapping,tag:n},{instancePath:s,schemaPath:`mapping`,parentSchema:!0}),i.endIf()}function p(t){let n=i.name(`valid`);return e.subschema({keyword:`mapping`,schemaProp:t,jtdDiscriminator:s},n),n}}}})),Vf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q(),n=Z(),r=Af(),i=Ff();e.default={keyword:`values`,schemaType:`object`,error:(0,Nf().typeError)(`object`),code(e){(0,r.checkMetadata)(e);let{gen:a,data:o,schema:s,it:c}=e,[l,u]=(0,i.checkNullableObject)(e,o);(0,t.alwaysValidSchema)(c,s)?a.if((0,n.not)((0,n.or)(u,l)),()=>e.error()):(a.if(u),a.assign(l,d()),a.elseIf((0,n.not)(l)),e.error(),a.endIf()),e.ok(l);function d(){let r=a.name(`valid`);if(c.allErrors){let e=a.let(`valid`,!0);return i(()=>a.assign(e,!1)),e}return a.var(r,!0),i(()=>a.break()),r;function i(i){a.forIn(`key`,o,o=>{e.subschema({keyword:`values`,dataProp:o,dataPropType:t.Type.Str},r),a.if((0,n.not)(r),i)})}}}}})),Hf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`union`,schemaType:`array`,trackErrors:!0,code:Ed().validateUnion,error:{message:`must match a schema in union`}}})),Uf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=jf(),n=Pf(),r=If(),i=Lf(),a=Rf(),o=zf(),s=Bf(),c=Vf(),l=Hf(),u=Af();e.default=[`definitions`,t.default,n.default,r.default,i.default,a.default,o.default,s.default,c.default,l.default,u.default,{keyword:`additionalProperties`,schemaType:`boolean`},{keyword:`nullable`,schemaType:`boolean`}]})),Wf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=e=>{let t={nullable:{type:`boolean`},metadata:{optionalProperties:{union:{elements:{ref:`schema`}}},additionalProperties:!0}};return e&&(t.definitions={values:{ref:`schema`}}),t},n=e=>({optionalProperties:t(e)}),r=e=>({properties:{ref:{type:`string`}},optionalProperties:t(e)}),i=e=>({properties:{type:{enum:[`boolean`,`timestamp`,`string`,`float32`,`float64`,`int8`,`uint8`,`int16`,`uint16`,`int32`,`uint32`]}},optionalProperties:t(e)}),a=e=>({properties:{enum:{elements:{type:`string`}}},optionalProperties:t(e)}),o=e=>({properties:{elements:{ref:`schema`}},optionalProperties:t(e)}),s=e=>({properties:{properties:{values:{ref:`schema`}}},optionalProperties:{optionalProperties:{values:{ref:`schema`}},additionalProperties:{type:`boolean`},...t(e)}}),c=e=>({properties:{optionalProperties:{values:{ref:`schema`}}},optionalProperties:{additionalProperties:{type:`boolean`},...t(e)}}),l=e=>({properties:{discriminator:{type:`string`},mapping:{values:{metadata:{union:[s(!1),c(!1)]}}}},optionalProperties:t(e)}),u=e=>({properties:{values:{ref:`schema`}},optionalProperties:t(e)}),d=e=>({metadata:{union:[n,r,i,a,o,s,c,l,u].map(t=>t(e))}});e.default={definitions:{schema:d(!1)},...d(!0)}})),Gf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.jtdForms=void 0,e.jtdForms=[`elements`,`values`,`discriminator`,`properties`,`optionalProperties`,`enum`,`type`,`ref`]})),Kf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=/[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n={"\b":`\\b`," ":`\\t`,"\n":`\\n`,"\f":`\\f`,"\r":`\\r`,'"':`\\"`,"\\":`\\\\`};function r(e){return t.lastIndex=0,`"`+(t.test(e)?e.replace(t,e=>{let t=n[e];return typeof t==`string`?t:`\\u`+(`0000`+e.charCodeAt(0).toString(16)).slice(-4)}):e)+`"`}e.default=r,r.code=`require("ajv/dist/runtime/quote").default`})),qf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Gf(),n=Fd(),r=Z(),i=Pd(),a=yd(),o=Ed(),s=jf(),c=Q(),l=Kf(),u={elements:m,values:h,discriminator:_,properties:v,optionalProperties:v,enum:x,type:b,ref:C};function d(e,t){let i=n.getCompilingSchema.call(this,e);if(i)return i;let{es5:o,lines:s}=this.opts.code,{ownProperties:c}=this.opts,l=new r.CodeGen(this.scope,{es5:o,lines:s,ownProperties:c}),u=l.scopeName(`serialize`),d={self:this,gen:l,schema:e.schema,schemaEnv:e,definitions:t,data:a.default.data},p;try{this._compilations.add(e),e.serializeName=u,l.func(u,a.default.data,!1,()=>{l.let(a.default.json,(0,r.str)``),f(d),l.return(a.default.json)}),l.optimize(this.opts.code.optimize);let t=l.toString();p=`${l.scopeRefs(a.default.scope)}return ${t}`;let n=Function(`${a.default.scope}`,p)(this.scope.get());this.scope.value(u,{ref:n}),e.serialize=n}catch(t){throw p&&this.logger.error(`Error compiling serializer, function code:`,p),delete e.serialize,delete e.serializeName,t}finally{this._compilations.delete(e)}return e}e.default=d;function f(e){let n;for(let r of t.jtdForms)if(r in e.schema){n=r;break}p(e,n?u[n]:T)}function p(e,t){let{gen:n,schema:i,data:o}=e;if(!i.nullable)return t(e);n.if((0,r._)`${o} === undefined || ${o} === null`,()=>n.add(a.default.json,(0,r._)`"null"`),()=>t(e))}function m(e){let{gen:t,schema:n,data:i}=e;t.add(a.default.json,(0,r.str)`[`);let o=t.let(`first`,!0);t.forOf(`el`,i,t=>{E(e,o),f({...e,schema:n.elements,data:t})}),t.add(a.default.json,(0,r.str)`]`)}function h(e){let{gen:t,schema:n,data:i}=e;t.add(a.default.json,(0,r.str)`{`);let o=t.let(`first`,!0);t.forIn(`key`,i,t=>g(e,t,n.values,o)),t.add(a.default.json,(0,r.str)`}`)}function g(e,t,n,i){let{gen:o,data:s}=e;E(e,i),x({...e,data:t}),o.add(a.default.json,(0,r.str)`:`);let c=o.const(`value`,(0,r._)`${s}${(0,r.getProperty)(t)}`);f({...e,schema:n,data:c})}function _(e){let{gen:t,schema:n,data:i}=e,{discriminator:o}=n;t.add(a.default.json,(0,r.str)`{${JSON.stringify(o)}:`);let s=t.const(`tag`,(0,r._)`${i}${(0,r.getProperty)(o)}`);x({...e,data:s}),t.if(!1);for(let i in n.mapping){t.elseIf((0,r._)`${s} === ${i}`);let a=n.mapping[i];y({...e,schema:a},o)}t.endIf(),t.add(a.default.json,(0,r.str)`}`)}function v(e){let{gen:t}=e;t.add(a.default.json,(0,r.str)`{`),y(e),t.add(a.default.json,(0,r.str)`}`)}function y(e,t){let{gen:n,schema:i,data:s}=e,{properties:c,optionalProperties:l}=i,u=_(c),d=_(l),p=v(u.concat(d)),m=!t,h;for(let e of u)m?m=!1:n.add(a.default.json,(0,r.str)`,`),b(e,c[e],y(e));m&&(h=n.let(`first`,!0));for(let t of d){let i=y(t);n.if((0,r.and)((0,r._)`${i} !== undefined`,(0,o.isOwnProperty)(n,s,t)),()=>{E(e,h),b(t,l[t],i)})}i.additionalProperties&&n.forIn(`key`,s,t=>n.if(x(t,p),()=>g(e,t,{},h)));function _(e){return e?Object.keys(e):[]}function v(e){if(t&&e.push(t),new Set(e).size!==e.length)throw Error(`JTD: properties/optionalProperties/disciminator overlap`);return e}function y(e){return n.const(`value`,(0,r._)`${s}${(0,r.getProperty)(e)}`)}function b(t,i,o){n.add(a.default.json,(0,r.str)`${JSON.stringify(t)}:`),f({...e,schema:i,data:o})}function x(e,t){return t.length?(0,r.and)(...t.map(t=>(0,r._)`${e} !== ${t}`)):!0}}function b(e){let{gen:t,schema:n,data:i}=e;switch(n.type){case`boolean`:t.add(a.default.json,(0,r._)`${i} ? "true" : "false"`);break;case`string`:x(e);break;case`timestamp`:t.if((0,r._)`${i} instanceof Date`,()=>t.add(a.default.json,(0,r._)`'"' + ${i}.toISOString() + '"'`),()=>x(e));break;default:S(e)}}function x({gen:e,data:t}){e.add(a.default.json,(0,r._)`${(0,c.useFunc)(e,l.default)}(${t})`)}function S({gen:e,data:t,self:n}){let i=(0,r._)`${t} === Infinity || ${t} === -Infinity || ${t} !== ${t}`;n.opts.specialNumbers===void 0||n.opts.specialNumbers===`fast`?e.add(a.default.json,(0,r._)`"" + ${t}`):e.if(i,()=>e.add(a.default.json,(0,r._)`null`),()=>e.add(a.default.json,(0,r._)`"" + ${t}`))}function C(e){let{gen:t,self:o,data:c,definitions:l,schema:u,schemaEnv:p}=e,{ref:m}=u,h=l[m];if(!h)throw new i.default(o.opts.uriResolver,``,m,`No definition ${m}`);if(!(0,s.hasRef)(h))return f({...e,schema:h});let{root:g}=p,_=d.call(o,new n.SchemaEnv({schema:h,root:g}),l);t.add(a.default.json,(0,r._)`${w(t,_)}(${c})`)}function w(e,t){return t.serialize?e.scopeValue(`serialize`,{ref:t.serialize}):(0,r._)`${e.scopeValue(`wrapper`,{ref:t})}.serialize`}function T({gen:e,data:t}){e.add(a.default.json,(0,r._)`JSON.stringify(${t})`)}function E({gen:e},t){t?e.if(t,()=>e.assign(t,!1),()=>e.add(a.default.json,(0,r.str)`,`)):e.add(a.default.json,(0,r.str)`,`)}})),Jf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.parseJsonString=e.parseJsonNumber=e.parseJson=void 0;let t=/position\s(\d+)(?: \(line \d+ column \d+\))?$/;function n(e,r){let i;n.message=void 0;let a;r&&(e=e.slice(r));try{return n.position=r+e.length,JSON.parse(e)}catch(o){if(a=t.exec(o.message),!a){n.message=`unexpected end`;return}i=+a[1];let s=e[i];e=e.slice(0,i),n.position=r+i;try{return JSON.parse(e)}catch{n.message=`unexpected token ${s}`;return}}}e.parseJson=n,n.message=void 0,n.position=0,n.code=`require("ajv/dist/runtime/parseJson").parseJson`;function r(e,t,n){let i=``,a;if(r.message=void 0,e[t]===`-`&&(i+=`-`,t++),e[t]===`0`)i+=`0`,t++;else if(!o(n)){s();return}if(n)return r.position=t,+i;if(e[t]===`.`&&(i+=`.`,t++,!o())){s();return}if(a=e[t],(a===`e`||a===`E`)&&(i+=`e`,t++,a=e[t],(a===`+`||a===`-`)&&(i+=a,t++),!o())){s();return}return r.position=t,+i;function o(n){let r=!1;for(;a=e[t],a>=`0`&&a<=`9`&&(n===void 0||n-- >0);)r=!0,i+=a,t++;return r}function s(){r.position=t,r.message=t<e.length?`unexpected token ${e[t]}`:`unexpected end`}}e.parseJsonNumber=r,r.message=void 0,r.position=0,r.code=`require("ajv/dist/runtime/parseJson").parseJsonNumber`;let i={b:`\b`,f:`\f`,n:`
|
|
136
|
-
`,r:`\r`,t:` `,'"':`"`,"/":`/`,"\\":`\\`};function a(e,t){let n=``,r;for(a.message=void 0;r=e[t++],r!==`"`;)if(r===`\\`)if(r=e[t],r in i)n+=i[r],t++;else if(r===`u`){t++;let i=4,a=0;for(;i--;){if(a<<=4,r=e[t],r===void 0){o(`unexpected end`);return}if(r=r.toLowerCase(),r>=`a`&&r<=`f`)a+=r.charCodeAt(0)-97+10;else if(r>=`0`&&r<=`9`)a+=r.charCodeAt(0)-48;else{o(`unexpected token ${r}`);return}t++}n+=String.fromCharCode(a)}else{o(`unexpected token ${r}`);return}else if(r===void 0){o(`unexpected end`);return}else if(r.charCodeAt(0)>=32)n+=r;else{o(`unexpected token ${r}`);return}return a.position=t,n;function o(e){a.position=t,a.message=e}}e.parseJsonString=a,a.message=void 0,a.position=0,a.code=`require("ajv/dist/runtime/parseJson").parseJsonString`})),Yf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Gf(),n=Fd(),r=Z(),i=Pd(),a=yd(),o=Ed(),s=jf(),c=Pf(),l=Jf(),u=Q(),d=Mf(),f={elements:y,values:b,discriminator:w,properties:T,optionalProperties:T,enum:j,type:k,ref:N};function p(e,t){let i=n.getCompilingSchema.call(this,e);if(i)return i;let{es5:o,lines:s}=this.opts.code,{ownProperties:c}=this.opts,l=new r.CodeGen(this.scope,{es5:o,lines:s,ownProperties:c}),u=l.scopeName(`parse`),d={self:this,gen:l,schema:e.schema,schemaEnv:e,definitions:t,data:a.default.data,parseName:u,char:l.name(`c`)},f;try{this._compilations.add(e),e.parseName=u,h(d),l.optimize(this.opts.code.optimize);let t=l.toString();f=`${l.scopeRefs(a.default.scope)}return ${t}`;let n=Function(`${a.default.scope}`,f)(this.scope.get());this.scope.value(u,{ref:n}),e.parse=n}catch(t){throw f&&this.logger.error(`Error compiling parser, function code:`,f),delete e.parse,delete e.parseName,t}finally{this._compilations.delete(e)}return e}e.default=p;let m=(0,r._)`undefined`;function h(e){let{gen:t,parseName:n,char:i}=e;t.func(n,(0,r._)`${a.default.json}, ${a.default.jsonPos}, ${a.default.jsonPart}`,!1,()=>{t.let(a.default.data),t.let(i),t.assign((0,r._)`${n}.message`,m),t.assign((0,r._)`${n}.position`,m),t.assign(a.default.jsonPos,(0,r._)`${a.default.jsonPos} || 0`),t.const(a.default.jsonLen,(0,r._)`${a.default.json}.length`),g(e),L(e),t.if(a.default.jsonPart,()=>{t.assign((0,r._)`${n}.position`,a.default.jsonPos),t.return(a.default.data)}),t.if((0,r._)`${a.default.jsonPos} === ${a.default.jsonLen}`,()=>t.return(a.default.data)),ae(e)})}function g(e){let n;for(let r of t.jtdForms)if(r in e.schema){n=r;break}n?v(e,f[n]):P(e)}let _=ee(!0,ee(!1,ae));function v(e,t){let{gen:n,schema:r,data:i}=e;if(!r.nullable)return t(e);re(e,`null`,t,()=>n.assign(i,null))}function y(e){let{gen:t,schema:n,data:i}=e;I(e,`[`);let a=t.let(`i`,0);t.assign(i,(0,r._)`[]`),x(e,`]`,()=>{let o=t.let(`el`);g({...e,schema:n.elements,data:o}),t.assign((0,r._)`${i}[${a}++]`,o)})}function b(e){let{gen:t,schema:n,data:i}=e;I(e,`{`),t.assign(i,(0,r._)`{}`),x(e,`}`,()=>C(e,n.values))}function x(e,t,n){S(e,t,n),I(e,t)}function S(e,t,n){let{gen:i}=e;i.for((0,r._)`;${a.default.jsonPos}<${a.default.jsonLen} && ${ie(1)}!==${t};`,()=>{n(),re(e,`,`,()=>i.break(),o)});function o(){re(e,t,()=>{},ae)}}function C(e,t){let{gen:n}=e,r=n.let(`key`);A({...e,data:r}),I(e,`:`),O(e,r,t)}function w(e){let{gen:t,data:n,schema:i}=e,{discriminator:o,mapping:s}=i;I(e,`{`),t.assign(n,(0,r._)`{}`);let c=t.const(`pos`,a.default.jsonPos),l=t.let(`value`),u=t.let(`tag`);S(e,`}`,()=>{let i=t.let(`key`);A({...e,data:i}),I(e,`:`),t.if((0,r._)`${i} === ${o}`,()=>{A({...e,data:u}),t.assign((0,r._)`${n}[${i}]`,u),t.break()},()=>P({...e,data:l}))}),t.assign(a.default.jsonPos,c),t.if((0,r._)`${u} === undefined`),R(e,(0,r.str)`discriminator tag not found`);for(let n in s)t.elseIf((0,r._)`${u} === ${n}`),E({...e,schema:s[n]},o);t.else(),R(e,(0,r.str)`discriminator value not in schema`),t.endIf()}function T(e){let{gen:t,data:n}=e;I(e,`{`),t.assign(n,(0,r._)`{}`),E(e)}function E(e,t){let{gen:n,schema:i,data:a}=e,{properties:s,optionalProperties:c,additionalProperties:l}=i;if(x(e,`}`,()=>{let i=n.let(`key`);if(A({...e,data:i}),I(e,`:`),n.if(!1),D(e,i,s),D(e,i,c),t){n.elseIf((0,r._)`${i} === ${t}`);let a=n.let(`tag`);A({...e,data:a})}n.else(),l?P({...e,data:(0,r._)`${a}[${i}]`}):R(e,(0,r.str)`property ${i} not allowed`),n.endIf()}),s){let t=(0,o.hasPropFunc)(n),i=(0,r.and)(...Object.keys(s).map(e=>(0,r._)`${t}.call(${a}, ${e})`));n.if((0,r.not)(i),()=>R(e,(0,r.str)`missing required properties`))}}function D(e,t,n={}){let{gen:i}=e;for(let a in n)i.elseIf((0,r._)`${t} === ${a}`),O(e,t,n[a])}function O(e,t,n){g({...e,schema:n,data:(0,r._)`${e.data}[${t}]`})}function k(e){let{gen:t,schema:n,data:i,self:a}=e;switch(n.type){case`boolean`:_(e);break;case`string`:A(e);break;case`timestamp`:{A(e);let n=(0,u.useFunc)(t,d.default),{allowDate:o,parseDate:s}=a.opts,c=o?(0,r._)`!${n}(${i}, true)`:(0,r._)`!${n}(${i})`,l=s?(0,r.or)(c,(0,r._)`(${i} = new Date(${i}), false)`,(0,r._)`isNaN(${i}.valueOf())`):c;t.if(l,()=>R(e,(0,r.str)`invalid timestamp`));break}case`float32`:case`float64`:M(e);break;default:{let o=n.type;if(!a.opts.int32range&&(o===`int32`||o===`uint32`))M(e,16),o===`uint32`&&t.if((0,r._)`${i} < 0`,()=>R(e,(0,r.str)`integer out of range`));else{let[n,a,s]=c.intRange[o];M(e,s),t.if((0,r._)`${i} < ${n} || ${i} > ${a}`,()=>R(e,(0,r.str)`integer out of range`))}}}}function A(e){I(e,`"`),ne(e,l.parseJsonString)}function j(e){let{gen:t,data:n,schema:i}=e,o=i.enum;I(e,`"`),t.if(!1);for(let e of o){let i=JSON.stringify(e).slice(1);t.elseIf((0,r._)`${ie(i.length)} === ${i}`),t.assign(n,(0,r.str)`${e}`),t.add(a.default.jsonPos,i.length)}t.else(),ae(e),t.endIf()}function M(e,t){let{gen:n}=e;L(e),n.if((0,r._)`"-0123456789".indexOf(${ie(1)}) < 0`,()=>ae(e),()=>ne(e,l.parseJsonNumber,t))}function ee(e,t){return n=>{let{gen:r,data:i}=n;re(n,`${e}`,()=>t(n),()=>r.assign(i,e))}}function N(e){let{gen:t,self:r,definitions:a,schema:o,schemaEnv:c}=e,{ref:l}=o,u=a[l];if(!u)throw new i.default(r.opts.uriResolver,``,l,`No definition ${l}`);if(!(0,s.hasRef)(u))return g({...e,schema:u});let{root:d}=c;F(e,te(t,p.call(r,new n.SchemaEnv({schema:u,root:d}),a)),!0)}function te(e,t){return t.parse?e.scopeValue(`parse`,{ref:t.parse}):(0,r._)`${e.scopeValue(`wrapper`,{ref:t})}.parse`}function P(e){ne(e,l.parseJson)}function ne(e,t,n){F(e,(0,u.useFunc)(e.gen,t),n)}function F(e,t,n){let{gen:i,data:o}=e;i.assign(o,(0,r._)`${t}(${a.default.json}, ${a.default.jsonPos}${n?(0,r._)`, ${n}`:r.nil})`),i.assign(a.default.jsonPos,(0,r._)`${t}.position`),i.if((0,r._)`${o} === undefined`,()=>R(e,(0,r._)`${t}.message`))}function I(e,t){re(e,t,ae)}function re(e,t,n,i){let{gen:o}=e,s=t.length;L(e),o.if((0,r._)`${ie(s)} === ${t}`,()=>{o.add(a.default.jsonPos,s),i?.(e)},()=>n(e))}function L({gen:e,char:t}){e.code((0,r._)`while((${t}=${a.default.json}[${a.default.jsonPos}],${t}===" "||${t}==="\\n"||${t}==="\\r"||${t}==="\\t"))${a.default.jsonPos}++;`)}function ie(e){return e===1?(0,r._)`${a.default.json}[${a.default.jsonPos}]`:(0,r._)`${a.default.json}.slice(${a.default.jsonPos}, ${a.default.jsonPos}+${e})`}function ae(e){R(e,(0,r._)`"unexpected token " + ${a.default.json}[${a.default.jsonPos}]`)}function R({gen:e,parseName:t},n){e.assign((0,r._)`${t}.message`,n),e.assign((0,r._)`${t}.position`,a.default.jsonPos),e.return(m)}})),Xf=o(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let n=Vd(),r=Uf(),i=Wf(),a=qf(),o=Yf(),s=`JTD-meta-schema`;var c=class extends n.default{constructor(e={}){super({...e,jtd:!0})}_addVocabularies(){super._addVocabularies(),this.addVocabulary(r.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema(),this.opts.meta&&this.addMetaSchema(i.default,s,!1)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}compileSerializer(e){let t=this._addSchema(e);return t.serialize||this._compileSerializer(t)}compileParser(e){let t=this._addSchema(e);return t.parse||this._compileParser(t)}_compileSerializer(e){if(a.default.call(this,e,e.schema.definitions||{}),!e.serialize)throw Error(`ajv implementation error`);return e.serialize}_compileParser(e){if(o.default.call(this,e,e.schema.definitions||{}),!e.parse)throw Error(`ajv implementation error`);return e.parse}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=c;var l=Md();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return l.KeywordCxt}});var u=Z();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return u.CodeGen}});var d=Nd();Object.defineProperty(e,`ValidationError`,{enumerable:!0,get:function(){return d.default}});var f=Pd();Object.defineProperty(e,`MissingRefError`,{enumerable:!0,get:function(){return f.default}})})),Zf=o(((e,t)=>{let n=zd();t.exports=Object.freeze({coerceTypes:`array`,useDefaults:!0,removeAdditional:!0,uriResolver:n,addUsedSchema:!1,allErrors:!1})})),Qf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(a,o),time:t(c(!0),l),"date-time":t(f(!0),p),"iso-time":t(c(),u),"iso-date-time":t(f(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:E,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:y,int32:{type:`number`,validate:S},int64:{type:`number`,validate:C},float:{type:`number`,validate:w},double:{type:`number`,validate:w},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function n(e){return e%4==0&&(e%100!=0||e%400==0)}let r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e){let t=r.exec(e);if(!t)return!1;let a=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o===2&&n(a)?29:i[o])}function o(e,t){if(e&&t)return e>t?1:e<t?-1:0}let s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){let n=s.exec(t);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4],c=n[5]===`-`?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!o)return!1;if(r<=23&&i<=59&&a<60)return!0;let d=i-u*c,f=r-l*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&a<61}}function l(e,t){if(!(e&&t))return;let n=new Date(`2020-01-01T`+e).valueOf(),r=new Date(`2020-01-01T`+t).valueOf();if(n&&r)return n-r}function u(e,t){if(!(e&&t))return;let n=s.exec(e),r=s.exec(t);if(n&&r)return e=n[1]+n[2]+n[3],t=r[1]+r[2]+r[3],e>t?1:e<t?-1:0}let d=/t|\s/i;function f(e){let t=c(e);return function(e){let n=e.split(d);return n.length===2&&a(n[0])&&t(n[1])}}function p(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function m(e,t){if(!(e&&t))return;let[n,r]=e.split(d),[i,a]=t.split(d),s=o(n,i);if(s!==void 0)return s||l(r,a)}let h=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function _(e){return h.test(e)&&g.test(e)}let v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(e){return v.lastIndex=0,v.test(e)}let b=-(2**31),x=2**31-1;function S(e){return Number.isInteger(e)&&e<=x&&e>=b}function C(e){return Number.isInteger(e)}function w(){return!0}let T=/[^\\]\\Z/;function E(e){if(T.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),$f=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatLimitDefinition=void 0;let t=kf(),n=Z(),r=n.operators,i={formatMaximum:{okStr:`<=`,ok:r.LTE,fail:r.GT},formatMinimum:{okStr:`>=`,ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:`<`,ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:`>`,ok:r.GT,fail:r.LTE}};e.formatLimitDefinition={keyword:Object.keys(i),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,n.str)`should be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,n._)`{comparison: ${i[e].okStr}, limit: ${t}}`},code(e){let{gen:r,data:a,schemaCode:o,keyword:s,it:c}=e,{opts:l,self:u}=c;if(!l.validateFormats)return;let d=new t.KeywordCxt(c,u.RULES.all.format.definition,`format`);d.$data?f():p();function f(){let t=r.scopeValue(`formats`,{ref:u.formats,code:l.code.formats}),i=r.const(`fmt`,(0,n._)`${t}[${d.schemaCode}]`);e.fail$data((0,n.or)((0,n._)`typeof ${i} != "object"`,(0,n._)`${i} instanceof RegExp`,(0,n._)`typeof ${i}.compare != "function"`,m(i)))}function p(){let t=d.schema,i=u.formats[t];if(!i||i===!0)return;if(typeof i!=`object`||i instanceof RegExp||typeof i.compare!=`function`)throw Error(`"${s}": format "${t}" does not define "compare" function`);let a=r.scopeValue(`formats`,{key:t,ref:i,code:l.code.formats?(0,n._)`${l.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(m(a))}function m(e){return(0,n._)`${e}.compare(${a}, ${o}) ${i[s].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),ep=o(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0});let n=Qf(),r=$f(),i=Z(),a=new i.Name(`fullFormats`),o=new i.Name(`fastFormats`),s=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,a),e;let[i,s]=t.mode===`fast`?[n.fastFormats,o]:[n.fullFormats,a];return c(e,t.formats||n.formatNames,i,s),t.keywords&&(0,r.default)(e),e};s.get=(e,t=`full`)=>{let r=(t===`fast`?n.fastFormats:n.fullFormats)[e];if(!r)throw Error(`Unknown format "${e}"`);return r};function c(e,t,n,r){var a;(a=e.opts.code).formats??(a.formats=(0,i._)`require("ajv-formats/dist/formats").${r}`);for(let r of t)e.addFormat(r,n[r])}t.exports=e=s,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=s})),tp=o(((e,t)=>{let n=kf().default,r=Xf(),i=Zf();t.exports=class{constructor(e,t){t.mode===`JTD`?this.ajv=new r(Object.assign({},i,t.customOptions)):this.ajv=new n(Object.assign({},i,t.customOptions));let a=!0;if(t.plugins&&t.plugins.length>0)for(let e of t.plugins)Array.isArray(e)?(a&&=e[0].name!==`formatsPlugin`,e[0](this.ajv,e[1])):(a&&=e.name!==`formatsPlugin`,e(this.ajv));a&&ep()(this.ajv),t.onCreate?.(this.ajv);let o=Object.values(e);for(let e of o)this.ajv.addSchema(e)}buildValidatorFunction({schema:e}){if(e.$id){let t=this.ajv.getSchema(e.$id);if(t)return t}return this.ajv.compile(e)}}})),np=o(((e,t)=>{let n=Xf(),r=Zf();t.exports=class{constructor(e,t){this.ajv=new n(Object.assign({},r,t))}buildSerializerFunction({schema:e}){return this.ajv.compileSerializer(e)}}})),rp=o(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0});let n=vd(),r=_d();function i(e,t){if(!e.opts.code.source)throw Error(`moduleCode: ajv instance must have code.source option`);let{_n:i}=e.scope.opts;return typeof t==`function`?o(t.source):t===void 0?s(e.schemas,t=>t.meta?void 0:e.compile(t.schema)):s(t,a);function a(t){let n=e.getSchema(t);if(!n)throw Error(`moduleCode: no schema with id ${t}`);return n}function o(t){let n={},r=t?.validateName,a=c(n,t);return e.opts.code.esm?`"use strict";${i}export const validate = ${r};${i}export default ${r};${i}${a}`:`"use strict";${i}module.exports = ${r};${i}module.exports.default = ${r};${i}${a}`}function s(t,n){let a={},o=(0,r._)`"use strict";`;for(let s in t){let l=n(t[s]);if(l){let t=c(a,l.source),n=e.opts.code.esm?(0,r._)`export const ${(0,r.getEsmExportName)(s)}`:(0,r._)`exports${(0,r.getProperty)(s)}`;o=(0,r._)`${o}${i}${n} = ${l.source?.validateName};${i}${t}`}}return`${o}`}function c(t,a){if(!a)throw Error(`moduleCode: function does not have "source" property`);if(u(a.validateName)===n.UsedValueState.Completed)return r.nil;d(a.validateName,n.UsedValueState.Started);let o=e.scope.scopeCode(a.scopeValues,t,l),s=new r._Code(`${o}${i}${a.validateCode}`);return a.evaluated?(0,r._)`${s}${a.validateName}.evaluated = ${a.evaluated};${i}`:s;function l(a){let o=a.value?.ref;if(a.prefix===`validate`&&typeof o==`function`)return c(t,o.source);if((a.prefix===`root`||a.prefix===`wrapper`)&&typeof o==`object`){let{validate:s,validateName:l}=o;if(!l)throw Error(`ajv internal error`);let d=e.opts.code.es5?n.varKinds.var:n.varKinds.const,f=(0,r._)`${d} ${a} = {validate: ${l}};`;if(u(l)===n.UsedValueState.Started)return f;let p=c(t,s?.source);return(0,r._)`${f}${i}${p}`}}function u(e){return t[e.prefix]?.get(e)}function d(e,n){let{prefix:r}=e;(t[r]=t[r]||new Map).set(e,n)}}}t.exports=e=i,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=i})),ip=o(((e,t)=>{let n=ap(),r=rp().default;function i(e={readMode:!0}){if(e.readMode===!0&&!e.restoreFunction)throw Error(`You must provide a restoreFunction options when readMode ON`);if(e.readMode!==!0&&!e.storeFunction)throw Error(`You must provide a storeFunction options when readMode OFF`);if(e.readMode===!0)return function(){return function(t){return e.restoreFunction(t)}};let t=n();return function(i,a={}){(!a.customOptions||!a.customOptions.code)&&(a.customOptions=Object.assign({},a.customOptions,{code:{source:!0}}));let o=t(i,a);return function(t){let i=o(t),a=r(o[n.AjvReference].ajv,i);return e.storeFunction(t,a),i}}}t.exports=i})),ap=o(((e,t)=>{let n=Symbol.for(`fastify.ajv-compiler.reference`),r=tp(),i=np();function a(e){let t=new Map,a=new Map;return e&&e.jtdSerializer===!0?function(e,t){let n=o({},t);if(a.has(n))return a.get(n);let r=new i(e,t),s=r.buildSerializerFunction.bind(r);return a.set(n,s),s}:function(e,i){let a=o(e,i.customOptions);if(t.has(a))return t.get(a);let s=new r(e,i),c=s.buildValidatorFunction.bind(s);return t.set(a,c),i.customOptions.code!==void 0&&(c[n]=s),c}}function o(e,t){return`${JSON.stringify(e)}${JSON.stringify(t)}`}t.exports=a,t.exports.default=a,t.exports.AjvCompiler=a,t.exports.AjvReference=n,t.exports.StandaloneValidator=ip()})),op=o((e=>{var t=Object.prototype.hasOwnProperty;function n(e,t,n){for(n of e.keys())if(r(n,t))return n}function r(e,i){var a,o,s;if(e===i)return!0;if(e&&i&&(a=e.constructor)===i.constructor){if(a===Date)return e.getTime()===i.getTime();if(a===RegExp)return e.toString()===i.toString();if(a===Array){if((o=e.length)===i.length)for(;o--&&r(e[o],i[o]););return o===-1}if(a===Set){if(e.size!==i.size)return!1;for(o of e)if(s=o,s&&typeof s==`object`&&(s=n(i,s),!s)||!i.has(s))return!1;return!0}if(a===Map){if(e.size!==i.size)return!1;for(o of e)if(s=o[0],s&&typeof s==`object`&&(s=n(i,s),!s)||!r(o[1],i.get(s)))return!1;return!0}if(a===ArrayBuffer)e=new Uint8Array(e),i=new Uint8Array(i);else if(a===DataView){if((o=e.byteLength)===i.byteLength)for(;o--&&e.getInt8(o)===i.getInt8(o););return o===-1}if(ArrayBuffer.isView(e)){if((o=e.byteLength)===i.byteLength)for(;o--&&e[o]===i[o];);return o===-1}if(!a||typeof e==`object`){for(a in o=0,e)if(t.call(e,a)&&++o&&!t.call(i,a)||!(a in i)||!r(e[a],i[a]))return!1;return Object.keys(i).length===o}}return e!==e&&i!==i}e.dequal=r})),sp=o(((e,t)=>{let{dequal:n}=op(),r=Symbol.for(`json-schema-ref`);var i=class{#e;#t;#n;#r;#i;constructor(e={}){this.#e={},this.#t={},this.#n=e.insertRefSymbol??!1,this.#r=e.allowEqualDuplicates??!0,this.#i=e.cloneSchemaWithoutRefs??!1}addSchema(e,t,n=!0){n&&(e.$id!==void 0&&e.$id.charAt(0)!==`#`?t=e.$id:this.#c(e,t));let r=e.$id;r!==void 0&&typeof r==`string`&&(r.charAt(0)===`#`?this.#l(e,t,r):(this.#c(e,r),t=r));let i=e.$ref;if(i!==void 0&&typeof i==`string`){let{refSchemaId:e,refJsonPointer:n}=this.#a(i,t);this.#e[t].refs.push({schemaId:e,jsonPointer:n})}for(let n in e)typeof e[n]==`object`&&e[n]!==null&&this.addSchema(e[n],t,!1)}getSchema(e,t=`#`){let n=this.#e[e];if(n===void 0)throw Error(`Cannot resolve ref "${e}${t}". Schema with id "${e}" is not found.`);return n.anchors[t]===void 0?a(n.schema,t):n.anchors[t]}hasSchema(e){return this.#e[e]!==void 0}getSchemaRefs(e){let t=this.#e[e];if(t===void 0)throw Error(`Schema with id "${e}" is not found.`);return t.refs}getSchemaDependencies(e,t={}){let n=this.#e[e];for(let r of n.refs){let n=r.schemaId;n===e||t[n]!==void 0||(t[n]=this.getSchema(n),this.getSchemaDependencies(n,t))}return t}derefSchema(e){if(this.#t[e]!==void 0)return;let t=this.#e[e];if(t===void 0)throw Error(`Schema with id "${e}" is not found.`);!this.#i&&t.refs.length===0&&(this.#t[e]={schema:t.schema,anchors:t.anchors});let n=[];this.#o(t.schema,e,!0,n);let r=this.getSchemaDependencies(e);for(let e in r){let t=r[e];this.#o(t,e,!0,n)}for(let e of n){let{refSchemaId:t,refJsonPointer:n}=this.#a(e.ref,e.sourceSchemaId),r=this.getDerefSchema(t,n);if(r===null)throw Error(`Cannot resolve ref "${e.ref}". Ref "${n}" is not found in schema "${t}".`);e.targetSchema=r,e.targetSchemaId=t}for(let e of n)this.#s(e,n)}getDerefSchema(e,t=`#`){let n=this.#t[e];return n===void 0&&(this.derefSchema(e),n=this.#t[e]),n.anchors[t]===void 0?a(n.schema,t):n.anchors[t]}#a(e,t){let n=e.indexOf(`#`);return n===-1?{refSchemaId:e,refJsonPointer:`#`}:n===0?{refSchemaId:t,refJsonPointer:e}:{refSchemaId:e.slice(0,n),refJsonPointer:e.slice(n)}}#o(e,t,n,r=[]){let i=Array.isArray(e)?[...e]:{...e};n&&(e.$id!==void 0&&e.$id.charAt(0)!==`#`?t=e.$id:this.#u(i,t));let a=i.$id;a!==void 0&&typeof a==`string`&&(a.charAt(0)===`#`?this.#d(i,t,a):(this.#u(i,a),t=a)),i.$ref!==void 0&&r.push({ref:i.$ref,sourceSchemaId:t,sourceSchema:i});for(let e in i){let n=i[e];typeof n==`object`&&n&&(i[e]=this.#o(n,t,!1,r))}return i}#s(e,t){let{sourceSchema:i,targetSchema:a}=e;if(i.$ref){if(this.#n&&(i[r]=i.$ref),delete i.$ref,a.$ref){let e=t.find(e=>e.sourceSchema===a);this.#s(e,t)}for(let t in a)if(t!==`$id`){if(i[t]!==void 0){if(n(i[t],a[t]))continue;throw Error(`Cannot resolve ref "${e.ref}". Property "${t}" already exists in schema "${e.sourceSchemaId}".`)}i[t]=a[t]}e.isResolved=!0}}#c(e,t){let r=this.#e[t];if(r!==void 0){if(this.#r&&n(e,r.schema))return;throw Error(`There is already another schema with id "${t}".`)}this.#e[t]={schema:e,anchors:{},refs:[]}}#l(e,t,n){let{anchors:r}=this.#e[t];if(r[n]!==void 0)throw Error(`There is already another anchor "${n}" in schema "${t}".`);r[n]=e}#u(e,t){this.#t[t]===void 0&&(this.#t[t]={schema:e,anchors:{}})}#d(e,t,n){let{anchors:r}=this.#t[t];r[n]=e}};function a(e,t){let n=t.split(`/`),r=e;for(let e of n)if(!(e===``||e===`#`)){if(typeof r!=`object`||!r)return null;r=r[e]}return r??null}t.exports={RefResolver:i}})),cp=o(((e,t)=>{let n=kf(),r=zd(),i=ep(),a=nd()({proto:!0});t.exports=class e{constructor(e){this.ajv=new n({...e,strictSchema:!1,validateSchema:!1,allowUnionTypes:!0,uriResolver:r}),i(this.ajv),this.ajv.addKeyword({keyword:`fjs_type`,type:`object`,errors:!1,validate:(e,t)=>t&&typeof t.toJSON==`function`}),this._ajvSchemas={},this._ajvOptions=e||{}}addSchema(e,t){let n=e.$id||t;if(e.$id!==void 0&&e.$id[0]===`#`&&(n=t+e.$id),this.ajv.refs[n]===void 0&&this.ajv.schemas[n]===void 0){let t=a(e);this.convertSchemaToAjvFormat(t),this.ajv.addSchema(t,n),this._ajvSchemas[n]=e}}validate(e,t){return this.ajv.validate(e,t)}convertSchemaToAjvFormat(e){if(e!==null){e.type===`string`?(e.fjs_type=`string`,e.type=[`string`,`object`]):Array.isArray(e.type)&&e.type.includes(`string`)&&!e.type.includes(`object`)&&(e.fjs_type=`string`,e.type.push(`object`));for(let t in e)typeof e[t]==`object`&&this.convertSchemaToAjvFormat(e[t])}}getState(){return{ajvOptions:this._ajvOptions,ajvSchemas:this._ajvSchemas}}static restoreFromState(t){let n=new e(t.ajvOptions);for(let[e,r]of Object.entries(t.ajvSchemas))n.ajv.addSchema(r,e);return n}}})),lp=o(((e,t)=>{t.exports=class e{constructor(e,t,n=`#`){this.schema=e,this.schemaId=t,this.jsonPointer=n}getPropertyLocation(t){return new e(this.schema[t],this.schemaId,this.jsonPointer+`/`+t)}getSchemaRef(){return this.schemaId+this.jsonPointer}}})),up=o(((e,t)=>{t.exports=d,t.exports.default=d;let n={$schema:`http://json-schema.org/draft-07/schema#`,$id:`http://json-schema.org/draft-07/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:!0},r={enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},i=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,a=Qf().fullFormats.uri,o=Qf().fullFormats.regex;function s(e,{instancePath:t=``,parentData:n,parentDataProperty:r,rootData:i=e}={}){return typeof e==`number`&&!(e%1)&&!isNaN(e)&&isFinite(e)?typeof e==`number`&&isFinite(e)&&(e<0||isNaN(e))?(s.errors=[{instancePath:t,schemaPath:`#/definitions/nonNegativeInteger/minimum`,keyword:`minimum`,params:{comparison:`>=`,limit:0},message:`must be >= 0`}],!1):(s.errors=null,!0):(s.errors=[{instancePath:t,schemaPath:`#/definitions/nonNegativeInteger/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1)}let c={validate:d};function l(e,{instancePath:t=``,parentData:n,parentDataProperty:r,rootData:i=e}={}){let a=null,o=0;if(o===0)if(Array.isArray(e)){if(e.length<1)return l.errors=[{instancePath:t,schemaPath:`#/minItems`,keyword:`minItems`,params:{limit:1},message:`must NOT have fewer than 1 items`}],!1;{let n=e.length;for(let r=0;r<n;r++){let n=o;if(c.validate(e[r],{instancePath:t+`/`+r,parentData:e,parentDataProperty:r,rootData:i})||(a=a===null?c.validate.errors:a.concat(c.validate.errors),o=a.length),n!==o)break}}}else return l.errors=[{instancePath:t,schemaPath:`#/type`,keyword:`type`,params:{type:`array`},message:`must be array`}],!1;return l.errors=a,o===0}let u=$d().default;function d(e,{instancePath:t=``,parentData:c,parentDataProperty:f,rootData:p=e}={}){let m=null,h=0;if(!(e&&typeof e==`object`&&!Array.isArray(e))&&typeof e!=`boolean`)return d.errors=[{instancePath:t,schemaPath:`#/type`,keyword:`type`,params:{type:n.type},message:`must be object,boolean`}],!1;if(h===0&&e&&typeof e==`object`&&!Array.isArray(e)){if(e.$id!==void 0){let n=e.$id,r=h;if(h===r&&h===r)if(typeof n==`string`){if(!i.test(n))return d.errors=[{instancePath:t+`/$id`,schemaPath:`#/properties/%24id/format`,keyword:`format`,params:{format:`uri-reference`},message:`must match format "uri-reference"`}],!1}else return d.errors=[{instancePath:t+`/$id`,schemaPath:`#/properties/%24id/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=r===h}else var g=!0;if(g){if(e.$schema!==void 0){let n=e.$schema,r=h;if(h===r&&h===r)if(typeof n==`string`){if(!a(n))return d.errors=[{instancePath:t+`/$schema`,schemaPath:`#/properties/%24schema/format`,keyword:`format`,params:{format:`uri`},message:`must match format "uri"`}],!1}else return d.errors=[{instancePath:t+`/$schema`,schemaPath:`#/properties/%24schema/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=r===h}else var g=!0;if(g){if(e.$ref!==void 0){let n=e.$ref,r=h;if(h===r&&h===r)if(typeof n==`string`){if(!i.test(n))return d.errors=[{instancePath:t+`/$ref`,schemaPath:`#/properties/%24ref/format`,keyword:`format`,params:{format:`uri-reference`},message:`must match format "uri-reference"`}],!1}else return d.errors=[{instancePath:t+`/$ref`,schemaPath:`#/properties/%24ref/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=r===h}else var g=!0;if(g){if(e.$comment!==void 0){let n=h;if(typeof e.$comment!=`string`)return d.errors=[{instancePath:t+`/$comment`,schemaPath:`#/properties/%24comment/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=n===h}else var g=!0;if(g){if(e.title!==void 0){let n=h;if(typeof e.title!=`string`)return d.errors=[{instancePath:t+`/title`,schemaPath:`#/properties/title/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=n===h}else var g=!0;if(g){if(e.description!==void 0){let n=h;if(typeof e.description!=`string`)return d.errors=[{instancePath:t+`/description`,schemaPath:`#/properties/description/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=n===h}else var g=!0;if(g){if(e.readOnly!==void 0){let n=h;if(typeof e.readOnly!=`boolean`)return d.errors=[{instancePath:t+`/readOnly`,schemaPath:`#/properties/readOnly/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;var g=n===h}else var g=!0;if(g){if(e.examples!==void 0){let n=h;if(h===n&&!Array.isArray(e.examples))return d.errors=[{instancePath:t+`/examples`,schemaPath:`#/properties/examples/type`,keyword:`type`,params:{type:`array`},message:`must be array`}],!1;var g=n===h}else var g=!0;if(g){if(e.multipleOf!==void 0){let n=e.multipleOf,r=h;if(h===r)if(typeof n==`number`&&isFinite(n)){if(n<=0||isNaN(n))return d.errors=[{instancePath:t+`/multipleOf`,schemaPath:`#/properties/multipleOf/exclusiveMinimum`,keyword:`exclusiveMinimum`,params:{comparison:`>`,limit:0},message:`must be > 0`}],!1}else return d.errors=[{instancePath:t+`/multipleOf`,schemaPath:`#/properties/multipleOf/type`,keyword:`type`,params:{type:`number`},message:`must be number`}],!1;var g=r===h}else var g=!0;if(g){if(e.maximum!==void 0){let n=e.maximum,r=h;if(!(typeof n==`number`&&isFinite(n)))return d.errors=[{instancePath:t+`/maximum`,schemaPath:`#/properties/maximum/type`,keyword:`type`,params:{type:`number`},message:`must be number`}],!1;var g=r===h}else var g=!0;if(g){if(e.exclusiveMaximum!==void 0){let n=e.exclusiveMaximum,r=h;if(!(typeof n==`number`&&isFinite(n)))return d.errors=[{instancePath:t+`/exclusiveMaximum`,schemaPath:`#/properties/exclusiveMaximum/type`,keyword:`type`,params:{type:`number`},message:`must be number`}],!1;var g=r===h}else var g=!0;if(g){if(e.minimum!==void 0){let n=e.minimum,r=h;if(!(typeof n==`number`&&isFinite(n)))return d.errors=[{instancePath:t+`/minimum`,schemaPath:`#/properties/minimum/type`,keyword:`type`,params:{type:`number`},message:`must be number`}],!1;var g=r===h}else var g=!0;if(g){if(e.exclusiveMinimum!==void 0){let n=e.exclusiveMinimum,r=h;if(!(typeof n==`number`&&isFinite(n)))return d.errors=[{instancePath:t+`/exclusiveMinimum`,schemaPath:`#/properties/exclusiveMinimum/type`,keyword:`type`,params:{type:`number`},message:`must be number`}],!1;var g=r===h}else var g=!0;if(g){if(e.maxLength!==void 0){let n=e.maxLength,r=h,i=h;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n)))return d.errors=[{instancePath:t+`/maxLength`,schemaPath:`#/definitions/nonNegativeInteger/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;if(h===i&&typeof n==`number`&&isFinite(n)&&(n<0||isNaN(n)))return d.errors=[{instancePath:t+`/maxLength`,schemaPath:`#/definitions/nonNegativeInteger/minimum`,keyword:`minimum`,params:{comparison:`>=`,limit:0},message:`must be >= 0`}],!1;var g=r===h}else var g=!0;if(g){if(e.minLength!==void 0){let n=h;s(e.minLength,{instancePath:t+`/minLength`,parentData:e,parentDataProperty:`minLength`,rootData:p})||(m=m===null?s.errors:m.concat(s.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.pattern!==void 0){let n=e.pattern,r=h;if(h===r&&h===r)if(typeof n==`string`){if(!o(n))return d.errors=[{instancePath:t+`/pattern`,schemaPath:`#/properties/pattern/format`,keyword:`format`,params:{format:`regex`},message:`must match format "regex"`}],!1}else return d.errors=[{instancePath:t+`/pattern`,schemaPath:`#/properties/pattern/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=r===h}else var g=!0;if(g){if(e.additionalItems!==void 0){let n=h;d(e.additionalItems,{instancePath:t+`/additionalItems`,parentData:e,parentDataProperty:`additionalItems`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.items!==void 0){let n=e.items,r=h,i=h,a=!1,o=h;d(n,{instancePath:t+`/items`,parentData:e,parentDataProperty:`items`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var _=o===h;if(a||=_,!a){let r=h;l(n,{instancePath:t+`/items`,parentData:e,parentDataProperty:`items`,rootData:p})||(m=m===null?l.errors:m.concat(l.errors),h=m.length);var _=r===h;a||=_}if(a)h=i,m!==null&&(i?m.length=i:m=null);else{let e={instancePath:t+`/items`,schemaPath:`#/properties/items/anyOf`,keyword:`anyOf`,params:{},message:`must match a schema in anyOf`};return m===null?m=[e]:m.push(e),h++,d.errors=m,!1}var g=r===h}else var g=!0;if(g){if(e.maxItems!==void 0){let n=e.maxItems,r=h,i=h;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n)))return d.errors=[{instancePath:t+`/maxItems`,schemaPath:`#/definitions/nonNegativeInteger/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;if(h===i&&typeof n==`number`&&isFinite(n)&&(n<0||isNaN(n)))return d.errors=[{instancePath:t+`/maxItems`,schemaPath:`#/definitions/nonNegativeInteger/minimum`,keyword:`minimum`,params:{comparison:`>=`,limit:0},message:`must be >= 0`}],!1;var g=r===h}else var g=!0;if(g){if(e.minItems!==void 0){let n=h;s(e.minItems,{instancePath:t+`/minItems`,parentData:e,parentDataProperty:`minItems`,rootData:p})||(m=m===null?s.errors:m.concat(s.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.uniqueItems!==void 0){let n=h;if(typeof e.uniqueItems!=`boolean`)return d.errors=[{instancePath:t+`/uniqueItems`,schemaPath:`#/properties/uniqueItems/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;var g=n===h}else var g=!0;if(g){if(e.contains!==void 0){let n=h;d(e.contains,{instancePath:t+`/contains`,parentData:e,parentDataProperty:`contains`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.maxProperties!==void 0){let n=e.maxProperties,r=h,i=h;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n)))return d.errors=[{instancePath:t+`/maxProperties`,schemaPath:`#/definitions/nonNegativeInteger/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;if(h===i&&typeof n==`number`&&isFinite(n)&&(n<0||isNaN(n)))return d.errors=[{instancePath:t+`/maxProperties`,schemaPath:`#/definitions/nonNegativeInteger/minimum`,keyword:`minimum`,params:{comparison:`>=`,limit:0},message:`must be >= 0`}],!1;var g=r===h}else var g=!0;if(g){if(e.minProperties!==void 0){let n=h;s(e.minProperties,{instancePath:t+`/minProperties`,parentData:e,parentDataProperty:`minProperties`,rootData:p})||(m=m===null?s.errors:m.concat(s.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.required!==void 0){let n=e.required,r=h;if(h===h)if(Array.isArray(n)){var v=!0;let e=n.length;for(let r=0;r<e;r++){let e=h;if(typeof n[r]!=`string`)return d.errors=[{instancePath:t+`/required/`+r,schemaPath:`#/definitions/stringArray/items/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var v=e===h;if(!v)break}if(v){let e=n.length,r;if(e>1){let i={};for(;e--;){let a=n[e];if(typeof a==`string`){if(typeof i[a]==`number`)return r=i[a],d.errors=[{instancePath:t+`/required`,schemaPath:`#/definitions/stringArray/uniqueItems`,keyword:`uniqueItems`,params:{i:e,j:r},message:`must NOT have duplicate items (items ## `+r+` and `+e+` are identical)`}],!1;i[a]=e}}}}}else return d.errors=[{instancePath:t+`/required`,schemaPath:`#/definitions/stringArray/type`,keyword:`type`,params:{type:`array`},message:`must be array`}],!1;var g=r===h}else var g=!0;if(g){if(e.additionalProperties!==void 0){let n=h;d(e.additionalProperties,{instancePath:t+`/additionalProperties`,parentData:e,parentDataProperty:`additionalProperties`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.definitions!==void 0){let n=e.definitions,r=h;if(h===r)if(n&&typeof n==`object`&&!Array.isArray(n))for(let e in n){let r=h;if(d(n[e],{instancePath:t+`/definitions/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),parentData:n,parentDataProperty:e,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length),r!==h)break}else return d.errors=[{instancePath:t+`/definitions`,schemaPath:`#/properties/definitions/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var g=r===h}else var g=!0;if(g){if(e.properties!==void 0){let n=e.properties,r=h;if(h===r)if(n&&typeof n==`object`&&!Array.isArray(n))for(let e in n){let r=h;if(d(n[e],{instancePath:t+`/properties/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),parentData:n,parentDataProperty:e,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length),r!==h)break}else return d.errors=[{instancePath:t+`/properties`,schemaPath:`#/properties/properties/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var g=r===h}else var g=!0;if(g){if(e.patternProperties!==void 0){let n=e.patternProperties,r=h;if(h===r)if(n&&typeof n==`object`&&!Array.isArray(n)){for(let e in n){let n=h;if(h===n&&typeof e==`string`&&!o(e)){let n={instancePath:t+`/patternProperties`,schemaPath:`#/properties/patternProperties/propertyNames/format`,keyword:`format`,params:{format:`regex`},message:`must match format "regex"`,propertyName:e};m===null?m=[n]:m.push(n),h++}var y=n===h;if(!y){let n={instancePath:t+`/patternProperties`,schemaPath:`#/properties/patternProperties/propertyNames`,keyword:`propertyNames`,params:{propertyName:e},message:`property name must be valid`};return m===null?m=[n]:m.push(n),h++,d.errors=m,!1}}if(y)for(let e in n){let r=h;if(d(n[e],{instancePath:t+`/patternProperties/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),parentData:n,parentDataProperty:e,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length),r!==h)break}}else return d.errors=[{instancePath:t+`/patternProperties`,schemaPath:`#/properties/patternProperties/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var g=r===h}else var g=!0;if(g){if(e.dependencies!==void 0){let n=e.dependencies,r=h;if(h===r)if(n&&typeof n==`object`&&!Array.isArray(n))for(let e in n){let r=n[e],i=h,a=h,o=!1,s=h;d(r,{instancePath:t+`/dependencies/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),parentData:n,parentDataProperty:e,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var b=s===h;if(o||=b,!o){let n=h;if(h===h)if(Array.isArray(r)){var x=!0;let n=r.length;for(let i=0;i<n;i++){let n=h;if(typeof r[i]!=`string`){let n={instancePath:t+`/dependencies/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`)+`/`+i,schemaPath:`#/definitions/stringArray/items/type`,keyword:`type`,params:{type:`string`},message:`must be string`};m===null?m=[n]:m.push(n),h++}var x=n===h;if(!x)break}if(x){let n=r.length,i;if(n>1){let a={};for(;n--;){let o=r[n];if(typeof o==`string`){if(typeof a[o]==`number`){i=a[o];let r={instancePath:t+`/dependencies/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),schemaPath:`#/definitions/stringArray/uniqueItems`,keyword:`uniqueItems`,params:{i:n,j:i},message:`must NOT have duplicate items (items ## `+i+` and `+n+` are identical)`};m===null?m=[r]:m.push(r),h++;break}a[o]=n}}}}}else{let n={instancePath:t+`/dependencies/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),schemaPath:`#/definitions/stringArray/type`,keyword:`type`,params:{type:`array`},message:`must be array`};m===null?m=[n]:m.push(n),h++}var b=n===h;o||=b}if(o)h=a,m!==null&&(a?m.length=a:m=null);else{let n={instancePath:t+`/dependencies/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),schemaPath:`#/properties/dependencies/additionalProperties/anyOf`,keyword:`anyOf`,params:{},message:`must match a schema in anyOf`};return m===null?m=[n]:m.push(n),h++,d.errors=m,!1}if(i!==h)break}else return d.errors=[{instancePath:t+`/dependencies`,schemaPath:`#/properties/dependencies/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var g=r===h}else var g=!0;if(g){if(e.propertyNames!==void 0){let n=h;d(e.propertyNames,{instancePath:t+`/propertyNames`,parentData:e,parentDataProperty:`propertyNames`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.enum!==void 0){let n=e.enum,r=h;if(h===r)if(Array.isArray(n)){if(n.length<1)return d.errors=[{instancePath:t+`/enum`,schemaPath:`#/properties/enum/minItems`,keyword:`minItems`,params:{limit:1},message:`must NOT have fewer than 1 items`}],!1;{let e=n.length,r;if(e>1){outer0:for(;e--;)for(r=e;r--;)if(u(n[e],n[r]))return d.errors=[{instancePath:t+`/enum`,schemaPath:`#/properties/enum/uniqueItems`,keyword:`uniqueItems`,params:{i:e,j:r},message:`must NOT have duplicate items (items ## `+r+` and `+e+` are identical)`}],!1}}}else return d.errors=[{instancePath:t+`/enum`,schemaPath:`#/properties/enum/type`,keyword:`type`,params:{type:`array`},message:`must be array`}],!1;var g=r===h}else var g=!0;if(g){if(e.type!==void 0){let n=e.type,i=h,a=h,o=!1,s=h;if(!(n===`array`||n===`boolean`||n===`integer`||n===`null`||n===`number`||n===`object`||n===`string`)){let e={instancePath:t+`/type`,schemaPath:`#/definitions/simpleTypes/enum`,keyword:`enum`,params:{allowedValues:r.enum},message:`must be equal to one of the allowed values`};m===null?m=[e]:m.push(e),h++}var S=s===h;if(o||=S,!o){let e=h;if(h===e)if(Array.isArray(n))if(n.length<1){let e={instancePath:t+`/type`,schemaPath:`#/properties/type/anyOf/1/minItems`,keyword:`minItems`,params:{limit:1},message:`must NOT have fewer than 1 items`};m===null?m=[e]:m.push(e),h++}else{var C=!0;let e=n.length;for(let i=0;i<e;i++){let e=n[i],a=h;if(!(e===`array`||e===`boolean`||e===`integer`||e===`null`||e===`number`||e===`object`||e===`string`)){let e={instancePath:t+`/type/`+i,schemaPath:`#/definitions/simpleTypes/enum`,keyword:`enum`,params:{allowedValues:r.enum},message:`must be equal to one of the allowed values`};m===null?m=[e]:m.push(e),h++}var C=a===h;if(!C)break}if(C){let e=n.length,r;if(e>1){outer1:for(;e--;)for(r=e;r--;)if(u(n[e],n[r])){let n={instancePath:t+`/type`,schemaPath:`#/properties/type/anyOf/1/uniqueItems`,keyword:`uniqueItems`,params:{i:e,j:r},message:`must NOT have duplicate items (items ## `+r+` and `+e+` are identical)`};m===null?m=[n]:m.push(n),h++;break outer1}}}}else{let e={instancePath:t+`/type`,schemaPath:`#/properties/type/anyOf/1/type`,keyword:`type`,params:{type:`array`},message:`must be array`};m===null?m=[e]:m.push(e),h++}var S=e===h;o||=S}if(o)h=a,m!==null&&(a?m.length=a:m=null);else{let e={instancePath:t+`/type`,schemaPath:`#/properties/type/anyOf`,keyword:`anyOf`,params:{},message:`must match a schema in anyOf`};return m===null?m=[e]:m.push(e),h++,d.errors=m,!1}var g=i===h}else var g=!0;if(g){if(e.format!==void 0){let n=h;if(typeof e.format!=`string`)return d.errors=[{instancePath:t+`/format`,schemaPath:`#/properties/format/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=n===h}else var g=!0;if(g){if(e.contentMediaType!==void 0){let n=h;if(typeof e.contentMediaType!=`string`)return d.errors=[{instancePath:t+`/contentMediaType`,schemaPath:`#/properties/contentMediaType/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=n===h}else var g=!0;if(g){if(e.contentEncoding!==void 0){let n=h;if(typeof e.contentEncoding!=`string`)return d.errors=[{instancePath:t+`/contentEncoding`,schemaPath:`#/properties/contentEncoding/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=n===h}else var g=!0;if(g){if(e.if!==void 0){let n=h;d(e.if,{instancePath:t+`/if`,parentData:e,parentDataProperty:`if`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.then!==void 0){let n=h;d(e.then,{instancePath:t+`/then`,parentData:e,parentDataProperty:`then`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.else!==void 0){let n=h;d(e.else,{instancePath:t+`/else`,parentData:e,parentDataProperty:`else`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.allOf!==void 0){let n=h;l(e.allOf,{instancePath:t+`/allOf`,parentData:e,parentDataProperty:`allOf`,rootData:p})||(m=m===null?l.errors:m.concat(l.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.anyOf!==void 0){let n=h;l(e.anyOf,{instancePath:t+`/anyOf`,parentData:e,parentDataProperty:`anyOf`,rootData:p})||(m=m===null?l.errors:m.concat(l.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.oneOf!==void 0){let n=h;l(e.oneOf,{instancePath:t+`/oneOf`,parentData:e,parentDataProperty:`oneOf`,rootData:p})||(m=m===null?l.errors:m.concat(l.errors),h=m.length);var g=n===h}else var g=!0;if(g)if(e.not!==void 0){let n=h;d(e.not,{instancePath:t+`/not`,parentData:e,parentDataProperty:`not`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}return d.errors=m,h===0}})),dp=o(((e,t)=>{t.exports={MergeError:class extends Error{constructor(e,t){super(),this.name=`JsonSchemaMergeError`,this.code=`JSON_SCHEMA_MERGE_ERROR`,this.message=`Failed to merge "${e}" keyword schemas.`,this.schemas=t}},ResolverNotFoundError:class extends Error{constructor(e,t){super(),this.name=`JsonSchemaMergeError`,this.code=`JSON_SCHEMA_MERGE_ERROR`,this.message=`Resolver for "${e}" keyword not found.`,this.schemas=t}},InvalidOnConflictOptionError:class extends Error{constructor(e){super(),this.name=`JsonSchemaMergeError`,this.code=`JSON_SCHEMA_MERGE_ERROR`,this.message=`Invalid "onConflict" option: "${e}".`}}}})),fp=o(((e,t)=>{let{dequal:n}=op(),{MergeError:r}=dp();function i(e){let t=e[0];for(let n=1;n<e.length;n++)t=t.filter(t=>e[n].includes(t));return t}function a(e,t,n){let a=i(t);if(a.length===0)throw new r(e,t);n[e]=a}function o(e,t,n){for(let e=0;e<t.length;e++)Array.isArray(t[e])||(t[e]=[t[e]]);let a=i(t);if(a.length===0)throw new r(e,t);a.length===1?n[e]=a[0]:n[e]=a}function s(e,t,n){let r=[];for(let e of t)for(let t of e)r.includes(t)||r.push(t);n[e]=r}function c(e,t,n){n[e]=Math.min(...t)}function l(e,t,n){n[e]=Math.max(...t)}function u(e,t,n){let r=(e,t)=>t?r(t,e%t):e,i=(e,t)=>e*t/r(e,t),a=1;for(let e of t)for(;e*a%1!=0;)a*=10;let o=t[0]*a;for(let e of t)o=i(o,e*a);n[e]=o/a}function d(e,t,i){let a=t[0];for(let i=1;i<t.length;i++)if(!n(t[i],a))throw new r(e,t);i[e]=a}function f(){}function p(e,t,n){for(let r of t)if(r===!1){n[e]=!1;return}n[e]=!0}function m(e,t,n){for(let r of t)if(r===!0){n[e]=!0;return}n[e]=!1}t.exports={arraysIntersection:a,hybridArraysIntersection:o,arraysUnion:s,minNumber:c,maxNumber:l,commonMultiple:u,allEqual:d,booleanAnd:p,booleanOr:m,skip:f}})),pp=o(((e,t)=>{let{dequal:n}=op(),r=fp(),i=dp(),a={$id:r.skip,type:r.hybridArraysIntersection,enum:r.arraysIntersection,minLength:r.maxNumber,maxLength:r.minNumber,minimum:r.maxNumber,maximum:r.minNumber,multipleOf:r.commonMultiple,exclusiveMinimum:r.maxNumber,exclusiveMaximum:r.minNumber,minItems:r.maxNumber,maxItems:r.minNumber,maxProperties:r.minNumber,minProperties:r.maxNumber,const:r.allEqual,default:r.allEqual,format:r.allEqual,required:r.arraysUnion,properties:p,patternProperties:m,additionalProperties:o,items:u,additionalItems:d,definitions:m,$defs:m,nullable:r.booleanAnd,oneOf:c,anyOf:c,allOf:r.arraysUnion,not:o,if:h,then:r.skip,else:r.skip,dependencies:g,dependentRequired:g,dependentSchemas:m,propertyNames:o,uniqueItems:r.booleanOr,contains:o};function o(e,t,n,r,i){n[e]=_(t,i)}function s(e){let t=[[]];for(let n of e){let e=[];for(let r of t)for(let t of n)e.push([...r,t]);t=e}return t}function c(e,t,n,r,a){if(t.length===1){n[e]=t[0];return}let o=s(t),c=[];for(let e of o)try{let t=_(e,a);t!==void 0&&c.push(t)}catch(e){if(e instanceof i.MergeError)continue;throw e}n[e]=c}function l(e,t){let{items:n,additionalItems:r}=e;return Array.isArray(n)?t<n.length?n[t]:r:n===void 0?r:n}function u(e,t,n,r,i){let a=0;for(let e of t)Array.isArray(e)&&(a=Math.max(a,e.length));if(a===0){n[e]=_(t,i);return}let o=[];for(let e=0;e<a;e++){let t=[];for(let n of r){let r=l(n,e);r!==void 0&&t.push(r)}o[e]=_(t,i)}n[e]=o}function d(e,t,n,r,i){let a=!1;for(let e of r)if(Array.isArray(e.items)){a=!0;break}if(!a){n[e]=_(t,i);return}let o=[];for(let e of r){let t=e.additionalItems;t===void 0&&!Array.isArray(e.items)&&(t=e.items),t!==void 0&&o.push(t)}n[e]=_(o,i)}function f(e,t){let{properties:n,patternProperties:r,additionalProperties:i}=e;if(n?.[t]!==void 0)return n[t];for(let e of Object.keys(r??{}))if(new RegExp(e).test(t))return r[e];return i}function p(e,t,n,r,i){let a={};for(let e of r){let t=e.properties??{};for(let n of Object.keys(t))if(a[n]===void 0){a[n]=[t[n]];for(let t of r){if(e===t)continue;let r=f(t,n);r!==void 0&&a[n].push(r)}}}let o={};for(let e of Object.keys(a)){let t=a[e];o[e]=_(t,i)}n[e]=o}function m(e,t,n,r,i){let a={};for(let e of t)for(let t of Object.keys(e))a[t]===void 0&&(a[t]=[]),a[t].push(e[t]);let o={};for(let e of Object.keys(a)){let t=a[e];o[e]=_(t,i)}n[e]=o}function h(e,t,n,r,i){for(let e=0;e<r.length;e++){let t={if:r[e].if,then:r[e].then,else:r[e].else};if(t.if!==void 0){if(n.if===void 0){n.if=t.if,t.then!==void 0&&(n.then=t.then),t.else!==void 0&&(n.else=t.else);continue}n.then!==void 0&&(n.then=_([n.then,t],i)),n.else!==void 0&&(n.else=_([n.else,t],i))}}}function g(e,t,n){let r={};for(let e of t)for(let t of Object.keys(e)){r[t]===void 0&&(r[t]=[]);let n=r[t];for(let r of e[t])n.includes(r)||n.push(r)}n[e]=r}function _(e,t){if(e.length===0)return{};if(e.length===1)return e[0];let n={},r={},i=!0;for(let t of e){if(t===!1)return!1;if(t!==!0){i=!1;for(let e of Object.keys(t))r[e]===void 0&&(r[e]=[]),r[e].push(t[e])}}if(i)return!0;for(let i of Object.keys(r)){let a=r[i];(t.resolvers[i]??t.defaultResolver)(i,a,n,e,t)}return n}function v(e,t,r,a,o){let s=o.onConflict??`throw`;if(t.length===1||s===`first`){r[e]=t[0];return}let c=!0;for(let e=1;e<t.length;e++)if(!n(t[e],t[0])){c=!1;break}if(c){r[e]=t[0];return}if(s===`throw`)throw new i.ResolverNotFoundError(e,t);if(s!==`skip`)throw new i.InvalidOnConflictOptionError(s)}function y(e,t={}){return t.defaultResolver===void 0&&(t.defaultResolver=v),t.resolvers={...a,...t.resolvers},_(e,t)}t.exports={mergeSchemas:y,keywordsResolvers:a,defaultResolver:v,...i}})),mp=o(((e,t)=>{let{mergeSchemas:n}=pp();function r(e){return n(e,{onConflict:`skip`})}t.exports=r})),hp=o(((e,t)=>{function n(e,t,n,r){let i=``;t.validatorSchemasIds.size>0?(i+=`const Validator = require('fast-json-stringify/lib/validator')
|
|
135
|
+
deps: ${r}}`};let i={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,n]=a(e);o(e,t),s(e,n)}};function a({schema:e}){let t={},n={};for(let r in e){if(r===`__proto__`)continue;let i=Array.isArray(e[r])?t:n;i[r]=e[r]}return[t,n]}function o(e,n=e.schema){let{gen:i,data:a,it:o}=e;if(Object.keys(n).length===0)return;let s=i.let(`missing`);for(let c in n){let l=n[c];if(l.length===0)continue;let u=(0,r.propertyInData)(i,a,c,o.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(`, `)}),o.allErrors?i.if(u,()=>{for(let t of l)(0,r.checkReportMissingProp)(e,t)}):(i.if((0,t._)`${u} && (${(0,r.checkMissingProp)(e,l,s)})`),(0,r.reportMissingProp)(e,s),i.else())}}e.validatePropertyDeps=o;function s(e,t=e.schema){let{gen:i,data:a,keyword:o,it:s}=e,c=i.name(`valid`);for(let l in t)(0,n.alwaysValidSchema)(s,t[l])||(i.if((0,r.propertyInData)(i,a,l,s.opts.ownProperties),()=>{let t=e.subschema({keyword:o,schemaProp:l},c);e.mergeValidEvaluated(t,c)},()=>i.var(c,!0)),e.ok(c))}e.validateSchemaDeps=s,e.default=i})),ff=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z(),n=yd();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:r,schema:i,data:a,it:o}=e;if((0,n.alwaysValidSchema)(o,i))return;let s=r.name(`valid`);r.forIn(`key`,a,n=>{e.setParams({propertyName:n}),e.subschema({keyword:`propertyNames`,data:n,dataTypes:[`string`],propertyName:n,compositeRule:!0},s),r.if((0,t.not)(s),()=>{e.error(!0),o.allErrors||r.break()})}),e.ok(s)}}})),pf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Dd(),n=Z(),r=bd(),i=yd();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,n._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:a,schema:o,parentSchema:s,data:c,errsCount:l,it:u}=e;if(!l)throw Error(`ajv implementation error`);let{allErrors:d,opts:f}=u;if(u.props=!0,f.removeAdditional!==`all`&&(0,i.alwaysValidSchema)(u,o))return;let p=(0,t.allSchemaProperties)(s.properties),m=(0,t.allSchemaProperties)(s.patternProperties);h(),e.ok((0,n._)`${l} === ${r.default.errors}`);function h(){a.forIn(`key`,c,e=>{!p.length&&!m.length?v(e):a.if(g(e),()=>v(e))})}function g(r){let o;if(p.length>8){let e=(0,i.schemaRefOrVal)(u,s.properties,`properties`);o=(0,t.isOwnProperty)(a,e,r)}else o=p.length?(0,n.or)(...p.map(e=>(0,n._)`${r} === ${e}`)):n.nil;return m.length&&(o=(0,n.or)(o,...m.map(i=>(0,n._)`${(0,t.usePattern)(e,i)}.test(${r})`))),(0,n.not)(o)}function _(e){a.code((0,n._)`delete ${c}[${e}]`)}function v(t){if(f.removeAdditional===`all`||f.removeAdditional&&o===!1){_(t);return}if(o===!1){e.setParams({additionalProperty:t}),e.error(),d||a.break();return}if(typeof o==`object`&&!(0,i.alwaysValidSchema)(u,o)){let r=a.name(`valid`);f.removeAdditional===`failing`?(y(t,r,!1),a.if((0,n.not)(r),()=>{e.reset(),_(t)})):(y(t,r),d||a.if((0,n.not)(r),()=>a.break()))}}function y(t,n,r){let a={keyword:`additionalProperties`,dataProp:t,dataPropType:i.Type.Str};r===!1&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(a,n)}}}})),mf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Nd(),n=Dd(),r=yd(),i=pf();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,parentSchema:s,data:c,it:l}=e;l.opts.removeAdditional===`all`&&s.additionalProperties===void 0&&i.default.code(new t.KeywordCxt(l,i.default,`additionalProperties`));let u=(0,n.allSchemaProperties)(o);for(let e of u)l.definedProperties.add(e);l.opts.unevaluated&&u.length&&l.props!==!0&&(l.props=r.mergeEvaluated.props(a,(0,r.toHash)(u),l.props));let d=u.filter(e=>!(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0)return;let f=a.name(`valid`);for(let t of d)p(t)?m(t):(a.if((0,n.propertyInData)(a,c,t,l.opts.ownProperties)),m(t),l.allErrors||a.else().var(f,!0),a.endIf()),e.it.definedProperties.add(t),e.ok(f);function p(e){return l.opts.useDefaults&&!l.compositeRule&&o[e].default!==void 0}function m(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},f)}}}})),hf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Dd(),n=Z(),r=yd(),i=yd();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,data:s,parentSchema:c,it:l}=e,{opts:u}=l,d=(0,t.allSchemaProperties)(o),f=d.filter(e=>(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0||f.length===d.length&&(!l.opts.unevaluated||l.props===!0))return;let p=u.strictSchema&&!u.allowMatchingProperties&&c.properties,m=a.name(`valid`);l.props!==!0&&!(l.props instanceof n.Name)&&(l.props=(0,i.evaluatedPropsToName)(a,l.props));let{props:h}=l;g();function g(){for(let e of d)p&&_(e),l.allErrors?v(e):(a.var(m,!0),v(e),a.if(m))}function _(e){for(let t in p)new RegExp(e).test(t)&&(0,r.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function v(r){a.forIn(`key`,s,o=>{a.if((0,n._)`${(0,t.usePattern)(e,r)}.test(${o})`,()=>{let t=f.includes(r);t||e.subschema({keyword:`patternProperties`,schemaProp:r,dataProp:o,dataPropType:i.Type.Str},m),l.opts.unevaluated&&h!==!0?a.assign((0,n._)`${h}[${o}]`,!0):!t&&!l.allErrors&&a.if((0,n.not)(m),()=>a.break())})})}}}})),gf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=yd();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:n,schema:r,it:i}=e;if((0,t.alwaysValidSchema)(i,r)){e.fail();return}let a=n.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),_f=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:Dd().validateUnion,error:{message:`must match a schema in anyOf`}}})),vf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z(),n=yd();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:r,schema:i,parentSchema:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(o.opts.discriminator&&a.discriminator)return;let s=i,c=r.let(`valid`,!1),l=r.let(`passing`,null),u=r.name(`_valid`);e.setParams({passing:l}),r.block(d),e.result(c,()=>e.reset(),()=>e.error(!0));function d(){s.forEach((i,a)=>{let s;(0,n.alwaysValidSchema)(o,i)?r.var(u,!0):s=e.subschema({keyword:`oneOf`,schemaProp:a,compositeRule:!0},u),a>0&&r.if((0,t._)`${u} && ${c}`).assign(c,!1).assign(l,(0,t._)`[${l}, ${a}]`).else(),r.if(u,()=>{r.assign(c,!0),r.assign(l,a),s&&e.mergeEvaluated(s,t.Name)})})}}}})),yf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=yd();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid`);r.forEach((n,r)=>{if((0,t.alwaysValidSchema)(i,n))return;let o=e.subschema({keyword:`allOf`,schemaProp:r},a);e.ok(a),e.mergeEvaluated(o)})}}})),bf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z(),n=yd(),r={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:r,parentSchema:a,it:o}=e;a.then===void 0&&a.else===void 0&&(0,n.checkStrictMode)(o,`"if" without "then" and "else" is ignored`);let s=i(o,`then`),c=i(o,`else`);if(!s&&!c)return;let l=r.let(`valid`,!0),u=r.name(`_valid`);if(d(),e.reset(),s&&c){let t=r.let(`ifClause`);e.setParams({ifClause:t}),r.if(u,f(`then`,t),f(`else`,t))}else s?r.if(u,f(`then`)):r.if((0,t.not)(u),f(`else`));e.pass(l,()=>e.error(!0));function d(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}function f(n,i){return()=>{let a=e.subschema({keyword:n},u);r.assign(l,u),e.mergeValidEvaluated(a,l),i?r.assign(i,(0,t._)`${n}`):e.setParams({ifClause:n})}}}};function i(e,t){let r=e.schema[t];return r!==void 0&&!(0,n.alwaysValidSchema)(e,r)}e.default=r})),xf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=yd();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:n,it:r}){n.if===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "if" is ignored`)}}})),Sf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=of(),n=cf(),r=sf(),i=lf(),a=uf(),o=df(),s=ff(),c=pf(),l=mf(),u=hf(),d=gf(),f=_f(),p=vf(),m=yf(),h=bf(),g=xf();function _(e=!1){let _=[d.default,f.default,p.default,m.default,h.default,g.default,s.default,c.default,o.default,l.default,u.default];return e?_.push(n.default,i.default):_.push(t.default,r.default),_.push(a.default),_}e.default=_})),Cf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,n){let{gen:r,data:i,$data:a,schema:o,schemaCode:s,it:c}=e,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;a?p():m();function p(){let a=r.scopeValue(`formats`,{ref:f.formats,code:l.code.formats}),o=r.const(`fDef`,(0,t._)`${a}[${s}]`),c=r.let(`fType`),u=r.let(`format`);r.if((0,t._)`typeof ${o} == "object" && !(${o} instanceof RegExp)`,()=>r.assign(c,(0,t._)`${o}.type || "string"`).assign(u,(0,t._)`${o}.validate`),()=>r.assign(c,(0,t._)`"string"`).assign(u,o)),e.fail$data((0,t.or)(p(),m()));function p(){return l.strictSchema===!1?t.nil:(0,t._)`${s} && !${u}`}function m(){let e=d.$async?(0,t._)`(${o}.async ? await ${u}(${i}) : ${u}(${i}))`:(0,t._)`${u}(${i})`,r=(0,t._)`(typeof ${u} == "function" ? ${e} : ${u}.test(${i}))`;return(0,t._)`${u} && ${u} !== true && ${c} === ${n} && !${r}`}}function m(){let a=f.formats[o];if(!a){m();return}if(a===!0)return;let[s,c,p]=h(a);s===n&&e.pass(g());function m(){if(l.strictSchema===!1){f.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function h(e){let n=e instanceof RegExp?(0,t.regexpCode)(e):l.code.formats?(0,t._)`${l.code.formats}${(0,t.getProperty)(o)}`:void 0,i=r.scopeValue(`formats`,{key:o,ref:e,code:n});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${i}.validate`]:[`string`,e,i]}function g(){if(typeof a==`object`&&!(a instanceof RegExp)&&a.async){if(!d.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${p}(${i})`}return typeof c==`function`?(0,t._)`${p}(${i})`:(0,t._)`${p}.test(${i})`}}}}})),wf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=[Cf().default]})),Tf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),Ef=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Gd(),n=af(),r=Sf(),i=wf(),a=Tf();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),Df=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),Of=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z(),n=Df(),r=Id(),i=Fd(),a=yd();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:n,tagName:r}})=>(0,t._)`{error: ${e}, tag: ${r}, tagValue: ${n}}`},code(e){let{gen:o,data:s,schema:c,parentSchema:l,it:u}=e,{oneOf:d}=l;if(!u.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let f=c.propertyName;if(typeof f!=`string`)throw Error(`discriminator: requires propertyName`);if(c.mapping)throw Error(`discriminator: mapping is not supported`);if(!d)throw Error(`discriminator: requires oneOf keyword`);let p=o.let(`valid`,!1),m=o.const(`tag`,(0,t._)`${s}${(0,t.getProperty)(f)}`);o.if((0,t._)`typeof ${m} == "string"`,()=>h(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:m,tagName:f})),e.ok(p);function h(){let r=_();o.if(!1);for(let e in r)o.elseIf((0,t._)`${m} === ${e}`),o.assign(p,g(r[e]));o.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:m,tagName:f}),o.endIf()}function g(n){let r=o.name(`valid`),i=e.subschema({keyword:`oneOf`,schemaProp:n},r);return e.mergeEvaluated(i,t.Name),r}function _(){let e={},t=o(l),n=!0;for(let e=0;e<d.length;e++){let c=d[e];if(c?.$ref&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){let e=c.$ref;if(c=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof r.SchemaEnv&&(c=c.schema),c===void 0)throw new i.default(u.opts.uriResolver,u.baseId,e)}let l=c?.properties?.[f];if(typeof l!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);n&&=t||o(c),s(l,e)}if(!n)throw Error(`discriminator: "${f}" must be required`);return e;function o({required:e}){return Array.isArray(e)&&e.includes(f)}function s(e,t){if(e.const)c(e.const,t);else if(e.enum)for(let n of e.enum)c(n,t);else throw Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function c(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${f}" values must be unique strings`);e[t]=n}}}}})),kf=o(((e,t)=>{t.exports={$schema:`http://json-schema.org/draft-07/schema#`,$id:`http://json-schema.org/draft-07/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:!0}})),Af=o(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let n=Hd(),r=Ef(),i=Of(),a=kf(),o=[`/properties`],s=`http://json-schema.org/draft-07/schema`;var c=class extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,s,!1),this.refs[`http://json-schema.org/schema`]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=c;var l=Nd();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return l.KeywordCxt}});var u=Z();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return u.CodeGen}});var d=Pd();Object.defineProperty(e,`ValidationError`,{enumerable:!0,get:function(){return d.default}});var f=Fd();Object.defineProperty(e,`MissingRefError`,{enumerable:!0,get:function(){return f.default}})})),jf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.checkMetadata=void 0;let t=yd(),n={keyword:`metadata`,schemaType:`object`,code(e){r(e);let{gen:n,schema:i,it:a}=e;if((0,t.alwaysValidSchema)(a,i))return;let o=n.name(`valid`);e.subschema({keyword:`metadata`,jtdMetadata:!0},o),e.ok(o)}};function r({it:e,keyword:t},n){if(e.jtdMetadata!==n)throw Error(`JTD: "${t}" cannot be used in this schema location`)}e.checkMetadata=r,e.default=n})),Mf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.hasRef=void 0;let t=Id(),n=Z(),r=Fd(),i=bd(),a=Wd(),o=jf(),s={keyword:`ref`,schemaType:`string`,code(e){(0,o.checkMetadata)(e);let{gen:s,data:l,schema:u,parentSchema:d,it:f}=e,{schemaEnv:{root:p}}=f,m=s.name(`valid`);d.nullable?(s.var(m,(0,n._)`${l} === null`),s.if((0,n.not)(m),h)):(s.var(m,!1),h()),e.ok(m);function h(){let e=p.schema.definitions?.[u];if(!e)throw new r.default(f.opts.uriResolver,``,u,`No definition ${u}`);c(e)||!f.opts.inlineRefs?g(e):_(e)}function g(r){let o=t.compileSchema.call(f.self,new t.SchemaEnv({schema:r,root:p,schemaPath:`/definitions/${u}`})),c=(0,a.getValidate)(e,o),l=s.const(`_errs`,i.default.errors);(0,a.callRef)(e,c,o,o.$async),s.assign(m,(0,n._)`${l} === ${i.default.errors}`)}function _(t){let r=s.scopeValue(`schema`,f.opts.code.source===!0?{ref:t,code:(0,n.stringify)(t)}:{ref:t});e.subschema({schema:t,dataTypes:[],schemaPath:n.nil,topSchemaRef:r,errSchemaPath:`/definitions/${u}`},m)}}};function c(e){for(let t in e){let n;if(t===`ref`||typeof(n=e[t])==`object`&&c(n))return!0}return!1}e.hasRef=c,e.default=s})),Nf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=/t|\s/i,n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,r=/^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:z|([+-]\d\d)(?::?(\d\d))?)$/i,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e,n){let r=e.split(t);return r.length===2&&o(r[0])&&s(r[1])||n&&r.length===1&&o(r[0])}e.default=a;function o(e){let t=n.exec(e);if(!t)return!1;let r=+t[1],a=+t[2],o=+t[3];return a>=1&&a<=12&&o>=1&&(o<=i[a]||a===2&&o===29&&(r%100==0?r%400==0:r%4==0))}function s(e){let t=r.exec(e);if(!t)return!1;let n=+t[1],i=+t[2],a=+t[3],o=+(t[4]||0),s=+(t[5]||0);return n<=23&&i<=59&&a<=59||n-o===23&&i-s===59&&a===60}a.code=`require("ajv/dist/runtime/timestamp").default`})),Pf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.typeErrorParams=e.typeErrorMessage=e.typeError=void 0;let t=Z();function n(e){return{message:t=>r(t,e),params:t=>i(t,e)}}e.typeError=n;function r({parentSchema:e},t){return e?.nullable?`must be ${t} or null`:`must be ${t}`}e.typeErrorMessage=r;function i({parentSchema:e},n){return(0,t._)`{type: ${n}, nullable: ${!!e?.nullable}}`}e.typeErrorParams=i})),Ff=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.intRange=void 0;let t=Z(),n=Nf(),r=yd(),i=jf(),a=Pf();e.intRange={int8:[-128,127,3],uint8:[0,255,3],int16:[-32768,32767,5],uint16:[0,65535,5],int32:[-2147483648,2147483647,10],uint32:[0,4294967295,10]};let o={message:e=>(0,a.typeErrorMessage)(e,e.schema),params:e=>(0,a.typeErrorParams)(e,e.schema)};function s(e){let{gen:i,data:a,it:o}=e,{timestamp:s,allowDate:c}=o.opts;if(s===`date`)return(0,t._)`${a} instanceof Date `;let l=(0,r.useFunc)(i,n.default),u=c?(0,t._)`, true`:t.nil,d=(0,t._)`typeof ${a} == "string" && ${l}(${a}${u})`;return s===`string`?d:(0,t.or)((0,t._)`${a} instanceof Date`,d)}e.default={keyword:`type`,schemaType:`string`,error:o,code(n){(0,i.checkMetadata)(n);let{data:r,schema:a,parentSchema:o,it:c}=n,l;switch(a){case`boolean`:case`string`:l=(0,t._)`typeof ${r} == ${a}`;break;case`timestamp`:l=s(n);break;case`float32`:case`float64`:l=(0,t._)`typeof ${r} == "number"`;break;default:{let n=a;if(l=(0,t._)`typeof ${r} == "number" && isFinite(${r}) && !(${r} % 1)`,!c.opts.int32range&&(n===`int32`||n===`uint32`))n===`uint32`&&(l=(0,t._)`${l} && ${r} >= 0`);else{let[i,a]=e.intRange[n];l=(0,t._)`${l} && ${r} >= ${i} && ${r} <= ${a}`}}}n.pass(o.nullable?(0,t.or)((0,t._)`${r} === null`,l):l)}}})),If=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.checkNullableObject=e.checkNullable=void 0;let t=Z();function n({gen:e,data:n,parentSchema:r},i=t.nil){let a=e.name(`valid`);return r.nullable?(e.let(a,(0,t._)`${n} === null`),i=(0,t.not)(a)):e.let(a,!1),[a,i]}e.checkNullable=n;function r(e,r){let[i,a]=n(e,r);return[i,(0,t._)`${a} && typeof ${e.data} == "object" && !Array.isArray(${e.data})`]}e.checkNullableObject=r})),Lf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z(),n=jf(),r=If();e.default={keyword:`enum`,schemaType:`array`,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){(0,n.checkMetadata)(e);let{gen:i,data:a,schema:o,schemaValue:s,parentSchema:c,it:l}=e;if(o.length===0)throw Error(`enum must have non-empty array`);if(o.length!==new Set(o).size)throw Error(`enum items must be unique`);let u,d=(0,t._)`typeof ${a} == "string"`;if(o.length>=l.opts.loopEnum){let t;[u,t]=(0,r.checkNullable)(e,d),i.if(t,f)}else{if(!Array.isArray(o))throw Error(`ajv implementation error`);u=(0,t.and)(d,(0,t.or)(...o.map(e=>(0,t._)`${a} === ${e}`))),c.nullable&&(u=(0,t.or)((0,t._)`${a} === null`,u))}e.pass(u);function f(){i.forOf(`v`,s,e=>i.if((0,t._)`${u} = ${a} === ${e}`,()=>i.break()))}}}})),Rf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=yd(),n=Dd(),r=Z(),i=jf(),a=If();e.default={keyword:`elements`,schemaType:`object`,error:(0,Pf().typeError)(`array`),code(e){(0,i.checkMetadata)(e);let{gen:o,data:s,schema:c,it:l}=e;if((0,t.alwaysValidSchema)(l,c))return;let[u]=(0,a.checkNullable)(e);o.if((0,r.not)(u),()=>o.if((0,r._)`Array.isArray(${s})`,()=>o.assign(u,(0,n.validateArray)(e)),()=>e.error())),e.ok(u)}}})),zf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateProperties=e.error=void 0;let t=Dd(),n=yd(),r=Z(),i=jf(),a=If(),o=Pf();var s;(function(e){e.Additional=`additional`,e.Missing=`missing`})(s||={}),e.error={message:e=>{let{params:t}=e;return t.propError?t.propError===s.Additional?`must NOT have additional properties`:`must have property '${t.missingProperty}'`:(0,o.typeErrorMessage)(e,`object`)},params:e=>{let{params:t}=e;return t.propError?t.propError===s.Additional?(0,r._)`{error: ${t.propError}, additionalProperty: ${t.additionalProperty}}`:(0,r._)`{error: ${t.propError}, missingProperty: ${t.missingProperty}}`:(0,o.typeErrorParams)(e,`object`)}};let c={keyword:`properties`,schemaType:`object`,error:e.error,code:l};function l(e){(0,i.checkMetadata)(e);let{gen:o,data:c,parentSchema:l,it:u}=e,{additionalProperties:d,nullable:f}=l;if(u.jtdDiscriminator&&f)throw Error(`JTD: nullable inside discriminator mapping`);if(y())throw Error(`JTD: properties and optionalProperties have common members`);let[p,m]=b(`properties`),[h,g]=b(`optionalProperties`);if(m.length===0&&g.length===0&&d)return;let[_,v]=u.jtdDiscriminator===void 0?(0,a.checkNullableObject)(e,c):[o.let(`valid`,!1),!0];o.if(v,()=>o.assign(_,!0).block(()=>{x(m,`properties`,!0),x(g,`optionalProperties`),d||C()})),e.pass(_);function y(){let e=l.properties,t=l.optionalProperties;if(!(e&&t))return!1;for(let n in e)if(Object.prototype.hasOwnProperty.call(t,n))return!0;return!1}function b(e){let r=l[e],i=r?(0,t.allSchemaProperties)(r):[];if(u.jtdDiscriminator&&i.some(e=>e===u.jtdDiscriminator))throw Error(`JTD: discriminator tag used in ${e}`);return[i,i.filter(e=>!(0,n.alwaysValidSchema)(u,r[e]))]}function x(n,r,i){let a=o.var(`valid`);for(let i of n)o.if((0,t.propertyInData)(o,c,i,u.opts.ownProperties),()=>S(i,r,a),()=>l(i)),e.ok(a);function l(t){i?(o.assign(a,!1),e.error(!1,{propError:s.Missing,missingProperty:t},{schemaPath:t})):o.assign(a,!0)}}function S(t,n,r){e.subschema({keyword:n,schemaProp:t,dataProp:t},r)}function C(){o.forIn(`key`,c,t=>{let n=w(t,p,`properties`,u.jtdDiscriminator),i=w(t,h,`optionalProperties`),a=n===!0?i:i===!0?n:(0,r.and)(n,i);o.if(a,()=>{u.opts.removeAdditional?o.code((0,r._)`delete ${c}[${t}]`):(e.error(!1,{propError:s.Additional,additionalProperty:t},{instancePath:t,parentSchema:!0}),u.opts.allErrors||o.break())})})}function w(e,i,a,s){let c;if(i.length>8){let i=(0,n.schemaRefOrVal)(u,l[a],a);c=(0,r.not)((0,t.isOwnProperty)(o,i,e)),s!==void 0&&(c=(0,r.and)(c,(0,r._)`${e} !== ${s}`))}else if(i.length||s!==void 0){let t=s===void 0?i:[s].concat(i);c=(0,r.and)(...t.map(t=>(0,r._)`${e} !== ${t}`))}else c=!0;return c}}e.validateProperties=l,e.default=c})),Bf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=zf();e.default={keyword:`optionalProperties`,schemaType:`object`,error:t.error,code(e){e.parentSchema.properties||(0,t.validateProperties)(e)}}})),Vf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z(),n=jf(),r=If(),i=Pf(),a=Df();e.default={keyword:`discriminator`,schemaType:`string`,implements:[`mapping`],error:{message:e=>{let{schema:t,params:n}=e;return n.discrError?n.discrError===a.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in mapping`:(0,i.typeErrorMessage)(e,`object`)},params:e=>{let{schema:n,params:r}=e;return r.discrError?(0,t._)`{error: ${r.discrError}, tag: ${n}, tagValue: ${r.tag}}`:(0,i.typeErrorParams)(e,`object`)}},code(e){(0,n.checkMetadata)(e);let{gen:i,data:o,schema:s,parentSchema:c}=e,[l,u]=(0,r.checkNullableObject)(e,o);i.if(u),d(),i.elseIf((0,t.not)(l)),e.error(),i.endIf(),e.ok(l);function d(){let n=i.const(`tag`,(0,t._)`${o}${(0,t.getProperty)(s)}`);i.if((0,t._)`${n} === undefined`),e.error(!1,{discrError:a.DiscrError.Tag,tag:n}),i.elseIf((0,t._)`typeof ${n} == "string"`),f(n),i.else(),e.error(!1,{discrError:a.DiscrError.Tag,tag:n},{instancePath:s}),i.endIf()}function f(n){i.if(!1);for(let e in c.mapping)i.elseIf((0,t._)`${n} === ${e}`),i.assign(l,p(e));i.else(),e.error(!1,{discrError:a.DiscrError.Mapping,tag:n},{instancePath:s,schemaPath:`mapping`,parentSchema:!0}),i.endIf()}function p(t){let n=i.name(`valid`);return e.subschema({keyword:`mapping`,schemaProp:t,jtdDiscriminator:s},n),n}}}})),Hf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=yd(),n=Z(),r=jf(),i=If();e.default={keyword:`values`,schemaType:`object`,error:(0,Pf().typeError)(`object`),code(e){(0,r.checkMetadata)(e);let{gen:a,data:o,schema:s,it:c}=e,[l,u]=(0,i.checkNullableObject)(e,o);(0,t.alwaysValidSchema)(c,s)?a.if((0,n.not)((0,n.or)(u,l)),()=>e.error()):(a.if(u),a.assign(l,d()),a.elseIf((0,n.not)(l)),e.error(),a.endIf()),e.ok(l);function d(){let r=a.name(`valid`);if(c.allErrors){let e=a.let(`valid`,!0);return i(()=>a.assign(e,!1)),e}return a.var(r,!0),i(()=>a.break()),r;function i(i){a.forIn(`key`,o,o=>{e.subschema({keyword:`values`,dataProp:o,dataPropType:t.Type.Str},r),a.if((0,n.not)(r),i)})}}}}})),Uf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`union`,schemaType:`array`,trackErrors:!0,code:Dd().validateUnion,error:{message:`must match a schema in union`}}})),Wf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Mf(),n=Ff(),r=Lf(),i=Rf(),a=zf(),o=Bf(),s=Vf(),c=Hf(),l=Uf(),u=jf();e.default=[`definitions`,t.default,n.default,r.default,i.default,a.default,o.default,s.default,c.default,l.default,u.default,{keyword:`additionalProperties`,schemaType:`boolean`},{keyword:`nullable`,schemaType:`boolean`}]})),Gf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=e=>{let t={nullable:{type:`boolean`},metadata:{optionalProperties:{union:{elements:{ref:`schema`}}},additionalProperties:!0}};return e&&(t.definitions={values:{ref:`schema`}}),t},n=e=>({optionalProperties:t(e)}),r=e=>({properties:{ref:{type:`string`}},optionalProperties:t(e)}),i=e=>({properties:{type:{enum:[`boolean`,`timestamp`,`string`,`float32`,`float64`,`int8`,`uint8`,`int16`,`uint16`,`int32`,`uint32`]}},optionalProperties:t(e)}),a=e=>({properties:{enum:{elements:{type:`string`}}},optionalProperties:t(e)}),o=e=>({properties:{elements:{ref:`schema`}},optionalProperties:t(e)}),s=e=>({properties:{properties:{values:{ref:`schema`}}},optionalProperties:{optionalProperties:{values:{ref:`schema`}},additionalProperties:{type:`boolean`},...t(e)}}),c=e=>({properties:{optionalProperties:{values:{ref:`schema`}}},optionalProperties:{additionalProperties:{type:`boolean`},...t(e)}}),l=e=>({properties:{discriminator:{type:`string`},mapping:{values:{metadata:{union:[s(!1),c(!1)]}}}},optionalProperties:t(e)}),u=e=>({properties:{values:{ref:`schema`}},optionalProperties:t(e)}),d=e=>({metadata:{union:[n,r,i,a,o,s,c,l,u].map(t=>t(e))}});e.default={definitions:{schema:d(!1)},...d(!0)}})),Kf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.jtdForms=void 0,e.jtdForms=[`elements`,`values`,`discriminator`,`properties`,`optionalProperties`,`enum`,`type`,`ref`]})),qf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=/[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n={"\b":`\\b`," ":`\\t`,"\n":`\\n`,"\f":`\\f`,"\r":`\\r`,'"':`\\"`,"\\":`\\\\`};function r(e){return t.lastIndex=0,`"`+(t.test(e)?e.replace(t,e=>{let t=n[e];return typeof t==`string`?t:`\\u`+(`0000`+e.charCodeAt(0).toString(16)).slice(-4)}):e)+`"`}e.default=r,r.code=`require("ajv/dist/runtime/quote").default`})),Jf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Kf(),n=Id(),r=Z(),i=Fd(),a=bd(),o=Dd(),s=Mf(),c=yd(),l=qf(),u={elements:m,values:h,discriminator:_,properties:v,optionalProperties:v,enum:x,type:b,ref:C};function d(e,t){let i=n.getCompilingSchema.call(this,e);if(i)return i;let{es5:o,lines:s}=this.opts.code,{ownProperties:c}=this.opts,l=new r.CodeGen(this.scope,{es5:o,lines:s,ownProperties:c}),u=l.scopeName(`serialize`),d={self:this,gen:l,schema:e.schema,schemaEnv:e,definitions:t,data:a.default.data},p;try{this._compilations.add(e),e.serializeName=u,l.func(u,a.default.data,!1,()=>{l.let(a.default.json,(0,r.str)``),f(d),l.return(a.default.json)}),l.optimize(this.opts.code.optimize);let t=l.toString();p=`${l.scopeRefs(a.default.scope)}return ${t}`;let n=Function(`${a.default.scope}`,p)(this.scope.get());this.scope.value(u,{ref:n}),e.serialize=n}catch(t){throw p&&this.logger.error(`Error compiling serializer, function code:`,p),delete e.serialize,delete e.serializeName,t}finally{this._compilations.delete(e)}return e}e.default=d;function f(e){let n;for(let r of t.jtdForms)if(r in e.schema){n=r;break}p(e,n?u[n]:T)}function p(e,t){let{gen:n,schema:i,data:o}=e;if(!i.nullable)return t(e);n.if((0,r._)`${o} === undefined || ${o} === null`,()=>n.add(a.default.json,(0,r._)`"null"`),()=>t(e))}function m(e){let{gen:t,schema:n,data:i}=e;t.add(a.default.json,(0,r.str)`[`);let o=t.let(`first`,!0);t.forOf(`el`,i,t=>{E(e,o),f({...e,schema:n.elements,data:t})}),t.add(a.default.json,(0,r.str)`]`)}function h(e){let{gen:t,schema:n,data:i}=e;t.add(a.default.json,(0,r.str)`{`);let o=t.let(`first`,!0);t.forIn(`key`,i,t=>g(e,t,n.values,o)),t.add(a.default.json,(0,r.str)`}`)}function g(e,t,n,i){let{gen:o,data:s}=e;E(e,i),x({...e,data:t}),o.add(a.default.json,(0,r.str)`:`);let c=o.const(`value`,(0,r._)`${s}${(0,r.getProperty)(t)}`);f({...e,schema:n,data:c})}function _(e){let{gen:t,schema:n,data:i}=e,{discriminator:o}=n;t.add(a.default.json,(0,r.str)`{${JSON.stringify(o)}:`);let s=t.const(`tag`,(0,r._)`${i}${(0,r.getProperty)(o)}`);x({...e,data:s}),t.if(!1);for(let i in n.mapping){t.elseIf((0,r._)`${s} === ${i}`);let a=n.mapping[i];y({...e,schema:a},o)}t.endIf(),t.add(a.default.json,(0,r.str)`}`)}function v(e){let{gen:t}=e;t.add(a.default.json,(0,r.str)`{`),y(e),t.add(a.default.json,(0,r.str)`}`)}function y(e,t){let{gen:n,schema:i,data:s}=e,{properties:c,optionalProperties:l}=i,u=_(c),d=_(l),p=v(u.concat(d)),m=!t,h;for(let e of u)m?m=!1:n.add(a.default.json,(0,r.str)`,`),b(e,c[e],y(e));m&&(h=n.let(`first`,!0));for(let t of d){let i=y(t);n.if((0,r.and)((0,r._)`${i} !== undefined`,(0,o.isOwnProperty)(n,s,t)),()=>{E(e,h),b(t,l[t],i)})}i.additionalProperties&&n.forIn(`key`,s,t=>n.if(x(t,p),()=>g(e,t,{},h)));function _(e){return e?Object.keys(e):[]}function v(e){if(t&&e.push(t),new Set(e).size!==e.length)throw Error(`JTD: properties/optionalProperties/disciminator overlap`);return e}function y(e){return n.const(`value`,(0,r._)`${s}${(0,r.getProperty)(e)}`)}function b(t,i,o){n.add(a.default.json,(0,r.str)`${JSON.stringify(t)}:`),f({...e,schema:i,data:o})}function x(e,t){return t.length?(0,r.and)(...t.map(t=>(0,r._)`${e} !== ${t}`)):!0}}function b(e){let{gen:t,schema:n,data:i}=e;switch(n.type){case`boolean`:t.add(a.default.json,(0,r._)`${i} ? "true" : "false"`);break;case`string`:x(e);break;case`timestamp`:t.if((0,r._)`${i} instanceof Date`,()=>t.add(a.default.json,(0,r._)`'"' + ${i}.toISOString() + '"'`),()=>x(e));break;default:S(e)}}function x({gen:e,data:t}){e.add(a.default.json,(0,r._)`${(0,c.useFunc)(e,l.default)}(${t})`)}function S({gen:e,data:t,self:n}){let i=(0,r._)`${t} === Infinity || ${t} === -Infinity || ${t} !== ${t}`;n.opts.specialNumbers===void 0||n.opts.specialNumbers===`fast`?e.add(a.default.json,(0,r._)`"" + ${t}`):e.if(i,()=>e.add(a.default.json,(0,r._)`null`),()=>e.add(a.default.json,(0,r._)`"" + ${t}`))}function C(e){let{gen:t,self:o,data:c,definitions:l,schema:u,schemaEnv:p}=e,{ref:m}=u,h=l[m];if(!h)throw new i.default(o.opts.uriResolver,``,m,`No definition ${m}`);if(!(0,s.hasRef)(h))return f({...e,schema:h});let{root:g}=p,_=d.call(o,new n.SchemaEnv({schema:h,root:g}),l);t.add(a.default.json,(0,r._)`${w(t,_)}(${c})`)}function w(e,t){return t.serialize?e.scopeValue(`serialize`,{ref:t.serialize}):(0,r._)`${e.scopeValue(`wrapper`,{ref:t})}.serialize`}function T({gen:e,data:t}){e.add(a.default.json,(0,r._)`JSON.stringify(${t})`)}function E({gen:e},t){t?e.if(t,()=>e.assign(t,!1),()=>e.add(a.default.json,(0,r.str)`,`)):e.add(a.default.json,(0,r.str)`,`)}})),Yf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.parseJsonString=e.parseJsonNumber=e.parseJson=void 0;let t=/position\s(\d+)(?: \(line \d+ column \d+\))?$/;function n(e,r){let i;n.message=void 0;let a;r&&(e=e.slice(r));try{return n.position=r+e.length,JSON.parse(e)}catch(o){if(a=t.exec(o.message),!a){n.message=`unexpected end`;return}i=+a[1];let s=e[i];e=e.slice(0,i),n.position=r+i;try{return JSON.parse(e)}catch{n.message=`unexpected token ${s}`;return}}}e.parseJson=n,n.message=void 0,n.position=0,n.code=`require("ajv/dist/runtime/parseJson").parseJson`;function r(e,t,n){let i=``,a;if(r.message=void 0,e[t]===`-`&&(i+=`-`,t++),e[t]===`0`)i+=`0`,t++;else if(!o(n)){s();return}if(n)return r.position=t,+i;if(e[t]===`.`&&(i+=`.`,t++,!o())){s();return}if(a=e[t],(a===`e`||a===`E`)&&(i+=`e`,t++,a=e[t],(a===`+`||a===`-`)&&(i+=a,t++),!o())){s();return}return r.position=t,+i;function o(n){let r=!1;for(;a=e[t],a>=`0`&&a<=`9`&&(n===void 0||n-- >0);)r=!0,i+=a,t++;return r}function s(){r.position=t,r.message=t<e.length?`unexpected token ${e[t]}`:`unexpected end`}}e.parseJsonNumber=r,r.message=void 0,r.position=0,r.code=`require("ajv/dist/runtime/parseJson").parseJsonNumber`;let i={b:`\b`,f:`\f`,n:`
|
|
136
|
+
`,r:`\r`,t:` `,'"':`"`,"/":`/`,"\\":`\\`};function a(e,t){let n=``,r;for(a.message=void 0;r=e[t++],r!==`"`;)if(r===`\\`)if(r=e[t],r in i)n+=i[r],t++;else if(r===`u`){t++;let i=4,a=0;for(;i--;){if(a<<=4,r=e[t],r===void 0){o(`unexpected end`);return}if(r=r.toLowerCase(),r>=`a`&&r<=`f`)a+=r.charCodeAt(0)-97+10;else if(r>=`0`&&r<=`9`)a+=r.charCodeAt(0)-48;else{o(`unexpected token ${r}`);return}t++}n+=String.fromCharCode(a)}else{o(`unexpected token ${r}`);return}else if(r===void 0){o(`unexpected end`);return}else if(r.charCodeAt(0)>=32)n+=r;else{o(`unexpected token ${r}`);return}return a.position=t,n;function o(e){a.position=t,a.message=e}}e.parseJsonString=a,a.message=void 0,a.position=0,a.code=`require("ajv/dist/runtime/parseJson").parseJsonString`})),Xf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Kf(),n=Id(),r=Z(),i=Fd(),a=bd(),o=Dd(),s=Mf(),c=Ff(),l=Yf(),u=yd(),d=Nf(),f={elements:y,values:b,discriminator:w,properties:T,optionalProperties:T,enum:j,type:k,ref:N};function p(e,t){let i=n.getCompilingSchema.call(this,e);if(i)return i;let{es5:o,lines:s}=this.opts.code,{ownProperties:c}=this.opts,l=new r.CodeGen(this.scope,{es5:o,lines:s,ownProperties:c}),u=l.scopeName(`parse`),d={self:this,gen:l,schema:e.schema,schemaEnv:e,definitions:t,data:a.default.data,parseName:u,char:l.name(`c`)},f;try{this._compilations.add(e),e.parseName=u,h(d),l.optimize(this.opts.code.optimize);let t=l.toString();f=`${l.scopeRefs(a.default.scope)}return ${t}`;let n=Function(`${a.default.scope}`,f)(this.scope.get());this.scope.value(u,{ref:n}),e.parse=n}catch(t){throw f&&this.logger.error(`Error compiling parser, function code:`,f),delete e.parse,delete e.parseName,t}finally{this._compilations.delete(e)}return e}e.default=p;let m=(0,r._)`undefined`;function h(e){let{gen:t,parseName:n,char:i}=e;t.func(n,(0,r._)`${a.default.json}, ${a.default.jsonPos}, ${a.default.jsonPart}`,!1,()=>{t.let(a.default.data),t.let(i),t.assign((0,r._)`${n}.message`,m),t.assign((0,r._)`${n}.position`,m),t.assign(a.default.jsonPos,(0,r._)`${a.default.jsonPos} || 0`),t.const(a.default.jsonLen,(0,r._)`${a.default.json}.length`),g(e),L(e),t.if(a.default.jsonPart,()=>{t.assign((0,r._)`${n}.position`,a.default.jsonPos),t.return(a.default.data)}),t.if((0,r._)`${a.default.jsonPos} === ${a.default.jsonLen}`,()=>t.return(a.default.data)),ae(e)})}function g(e){let n;for(let r of t.jtdForms)if(r in e.schema){n=r;break}n?v(e,f[n]):P(e)}let _=ee(!0,ee(!1,ae));function v(e,t){let{gen:n,schema:r,data:i}=e;if(!r.nullable)return t(e);re(e,`null`,t,()=>n.assign(i,null))}function y(e){let{gen:t,schema:n,data:i}=e;I(e,`[`);let a=t.let(`i`,0);t.assign(i,(0,r._)`[]`),x(e,`]`,()=>{let o=t.let(`el`);g({...e,schema:n.elements,data:o}),t.assign((0,r._)`${i}[${a}++]`,o)})}function b(e){let{gen:t,schema:n,data:i}=e;I(e,`{`),t.assign(i,(0,r._)`{}`),x(e,`}`,()=>C(e,n.values))}function x(e,t,n){S(e,t,n),I(e,t)}function S(e,t,n){let{gen:i}=e;i.for((0,r._)`;${a.default.jsonPos}<${a.default.jsonLen} && ${ie(1)}!==${t};`,()=>{n(),re(e,`,`,()=>i.break(),o)});function o(){re(e,t,()=>{},ae)}}function C(e,t){let{gen:n}=e,r=n.let(`key`);A({...e,data:r}),I(e,`:`),O(e,r,t)}function w(e){let{gen:t,data:n,schema:i}=e,{discriminator:o,mapping:s}=i;I(e,`{`),t.assign(n,(0,r._)`{}`);let c=t.const(`pos`,a.default.jsonPos),l=t.let(`value`),u=t.let(`tag`);S(e,`}`,()=>{let i=t.let(`key`);A({...e,data:i}),I(e,`:`),t.if((0,r._)`${i} === ${o}`,()=>{A({...e,data:u}),t.assign((0,r._)`${n}[${i}]`,u),t.break()},()=>P({...e,data:l}))}),t.assign(a.default.jsonPos,c),t.if((0,r._)`${u} === undefined`),R(e,(0,r.str)`discriminator tag not found`);for(let n in s)t.elseIf((0,r._)`${u} === ${n}`),E({...e,schema:s[n]},o);t.else(),R(e,(0,r.str)`discriminator value not in schema`),t.endIf()}function T(e){let{gen:t,data:n}=e;I(e,`{`),t.assign(n,(0,r._)`{}`),E(e)}function E(e,t){let{gen:n,schema:i,data:a}=e,{properties:s,optionalProperties:c,additionalProperties:l}=i;if(x(e,`}`,()=>{let i=n.let(`key`);if(A({...e,data:i}),I(e,`:`),n.if(!1),D(e,i,s),D(e,i,c),t){n.elseIf((0,r._)`${i} === ${t}`);let a=n.let(`tag`);A({...e,data:a})}n.else(),l?P({...e,data:(0,r._)`${a}[${i}]`}):R(e,(0,r.str)`property ${i} not allowed`),n.endIf()}),s){let t=(0,o.hasPropFunc)(n),i=(0,r.and)(...Object.keys(s).map(e=>(0,r._)`${t}.call(${a}, ${e})`));n.if((0,r.not)(i),()=>R(e,(0,r.str)`missing required properties`))}}function D(e,t,n={}){let{gen:i}=e;for(let a in n)i.elseIf((0,r._)`${t} === ${a}`),O(e,t,n[a])}function O(e,t,n){g({...e,schema:n,data:(0,r._)`${e.data}[${t}]`})}function k(e){let{gen:t,schema:n,data:i,self:a}=e;switch(n.type){case`boolean`:_(e);break;case`string`:A(e);break;case`timestamp`:{A(e);let n=(0,u.useFunc)(t,d.default),{allowDate:o,parseDate:s}=a.opts,c=o?(0,r._)`!${n}(${i}, true)`:(0,r._)`!${n}(${i})`,l=s?(0,r.or)(c,(0,r._)`(${i} = new Date(${i}), false)`,(0,r._)`isNaN(${i}.valueOf())`):c;t.if(l,()=>R(e,(0,r.str)`invalid timestamp`));break}case`float32`:case`float64`:M(e);break;default:{let o=n.type;if(!a.opts.int32range&&(o===`int32`||o===`uint32`))M(e,16),o===`uint32`&&t.if((0,r._)`${i} < 0`,()=>R(e,(0,r.str)`integer out of range`));else{let[n,a,s]=c.intRange[o];M(e,s),t.if((0,r._)`${i} < ${n} || ${i} > ${a}`,()=>R(e,(0,r.str)`integer out of range`))}}}}function A(e){I(e,`"`),ne(e,l.parseJsonString)}function j(e){let{gen:t,data:n,schema:i}=e,o=i.enum;I(e,`"`),t.if(!1);for(let e of o){let i=JSON.stringify(e).slice(1);t.elseIf((0,r._)`${ie(i.length)} === ${i}`),t.assign(n,(0,r.str)`${e}`),t.add(a.default.jsonPos,i.length)}t.else(),ae(e),t.endIf()}function M(e,t){let{gen:n}=e;L(e),n.if((0,r._)`"-0123456789".indexOf(${ie(1)}) < 0`,()=>ae(e),()=>ne(e,l.parseJsonNumber,t))}function ee(e,t){return n=>{let{gen:r,data:i}=n;re(n,`${e}`,()=>t(n),()=>r.assign(i,e))}}function N(e){let{gen:t,self:r,definitions:a,schema:o,schemaEnv:c}=e,{ref:l}=o,u=a[l];if(!u)throw new i.default(r.opts.uriResolver,``,l,`No definition ${l}`);if(!(0,s.hasRef)(u))return g({...e,schema:u});let{root:d}=c;F(e,te(t,p.call(r,new n.SchemaEnv({schema:u,root:d}),a)),!0)}function te(e,t){return t.parse?e.scopeValue(`parse`,{ref:t.parse}):(0,r._)`${e.scopeValue(`wrapper`,{ref:t})}.parse`}function P(e){ne(e,l.parseJson)}function ne(e,t,n){F(e,(0,u.useFunc)(e.gen,t),n)}function F(e,t,n){let{gen:i,data:o}=e;i.assign(o,(0,r._)`${t}(${a.default.json}, ${a.default.jsonPos}${n?(0,r._)`, ${n}`:r.nil})`),i.assign(a.default.jsonPos,(0,r._)`${t}.position`),i.if((0,r._)`${o} === undefined`,()=>R(e,(0,r._)`${t}.message`))}function I(e,t){re(e,t,ae)}function re(e,t,n,i){let{gen:o}=e,s=t.length;L(e),o.if((0,r._)`${ie(s)} === ${t}`,()=>{o.add(a.default.jsonPos,s),i?.(e)},()=>n(e))}function L({gen:e,char:t}){e.code((0,r._)`while((${t}=${a.default.json}[${a.default.jsonPos}],${t}===" "||${t}==="\\n"||${t}==="\\r"||${t}==="\\t"))${a.default.jsonPos}++;`)}function ie(e){return e===1?(0,r._)`${a.default.json}[${a.default.jsonPos}]`:(0,r._)`${a.default.json}.slice(${a.default.jsonPos}, ${a.default.jsonPos}+${e})`}function ae(e){R(e,(0,r._)`"unexpected token " + ${a.default.json}[${a.default.jsonPos}]`)}function R({gen:e,parseName:t},n){e.assign((0,r._)`${t}.message`,n),e.assign((0,r._)`${t}.position`,a.default.jsonPos),e.return(m)}})),Zf=o(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let n=Hd(),r=Wf(),i=Gf(),a=Jf(),o=Xf(),s=`JTD-meta-schema`;var c=class extends n.default{constructor(e={}){super({...e,jtd:!0})}_addVocabularies(){super._addVocabularies(),this.addVocabulary(r.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema(),this.opts.meta&&this.addMetaSchema(i.default,s,!1)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}compileSerializer(e){let t=this._addSchema(e);return t.serialize||this._compileSerializer(t)}compileParser(e){let t=this._addSchema(e);return t.parse||this._compileParser(t)}_compileSerializer(e){if(a.default.call(this,e,e.schema.definitions||{}),!e.serialize)throw Error(`ajv implementation error`);return e.serialize}_compileParser(e){if(o.default.call(this,e,e.schema.definitions||{}),!e.parse)throw Error(`ajv implementation error`);return e.parse}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=c;var l=Nd();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return l.KeywordCxt}});var u=Z();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return u.CodeGen}});var d=Pd();Object.defineProperty(e,`ValidationError`,{enumerable:!0,get:function(){return d.default}});var f=Fd();Object.defineProperty(e,`MissingRefError`,{enumerable:!0,get:function(){return f.default}})})),Qf=o(((e,t)=>{let n=Bd();t.exports=Object.freeze({coerceTypes:`array`,useDefaults:!0,removeAdditional:!0,uriResolver:n,addUsedSchema:!1,allErrors:!1})})),$f=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(a,o),time:t(c(!0),l),"date-time":t(f(!0),p),"iso-time":t(c(),u),"iso-date-time":t(f(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:E,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:y,int32:{type:`number`,validate:S},int64:{type:`number`,validate:C},float:{type:`number`,validate:w},double:{type:`number`,validate:w},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function n(e){return e%4==0&&(e%100!=0||e%400==0)}let r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e){let t=r.exec(e);if(!t)return!1;let a=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o===2&&n(a)?29:i[o])}function o(e,t){if(e&&t)return e>t?1:e<t?-1:0}let s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){let n=s.exec(t);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4],c=n[5]===`-`?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!o)return!1;if(r<=23&&i<=59&&a<60)return!0;let d=i-u*c,f=r-l*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&a<61}}function l(e,t){if(!(e&&t))return;let n=new Date(`2020-01-01T`+e).valueOf(),r=new Date(`2020-01-01T`+t).valueOf();if(n&&r)return n-r}function u(e,t){if(!(e&&t))return;let n=s.exec(e),r=s.exec(t);if(n&&r)return e=n[1]+n[2]+n[3],t=r[1]+r[2]+r[3],e>t?1:e<t?-1:0}let d=/t|\s/i;function f(e){let t=c(e);return function(e){let n=e.split(d);return n.length===2&&a(n[0])&&t(n[1])}}function p(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function m(e,t){if(!(e&&t))return;let[n,r]=e.split(d),[i,a]=t.split(d),s=o(n,i);if(s!==void 0)return s||l(r,a)}let h=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function _(e){return h.test(e)&&g.test(e)}let v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(e){return v.lastIndex=0,v.test(e)}let b=-(2**31),x=2**31-1;function S(e){return Number.isInteger(e)&&e<=x&&e>=b}function C(e){return Number.isInteger(e)}function w(){return!0}let T=/[^\\]\\Z/;function E(e){if(T.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),ep=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatLimitDefinition=void 0;let t=Af(),n=Z(),r=n.operators,i={formatMaximum:{okStr:`<=`,ok:r.LTE,fail:r.GT},formatMinimum:{okStr:`>=`,ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:`<`,ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:`>`,ok:r.GT,fail:r.LTE}};e.formatLimitDefinition={keyword:Object.keys(i),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,n.str)`should be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,n._)`{comparison: ${i[e].okStr}, limit: ${t}}`},code(e){let{gen:r,data:a,schemaCode:o,keyword:s,it:c}=e,{opts:l,self:u}=c;if(!l.validateFormats)return;let d=new t.KeywordCxt(c,u.RULES.all.format.definition,`format`);d.$data?f():p();function f(){let t=r.scopeValue(`formats`,{ref:u.formats,code:l.code.formats}),i=r.const(`fmt`,(0,n._)`${t}[${d.schemaCode}]`);e.fail$data((0,n.or)((0,n._)`typeof ${i} != "object"`,(0,n._)`${i} instanceof RegExp`,(0,n._)`typeof ${i}.compare != "function"`,m(i)))}function p(){let t=d.schema,i=u.formats[t];if(!i||i===!0)return;if(typeof i!=`object`||i instanceof RegExp||typeof i.compare!=`function`)throw Error(`"${s}": format "${t}" does not define "compare" function`);let a=r.scopeValue(`formats`,{key:t,ref:i,code:l.code.formats?(0,n._)`${l.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(m(a))}function m(e){return(0,n._)`${e}.compare(${a}, ${o}) ${i[s].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),tp=o(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0});let n=$f(),r=ep(),i=Z(),a=new i.Name(`fullFormats`),o=new i.Name(`fastFormats`),s=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,a),e;let[i,s]=t.mode===`fast`?[n.fastFormats,o]:[n.fullFormats,a];return c(e,t.formats||n.formatNames,i,s),t.keywords&&(0,r.default)(e),e};s.get=(e,t=`full`)=>{let r=(t===`fast`?n.fastFormats:n.fullFormats)[e];if(!r)throw Error(`Unknown format "${e}"`);return r};function c(e,t,n,r){var a;(a=e.opts.code).formats??(a.formats=(0,i._)`require("ajv-formats/dist/formats").${r}`);for(let r of t)e.addFormat(r,n[r])}t.exports=e=s,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=s})),np=o(((e,t)=>{let n=Af().default,r=Zf(),i=Qf();t.exports=class{constructor(e,t){t.mode===`JTD`?this.ajv=new r(Object.assign({},i,t.customOptions)):this.ajv=new n(Object.assign({},i,t.customOptions));let a=!0;if(t.plugins&&t.plugins.length>0)for(let e of t.plugins)Array.isArray(e)?(a&&=e[0].name!==`formatsPlugin`,e[0](this.ajv,e[1])):(a&&=e.name!==`formatsPlugin`,e(this.ajv));a&&tp()(this.ajv),t.onCreate?.(this.ajv);let o=Object.values(e);for(let e of o)this.ajv.addSchema(e)}buildValidatorFunction({schema:e}){if(e.$id){let t=this.ajv.getSchema(e.$id);if(t)return t}return this.ajv.compile(e)}}})),rp=o(((e,t)=>{let n=Zf(),r=Qf();t.exports=class{constructor(e,t){this.ajv=new n(Object.assign({},r,t))}buildSerializerFunction({schema:e}){return this.ajv.compileSerializer(e)}}})),ip=o(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0});let n=vd(),r=_d();function i(e,t){if(!e.opts.code.source)throw Error(`moduleCode: ajv instance must have code.source option`);let{_n:i}=e.scope.opts;return typeof t==`function`?o(t.source):t===void 0?s(e.schemas,t=>t.meta?void 0:e.compile(t.schema)):s(t,a);function a(t){let n=e.getSchema(t);if(!n)throw Error(`moduleCode: no schema with id ${t}`);return n}function o(t){let n={},r=t?.validateName,a=c(n,t);return e.opts.code.esm?`"use strict";${i}export const validate = ${r};${i}export default ${r};${i}${a}`:`"use strict";${i}module.exports = ${r};${i}module.exports.default = ${r};${i}${a}`}function s(t,n){let a={},o=(0,r._)`"use strict";`;for(let s in t){let l=n(t[s]);if(l){let t=c(a,l.source),n=e.opts.code.esm?(0,r._)`export const ${(0,r.getEsmExportName)(s)}`:(0,r._)`exports${(0,r.getProperty)(s)}`;o=(0,r._)`${o}${i}${n} = ${l.source?.validateName};${i}${t}`}}return`${o}`}function c(t,a){if(!a)throw Error(`moduleCode: function does not have "source" property`);if(u(a.validateName)===n.UsedValueState.Completed)return r.nil;d(a.validateName,n.UsedValueState.Started);let o=e.scope.scopeCode(a.scopeValues,t,l),s=new r._Code(`${o}${i}${a.validateCode}`);return a.evaluated?(0,r._)`${s}${a.validateName}.evaluated = ${a.evaluated};${i}`:s;function l(a){let o=a.value?.ref;if(a.prefix===`validate`&&typeof o==`function`)return c(t,o.source);if((a.prefix===`root`||a.prefix===`wrapper`)&&typeof o==`object`){let{validate:s,validateName:l}=o;if(!l)throw Error(`ajv internal error`);let d=e.opts.code.es5?n.varKinds.var:n.varKinds.const,f=(0,r._)`${d} ${a} = {validate: ${l}};`;if(u(l)===n.UsedValueState.Started)return f;let p=c(t,s?.source);return(0,r._)`${f}${i}${p}`}}function u(e){return t[e.prefix]?.get(e)}function d(e,n){let{prefix:r}=e;(t[r]=t[r]||new Map).set(e,n)}}}t.exports=e=i,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=i})),ap=o(((e,t)=>{let n=op(),r=ip().default;function i(e={readMode:!0}){if(e.readMode===!0&&!e.restoreFunction)throw Error(`You must provide a restoreFunction options when readMode ON`);if(e.readMode!==!0&&!e.storeFunction)throw Error(`You must provide a storeFunction options when readMode OFF`);if(e.readMode===!0)return function(){return function(t){return e.restoreFunction(t)}};let t=n();return function(i,a={}){(!a.customOptions||!a.customOptions.code)&&(a.customOptions=Object.assign({},a.customOptions,{code:{source:!0}}));let o=t(i,a);return function(t){let i=o(t),a=r(o[n.AjvReference].ajv,i);return e.storeFunction(t,a),i}}}t.exports=i})),op=o(((e,t)=>{let n=Symbol.for(`fastify.ajv-compiler.reference`),r=np(),i=rp();function a(e){let t=new Map,a=new Map;return e&&e.jtdSerializer===!0?function(e,t){let n=o({},t);if(a.has(n))return a.get(n);let r=new i(e,t),s=r.buildSerializerFunction.bind(r);return a.set(n,s),s}:function(e,i){let a=o(e,i.customOptions);if(t.has(a))return t.get(a);let s=new r(e,i),c=s.buildValidatorFunction.bind(s);return t.set(a,c),i.customOptions.code!==void 0&&(c[n]=s),c}}function o(e,t){return`${JSON.stringify(e)}${JSON.stringify(t)}`}t.exports=a,t.exports.default=a,t.exports.AjvCompiler=a,t.exports.AjvReference=n,t.exports.StandaloneValidator=ap()})),sp=o((e=>{var t=Object.prototype.hasOwnProperty;function n(e,t,n){for(n of e.keys())if(r(n,t))return n}function r(e,i){var a,o,s;if(e===i)return!0;if(e&&i&&(a=e.constructor)===i.constructor){if(a===Date)return e.getTime()===i.getTime();if(a===RegExp)return e.toString()===i.toString();if(a===Array){if((o=e.length)===i.length)for(;o--&&r(e[o],i[o]););return o===-1}if(a===Set){if(e.size!==i.size)return!1;for(o of e)if(s=o,s&&typeof s==`object`&&(s=n(i,s),!s)||!i.has(s))return!1;return!0}if(a===Map){if(e.size!==i.size)return!1;for(o of e)if(s=o[0],s&&typeof s==`object`&&(s=n(i,s),!s)||!r(o[1],i.get(s)))return!1;return!0}if(a===ArrayBuffer)e=new Uint8Array(e),i=new Uint8Array(i);else if(a===DataView){if((o=e.byteLength)===i.byteLength)for(;o--&&e.getInt8(o)===i.getInt8(o););return o===-1}if(ArrayBuffer.isView(e)){if((o=e.byteLength)===i.byteLength)for(;o--&&e[o]===i[o];);return o===-1}if(!a||typeof e==`object`){for(a in o=0,e)if(t.call(e,a)&&++o&&!t.call(i,a)||!(a in i)||!r(e[a],i[a]))return!1;return Object.keys(i).length===o}}return e!==e&&i!==i}e.dequal=r})),cp=o(((e,t)=>{let{dequal:n}=sp(),r=Symbol.for(`json-schema-ref`);var i=class{#e;#t;#n;#r;#i;constructor(e={}){this.#e={},this.#t={},this.#n=e.insertRefSymbol??!1,this.#r=e.allowEqualDuplicates??!0,this.#i=e.cloneSchemaWithoutRefs??!1}addSchema(e,t,n=!0){n&&(e.$id!==void 0&&e.$id.charAt(0)!==`#`?t=e.$id:this.#c(e,t));let r=e.$id;r!==void 0&&typeof r==`string`&&(r.charAt(0)===`#`?this.#l(e,t,r):(this.#c(e,r),t=r));let i=e.$ref;if(i!==void 0&&typeof i==`string`){let{refSchemaId:e,refJsonPointer:n}=this.#a(i,t);this.#e[t].refs.push({schemaId:e,jsonPointer:n})}for(let n in e)typeof e[n]==`object`&&e[n]!==null&&this.addSchema(e[n],t,!1)}getSchema(e,t=`#`){let n=this.#e[e];if(n===void 0)throw Error(`Cannot resolve ref "${e}${t}". Schema with id "${e}" is not found.`);return n.anchors[t]===void 0?a(n.schema,t):n.anchors[t]}hasSchema(e){return this.#e[e]!==void 0}getSchemaRefs(e){let t=this.#e[e];if(t===void 0)throw Error(`Schema with id "${e}" is not found.`);return t.refs}getSchemaDependencies(e,t={}){let n=this.#e[e];for(let r of n.refs){let n=r.schemaId;n===e||t[n]!==void 0||(t[n]=this.getSchema(n),this.getSchemaDependencies(n,t))}return t}derefSchema(e){if(this.#t[e]!==void 0)return;let t=this.#e[e];if(t===void 0)throw Error(`Schema with id "${e}" is not found.`);!this.#i&&t.refs.length===0&&(this.#t[e]={schema:t.schema,anchors:t.anchors});let n=[];this.#o(t.schema,e,!0,n);let r=this.getSchemaDependencies(e);for(let e in r){let t=r[e];this.#o(t,e,!0,n)}for(let e of n){let{refSchemaId:t,refJsonPointer:n}=this.#a(e.ref,e.sourceSchemaId),r=this.getDerefSchema(t,n);if(r===null)throw Error(`Cannot resolve ref "${e.ref}". Ref "${n}" is not found in schema "${t}".`);e.targetSchema=r,e.targetSchemaId=t}for(let e of n)this.#s(e,n)}getDerefSchema(e,t=`#`){let n=this.#t[e];return n===void 0&&(this.derefSchema(e),n=this.#t[e]),n.anchors[t]===void 0?a(n.schema,t):n.anchors[t]}#a(e,t){let n=e.indexOf(`#`);return n===-1?{refSchemaId:e,refJsonPointer:`#`}:n===0?{refSchemaId:t,refJsonPointer:e}:{refSchemaId:e.slice(0,n),refJsonPointer:e.slice(n)}}#o(e,t,n,r=[]){let i=Array.isArray(e)?[...e]:{...e};n&&(e.$id!==void 0&&e.$id.charAt(0)!==`#`?t=e.$id:this.#u(i,t));let a=i.$id;a!==void 0&&typeof a==`string`&&(a.charAt(0)===`#`?this.#d(i,t,a):(this.#u(i,a),t=a)),i.$ref!==void 0&&r.push({ref:i.$ref,sourceSchemaId:t,sourceSchema:i});for(let e in i){let n=i[e];typeof n==`object`&&n&&(i[e]=this.#o(n,t,!1,r))}return i}#s(e,t){let{sourceSchema:i,targetSchema:a}=e;if(i.$ref){if(this.#n&&(i[r]=i.$ref),delete i.$ref,a.$ref){let e=t.find(e=>e.sourceSchema===a);this.#s(e,t)}for(let t in a)if(t!==`$id`){if(i[t]!==void 0){if(n(i[t],a[t]))continue;throw Error(`Cannot resolve ref "${e.ref}". Property "${t}" already exists in schema "${e.sourceSchemaId}".`)}i[t]=a[t]}e.isResolved=!0}}#c(e,t){let r=this.#e[t];if(r!==void 0){if(this.#r&&n(e,r.schema))return;throw Error(`There is already another schema with id "${t}".`)}this.#e[t]={schema:e,anchors:{},refs:[]}}#l(e,t,n){let{anchors:r}=this.#e[t];if(r[n]!==void 0)throw Error(`There is already another anchor "${n}" in schema "${t}".`);r[n]=e}#u(e,t){this.#t[t]===void 0&&(this.#t[t]={schema:e,anchors:{}})}#d(e,t,n){let{anchors:r}=this.#t[t];r[n]=e}};function a(e,t){let n=t.split(`/`),r=e;for(let e of n)if(!(e===``||e===`#`)){if(typeof r!=`object`||!r)return null;r=r[e]}return r??null}t.exports={RefResolver:i}})),lp=o(((e,t)=>{let n=Af(),r=Bd(),i=tp(),a=nd()({proto:!0});t.exports=class e{constructor(e){this.ajv=new n({...e,strictSchema:!1,validateSchema:!1,allowUnionTypes:!0,uriResolver:r}),i(this.ajv),this.ajv.addKeyword({keyword:`fjs_type`,type:`object`,errors:!1,validate:(e,t)=>t&&typeof t.toJSON==`function`}),this._ajvSchemas={},this._ajvOptions=e||{}}addSchema(e,t){let n=e.$id||t;if(e.$id!==void 0&&e.$id[0]===`#`&&(n=t+e.$id),this.ajv.refs[n]===void 0&&this.ajv.schemas[n]===void 0){let t=a(e);this.convertSchemaToAjvFormat(t),this.ajv.addSchema(t,n),this._ajvSchemas[n]=e}}validate(e,t){return this.ajv.validate(e,t)}convertSchemaToAjvFormat(e){if(e!==null){e.type===`string`?(e.fjs_type=`string`,e.type=[`string`,`object`]):Array.isArray(e.type)&&e.type.includes(`string`)&&!e.type.includes(`object`)&&(e.fjs_type=`string`,e.type.push(`object`));for(let t in e)typeof e[t]==`object`&&this.convertSchemaToAjvFormat(e[t])}}getState(){return{ajvOptions:this._ajvOptions,ajvSchemas:this._ajvSchemas}}static restoreFromState(t){let n=new e(t.ajvOptions);for(let[e,r]of Object.entries(t.ajvSchemas))n.ajv.addSchema(r,e);return n}}})),up=o(((e,t)=>{t.exports=class e{constructor(e,t,n=`#`){this.schema=e,this.schemaId=t,this.jsonPointer=n}getPropertyLocation(t){return new e(this.schema[t],this.schemaId,this.jsonPointer+`/`+t)}getSchemaRef(){return this.schemaId+this.jsonPointer}}})),dp=o(((e,t)=>{t.exports=d,t.exports.default=d;let n={$schema:`http://json-schema.org/draft-07/schema#`,$id:`http://json-schema.org/draft-07/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:!0},r={enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},i=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,a=$f().fullFormats.uri,o=$f().fullFormats.regex;function s(e,{instancePath:t=``,parentData:n,parentDataProperty:r,rootData:i=e}={}){return typeof e==`number`&&!(e%1)&&!isNaN(e)&&isFinite(e)?typeof e==`number`&&isFinite(e)&&(e<0||isNaN(e))?(s.errors=[{instancePath:t,schemaPath:`#/definitions/nonNegativeInteger/minimum`,keyword:`minimum`,params:{comparison:`>=`,limit:0},message:`must be >= 0`}],!1):(s.errors=null,!0):(s.errors=[{instancePath:t,schemaPath:`#/definitions/nonNegativeInteger/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1)}let c={validate:d};function l(e,{instancePath:t=``,parentData:n,parentDataProperty:r,rootData:i=e}={}){let a=null,o=0;if(o===0)if(Array.isArray(e)){if(e.length<1)return l.errors=[{instancePath:t,schemaPath:`#/minItems`,keyword:`minItems`,params:{limit:1},message:`must NOT have fewer than 1 items`}],!1;{let n=e.length;for(let r=0;r<n;r++){let n=o;if(c.validate(e[r],{instancePath:t+`/`+r,parentData:e,parentDataProperty:r,rootData:i})||(a=a===null?c.validate.errors:a.concat(c.validate.errors),o=a.length),n!==o)break}}}else return l.errors=[{instancePath:t,schemaPath:`#/type`,keyword:`type`,params:{type:`array`},message:`must be array`}],!1;return l.errors=a,o===0}let u=ef().default;function d(e,{instancePath:t=``,parentData:c,parentDataProperty:f,rootData:p=e}={}){let m=null,h=0;if(!(e&&typeof e==`object`&&!Array.isArray(e))&&typeof e!=`boolean`)return d.errors=[{instancePath:t,schemaPath:`#/type`,keyword:`type`,params:{type:n.type},message:`must be object,boolean`}],!1;if(h===0&&e&&typeof e==`object`&&!Array.isArray(e)){if(e.$id!==void 0){let n=e.$id,r=h;if(h===r&&h===r)if(typeof n==`string`){if(!i.test(n))return d.errors=[{instancePath:t+`/$id`,schemaPath:`#/properties/%24id/format`,keyword:`format`,params:{format:`uri-reference`},message:`must match format "uri-reference"`}],!1}else return d.errors=[{instancePath:t+`/$id`,schemaPath:`#/properties/%24id/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=r===h}else var g=!0;if(g){if(e.$schema!==void 0){let n=e.$schema,r=h;if(h===r&&h===r)if(typeof n==`string`){if(!a(n))return d.errors=[{instancePath:t+`/$schema`,schemaPath:`#/properties/%24schema/format`,keyword:`format`,params:{format:`uri`},message:`must match format "uri"`}],!1}else return d.errors=[{instancePath:t+`/$schema`,schemaPath:`#/properties/%24schema/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=r===h}else var g=!0;if(g){if(e.$ref!==void 0){let n=e.$ref,r=h;if(h===r&&h===r)if(typeof n==`string`){if(!i.test(n))return d.errors=[{instancePath:t+`/$ref`,schemaPath:`#/properties/%24ref/format`,keyword:`format`,params:{format:`uri-reference`},message:`must match format "uri-reference"`}],!1}else return d.errors=[{instancePath:t+`/$ref`,schemaPath:`#/properties/%24ref/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=r===h}else var g=!0;if(g){if(e.$comment!==void 0){let n=h;if(typeof e.$comment!=`string`)return d.errors=[{instancePath:t+`/$comment`,schemaPath:`#/properties/%24comment/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=n===h}else var g=!0;if(g){if(e.title!==void 0){let n=h;if(typeof e.title!=`string`)return d.errors=[{instancePath:t+`/title`,schemaPath:`#/properties/title/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=n===h}else var g=!0;if(g){if(e.description!==void 0){let n=h;if(typeof e.description!=`string`)return d.errors=[{instancePath:t+`/description`,schemaPath:`#/properties/description/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=n===h}else var g=!0;if(g){if(e.readOnly!==void 0){let n=h;if(typeof e.readOnly!=`boolean`)return d.errors=[{instancePath:t+`/readOnly`,schemaPath:`#/properties/readOnly/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;var g=n===h}else var g=!0;if(g){if(e.examples!==void 0){let n=h;if(h===n&&!Array.isArray(e.examples))return d.errors=[{instancePath:t+`/examples`,schemaPath:`#/properties/examples/type`,keyword:`type`,params:{type:`array`},message:`must be array`}],!1;var g=n===h}else var g=!0;if(g){if(e.multipleOf!==void 0){let n=e.multipleOf,r=h;if(h===r)if(typeof n==`number`&&isFinite(n)){if(n<=0||isNaN(n))return d.errors=[{instancePath:t+`/multipleOf`,schemaPath:`#/properties/multipleOf/exclusiveMinimum`,keyword:`exclusiveMinimum`,params:{comparison:`>`,limit:0},message:`must be > 0`}],!1}else return d.errors=[{instancePath:t+`/multipleOf`,schemaPath:`#/properties/multipleOf/type`,keyword:`type`,params:{type:`number`},message:`must be number`}],!1;var g=r===h}else var g=!0;if(g){if(e.maximum!==void 0){let n=e.maximum,r=h;if(!(typeof n==`number`&&isFinite(n)))return d.errors=[{instancePath:t+`/maximum`,schemaPath:`#/properties/maximum/type`,keyword:`type`,params:{type:`number`},message:`must be number`}],!1;var g=r===h}else var g=!0;if(g){if(e.exclusiveMaximum!==void 0){let n=e.exclusiveMaximum,r=h;if(!(typeof n==`number`&&isFinite(n)))return d.errors=[{instancePath:t+`/exclusiveMaximum`,schemaPath:`#/properties/exclusiveMaximum/type`,keyword:`type`,params:{type:`number`},message:`must be number`}],!1;var g=r===h}else var g=!0;if(g){if(e.minimum!==void 0){let n=e.minimum,r=h;if(!(typeof n==`number`&&isFinite(n)))return d.errors=[{instancePath:t+`/minimum`,schemaPath:`#/properties/minimum/type`,keyword:`type`,params:{type:`number`},message:`must be number`}],!1;var g=r===h}else var g=!0;if(g){if(e.exclusiveMinimum!==void 0){let n=e.exclusiveMinimum,r=h;if(!(typeof n==`number`&&isFinite(n)))return d.errors=[{instancePath:t+`/exclusiveMinimum`,schemaPath:`#/properties/exclusiveMinimum/type`,keyword:`type`,params:{type:`number`},message:`must be number`}],!1;var g=r===h}else var g=!0;if(g){if(e.maxLength!==void 0){let n=e.maxLength,r=h,i=h;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n)))return d.errors=[{instancePath:t+`/maxLength`,schemaPath:`#/definitions/nonNegativeInteger/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;if(h===i&&typeof n==`number`&&isFinite(n)&&(n<0||isNaN(n)))return d.errors=[{instancePath:t+`/maxLength`,schemaPath:`#/definitions/nonNegativeInteger/minimum`,keyword:`minimum`,params:{comparison:`>=`,limit:0},message:`must be >= 0`}],!1;var g=r===h}else var g=!0;if(g){if(e.minLength!==void 0){let n=h;s(e.minLength,{instancePath:t+`/minLength`,parentData:e,parentDataProperty:`minLength`,rootData:p})||(m=m===null?s.errors:m.concat(s.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.pattern!==void 0){let n=e.pattern,r=h;if(h===r&&h===r)if(typeof n==`string`){if(!o(n))return d.errors=[{instancePath:t+`/pattern`,schemaPath:`#/properties/pattern/format`,keyword:`format`,params:{format:`regex`},message:`must match format "regex"`}],!1}else return d.errors=[{instancePath:t+`/pattern`,schemaPath:`#/properties/pattern/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=r===h}else var g=!0;if(g){if(e.additionalItems!==void 0){let n=h;d(e.additionalItems,{instancePath:t+`/additionalItems`,parentData:e,parentDataProperty:`additionalItems`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.items!==void 0){let n=e.items,r=h,i=h,a=!1,o=h;d(n,{instancePath:t+`/items`,parentData:e,parentDataProperty:`items`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var _=o===h;if(a||=_,!a){let r=h;l(n,{instancePath:t+`/items`,parentData:e,parentDataProperty:`items`,rootData:p})||(m=m===null?l.errors:m.concat(l.errors),h=m.length);var _=r===h;a||=_}if(a)h=i,m!==null&&(i?m.length=i:m=null);else{let e={instancePath:t+`/items`,schemaPath:`#/properties/items/anyOf`,keyword:`anyOf`,params:{},message:`must match a schema in anyOf`};return m===null?m=[e]:m.push(e),h++,d.errors=m,!1}var g=r===h}else var g=!0;if(g){if(e.maxItems!==void 0){let n=e.maxItems,r=h,i=h;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n)))return d.errors=[{instancePath:t+`/maxItems`,schemaPath:`#/definitions/nonNegativeInteger/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;if(h===i&&typeof n==`number`&&isFinite(n)&&(n<0||isNaN(n)))return d.errors=[{instancePath:t+`/maxItems`,schemaPath:`#/definitions/nonNegativeInteger/minimum`,keyword:`minimum`,params:{comparison:`>=`,limit:0},message:`must be >= 0`}],!1;var g=r===h}else var g=!0;if(g){if(e.minItems!==void 0){let n=h;s(e.minItems,{instancePath:t+`/minItems`,parentData:e,parentDataProperty:`minItems`,rootData:p})||(m=m===null?s.errors:m.concat(s.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.uniqueItems!==void 0){let n=h;if(typeof e.uniqueItems!=`boolean`)return d.errors=[{instancePath:t+`/uniqueItems`,schemaPath:`#/properties/uniqueItems/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;var g=n===h}else var g=!0;if(g){if(e.contains!==void 0){let n=h;d(e.contains,{instancePath:t+`/contains`,parentData:e,parentDataProperty:`contains`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.maxProperties!==void 0){let n=e.maxProperties,r=h,i=h;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n)))return d.errors=[{instancePath:t+`/maxProperties`,schemaPath:`#/definitions/nonNegativeInteger/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;if(h===i&&typeof n==`number`&&isFinite(n)&&(n<0||isNaN(n)))return d.errors=[{instancePath:t+`/maxProperties`,schemaPath:`#/definitions/nonNegativeInteger/minimum`,keyword:`minimum`,params:{comparison:`>=`,limit:0},message:`must be >= 0`}],!1;var g=r===h}else var g=!0;if(g){if(e.minProperties!==void 0){let n=h;s(e.minProperties,{instancePath:t+`/minProperties`,parentData:e,parentDataProperty:`minProperties`,rootData:p})||(m=m===null?s.errors:m.concat(s.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.required!==void 0){let n=e.required,r=h;if(h===h)if(Array.isArray(n)){var v=!0;let e=n.length;for(let r=0;r<e;r++){let e=h;if(typeof n[r]!=`string`)return d.errors=[{instancePath:t+`/required/`+r,schemaPath:`#/definitions/stringArray/items/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var v=e===h;if(!v)break}if(v){let e=n.length,r;if(e>1){let i={};for(;e--;){let a=n[e];if(typeof a==`string`){if(typeof i[a]==`number`)return r=i[a],d.errors=[{instancePath:t+`/required`,schemaPath:`#/definitions/stringArray/uniqueItems`,keyword:`uniqueItems`,params:{i:e,j:r},message:`must NOT have duplicate items (items ## `+r+` and `+e+` are identical)`}],!1;i[a]=e}}}}}else return d.errors=[{instancePath:t+`/required`,schemaPath:`#/definitions/stringArray/type`,keyword:`type`,params:{type:`array`},message:`must be array`}],!1;var g=r===h}else var g=!0;if(g){if(e.additionalProperties!==void 0){let n=h;d(e.additionalProperties,{instancePath:t+`/additionalProperties`,parentData:e,parentDataProperty:`additionalProperties`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.definitions!==void 0){let n=e.definitions,r=h;if(h===r)if(n&&typeof n==`object`&&!Array.isArray(n))for(let e in n){let r=h;if(d(n[e],{instancePath:t+`/definitions/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),parentData:n,parentDataProperty:e,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length),r!==h)break}else return d.errors=[{instancePath:t+`/definitions`,schemaPath:`#/properties/definitions/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var g=r===h}else var g=!0;if(g){if(e.properties!==void 0){let n=e.properties,r=h;if(h===r)if(n&&typeof n==`object`&&!Array.isArray(n))for(let e in n){let r=h;if(d(n[e],{instancePath:t+`/properties/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),parentData:n,parentDataProperty:e,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length),r!==h)break}else return d.errors=[{instancePath:t+`/properties`,schemaPath:`#/properties/properties/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var g=r===h}else var g=!0;if(g){if(e.patternProperties!==void 0){let n=e.patternProperties,r=h;if(h===r)if(n&&typeof n==`object`&&!Array.isArray(n)){for(let e in n){let n=h;if(h===n&&typeof e==`string`&&!o(e)){let n={instancePath:t+`/patternProperties`,schemaPath:`#/properties/patternProperties/propertyNames/format`,keyword:`format`,params:{format:`regex`},message:`must match format "regex"`,propertyName:e};m===null?m=[n]:m.push(n),h++}var y=n===h;if(!y){let n={instancePath:t+`/patternProperties`,schemaPath:`#/properties/patternProperties/propertyNames`,keyword:`propertyNames`,params:{propertyName:e},message:`property name must be valid`};return m===null?m=[n]:m.push(n),h++,d.errors=m,!1}}if(y)for(let e in n){let r=h;if(d(n[e],{instancePath:t+`/patternProperties/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),parentData:n,parentDataProperty:e,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length),r!==h)break}}else return d.errors=[{instancePath:t+`/patternProperties`,schemaPath:`#/properties/patternProperties/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var g=r===h}else var g=!0;if(g){if(e.dependencies!==void 0){let n=e.dependencies,r=h;if(h===r)if(n&&typeof n==`object`&&!Array.isArray(n))for(let e in n){let r=n[e],i=h,a=h,o=!1,s=h;d(r,{instancePath:t+`/dependencies/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),parentData:n,parentDataProperty:e,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var b=s===h;if(o||=b,!o){let n=h;if(h===h)if(Array.isArray(r)){var x=!0;let n=r.length;for(let i=0;i<n;i++){let n=h;if(typeof r[i]!=`string`){let n={instancePath:t+`/dependencies/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`)+`/`+i,schemaPath:`#/definitions/stringArray/items/type`,keyword:`type`,params:{type:`string`},message:`must be string`};m===null?m=[n]:m.push(n),h++}var x=n===h;if(!x)break}if(x){let n=r.length,i;if(n>1){let a={};for(;n--;){let o=r[n];if(typeof o==`string`){if(typeof a[o]==`number`){i=a[o];let r={instancePath:t+`/dependencies/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),schemaPath:`#/definitions/stringArray/uniqueItems`,keyword:`uniqueItems`,params:{i:n,j:i},message:`must NOT have duplicate items (items ## `+i+` and `+n+` are identical)`};m===null?m=[r]:m.push(r),h++;break}a[o]=n}}}}}else{let n={instancePath:t+`/dependencies/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),schemaPath:`#/definitions/stringArray/type`,keyword:`type`,params:{type:`array`},message:`must be array`};m===null?m=[n]:m.push(n),h++}var b=n===h;o||=b}if(o)h=a,m!==null&&(a?m.length=a:m=null);else{let n={instancePath:t+`/dependencies/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),schemaPath:`#/properties/dependencies/additionalProperties/anyOf`,keyword:`anyOf`,params:{},message:`must match a schema in anyOf`};return m===null?m=[n]:m.push(n),h++,d.errors=m,!1}if(i!==h)break}else return d.errors=[{instancePath:t+`/dependencies`,schemaPath:`#/properties/dependencies/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var g=r===h}else var g=!0;if(g){if(e.propertyNames!==void 0){let n=h;d(e.propertyNames,{instancePath:t+`/propertyNames`,parentData:e,parentDataProperty:`propertyNames`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.enum!==void 0){let n=e.enum,r=h;if(h===r)if(Array.isArray(n)){if(n.length<1)return d.errors=[{instancePath:t+`/enum`,schemaPath:`#/properties/enum/minItems`,keyword:`minItems`,params:{limit:1},message:`must NOT have fewer than 1 items`}],!1;{let e=n.length,r;if(e>1){outer0:for(;e--;)for(r=e;r--;)if(u(n[e],n[r]))return d.errors=[{instancePath:t+`/enum`,schemaPath:`#/properties/enum/uniqueItems`,keyword:`uniqueItems`,params:{i:e,j:r},message:`must NOT have duplicate items (items ## `+r+` and `+e+` are identical)`}],!1}}}else return d.errors=[{instancePath:t+`/enum`,schemaPath:`#/properties/enum/type`,keyword:`type`,params:{type:`array`},message:`must be array`}],!1;var g=r===h}else var g=!0;if(g){if(e.type!==void 0){let n=e.type,i=h,a=h,o=!1,s=h;if(!(n===`array`||n===`boolean`||n===`integer`||n===`null`||n===`number`||n===`object`||n===`string`)){let e={instancePath:t+`/type`,schemaPath:`#/definitions/simpleTypes/enum`,keyword:`enum`,params:{allowedValues:r.enum},message:`must be equal to one of the allowed values`};m===null?m=[e]:m.push(e),h++}var S=s===h;if(o||=S,!o){let e=h;if(h===e)if(Array.isArray(n))if(n.length<1){let e={instancePath:t+`/type`,schemaPath:`#/properties/type/anyOf/1/minItems`,keyword:`minItems`,params:{limit:1},message:`must NOT have fewer than 1 items`};m===null?m=[e]:m.push(e),h++}else{var C=!0;let e=n.length;for(let i=0;i<e;i++){let e=n[i],a=h;if(!(e===`array`||e===`boolean`||e===`integer`||e===`null`||e===`number`||e===`object`||e===`string`)){let e={instancePath:t+`/type/`+i,schemaPath:`#/definitions/simpleTypes/enum`,keyword:`enum`,params:{allowedValues:r.enum},message:`must be equal to one of the allowed values`};m===null?m=[e]:m.push(e),h++}var C=a===h;if(!C)break}if(C){let e=n.length,r;if(e>1){outer1:for(;e--;)for(r=e;r--;)if(u(n[e],n[r])){let n={instancePath:t+`/type`,schemaPath:`#/properties/type/anyOf/1/uniqueItems`,keyword:`uniqueItems`,params:{i:e,j:r},message:`must NOT have duplicate items (items ## `+r+` and `+e+` are identical)`};m===null?m=[n]:m.push(n),h++;break outer1}}}}else{let e={instancePath:t+`/type`,schemaPath:`#/properties/type/anyOf/1/type`,keyword:`type`,params:{type:`array`},message:`must be array`};m===null?m=[e]:m.push(e),h++}var S=e===h;o||=S}if(o)h=a,m!==null&&(a?m.length=a:m=null);else{let e={instancePath:t+`/type`,schemaPath:`#/properties/type/anyOf`,keyword:`anyOf`,params:{},message:`must match a schema in anyOf`};return m===null?m=[e]:m.push(e),h++,d.errors=m,!1}var g=i===h}else var g=!0;if(g){if(e.format!==void 0){let n=h;if(typeof e.format!=`string`)return d.errors=[{instancePath:t+`/format`,schemaPath:`#/properties/format/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=n===h}else var g=!0;if(g){if(e.contentMediaType!==void 0){let n=h;if(typeof e.contentMediaType!=`string`)return d.errors=[{instancePath:t+`/contentMediaType`,schemaPath:`#/properties/contentMediaType/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=n===h}else var g=!0;if(g){if(e.contentEncoding!==void 0){let n=h;if(typeof e.contentEncoding!=`string`)return d.errors=[{instancePath:t+`/contentEncoding`,schemaPath:`#/properties/contentEncoding/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=n===h}else var g=!0;if(g){if(e.if!==void 0){let n=h;d(e.if,{instancePath:t+`/if`,parentData:e,parentDataProperty:`if`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.then!==void 0){let n=h;d(e.then,{instancePath:t+`/then`,parentData:e,parentDataProperty:`then`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.else!==void 0){let n=h;d(e.else,{instancePath:t+`/else`,parentData:e,parentDataProperty:`else`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.allOf!==void 0){let n=h;l(e.allOf,{instancePath:t+`/allOf`,parentData:e,parentDataProperty:`allOf`,rootData:p})||(m=m===null?l.errors:m.concat(l.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.anyOf!==void 0){let n=h;l(e.anyOf,{instancePath:t+`/anyOf`,parentData:e,parentDataProperty:`anyOf`,rootData:p})||(m=m===null?l.errors:m.concat(l.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.oneOf!==void 0){let n=h;l(e.oneOf,{instancePath:t+`/oneOf`,parentData:e,parentDataProperty:`oneOf`,rootData:p})||(m=m===null?l.errors:m.concat(l.errors),h=m.length);var g=n===h}else var g=!0;if(g)if(e.not!==void 0){let n=h;d(e.not,{instancePath:t+`/not`,parentData:e,parentDataProperty:`not`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}return d.errors=m,h===0}})),fp=o(((e,t)=>{t.exports={MergeError:class extends Error{constructor(e,t){super(),this.name=`JsonSchemaMergeError`,this.code=`JSON_SCHEMA_MERGE_ERROR`,this.message=`Failed to merge "${e}" keyword schemas.`,this.schemas=t}},ResolverNotFoundError:class extends Error{constructor(e,t){super(),this.name=`JsonSchemaMergeError`,this.code=`JSON_SCHEMA_MERGE_ERROR`,this.message=`Resolver for "${e}" keyword not found.`,this.schemas=t}},InvalidOnConflictOptionError:class extends Error{constructor(e){super(),this.name=`JsonSchemaMergeError`,this.code=`JSON_SCHEMA_MERGE_ERROR`,this.message=`Invalid "onConflict" option: "${e}".`}}}})),pp=o(((e,t)=>{let{dequal:n}=sp(),{MergeError:r}=fp();function i(e){let t=e[0];for(let n=1;n<e.length;n++)t=t.filter(t=>e[n].includes(t));return t}function a(e,t,n){let a=i(t);if(a.length===0)throw new r(e,t);n[e]=a}function o(e,t,n){for(let e=0;e<t.length;e++)Array.isArray(t[e])||(t[e]=[t[e]]);let a=i(t);if(a.length===0)throw new r(e,t);a.length===1?n[e]=a[0]:n[e]=a}function s(e,t,n){let r=[];for(let e of t)for(let t of e)r.includes(t)||r.push(t);n[e]=r}function c(e,t,n){n[e]=Math.min(...t)}function l(e,t,n){n[e]=Math.max(...t)}function u(e,t,n){let r=(e,t)=>t?r(t,e%t):e,i=(e,t)=>e*t/r(e,t),a=1;for(let e of t)for(;e*a%1!=0;)a*=10;let o=t[0]*a;for(let e of t)o=i(o,e*a);n[e]=o/a}function d(e,t,i){let a=t[0];for(let i=1;i<t.length;i++)if(!n(t[i],a))throw new r(e,t);i[e]=a}function f(){}function p(e,t,n){for(let r of t)if(r===!1){n[e]=!1;return}n[e]=!0}function m(e,t,n){for(let r of t)if(r===!0){n[e]=!0;return}n[e]=!1}t.exports={arraysIntersection:a,hybridArraysIntersection:o,arraysUnion:s,minNumber:c,maxNumber:l,commonMultiple:u,allEqual:d,booleanAnd:p,booleanOr:m,skip:f}})),mp=o(((e,t)=>{let{dequal:n}=sp(),r=pp(),i=fp(),a={$id:r.skip,type:r.hybridArraysIntersection,enum:r.arraysIntersection,minLength:r.maxNumber,maxLength:r.minNumber,minimum:r.maxNumber,maximum:r.minNumber,multipleOf:r.commonMultiple,exclusiveMinimum:r.maxNumber,exclusiveMaximum:r.minNumber,minItems:r.maxNumber,maxItems:r.minNumber,maxProperties:r.minNumber,minProperties:r.maxNumber,const:r.allEqual,default:r.allEqual,format:r.allEqual,required:r.arraysUnion,properties:p,patternProperties:m,additionalProperties:o,items:u,additionalItems:d,definitions:m,$defs:m,nullable:r.booleanAnd,oneOf:c,anyOf:c,allOf:r.arraysUnion,not:o,if:h,then:r.skip,else:r.skip,dependencies:g,dependentRequired:g,dependentSchemas:m,propertyNames:o,uniqueItems:r.booleanOr,contains:o};function o(e,t,n,r,i){n[e]=_(t,i)}function s(e){let t=[[]];for(let n of e){let e=[];for(let r of t)for(let t of n)e.push([...r,t]);t=e}return t}function c(e,t,n,r,a){if(t.length===1){n[e]=t[0];return}let o=s(t),c=[];for(let e of o)try{let t=_(e,a);t!==void 0&&c.push(t)}catch(e){if(e instanceof i.MergeError)continue;throw e}n[e]=c}function l(e,t){let{items:n,additionalItems:r}=e;return Array.isArray(n)?t<n.length?n[t]:r:n===void 0?r:n}function u(e,t,n,r,i){let a=0;for(let e of t)Array.isArray(e)&&(a=Math.max(a,e.length));if(a===0){n[e]=_(t,i);return}let o=[];for(let e=0;e<a;e++){let t=[];for(let n of r){let r=l(n,e);r!==void 0&&t.push(r)}o[e]=_(t,i)}n[e]=o}function d(e,t,n,r,i){let a=!1;for(let e of r)if(Array.isArray(e.items)){a=!0;break}if(!a){n[e]=_(t,i);return}let o=[];for(let e of r){let t=e.additionalItems;t===void 0&&!Array.isArray(e.items)&&(t=e.items),t!==void 0&&o.push(t)}n[e]=_(o,i)}function f(e,t){let{properties:n,patternProperties:r,additionalProperties:i}=e;if(n?.[t]!==void 0)return n[t];for(let e of Object.keys(r??{}))if(new RegExp(e).test(t))return r[e];return i}function p(e,t,n,r,i){let a={};for(let e of r){let t=e.properties??{};for(let n of Object.keys(t))if(a[n]===void 0){a[n]=[t[n]];for(let t of r){if(e===t)continue;let r=f(t,n);r!==void 0&&a[n].push(r)}}}let o={};for(let e of Object.keys(a)){let t=a[e];o[e]=_(t,i)}n[e]=o}function m(e,t,n,r,i){let a={};for(let e of t)for(let t of Object.keys(e))a[t]===void 0&&(a[t]=[]),a[t].push(e[t]);let o={};for(let e of Object.keys(a)){let t=a[e];o[e]=_(t,i)}n[e]=o}function h(e,t,n,r,i){for(let e=0;e<r.length;e++){let t={if:r[e].if,then:r[e].then,else:r[e].else};if(t.if!==void 0){if(n.if===void 0){n.if=t.if,t.then!==void 0&&(n.then=t.then),t.else!==void 0&&(n.else=t.else);continue}n.then!==void 0&&(n.then=_([n.then,t],i)),n.else!==void 0&&(n.else=_([n.else,t],i))}}}function g(e,t,n){let r={};for(let e of t)for(let t of Object.keys(e)){r[t]===void 0&&(r[t]=[]);let n=r[t];for(let r of e[t])n.includes(r)||n.push(r)}n[e]=r}function _(e,t){if(e.length===0)return{};if(e.length===1)return e[0];let n={},r={},i=!0;for(let t of e){if(t===!1)return!1;if(t!==!0){i=!1;for(let e of Object.keys(t))r[e]===void 0&&(r[e]=[]),r[e].push(t[e])}}if(i)return!0;for(let i of Object.keys(r)){let a=r[i];(t.resolvers[i]??t.defaultResolver)(i,a,n,e,t)}return n}function v(e,t,r,a,o){let s=o.onConflict??`throw`;if(t.length===1||s===`first`){r[e]=t[0];return}let c=!0;for(let e=1;e<t.length;e++)if(!n(t[e],t[0])){c=!1;break}if(c){r[e]=t[0];return}if(s===`throw`)throw new i.ResolverNotFoundError(e,t);if(s!==`skip`)throw new i.InvalidOnConflictOptionError(s)}function y(e,t={}){return t.defaultResolver===void 0&&(t.defaultResolver=v),t.resolvers={...a,...t.resolvers},_(e,t)}t.exports={mergeSchemas:y,keywordsResolvers:a,defaultResolver:v,...i}})),hp=o(((e,t)=>{let{mergeSchemas:n}=mp();function r(e){return n(e,{onConflict:`skip`})}t.exports=r})),gp=o(((e,t)=>{function n(e,t,n,r){let i=``;t.validatorSchemasIds.size>0?(i+=`const Validator = require('fast-json-stringify/lib/validator')
|
|
137
137
|
`,i+=`const validatorState = ${JSON.stringify(r.getState())}\n`,i+=`const validator = Validator.restoreFromState(validatorState)
|
|
138
138
|
`):i+=`const validator = null
|
|
139
139
|
`;let{schema:a,...o}=n.getState();return`
|
|
@@ -145,7 +145,7 @@ caused by: `+i(o,t)):a},a=e=>i(e,new Set),o=(e,t,i)=>{if(!n(e))return``;let a=i?
|
|
|
145
145
|
|
|
146
146
|
${i}
|
|
147
147
|
|
|
148
|
-
module.exports = ${e.toString()}(validator, serializer)`}t.exports=n,t.exports.dependencies={Serializer:id(),Validator:
|
|
148
|
+
module.exports = ${e.toString()}(validator, serializer)`}t.exports=n,t.exports.dependencies={Serializer:id(),Validator:lp()}})),_p=o(((e,t)=>{let{RefResolver:n}=cp(),r=id(),i=lp(),a=up(),o=dp(),s=hp(),c=/'/g,l=2e4,u=`default`,d=new Set([`floor`,`ceil`,`round`,`trunc`]),f=new Set([`default`,`json-stringify`]),p=0;function m(e,t){if(!o(e)){t=t?`"${t}" `:``;let e=o.errors[0],n=Error(`${t}schema is invalid: data${e.instancePath} ${e.message}`);throw n.errors=m.errors,n}}function h(e,t){let n=t.schema.$ref,r=n.indexOf(`#`);r===-1&&(r=n.length);let i=n.slice(0,r)||t.schemaId,o=n.slice(r)||`#`,s=e.refResolver.getSchema(i,o);if(s===null)throw Error(`Cannot find reference "${n}"`);let c=new a(s,i,o);return s.$ref===void 0?c:h(e,c)}function g(e,t){return new a(e.refResolver.getSchema(t,`#`),t,`#`)}function _(e,t){return e.$id&&e.$id.charAt(0)!==`#`?e.$id:t}function v(e,t){let n=t.getSchemaRef()||``;return n.startsWith(e.rootSchemaId)&&(n=n.replace(e.rootSchemaId,``)||`#`),n}function y(e,t){m(e),t||={};let o={functions:[],functionsCounter:0,functionsNamesBySchema:new Map,options:t,refResolver:new n,rootSchemaId:e.$id||`__fjs_root_${p++}`,validatorSchemasIds:new Set,mergedSchemasIds:new Map,recursiveSchemas:new Set,recursivePaths:new Set,buildingSet:new Set,uid:0},s=_(e,o.rootSchemaId);if(o.refResolver.hasSchema(s)||o.refResolver.addSchema(e,o.rootSchemaId),t.schema)for(let e in t.schema){let n=t.schema[e],r=_(n,e);o.refResolver.hasSchema(r)||(m(n,e),o.refResolver.addSchema(n,e))}if(t.rounding&&!d.has(t.rounding))throw Error(`Unsupported integer rounding method ${t.rounding}`);if(t.largeArrayMechanism)if(f.has(t.largeArrayMechanism))u=t.largeArrayMechanism;else throw Error(`Unsupported large array mechanism ${t.largeArrayMechanism}`);if(t.largeArraySize){let e=typeof t.largeArraySize,n;if(e===`string`&&Number.isFinite(n=Number.parseInt(t.largeArraySize,10)))l=n;else if(e===`number`&&Number.isInteger(t.largeArraySize))l=t.largeArraySize;else if(e===`bigint`)l=Number(t.largeArraySize);else throw Error(`Unsupported large array size. Expected integer-like, got ${typeof t.largeArraySize} with value ${t.largeArraySize}`)}let c=new a(e,o.rootSchemaId);P(o,c);let h=L(o,c,`input`),g=`
|
|
149
149
|
|
|
150
150
|
const {
|
|
151
151
|
asString,
|
|
@@ -185,7 +185,7 @@ const asInteger = serializer.asInteger.bind(serializer)
|
|
|
185
185
|
${o.functions.join(`
|
|
186
186
|
`)}
|
|
187
187
|
return main
|
|
188
|
-
`;let v=new r(t),y=new i(t.ajv);for(let e of o.validatorSchemasIds){let t=o.refResolver.getSchema(e);y.addSchema(t,e);let n=o.refResolver.getSchemaDependencies(e);for(let[e,t]of Object.entries(n))y.addSchema(t,e)}if(t.debugMode&&(t.mode=`debug`),t.mode===`debug`)return{validator:y,serializer:v,code:`validator\nserializer\n${g}`,ajv:y.ajv};let b=Function(`validator`,`serializer`,g);return t.mode===`standalone`?
|
|
188
|
+
`;let v=new r(t),y=new i(t.ajv);for(let e of o.validatorSchemasIds){let t=o.refResolver.getSchema(e);y.addSchema(t,e);let n=o.refResolver.getSchemaDependencies(e);for(let[e,t]of Object.entries(n))y.addSchema(t,e)}if(t.debugMode&&(t.mode=`debug`),t.mode===`debug`)return{validator:y,serializer:v,code:`validator\nserializer\n${g}`,ajv:y.ajv};let b=Function(`validator`,`serializer`,g);return t.mode===`standalone`?gp()(b,o,v,y):b(y,v)}let b=[`properties`,`required`,`additionalProperties`,`patternProperties`,`maxProperties`,`minProperties`,`dependencies`],x=[`items`,`additionalItems`,`maxItems`,`minItems`,`uniqueItems`,`contains`],S=[`maxLength`,`minLength`,`pattern`],C=[`multipleOf`,`maximum`,`exclusiveMaximum`,`minimum`,`exclusiveMinimum`];function w(e){for(let t of b)if(t in e)return`object`;for(let t of x)if(t in e)return`array`;for(let t of S)if(t in e)return`string`;for(let t of C)if(t in e)return`number`;return e.type}function T(e,t,n,r){let i=t.schema,a=Object.keys(i.properties||{}),o=`
|
|
189
189
|
for (const key of Object.keys(${r})) {
|
|
190
190
|
if (
|
|
191
191
|
${a.length>0?a.map(e=>`key === ${JSON.stringify(e)}`).join(` || `)+` ||`:``}
|
|
@@ -427,11 +427,11 @@ const asInteger = serializer.asInteger.bind(serializer)
|
|
|
427
427
|
} else {
|
|
428
428
|
`),r.const===void 0?Array.isArray(a)?i+=N(e,t,n):i+=te(e,t,n):i+=ne(t,n),o&&(i+=`
|
|
429
429
|
}
|
|
430
|
-
`),i}t.exports=y,t.exports.default=y,t.exports.build=y,t.exports.validLargeArrayMechanisms=f,t.exports.restore=function({code:e,validator:t,serializer:n}){return Function.apply(null,[`validator`,`serializer`,e]).apply(null,[t,n])}})),_p=o(((e,t)=>{let n=gp();function r(){return function(e,t){let n=Object.assign({},t,{schema:e});return i.bind(null,n)}}function i(e,{schema:t}){return e.schema&&t.$id&&e.schema[t.$id]&&(e.schema={...e.schema},delete e.schema[t.$id]),n(t,e)}function a(e={readMode:!0}){if(e.readMode===!0&&typeof e.restoreFunction!=`function`)throw Error(`You must provide a function for the restoreFunction-option when readMode ON`);if(e.readMode!==!0&&typeof e.storeFunction!=`function`)throw Error(`You must provide a function for the storeFunction-option when readMode OFF`);if(e.readMode===!0)return function(){return function(t){return e.restoreFunction(t)}};let t=r();return function(n,r={}){r.mode=`standalone`;let i=t(n,r);return function(t){let n=i(t);return e.storeFunction(t,n),Function(n)}}}t.exports.SerializerSelector=r,t.exports.StandaloneSerializer=a,t.exports.default=a})),vp=o(((e,t)=>{let{SerializerSelector:n,StandaloneSerializer:r}=_p();t.exports=n,t.exports.default=n,t.exports.SerializerSelector=n,t.exports.StandaloneSerializer=r})),yp=o(((e,t)=>{let{buildSchemas:n}=rd();function r(e,t){if(e)return new i(e,t);let r=Object.assign({buildValidator:null,buildSerializer:null},t?.compilersFactory);return r.buildValidator||=ap()(),r.buildSerializer||=vp()(),new i(void 0,{bucket:t&&t.bucket||n,compilersFactory:r,isCustomValidatorCompiler:typeof t?.compilersFactory?.buildValidator==`function`,isCustomSerializerCompiler:typeof t?.compilersFactory?.buildValidator==`function`})}var i=class{constructor(e,t){this.opts=t||e?.opts,this.addedSchemas=!1,this.compilersFactory=this.opts.compilersFactory,e?(this.schemaBucket=this.opts.bucket(e.getSchemas()),this.validatorCompiler=e.getValidatorCompiler(),this.serializerCompiler=e.getSerializerCompiler(),this.isCustomValidatorCompiler=e.isCustomValidatorCompiler,this.isCustomSerializerCompiler=e.isCustomSerializerCompiler,this.parent=e):(this.schemaBucket=this.opts.bucket(),this.isCustomValidatorCompiler=this.opts.isCustomValidatorCompiler||!1,this.isCustomSerializerCompiler=this.opts.isCustomSerializerCompiler||!1)}add(e){return this.addedSchemas=!0,this.schemaBucket.add(e)}getSchema(e){return this.schemaBucket.getSchema(e)}getSchemas(){return this.schemaBucket.getSchemas()}setValidatorCompiler(e){this.compilersFactory=Object.assign({},this.compilersFactory,{buildValidator:()=>e}),this.validatorCompiler=e,this.isCustomValidatorCompiler=!0}setSerializerCompiler(e){this.compilersFactory=Object.assign({},this.compilersFactory,{buildSerializer:()=>e}),this.serializerCompiler=e,this.isCustomSerializerCompiler=!0}getValidatorCompiler(){return this.validatorCompiler||this.parent&&this.parent.getValidatorCompiler()}getSerializerCompiler(){return this.serializerCompiler||this.parent&&this.parent.getSerializerCompiler()}getSerializerBuilder(){return this.compilersFactory.buildSerializer||this.parent&&this.parent.getSerializerBuilder()}getValidatorBuilder(){return this.compilersFactory.buildValidator||this.parent&&this.parent.getValidatorBuilder()}setupValidator(e){this.validatorCompiler!==void 0&&!this.addedSchemas||(this.validatorCompiler=this.getValidatorBuilder()(this.schemaBucket.getSchemas(),e.ajv))}setupSerializer(e){this.serializerCompiler!==void 0&&!this.addedSchemas||(this.serializerCompiler=this.getSerializerBuilder()(this.schemaBucket.getSchemas(),e.serializerOpts))}};i.buildSchemaController=r,t.exports=i})),bp=o(((e,t)=>{t.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:2**53-1||9007199254740991,RELEASE_TYPES:[`major`,`premajor`,`minor`,`preminor`,`patch`,`prepatch`,`prerelease`],SEMVER_SPEC_VERSION:`2.0.0`,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}})),xp=o(((e,t)=>{t.exports=typeof process==`object`&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error(`SEMVER`,...e):()=>{}})),Sp=o(((e,t)=>{let{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:i}=bp(),a=xp();e=t.exports={};let o=e.re=[],s=e.safeRe=[],c=e.src=[],l=e.safeSrc=[],u=e.t={},d=0,f=`[a-zA-Z0-9-]`,p=[[`\\s`,1],[`\\d`,i],[f,r]],m=e=>{for(let[t,n]of p)e=e.split(`${t}*`).join(`${t}{0,${n}}`).split(`${t}+`).join(`${t}{1,${n}}`);return e},h=(e,t,n)=>{let r=m(t),i=d++;a(e,i,t),u[e]=i,c[i]=t,l[i]=r,o[i]=new RegExp(t,n?`g`:void 0),s[i]=new RegExp(r,n?`g`:void 0)};h(`NUMERICIDENTIFIER`,`0|[1-9]\\d*`),h(`NUMERICIDENTIFIERLOOSE`,`\\d+`),h(`NONNUMERICIDENTIFIER`,`\\d*[a-zA-Z-]${f}*`),h(`MAINVERSION`,`(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})`),h(`MAINVERSIONLOOSE`,`(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})`),h(`PRERELEASEIDENTIFIER`,`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIER]})`),h(`PRERELEASEIDENTIFIERLOOSE`,`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIERLOOSE]})`),h(`PRERELEASE`,`(?:-(${c[u.PRERELEASEIDENTIFIER]}(?:\\.${c[u.PRERELEASEIDENTIFIER]})*))`),h(`PRERELEASELOOSE`,`(?:-?(${c[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[u.PRERELEASEIDENTIFIERLOOSE]})*))`),h(`BUILDIDENTIFIER`,`${f}+`),h(`BUILD`,`(?:\\+(${c[u.BUILDIDENTIFIER]}(?:\\.${c[u.BUILDIDENTIFIER]})*))`),h(`FULLPLAIN`,`v?${c[u.MAINVERSION]}${c[u.PRERELEASE]}?${c[u.BUILD]}?`),h(`FULL`,`^${c[u.FULLPLAIN]}$`),h(`LOOSEPLAIN`,`[v=\\s]*${c[u.MAINVERSIONLOOSE]}${c[u.PRERELEASELOOSE]}?${c[u.BUILD]}?`),h(`LOOSE`,`^${c[u.LOOSEPLAIN]}$`),h(`GTLT`,`((?:<|>)?=?)`),h(`XRANGEIDENTIFIERLOOSE`,`${c[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),h(`XRANGEIDENTIFIER`,`${c[u.NUMERICIDENTIFIER]}|x|X|\\*`),h(`XRANGEPLAIN`,`[v=\\s]*(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:${c[u.PRERELEASE]})?${c[u.BUILD]}?)?)?`),h(`XRANGEPLAINLOOSE`,`[v=\\s]*(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:${c[u.PRERELEASELOOSE]})?${c[u.BUILD]}?)?)?`),h(`XRANGE`,`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAIN]}$`),h(`XRANGELOOSE`,`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAINLOOSE]}$`),h(`COERCEPLAIN`,`(^|[^\\d])(\\d{1,${n}})(?:\\.(\\d{1,${n}}))?(?:\\.(\\d{1,${n}}))?`),h(`COERCE`,`${c[u.COERCEPLAIN]}(?:$|[^\\d])`),h(`COERCEFULL`,c[u.COERCEPLAIN]+`(?:${c[u.PRERELEASE]})?(?:${c[u.BUILD]})?(?:$|[^\\d])`),h(`COERCERTL`,c[u.COERCE],!0),h(`COERCERTLFULL`,c[u.COERCEFULL],!0),h(`LONETILDE`,`(?:~>?)`),h(`TILDETRIM`,`(\\s*)${c[u.LONETILDE]}\\s+`,!0),e.tildeTrimReplace=`$1~`,h(`TILDE`,`^${c[u.LONETILDE]}${c[u.XRANGEPLAIN]}$`),h(`TILDELOOSE`,`^${c[u.LONETILDE]}${c[u.XRANGEPLAINLOOSE]}$`),h(`LONECARET`,`(?:\\^)`),h(`CARETTRIM`,`(\\s*)${c[u.LONECARET]}\\s+`,!0),e.caretTrimReplace=`$1^`,h(`CARET`,`^${c[u.LONECARET]}${c[u.XRANGEPLAIN]}$`),h(`CARETLOOSE`,`^${c[u.LONECARET]}${c[u.XRANGEPLAINLOOSE]}$`),h(`COMPARATORLOOSE`,`^${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]})$|^$`),h(`COMPARATOR`,`^${c[u.GTLT]}\\s*(${c[u.FULLPLAIN]})$|^$`),h(`COMPARATORTRIM`,`(\\s*)${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]}|${c[u.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace=`$1$2$3`,h(`HYPHENRANGE`,`^\\s*(${c[u.XRANGEPLAIN]})\\s+-\\s+(${c[u.XRANGEPLAIN]})\\s*$`),h(`HYPHENRANGELOOSE`,`^\\s*(${c[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[u.XRANGEPLAINLOOSE]})\\s*$`),h(`STAR`,`(<|>)?=?\\s*\\*`),h(`GTE0`,`^\\s*>=\\s*0\\.0\\.0\\s*$`),h(`GTE0PRE`,`^\\s*>=\\s*0\\.0\\.0-0\\s*$`)})),Cp=o(((e,t)=>{let n=Object.freeze({loose:!0}),r=Object.freeze({});t.exports=e=>e?typeof e==`object`?e:n:r})),wp=o(((e,t)=>{let n=/^[0-9]+$/,r=(e,t)=>{if(typeof e==`number`&&typeof t==`number`)return e===t?0:e<t?-1:1;let r=n.test(e),i=n.test(t);return r&&i&&(e=+e,t=+t),e===t?0:r&&!i?-1:i&&!r?1:e<t?-1:1};t.exports={compareIdentifiers:r,rcompareIdentifiers:(e,t)=>r(t,e)}})),Tp=o(((e,t)=>{let n=xp(),{MAX_LENGTH:r,MAX_SAFE_INTEGER:i}=bp(),{safeRe:a,t:o}=Sp(),s=Cp(),{compareIdentifiers:c}=wp();t.exports=class e{constructor(t,c){if(c=s(c),t instanceof e){if(t.loose===!!c.loose&&t.includePrerelease===!!c.includePrerelease)return t;t=t.version}else if(typeof t!=`string`)throw TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>r)throw TypeError(`version is longer than ${r} characters`);n(`SemVer`,t,c),this.options=c,this.loose=!!c.loose,this.includePrerelease=!!c.includePrerelease;let l=t.trim().match(c.loose?a[o.LOOSE]:a[o.FULL]);if(!l)throw TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+l[1],this.minor=+l[2],this.patch=+l[3],this.major>i||this.major<0)throw TypeError(`Invalid major version`);if(this.minor>i||this.minor<0)throw TypeError(`Invalid minor version`);if(this.patch>i||this.patch<0)throw TypeError(`Invalid patch version`);l[4]?this.prerelease=l[4].split(`.`).map(e=>{if(/^[0-9]+$/.test(e)){let t=+e;if(t>=0&&t<i)return t}return e}):this.prerelease=[],this.build=l[5]?l[5].split(`.`):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(`.`)}`),this.version}toString(){return this.version}compare(t){if(n(`SemVer.compare`,this.version,this.options,t),!(t instanceof e)){if(typeof t==`string`&&t===this.version)return 0;t=new e(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return t instanceof e||(t=new e(t,this.options)),this.major<t.major?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:this.patch>t.patch?1:0}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let e=this.prerelease[r],i=t.prerelease[r];if(n(`prerelease compare`,r,e,i),e===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(e===void 0)return-1;if(e===i)continue;return c(e,i)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let e=this.build[r],i=t.build[r];if(n(`build compare`,r,e,i),e===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(e===void 0)return-1;if(e===i)continue;return c(e,i)}while(++r)}inc(e,t,n){if(e.startsWith(`pre`)){if(!t&&n===!1)throw Error(`invalid increment argument: identifier is empty`);if(t){let e=`-${t}`.match(this.options.loose?a[o.PRERELEASELOOSE]:a[o.PRERELEASE]);if(!e||e[1]!==t)throw Error(`invalid identifier: ${t}`)}}switch(e){case`premajor`:this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc(`pre`,t,n);break;case`preminor`:this.prerelease.length=0,this.patch=0,this.minor++,this.inc(`pre`,t,n);break;case`prepatch`:this.prerelease.length=0,this.inc(`patch`,t,n),this.inc(`pre`,t,n);break;case`prerelease`:this.prerelease.length===0&&this.inc(`patch`,t,n),this.inc(`pre`,t,n);break;case`release`:if(this.prerelease.length===0)throw Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case`major`:(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case`minor`:(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case`patch`:this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case`pre`:{let e=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[e];else{let r=this.prerelease.length;for(;--r>=0;)typeof this.prerelease[r]==`number`&&(this.prerelease[r]++,r=-2);if(r===-1){if(t===this.prerelease.join(`.`)&&n===!1)throw Error(`invalid increment argument: identifier already exists`);this.prerelease.push(e)}}if(t){let r=[t,e];n===!1&&(r=[t]),c(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=r):this.prerelease=r}break}default:throw Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(`.`)}`),this}}})),Ep=o(((e,t)=>{let n=Tp();t.exports=(e,t,r=!1)=>{if(e instanceof n)return e;try{return new n(e,t)}catch(e){if(!r)return null;throw e}}})),Dp=o(((e,t)=>{let n=Ep();t.exports=(e,t)=>{let r=n(e,t);return r?r.version:null}})),Op=o(((e,t)=>{let n=Ep();t.exports=(e,t)=>{let r=n(e.trim().replace(/^[=v]+/,``),t);return r?r.version:null}})),kp=o(((e,t)=>{let n=Tp();t.exports=(e,t,r,i,a)=>{typeof r==`string`&&(a=i,i=r,r=void 0);try{return new n(e instanceof n?e.version:e,r).inc(t,i,a).version}catch{return null}}})),Ap=o(((e,t)=>{let n=Ep();t.exports=(e,t)=>{let r=n(e,null,!0),i=n(t,null,!0),a=r.compare(i);if(a===0)return null;let o=a>0,s=o?r:i,c=o?i:r,l=!!s.prerelease.length;if(c.prerelease.length&&!l){if(!c.patch&&!c.minor)return`major`;if(c.compareMain(s)===0)return c.minor&&!c.patch?`minor`:`patch`}let u=l?`pre`:``;return r.major===i.major?r.minor===i.minor?r.patch===i.patch?`prerelease`:u+`patch`:u+`minor`:u+`major`}})),jp=o(((e,t)=>{let n=Tp();t.exports=(e,t)=>new n(e,t).major})),Mp=o(((e,t)=>{let n=Tp();t.exports=(e,t)=>new n(e,t).minor})),Np=o(((e,t)=>{let n=Tp();t.exports=(e,t)=>new n(e,t).patch})),Pp=o(((e,t)=>{let n=Ep();t.exports=(e,t)=>{let r=n(e,t);return r&&r.prerelease.length?r.prerelease:null}})),Fp=o(((e,t)=>{let n=Tp();t.exports=(e,t,r)=>new n(e,r).compare(new n(t,r))})),Ip=o(((e,t)=>{let n=Fp();t.exports=(e,t,r)=>n(t,e,r)})),Lp=o(((e,t)=>{let n=Fp();t.exports=(e,t)=>n(e,t,!0)})),Rp=o(((e,t)=>{let n=Tp();t.exports=(e,t,r)=>{let i=new n(e,r),a=new n(t,r);return i.compare(a)||i.compareBuild(a)}})),zp=o(((e,t)=>{let n=Rp();t.exports=(e,t)=>e.sort((e,r)=>n(e,r,t))})),Bp=o(((e,t)=>{let n=Rp();t.exports=(e,t)=>e.sort((e,r)=>n(r,e,t))})),Vp=o(((e,t)=>{let n=Fp();t.exports=(e,t,r)=>n(e,t,r)>0})),Hp=o(((e,t)=>{let n=Fp();t.exports=(e,t,r)=>n(e,t,r)<0})),Up=o(((e,t)=>{let n=Fp();t.exports=(e,t,r)=>n(e,t,r)===0})),Wp=o(((e,t)=>{let n=Fp();t.exports=(e,t,r)=>n(e,t,r)!==0})),Gp=o(((e,t)=>{let n=Fp();t.exports=(e,t,r)=>n(e,t,r)>=0})),Kp=o(((e,t)=>{let n=Fp();t.exports=(e,t,r)=>n(e,t,r)<=0})),qp=o(((e,t)=>{let n=Up(),r=Wp(),i=Vp(),a=Gp(),o=Hp(),s=Kp();t.exports=(e,t,c,l)=>{switch(t){case`===`:return typeof e==`object`&&(e=e.version),typeof c==`object`&&(c=c.version),e===c;case`!==`:return typeof e==`object`&&(e=e.version),typeof c==`object`&&(c=c.version),e!==c;case``:case`=`:case`==`:return n(e,c,l);case`!=`:return r(e,c,l);case`>`:return i(e,c,l);case`>=`:return a(e,c,l);case`<`:return o(e,c,l);case`<=`:return s(e,c,l);default:throw TypeError(`Invalid operator: ${t}`)}}})),Jp=o(((e,t)=>{let n=Tp(),r=Ep(),{safeRe:i,t:a}=Sp();t.exports=(e,t)=>{if(e instanceof n)return e;if(typeof e==`number`&&(e=String(e)),typeof e!=`string`)return null;t||={};let o=null;if(!t.rtl)o=e.match(t.includePrerelease?i[a.COERCEFULL]:i[a.COERCE]);else{let n=t.includePrerelease?i[a.COERCERTLFULL]:i[a.COERCERTL],r;for(;(r=n.exec(e))&&(!o||o.index+o[0].length!==e.length);)(!o||r.index+r[0].length!==o.index+o[0].length)&&(o=r),n.lastIndex=r.index+r[1].length+r[2].length;n.lastIndex=-1}if(o===null)return null;let s=o[2];return r(`${s}.${o[3]||`0`}.${o[4]||`0`}${t.includePrerelease&&o[5]?`-${o[5]}`:``}${t.includePrerelease&&o[6]?`+${o[6]}`:``}`,t)}})),Yp=o(((e,t)=>{t.exports=class{constructor(){this.max=1e3,this.map=new Map}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){let e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}}})),Xp=o(((e,t)=>{let n=/\s+/g;t.exports=class e{constructor(t,r){if(r=i(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof a)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=t.trim().replace(n,` `),this.set=this.raw.split(`||`).map(e=>this.parseRange(e.trim())).filter(e=>e.length),!this.set.length)throw TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let e=this.set[0];if(this.set=this.set.filter(e=>!h(e[0])),this.set.length===0)this.set=[e];else if(this.set.length>1){for(let e of this.set)if(e.length===1&&g(e[0])){this.set=[e];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted=``;for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+=`||`);let t=this.set[e];for(let e=0;e<t.length;e++)e>0&&(this.formatted+=` `),this.formatted+=t[e].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let t=((this.options.includePrerelease&&p)|(this.options.loose&&m))+`:`+e,n=r.get(t);if(n)return n;let i=this.options.loose,s=i?c[l.HYPHENRANGELOOSE]:c[l.HYPHENRANGE];e=e.replace(s,O(this.options.includePrerelease)),o(`hyphen replace`,e),e=e.replace(c[l.COMPARATORTRIM],u),o(`comparator trim`,e),e=e.replace(c[l.TILDETRIM],d),o(`tilde trim`,e),e=e.replace(c[l.CARETTRIM],f),o(`caret trim`,e);let g=e.split(` `).map(e=>v(e,this.options)).join(` `).split(/\s+/).map(e=>D(e,this.options));i&&(g=g.filter(e=>(o(`loose invalid filter`,e,this.options),!!e.match(c[l.COMPARATORLOOSE])))),o(`range list`,g);let _=new Map,y=g.map(e=>new a(e,this.options));for(let e of y){if(h(e))return[e];_.set(e.value,e)}_.size>1&&_.has(``)&&_.delete(``);let b=[..._.values()];return r.set(t,b),b}intersects(t,n){if(!(t instanceof e))throw TypeError(`a Range is required`);return this.set.some(e=>_(e,n)&&t.set.some(t=>_(t,n)&&e.every(e=>t.every(t=>e.intersects(t,n)))))}test(e){if(!e)return!1;if(typeof e==`string`)try{e=new s(e,this.options)}catch{return!1}for(let t=0;t<this.set.length;t++)if(k(this.set[t],e,this.options))return!0;return!1}};let r=new(Yp()),i=Cp(),a=Zp(),o=xp(),s=Tp(),{safeRe:c,t:l,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:f}=Sp(),{FLAG_INCLUDE_PRERELEASE:p,FLAG_LOOSE:m}=bp(),h=e=>e.value===`<0.0.0-0`,g=e=>e.value===``,_=(e,t)=>{let n=!0,r=e.slice(),i=r.pop();for(;n&&r.length;)n=r.every(e=>i.intersects(e,t)),i=r.pop();return n},v=(e,t)=>(e=e.replace(c[l.BUILD],``),o(`comp`,e,t),e=S(e,t),o(`caret`,e),e=b(e,t),o(`tildes`,e),e=w(e,t),o(`xrange`,e),e=E(e,t),o(`stars`,e),e),y=e=>!e||e.toLowerCase()===`x`||e===`*`,b=(e,t)=>e.trim().split(/\s+/).map(e=>x(e,t)).join(` `),x=(e,t)=>{let n=t.loose?c[l.TILDELOOSE]:c[l.TILDE];return e.replace(n,(t,n,r,i,a)=>{o(`tilde`,e,t,n,r,i,a);let s;return y(n)?s=``:y(r)?s=`>=${n}.0.0 <${+n+1}.0.0-0`:y(i)?s=`>=${n}.${r}.0 <${n}.${+r+1}.0-0`:a?(o(`replaceTilde pr`,a),s=`>=${n}.${r}.${i}-${a} <${n}.${+r+1}.0-0`):s=`>=${n}.${r}.${i} <${n}.${+r+1}.0-0`,o(`tilde return`,s),s})},S=(e,t)=>e.trim().split(/\s+/).map(e=>C(e,t)).join(` `),C=(e,t)=>{o(`caret`,e,t);let n=t.loose?c[l.CARETLOOSE]:c[l.CARET],r=t.includePrerelease?`-0`:``;return e.replace(n,(t,n,i,a,s)=>{o(`caret`,e,t,n,i,a,s);let c;return y(n)?c=``:y(i)?c=`>=${n}.0.0${r} <${+n+1}.0.0-0`:y(a)?c=n===`0`?`>=${n}.${i}.0${r} <${n}.${+i+1}.0-0`:`>=${n}.${i}.0${r} <${+n+1}.0.0-0`:s?(o(`replaceCaret pr`,s),c=n===`0`?i===`0`?`>=${n}.${i}.${a}-${s} <${n}.${i}.${+a+1}-0`:`>=${n}.${i}.${a}-${s} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${a}-${s} <${+n+1}.0.0-0`):(o(`no pr`),c=n===`0`?i===`0`?`>=${n}.${i}.${a}${r} <${n}.${i}.${+a+1}-0`:`>=${n}.${i}.${a}${r} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${a} <${+n+1}.0.0-0`),o(`caret return`,c),c})},w=(e,t)=>(o(`replaceXRanges`,e,t),e.split(/\s+/).map(e=>T(e,t)).join(` `)),T=(e,t)=>{e=e.trim();let n=t.loose?c[l.XRANGELOOSE]:c[l.XRANGE];return e.replace(n,(n,r,i,a,s,c)=>{o(`xRange`,e,n,r,i,a,s,c);let l=y(i),u=l||y(a),d=u||y(s),f=d;return r===`=`&&f&&(r=``),c=t.includePrerelease?`-0`:``,l?n=r===`>`||r===`<`?`<0.0.0-0`:`*`:r&&f?(u&&(a=0),s=0,r===`>`?(r=`>=`,u?(i=+i+1,a=0,s=0):(a=+a+1,s=0)):r===`<=`&&(r=`<`,u?i=+i+1:a=+a+1),r===`<`&&(c=`-0`),n=`${r+i}.${a}.${s}${c}`):u?n=`>=${i}.0.0${c} <${+i+1}.0.0-0`:d&&(n=`>=${i}.${a}.0${c} <${i}.${+a+1}.0-0`),o(`xRange return`,n),n})},E=(e,t)=>(o(`replaceStars`,e,t),e.trim().replace(c[l.STAR],``)),D=(e,t)=>(o(`replaceGTE0`,e,t),e.trim().replace(c[t.includePrerelease?l.GTE0PRE:l.GTE0],``)),O=e=>(t,n,r,i,a,o,s,c,l,u,d,f)=>(n=y(r)?``:y(i)?`>=${r}.0.0${e?`-0`:``}`:y(a)?`>=${r}.${i}.0${e?`-0`:``}`:o?`>=${n}`:`>=${n}${e?`-0`:``}`,c=y(l)?``:y(u)?`<${+l+1}.0.0-0`:y(d)?`<${l}.${+u+1}.0-0`:f?`<=${l}.${u}.${d}-${f}`:e?`<${l}.${u}.${+d+1}-0`:`<=${c}`,`${n} ${c}`.trim()),k=(e,t,n)=>{for(let n=0;n<e.length;n++)if(!e[n].test(t))return!1;if(t.prerelease.length&&!n.includePrerelease){for(let n=0;n<e.length;n++)if(o(e[n].semver),e[n].semver!==a.ANY&&e[n].semver.prerelease.length>0){let r=e[n].semver;if(r.major===t.major&&r.minor===t.minor&&r.patch===t.patch)return!0}return!1}return!0}})),Zp=o(((e,t)=>{let n=Symbol(`SemVer ANY`);t.exports=class e{static get ANY(){return n}constructor(t,i){if(i=r(i),t instanceof e){if(t.loose===!!i.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(` `),s(`comparator`,t,i),this.options=i,this.loose=!!i.loose,this.parse(t),this.semver===n?this.value=``:this.value=this.operator+this.semver.version,s(`comp`,this)}parse(e){let t=this.options.loose?i[a.COMPARATORLOOSE]:i[a.COMPARATOR],r=e.match(t);if(!r)throw TypeError(`Invalid comparator: ${e}`);this.operator=r[1]===void 0?``:r[1],this.operator===`=`&&(this.operator=``),r[2]?this.semver=new c(r[2],this.options.loose):this.semver=n}toString(){return this.value}test(e){if(s(`Comparator.test`,e,this.options.loose),this.semver===n||e===n)return!0;if(typeof e==`string`)try{e=new c(e,this.options)}catch{return!1}return o(e,this.operator,this.semver,this.options)}intersects(t,n){if(!(t instanceof e))throw TypeError(`a Comparator is required`);return this.operator===``?this.value===``?!0:new l(t.value,n).test(this.value):t.operator===``?t.value===``?!0:new l(this.value,n).test(t.semver):(n=r(n),n.includePrerelease&&(this.value===`<0.0.0-0`||t.value===`<0.0.0-0`)||!n.includePrerelease&&(this.value.startsWith(`<0.0.0`)||t.value.startsWith(`<0.0.0`))?!1:!!(this.operator.startsWith(`>`)&&t.operator.startsWith(`>`)||this.operator.startsWith(`<`)&&t.operator.startsWith(`<`)||this.semver.version===t.semver.version&&this.operator.includes(`=`)&&t.operator.includes(`=`)||o(this.semver,`<`,t.semver,n)&&this.operator.startsWith(`>`)&&t.operator.startsWith(`<`)||o(this.semver,`>`,t.semver,n)&&this.operator.startsWith(`<`)&&t.operator.startsWith(`>`)))}};let r=Cp(),{safeRe:i,t:a}=Sp(),o=qp(),s=xp(),c=Tp(),l=Xp()})),Qp=o(((e,t)=>{let n=Xp();t.exports=(e,t,r)=>{try{t=new n(t,r)}catch{return!1}return t.test(e)}})),$p=o(((e,t)=>{let n=Xp();t.exports=(e,t)=>new n(e,t).set.map(e=>e.map(e=>e.value).join(` `).trim().split(` `))})),em=o(((e,t)=>{let n=Tp(),r=Xp();t.exports=(e,t,i)=>{let a=null,o=null,s=null;try{s=new r(t,i)}catch{return null}return e.forEach(e=>{s.test(e)&&(!a||o.compare(e)===-1)&&(a=e,o=new n(a,i))}),a}})),tm=o(((e,t)=>{let n=Tp(),r=Xp();t.exports=(e,t,i)=>{let a=null,o=null,s=null;try{s=new r(t,i)}catch{return null}return e.forEach(e=>{s.test(e)&&(!a||o.compare(e)===1)&&(a=e,o=new n(a,i))}),a}})),nm=o(((e,t)=>{let n=Tp(),r=Xp(),i=Vp();t.exports=(e,t)=>{e=new r(e,t);let a=new n(`0.0.0`);if(e.test(a)||(a=new n(`0.0.0-0`),e.test(a)))return a;a=null;for(let t=0;t<e.set.length;++t){let r=e.set[t],o=null;r.forEach(e=>{let t=new n(e.semver.version);switch(e.operator){case`>`:t.prerelease.length===0?t.patch++:t.prerelease.push(0),t.raw=t.format();case``:case`>=`:(!o||i(t,o))&&(o=t);break;case`<`:case`<=`:break;default:throw Error(`Unexpected operation: ${e.operator}`)}}),o&&(!a||i(a,o))&&(a=o)}return a&&e.test(a)?a:null}})),rm=o(((e,t)=>{let n=Xp();t.exports=(e,t)=>{try{return new n(e,t).range||`*`}catch{return null}}})),im=o(((e,t)=>{let n=Tp(),r=Zp(),{ANY:i}=r,a=Xp(),o=Qp(),s=Vp(),c=Hp(),l=Kp(),u=Gp();t.exports=(e,t,d,f)=>{e=new n(e,f),t=new a(t,f);let p,m,h,g,_;switch(d){case`>`:p=s,m=l,h=c,g=`>`,_=`>=`;break;case`<`:p=c,m=u,h=s,g=`<`,_=`<=`;break;default:throw TypeError(`Must provide a hilo val of "<" or ">"`)}if(o(e,t,f))return!1;for(let n=0;n<t.set.length;++n){let a=t.set[n],o=null,s=null;if(a.forEach(e=>{e.semver===i&&(e=new r(`>=0.0.0`)),o||=e,s||=e,p(e.semver,o.semver,f)?o=e:h(e.semver,s.semver,f)&&(s=e)}),o.operator===g||o.operator===_||(!s.operator||s.operator===g)&&m(e,s.semver)||s.operator===_&&h(e,s.semver))return!1}return!0}})),am=o(((e,t)=>{let n=im();t.exports=(e,t,r)=>n(e,t,`>`,r)})),om=o(((e,t)=>{let n=im();t.exports=(e,t,r)=>n(e,t,`<`,r)})),sm=o(((e,t)=>{let n=Xp();t.exports=(e,t,r)=>(e=new n(e,r),t=new n(t,r),e.intersects(t,r))})),cm=o(((e,t)=>{let n=Qp(),r=Fp();t.exports=(e,t,i)=>{let a=[],o=null,s=null,c=e.sort((e,t)=>r(e,t,i));for(let e of c)n(e,t,i)?(s=e,o||=e):(s&&a.push([o,s]),s=null,o=null);o&&a.push([o,null]);let l=[];for(let[e,t]of a)e===t?l.push(e):!t&&e===c[0]?l.push(`*`):t?e===c[0]?l.push(`<=${t}`):l.push(`${e} - ${t}`):l.push(`>=${e}`);let u=l.join(` || `),d=typeof t.raw==`string`?t.raw:String(t);return u.length<d.length?u:t}})),lm=o(((e,t)=>{let n=Xp(),r=Zp(),{ANY:i}=r,a=Qp(),o=Fp(),s=(e,t,r={})=>{if(e===t)return!0;e=new n(e,r),t=new n(t,r);let i=!1;OUTER:for(let n of e.set){for(let e of t.set){let t=u(n,e,r);if(i||=t!==null,t)continue OUTER}if(i)return!1}return!0},c=[new r(`>=0.0.0-0`)],l=[new r(`>=0.0.0`)],u=(e,t,n)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===i){if(t.length===1&&t[0].semver===i)return!0;e=n.includePrerelease?c:l}if(t.length===1&&t[0].semver===i){if(n.includePrerelease)return!0;t=l}let r=new Set,s,u;for(let t of e)t.operator===`>`||t.operator===`>=`?s=d(s,t,n):t.operator===`<`||t.operator===`<=`?u=f(u,t,n):r.add(t.semver);if(r.size>1)return null;let p;if(s&&u&&(p=o(s.semver,u.semver,n),p>0||p===0&&(s.operator!==`>=`||u.operator!==`<=`)))return null;for(let e of r){if(s&&!a(e,String(s),n)||u&&!a(e,String(u),n))return null;for(let r of t)if(!a(e,String(r),n))return!1;return!0}let m,h,g,_,v=u&&!n.includePrerelease&&u.semver.prerelease.length?u.semver:!1,y=s&&!n.includePrerelease&&s.semver.prerelease.length?s.semver:!1;v&&v.prerelease.length===1&&u.operator===`<`&&v.prerelease[0]===0&&(v=!1);for(let e of t){if(_=_||e.operator===`>`||e.operator===`>=`,g=g||e.operator===`<`||e.operator===`<=`,s){if(y&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===y.major&&e.semver.minor===y.minor&&e.semver.patch===y.patch&&(y=!1),e.operator===`>`||e.operator===`>=`){if(m=d(s,e,n),m===e&&m!==s)return!1}else if(s.operator===`>=`&&!a(s.semver,String(e),n))return!1}if(u){if(v&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===v.major&&e.semver.minor===v.minor&&e.semver.patch===v.patch&&(v=!1),e.operator===`<`||e.operator===`<=`){if(h=f(u,e,n),h===e&&h!==u)return!1}else if(u.operator===`<=`&&!a(u.semver,String(e),n))return!1}if(!e.operator&&(u||s)&&p!==0)return!1}return!(s&&g&&!u&&p!==0||u&&_&&!s&&p!==0||y||v)},d=(e,t,n)=>{if(!e)return t;let r=o(e.semver,t.semver,n);return r>0?e:r<0||t.operator===`>`&&e.operator===`>=`?t:e},f=(e,t,n)=>{if(!e)return t;let r=o(e.semver,t.semver,n);return r<0?e:r>0||t.operator===`<`&&e.operator===`<=`?t:e};t.exports=s})),um=o(((e,t)=>{let n=Sp(),r=bp(),i=Tp(),a=wp();t.exports={parse:Ep(),valid:Dp(),clean:Op(),inc:kp(),diff:Ap(),major:jp(),minor:Mp(),patch:Np(),prerelease:Pp(),compare:Fp(),rcompare:Ip(),compareLoose:Lp(),compareBuild:Rp(),sort:zp(),rsort:Bp(),gt:Vp(),lt:Hp(),eq:Up(),neq:Wp(),gte:Gp(),lte:Kp(),cmp:qp(),coerce:Jp(),Comparator:Zp(),Range:Xp(),satisfies:Qp(),toComparators:$p(),maxSatisfying:em(),minSatisfying:tm(),minVersion:nm(),validRange:rm(),outside:im(),gtr:am(),ltr:om(),intersects:sm(),simplifyRange:cm(),subset:lm(),SemVer:i,re:n.re,src:n.src,tokens:n.t,SEMVER_SPEC_VERSION:r.SEMVER_SPEC_VERSION,RELEASE_TYPES:r.RELEASE_TYPES,compareIdentifiers:a.compareIdentifiers,rcompareIdentifiers:a.rcompareIdentifiers}})),dm=o(((e,t)=>{let n=um(),r=require(`node:assert`),i=Symbol.for(`registered-plugin`),{kTestInternals:a}=du(),{exist:o,existReply:s,existRequest:c}=sd(),{FST_ERR_PLUGIN_VERSION_MISMATCH:l,FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE:u,FST_ERR_PLUGIN_INVALID_ASYNC_HANDLER:d}=mu(),f=/-(?:rc|pre|alpha).+$/u;function p(e){return e[Symbol.for(`plugin-meta`)]}function m(e){let t=g(e);if(t)return t;let n=require.cache;if(n){let t=Object.keys(n);for(let r=0;r<t.length;r++){let i=t[r];if(n[i].exports===e)return i}}return e.name?e.name:null}function h(e){return e.toString().split(`
|
|
431
|
-
`,2).map(e=>e.trim()).join(` -- `)}function g(e){return e[Symbol.for(`fastify.display-name`)]}function _(e){return!!e[Symbol.for(`skip-override`)]}function v(e){let t=p(e);if(!t)return;let n=t.dependencies;n&&(r(Array.isArray(n),`The dependencies should be an array of strings`),n.forEach(e=>{r(this[i].indexOf(e)>-1,`The dependency '${e}' of plugin '${t.name}' is not registered`)}))}function y(e){let t=p(e);if(!t)return;let{decorators:n,name:r}=t;n&&(n.fastify&&x(this,`Fastify`,n.fastify,r),n.reply&&x(this,`Reply`,n.reply,r),n.request&&x(this,`Request`,n.request,r))}let b={Fastify:o,Request:c,Reply:s};function x(e,t,n,i){r(Array.isArray(n),`The decorators should be an array of strings`),n.forEach(n=>{let r=typeof i==`string`?` required by '${i}'`:``;if(!b[t].call(e,n))throw new u(n,r,t)})}function S(e){let t=p(e);if(t?.fastify==null)return;let r=t.fastify,i=f.test(this.version);if(!(i===!0&&n.gt(this.version,n.coerce(r))===!0)&&r&&n.satisfies(this.version,r,{includePrerelease:i})===!1)throw new l(t.name,r,this.version)}function C(e){let t=p(e);if(!t)return;let n=t.name;if(n)return this[i].push(n),n}function w(e,t){if(e.constructor.name===`AsyncFunction`&&e.length===3)throw new d(t)}function T(e){let t=C.call(this,e)||m(e);return w.call(this,e,t),S.call(this,e),y.call(this,e),v.call(this,e),_(e)}t.exports={getPluginName:m,getFuncPreview:h,kRegisteredPlugins:i,getDisplayName:g,registerPlugin:T},t.exports[a]={shouldSkipOverride:_,getMeta:p,checkDecorators:y,checkDependencies:v}})),fm=o(((e,t)=>{function n(e,t){let n=t||i();return e?a(e,n):n}function r(e,t){return e.genReqId(t)}function i(){let e=0;return function(){return e=e+1&2147483647,`req-${e.toString(36)}`}}function a(e,t){return function(n){return n.headers[e]||t(n)}}t.exports={getGenReqId:r,reqIdGenFactory:n}})),pm=o(((e,t)=>{var n=12,r=0,i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,7,7,7,7,7,7,7,7,7,7,7,7,8,7,7,10,9,9,9,11,4,4,4,4,4,4,4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,12,0,0,0,0,24,36,48,60,72,84,96,0,12,12,12,0,0,0,0,0,0,0,0,0,0,0,24,0,0,0,0,0,0,0,0,0,24,24,24,0,0,0,0,0,0,0,0,0,24,24,0,0,0,0,0,0,0,0,0,0,48,48,48,0,0,0,0,0,0,0,0,0,0,48,48,0,0,0,0,0,0,0,0,0,48,0,0,0,0,0,0,0,0,0,0,127,63,63,63,0,31,15,15,15,7,7,7];function a(e){var t=e.indexOf(`%`);if(t===-1)return e;for(var a=e.length,o=``,c=0,l=0,u=t,d=n;t>-1&&t<a;){var f=s(e[t+1],4)|s(e[t+2],0),p=i[f];if(d=i[256+d+p],l=l<<6|f&i[364+p],d===n)o+=e.slice(c,u),o+=l<=65535?String.fromCharCode(l):String.fromCharCode(55232+(l>>10),56320+(l&1023)),l=0,c=t+3,t=u=e.indexOf(`%`,c);else if(d===r)return null;else{if(t+=3,t<a&&e.charCodeAt(t)===37)continue;return null}}return o+e.slice(c)}var o={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};function s(e,t){var n=o[e];return n===void 0?255:n<<t}t.exports=a})),mm=o(((e,t)=>{let n=pm(),r=/\+/g,i=function(){};i.prototype=Object.create(null);function a(e){let t=new i;if(typeof e!=`string`)return t;let a=e.length,o=``,s=``,c=-1,l=-1,u=!1,d=!1,f=!1,p=!1,m=!1,h=0;for(let i=0;i<a+1;i++)if(h=i===a?38:e.charCodeAt(i),h===38){if(m=l>c,m||(l=i),o=e.slice(c+1,l),m||o.length>0){f&&(o=o.replace(r,` `)),u&&(o=n(o)||o),m&&(s=e.slice(l+1,i),p&&(s=s.replace(r,` `)),d&&(s=n(s)||s));let a=t[o];a===void 0?t[o]=s:a.pop?a.push(s):t[o]=[a,s]}s=``,c=i,l=i,u=!1,d=!1,f=!1,p=!1}else h===61?l<=c?l=i:d=!0:h===43?l>c?p=!0:f=!0:h===37&&(l>c?d=!0:u=!0);return t}t.exports=a})),hm=o(((e,t)=>{let n=Array.from({length:256},(e,t)=>`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase()),r=new Int8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,1,1,0,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,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,0,0,0,1,0,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,0,0,1,0]);function i(e){let t=e.length;if(t===0)return``;let i=``,a=0,o=0;outer:for(;o<t;o++){let s=e.charCodeAt(o);for(;s<128;){if(r[s]!==1&&(a<o&&(i+=e.slice(a,o)),a=o+1,i+=n[s]),++o===t)break outer;s=e.charCodeAt(o)}if(a<o&&(i+=e.slice(a,o)),s<2048){a=o+1,i+=n[192|s>>6]+n[128|s&63];continue}if(s<55296||s>=57344){a=o+1,i+=n[224|s>>12]+n[128|s>>6&63]+n[128|s&63];continue}if(++o,o>=t)throw Error(`URI malformed`);let c=e.charCodeAt(o)&1023;a=o+1,s=65536+((s&1023)<<10|c),i+=n[240|s>>18]+n[128|s>>12&63]+n[128|s>>6&63]+n[128|s&63]}return a===0?e:a<t?i+e.slice(a):i}t.exports={encodeString:i}})),gm=o(((e,t)=>{let{encodeString:n}=hm();function r(e){let t=typeof e;return t===`string`?n(e):t===`bigint`?e.toString():t===`boolean`?e?`true`:`false`:t===`number`&&Number.isFinite(e)?e<1e21?``+e:n(``+e):``}function i(e){let t=``;if(typeof e!=`object`||!e)return t;let i=Object.keys(e),a=i.length,o=0;for(let s=0;s<a;s++){let a=i[s],c=e[a],l=n(a)+`=`;if(s&&(t+=`&`),Array.isArray(c)){o=c.length;for(let e=0;e<o;e++)e&&(t+=`&`),t+=l,t+=r(c[e])}else t+=l,t+=r(c)}return t}t.exports=i})),_m=o(((e,t)=>{let n=mm(),r=gm(),i={parse:n,stringify:r};t.exports=i,t.exports.default=i,t.exports.parse=n,t.exports.stringify=r})),vm=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0})})),ym=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.types=void 0,(function(e){e[e.ROOT=0]=`ROOT`,e[e.GROUP=1]=`GROUP`,e[e.POSITION=2]=`POSITION`,e[e.SET=3]=`SET`,e[e.RANGE=4]=`RANGE`,e[e.REPETITION=5]=`REPETITION`,e[e.REFERENCE=6]=`REFERENCE`,e[e.CHAR=7]=`CHAR`})(e.types||={})})),bm=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0})})),xm=o((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!==`default`&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,`__esModule`,{value:!0}),n(vm(),e),n(ym(),e),n(bm(),e)})),Sm=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.anyChar=e.notWhitespace=e.whitespace=e.notInts=e.ints=e.notWords=e.words=void 0;let t=xm(),n=()=>[{type:t.types.RANGE,from:48,to:57}],r=()=>[{type:t.types.CHAR,value:95},{type:t.types.RANGE,from:97,to:122},{type:t.types.RANGE,from:65,to:90},{type:t.types.RANGE,from:48,to:57}],i=()=>[{type:t.types.CHAR,value:9},{type:t.types.CHAR,value:10},{type:t.types.CHAR,value:11},{type:t.types.CHAR,value:12},{type:t.types.CHAR,value:13},{type:t.types.CHAR,value:32},{type:t.types.CHAR,value:160},{type:t.types.CHAR,value:5760},{type:t.types.RANGE,from:8192,to:8202},{type:t.types.CHAR,value:8232},{type:t.types.CHAR,value:8233},{type:t.types.CHAR,value:8239},{type:t.types.CHAR,value:8287},{type:t.types.CHAR,value:12288},{type:t.types.CHAR,value:65279}],a=()=>[{type:t.types.CHAR,value:10},{type:t.types.CHAR,value:13},{type:t.types.CHAR,value:8232},{type:t.types.CHAR,value:8233}];e.words=()=>({type:t.types.SET,set:r(),not:!1}),e.notWords=()=>({type:t.types.SET,set:r(),not:!0}),e.ints=()=>({type:t.types.SET,set:n(),not:!1}),e.notInts=()=>({type:t.types.SET,set:n(),not:!0}),e.whitespace=()=>({type:t.types.SET,set:i(),not:!1}),e.notWhitespace=()=>({type:t.types.SET,set:i(),not:!0}),e.anyChar=()=>({type:t.types.SET,set:a(),not:!0})})),Cm=o((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,`__esModule`,{value:!0}),e.tokenizeClass=e.strToChars=void 0;let i=xm(),a=r(Sm());e.strToChars=e=>e.replace(/(\[\\b\])|(\\)?\\(?:u([A-F0-9]{4})|x([A-F0-9]{2})|c([@A-Z[\\\]^?])|([0tnvfr]))/g,(e,t,n,r,i,a,o)=>{if(n)return e;let s=t?8:r?parseInt(r,16):i?parseInt(i,16):a?`@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?`.indexOf(a):{0:0,t:9,n:10,v:11,f:12,r:13}[o],c=String.fromCharCode(s);return/[[\]{}^$.|?*+()]/.test(c)?`\\${c}`:c}),e.tokenizeClass=(e,t)=>{let n=[],r,o,s=/\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(((?:\\)])|(((?:\\)?([^\]])))))|(\])|(?:\\)?([^])/g;for(;(r=s.exec(e))!==null;){let e=(r[1]&&a.words())??(r[2]&&a.ints())??(r[3]&&a.whitespace())??(r[4]&&a.notWords())??(r[5]&&a.notInts())??(r[6]&&a.notWhitespace())??(r[7]&&{type:i.types.RANGE,from:(r[8]||r[9]).charCodeAt(0),to:(o=r[10]).charCodeAt(o.length-1)})??((o=r[16])&&{type:i.types.CHAR,value:o.charCodeAt(0)});if(e)n.push(e);else return[n,s.lastIndex]}throw SyntaxError(`Invalid regular expression: /${t}/: Unterminated character class`)}})),wm=o((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,`__esModule`,{value:!0}),e.tokenizer=void 0;let i=r(Cm()),a=xm(),o=r(Sm()),s=/^[a-zA-Z_$]$/i,c=/^[a-zA-Z0-9_$]$/i,l=/\d/;e.tokenizer=e=>{let t=0,n,r={type:a.types.ROOT,stack:[]},d=r,f=r.stack,p=[],m=[],h=0,g=t=>{throw SyntaxError(`Invalid regular expression: /${e}/: Nothing to repeat at column ${t-1}`)},_=i.strToChars(e);for(;t<_.length;)switch(n=_[t++]){case`\\`:if(t===_.length)throw SyntaxError(`Invalid regular expression: /${e}/: \\ at end of pattern`);switch(n=_[t++]){case`b`:f.push({type:a.types.POSITION,value:`b`});break;case`B`:f.push({type:a.types.POSITION,value:`B`});break;case`w`:f.push(o.words());break;case`W`:f.push(o.notWords());break;case`d`:f.push(o.ints());break;case`D`:f.push(o.notInts());break;case`s`:f.push(o.whitespace());break;case`S`:f.push(o.notWhitespace());break;default:if(l.test(n)){let e=n;for(;t<_.length&&l.test(_[t]);)e+=_[t++];let r=parseInt(e,10),i={type:a.types.REFERENCE,value:r};f.push(i),m.push({reference:i,stack:f,index:f.length-1})}else f.push({type:a.types.CHAR,value:n.charCodeAt(0)})}break;case`^`:f.push({type:a.types.POSITION,value:`^`});break;case`$`:f.push({type:a.types.POSITION,value:`$`});break;case`[`:{let n;_[t]===`^`?(n=!0,t++):n=!1;let r=i.tokenizeClass(_.slice(t),e);t+=r[1],f.push({type:a.types.SET,set:r[0],not:n});break}case`.`:f.push(o.anyChar());break;case`(`:{let r={type:a.types.GROUP,stack:[],remember:!0};if(_[t]===`?`)if(n=_[t+1],t+=2,n===`=`)r.followedBy=!0,r.remember=!1;else if(n===`!`)r.notFollowedBy=!0,r.remember=!1;else if(n===`<`){let n=``;if(s.test(_[t]))n+=_[t],t++;else throw SyntaxError(`Invalid regular expression: /${e}/: Invalid capture group name, character '${_[t]}' after '<' at column ${t+1}`);for(;t<_.length&&c.test(_[t]);)n+=_[t],t++;if(!n)throw SyntaxError(`Invalid regular expression: /${e}/: Invalid capture group name, character '${_[t]}' after '<' at column ${t+1}`);if(_[t]!==`>`)throw SyntaxError(`Invalid regular expression: /${e}/: Unclosed capture group name, expected '>', found '${_[t]}' at column ${t+1}`);r.name=n,t++}else if(n===`:`)r.remember=!1;else throw SyntaxError(`Invalid regular expression: /${e}/: Invalid group, character '${n}' after '?' at column ${t-1}`);else h+=1;f.push(r),p.push(d),d=r,f=r.stack;break}case`)`:if(p.length===0)throw SyntaxError(`Invalid regular expression: /${e}/: Unmatched ) at column ${t-1}`);d=p.pop(),f=d.options?d.options[d.options.length-1]:d.stack;break;case`|`:{d.options||(d.options=[d.stack],delete d.stack);let e=[];d.options.push(e),f=e;break}case`{`:{let e=/^(\d+)(,(\d+)?)?\}/.exec(_.slice(t)),n,r;e===null?f.push({type:a.types.CHAR,value:123}):(f.length===0&&g(t),n=parseInt(e[1],10),r=e[2]?e[3]?parseInt(e[3],10):1/0:n,t+=e[0].length,f.push({type:a.types.REPETITION,min:n,max:r,value:f.pop()}));break}case`?`:f.length===0&&g(t),f.push({type:a.types.REPETITION,min:0,max:1,value:f.pop()});break;case`+`:f.length===0&&g(t),f.push({type:a.types.REPETITION,min:1,max:1/0,value:f.pop()});break;case`*`:f.length===0&&g(t),f.push({type:a.types.REPETITION,min:0,max:1/0,value:f.pop()});break;default:f.push({type:a.types.CHAR,value:n.charCodeAt(0)})}if(p.length!==0)throw SyntaxError(`Invalid regular expression: /${e}/: Unterminated group`);return u(m,h),r};function u(e,t){for(let n of e.reverse())if(t<n.reference.value){n.reference.type=a.types.CHAR;let e=n.reference.value.toString();if(n.reference.value=parseInt(e,8),!/^[0-7]+$/.test(e)){let t=0;for(;e[t]!==`8`&&e[t]!==`9`;)t+=1;if(t===0?(n.reference.value=e.charCodeAt(0),t+=1):n.reference.value=parseInt(e.slice(0,t),8),e.length>t){let r=n.stack.splice(n.index+1);for(let r of e.slice(t))n.stack.push({type:a.types.CHAR,value:r.charCodeAt(0)});n.stack.push(...r)}}}}})),Tm=o((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,`__esModule`,{value:!0}),e.NOTANYCHAR=e.WHITESPACE=e.WORDS=e.INTS=void 0;let i=r(Sm()),a=xm();function o(e){let t={},n=0;for(let r of e)r.type===a.types.CHAR&&(t[r.value]=!0),r.type===a.types.RANGE&&(t[`${r.from}-${r.to}`]=!0),n+=1;return{lookup:()=>Object.assign({},t),len:n}}e.INTS=o(i.ints().set),e.WORDS=o(i.words().set),e.WHITESPACE=o(i.whitespace().set),e.NOTANYCHAR=o(i.anyChar().set)})),Em=o((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,`__esModule`,{value:!0}),e.writeSetTokens=e.setChar=void 0;let i=xm(),a=r(Tm());function o(e){return e===94?`\\^`:e===92?`\\\\`:e===93?`\\]`:e===45?`\\-`:String.fromCharCode(e)}e.setChar=o;function s(e,{lookup:t,len:n}){if(n!==e.length)return!1;let r=t();for(let t of e){if(t.type===i.types.SET)return!1;let e=t.type===i.types.CHAR?t.value:`${t.from}-${t.to}`;if(r[e])r[e]=!1;else return!1}return!0}function c(e,t=!1){if(s(e.set,a.INTS))return e.not?`\\D`:`\\d`;if(s(e.set,a.WORDS))return e.not?`\\W`:`\\w`;if(e.not&&s(e.set,a.NOTANYCHAR))return`.`;if(s(e.set,a.WHITESPACE))return e.not?`\\S`:`\\s`;let n=``;for(let t=0;t<e.set.length;t++){let r=e.set[t];n+=l(r)}let r=`${e.not?`^`:``}${n}`;return t?r:`[${r}]`}e.writeSetTokens=c;function l(e){return e.type===i.types.CHAR?o(e.value):e.type===i.types.RANGE?`${o(e.from)}-${o(e.to)}`:c(e,!0)}})),Dm=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.reconstruct=void 0;let t=xm(),n=Em(),r=t=>t.map(e.reconstruct).join(``),i=e=>{if(`options`in e)return e.options.map(r).join(`|`);if(`stack`in e)return r(e.stack);throw Error(`options or stack must be Root or Group token`)};e.reconstruct=r=>{switch(r.type){case t.types.ROOT:return i(r);case t.types.CHAR:{let e=String.fromCharCode(r.value);return(/[[\\{}$^.|?*+()]/.test(e)?`\\`:``)+e}case t.types.POSITION:return r.value===`^`||r.value===`$`?r.value:`\\${r.value}`;case t.types.REFERENCE:return`\\${r.value}`;case t.types.SET:return n.writeSetTokens(r);case t.types.GROUP:return`(${r.name?`?<${r.name}>`:r.remember?``:r.followedBy?`?=`:r.notFollowedBy?`?!`:`?:`}${i(r)})`;case t.types.REPETITION:{let{min:t,max:n}=r,i;return i=t===0&&n===1?`?`:t===1&&n===1/0?`+`:t===0&&n===1/0?`*`:n===1/0?`{${t},}`:t===n?`{${t}}`:`{${t},${n}}`,`${e.reconstruct(r.value)}${i}`}case t.types.RANGE:return`${n.setChar(r.from)}-${n.setChar(r.to)}`;default:throw Error(`Invalid token type ${r}`)}}})),Om=o(((e,t)=>{var n=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),r=e&&e.__exportStar||function(e,t){for(var r in e)r!==`default`&&!Object.prototype.hasOwnProperty.call(t,r)&&n(t,e,r)};Object.defineProperty(e,`__esModule`,{value:!0}),e.types=void 0;let i=xm();Object.defineProperty(e,`types`,{enumerable:!0,get:function(){return i.types}}),r(wm(),e),r(Dm(),e);let a=wm(),o=Dm();r(xm(),e),e.default=a.tokenizer,t.exports=a.tokenizer,t.exports.types=i.types,t.exports.reconstruct=o.reconstruct})),km=o(((e,t)=>{let n=Om(),r=n.types;function i(e,t){t||={};let i=t.limit===void 0?25:t.limit;a(e)?e=e.source:typeof e!=`string`&&(e=String(e));try{e=n(e)}catch{return!1}let o=0;return(function e(t,n){let a,s,c;if(t.type===r.REPETITION&&(n++,o++,n>1||o>i))return!1;if(t.options){for(a=0,c=t.options.length;a<c;a++)if(s=e({stack:t.options[a]},n),!s)return!1}let l=t.stack||t.value?.stack;if(!l)return!0;for(a=0;a<l.length;a++)if(s=e(l[a],n),!s)return!1;return!0})(e,0)}function a(e){return{}.toString.call(e)===`[object RegExp]`}t.exports=i,t.exports.default=i,t.exports.safeRegex=i})),Am=o(((e,t)=>{t.exports={name:`__fmw_internal_strategy_merged_tree_http_method__`,storage:function(){let e=new Map;return{get:t=>e.get(t)||null,set:(t,n)=>{e.set(t,n)}}},deriveConstraint:e=>e.method,mustMatchWhenDerived:!0}})),jm=o(((e,t)=>{let n=kd(),r=Am(),i=Symbol(`treeData`);function a(e,t=``){let n=``,r=Object.keys(e);for(let o=0;o<r.length;o++){let s=r[o],c=e[s],l=o===r.length-1,u=l?`└── `:`├── `,d=l?` `:`│ `,f=(c[i]||``).replaceAll(`
|
|
430
|
+
`),i}t.exports=y,t.exports.default=y,t.exports.build=y,t.exports.validLargeArrayMechanisms=f,t.exports.restore=function({code:e,validator:t,serializer:n}){return Function.apply(null,[`validator`,`serializer`,e]).apply(null,[t,n])}})),vp=o(((e,t)=>{let n=_p();function r(){return function(e,t){let n=Object.assign({},t,{schema:e});return i.bind(null,n)}}function i(e,{schema:t}){return e.schema&&t.$id&&e.schema[t.$id]&&(e.schema={...e.schema},delete e.schema[t.$id]),n(t,e)}function a(e={readMode:!0}){if(e.readMode===!0&&typeof e.restoreFunction!=`function`)throw Error(`You must provide a function for the restoreFunction-option when readMode ON`);if(e.readMode!==!0&&typeof e.storeFunction!=`function`)throw Error(`You must provide a function for the storeFunction-option when readMode OFF`);if(e.readMode===!0)return function(){return function(t){return e.restoreFunction(t)}};let t=r();return function(n,r={}){r.mode=`standalone`;let i=t(n,r);return function(t){let n=i(t);return e.storeFunction(t,n),Function(n)}}}t.exports.SerializerSelector=r,t.exports.StandaloneSerializer=a,t.exports.default=a})),yp=o(((e,t)=>{let{SerializerSelector:n,StandaloneSerializer:r}=vp();t.exports=n,t.exports.default=n,t.exports.SerializerSelector=n,t.exports.StandaloneSerializer=r})),bp=o(((e,t)=>{let{buildSchemas:n}=rd();function r(e,t){if(e)return new i(e,t);let r=Object.assign({buildValidator:null,buildSerializer:null},t?.compilersFactory);return r.buildValidator||=op()(),r.buildSerializer||=yp()(),new i(void 0,{bucket:t&&t.bucket||n,compilersFactory:r,isCustomValidatorCompiler:typeof t?.compilersFactory?.buildValidator==`function`,isCustomSerializerCompiler:typeof t?.compilersFactory?.buildValidator==`function`})}var i=class{constructor(e,t){this.opts=t||e?.opts,this.addedSchemas=!1,this.compilersFactory=this.opts.compilersFactory,e?(this.schemaBucket=this.opts.bucket(e.getSchemas()),this.validatorCompiler=e.getValidatorCompiler(),this.serializerCompiler=e.getSerializerCompiler(),this.isCustomValidatorCompiler=e.isCustomValidatorCompiler,this.isCustomSerializerCompiler=e.isCustomSerializerCompiler,this.parent=e):(this.schemaBucket=this.opts.bucket(),this.isCustomValidatorCompiler=this.opts.isCustomValidatorCompiler||!1,this.isCustomSerializerCompiler=this.opts.isCustomSerializerCompiler||!1)}add(e){return this.addedSchemas=!0,this.schemaBucket.add(e)}getSchema(e){return this.schemaBucket.getSchema(e)}getSchemas(){return this.schemaBucket.getSchemas()}setValidatorCompiler(e){this.compilersFactory=Object.assign({},this.compilersFactory,{buildValidator:()=>e}),this.validatorCompiler=e,this.isCustomValidatorCompiler=!0}setSerializerCompiler(e){this.compilersFactory=Object.assign({},this.compilersFactory,{buildSerializer:()=>e}),this.serializerCompiler=e,this.isCustomSerializerCompiler=!0}getValidatorCompiler(){return this.validatorCompiler||this.parent&&this.parent.getValidatorCompiler()}getSerializerCompiler(){return this.serializerCompiler||this.parent&&this.parent.getSerializerCompiler()}getSerializerBuilder(){return this.compilersFactory.buildSerializer||this.parent&&this.parent.getSerializerBuilder()}getValidatorBuilder(){return this.compilersFactory.buildValidator||this.parent&&this.parent.getValidatorBuilder()}setupValidator(e){this.validatorCompiler!==void 0&&!this.addedSchemas||(this.validatorCompiler=this.getValidatorBuilder()(this.schemaBucket.getSchemas(),e.ajv))}setupSerializer(e){this.serializerCompiler!==void 0&&!this.addedSchemas||(this.serializerCompiler=this.getSerializerBuilder()(this.schemaBucket.getSchemas(),e.serializerOpts))}};i.buildSchemaController=r,t.exports=i})),xp=o(((e,t)=>{t.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:2**53-1||9007199254740991,RELEASE_TYPES:[`major`,`premajor`,`minor`,`preminor`,`patch`,`prepatch`,`prerelease`],SEMVER_SPEC_VERSION:`2.0.0`,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}})),Sp=o(((e,t)=>{t.exports=typeof process==`object`&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error(`SEMVER`,...e):()=>{}})),Cp=o(((e,t)=>{let{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:i}=xp(),a=Sp();e=t.exports={};let o=e.re=[],s=e.safeRe=[],c=e.src=[],l=e.safeSrc=[],u=e.t={},d=0,f=`[a-zA-Z0-9-]`,p=[[`\\s`,1],[`\\d`,i],[f,r]],m=e=>{for(let[t,n]of p)e=e.split(`${t}*`).join(`${t}{0,${n}}`).split(`${t}+`).join(`${t}{1,${n}}`);return e},h=(e,t,n)=>{let r=m(t),i=d++;a(e,i,t),u[e]=i,c[i]=t,l[i]=r,o[i]=new RegExp(t,n?`g`:void 0),s[i]=new RegExp(r,n?`g`:void 0)};h(`NUMERICIDENTIFIER`,`0|[1-9]\\d*`),h(`NUMERICIDENTIFIERLOOSE`,`\\d+`),h(`NONNUMERICIDENTIFIER`,`\\d*[a-zA-Z-]${f}*`),h(`MAINVERSION`,`(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})`),h(`MAINVERSIONLOOSE`,`(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})`),h(`PRERELEASEIDENTIFIER`,`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIER]})`),h(`PRERELEASEIDENTIFIERLOOSE`,`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIERLOOSE]})`),h(`PRERELEASE`,`(?:-(${c[u.PRERELEASEIDENTIFIER]}(?:\\.${c[u.PRERELEASEIDENTIFIER]})*))`),h(`PRERELEASELOOSE`,`(?:-?(${c[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[u.PRERELEASEIDENTIFIERLOOSE]})*))`),h(`BUILDIDENTIFIER`,`${f}+`),h(`BUILD`,`(?:\\+(${c[u.BUILDIDENTIFIER]}(?:\\.${c[u.BUILDIDENTIFIER]})*))`),h(`FULLPLAIN`,`v?${c[u.MAINVERSION]}${c[u.PRERELEASE]}?${c[u.BUILD]}?`),h(`FULL`,`^${c[u.FULLPLAIN]}$`),h(`LOOSEPLAIN`,`[v=\\s]*${c[u.MAINVERSIONLOOSE]}${c[u.PRERELEASELOOSE]}?${c[u.BUILD]}?`),h(`LOOSE`,`^${c[u.LOOSEPLAIN]}$`),h(`GTLT`,`((?:<|>)?=?)`),h(`XRANGEIDENTIFIERLOOSE`,`${c[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),h(`XRANGEIDENTIFIER`,`${c[u.NUMERICIDENTIFIER]}|x|X|\\*`),h(`XRANGEPLAIN`,`[v=\\s]*(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:${c[u.PRERELEASE]})?${c[u.BUILD]}?)?)?`),h(`XRANGEPLAINLOOSE`,`[v=\\s]*(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:${c[u.PRERELEASELOOSE]})?${c[u.BUILD]}?)?)?`),h(`XRANGE`,`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAIN]}$`),h(`XRANGELOOSE`,`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAINLOOSE]}$`),h(`COERCEPLAIN`,`(^|[^\\d])(\\d{1,${n}})(?:\\.(\\d{1,${n}}))?(?:\\.(\\d{1,${n}}))?`),h(`COERCE`,`${c[u.COERCEPLAIN]}(?:$|[^\\d])`),h(`COERCEFULL`,c[u.COERCEPLAIN]+`(?:${c[u.PRERELEASE]})?(?:${c[u.BUILD]})?(?:$|[^\\d])`),h(`COERCERTL`,c[u.COERCE],!0),h(`COERCERTLFULL`,c[u.COERCEFULL],!0),h(`LONETILDE`,`(?:~>?)`),h(`TILDETRIM`,`(\\s*)${c[u.LONETILDE]}\\s+`,!0),e.tildeTrimReplace=`$1~`,h(`TILDE`,`^${c[u.LONETILDE]}${c[u.XRANGEPLAIN]}$`),h(`TILDELOOSE`,`^${c[u.LONETILDE]}${c[u.XRANGEPLAINLOOSE]}$`),h(`LONECARET`,`(?:\\^)`),h(`CARETTRIM`,`(\\s*)${c[u.LONECARET]}\\s+`,!0),e.caretTrimReplace=`$1^`,h(`CARET`,`^${c[u.LONECARET]}${c[u.XRANGEPLAIN]}$`),h(`CARETLOOSE`,`^${c[u.LONECARET]}${c[u.XRANGEPLAINLOOSE]}$`),h(`COMPARATORLOOSE`,`^${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]})$|^$`),h(`COMPARATOR`,`^${c[u.GTLT]}\\s*(${c[u.FULLPLAIN]})$|^$`),h(`COMPARATORTRIM`,`(\\s*)${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]}|${c[u.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace=`$1$2$3`,h(`HYPHENRANGE`,`^\\s*(${c[u.XRANGEPLAIN]})\\s+-\\s+(${c[u.XRANGEPLAIN]})\\s*$`),h(`HYPHENRANGELOOSE`,`^\\s*(${c[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[u.XRANGEPLAINLOOSE]})\\s*$`),h(`STAR`,`(<|>)?=?\\s*\\*`),h(`GTE0`,`^\\s*>=\\s*0\\.0\\.0\\s*$`),h(`GTE0PRE`,`^\\s*>=\\s*0\\.0\\.0-0\\s*$`)})),wp=o(((e,t)=>{let n=Object.freeze({loose:!0}),r=Object.freeze({});t.exports=e=>e?typeof e==`object`?e:n:r})),Tp=o(((e,t)=>{let n=/^[0-9]+$/,r=(e,t)=>{if(typeof e==`number`&&typeof t==`number`)return e===t?0:e<t?-1:1;let r=n.test(e),i=n.test(t);return r&&i&&(e=+e,t=+t),e===t?0:r&&!i?-1:i&&!r?1:e<t?-1:1};t.exports={compareIdentifiers:r,rcompareIdentifiers:(e,t)=>r(t,e)}})),Ep=o(((e,t)=>{let n=Sp(),{MAX_LENGTH:r,MAX_SAFE_INTEGER:i}=xp(),{safeRe:a,t:o}=Cp(),s=wp(),{compareIdentifiers:c}=Tp();t.exports=class e{constructor(t,c){if(c=s(c),t instanceof e){if(t.loose===!!c.loose&&t.includePrerelease===!!c.includePrerelease)return t;t=t.version}else if(typeof t!=`string`)throw TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>r)throw TypeError(`version is longer than ${r} characters`);n(`SemVer`,t,c),this.options=c,this.loose=!!c.loose,this.includePrerelease=!!c.includePrerelease;let l=t.trim().match(c.loose?a[o.LOOSE]:a[o.FULL]);if(!l)throw TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+l[1],this.minor=+l[2],this.patch=+l[3],this.major>i||this.major<0)throw TypeError(`Invalid major version`);if(this.minor>i||this.minor<0)throw TypeError(`Invalid minor version`);if(this.patch>i||this.patch<0)throw TypeError(`Invalid patch version`);l[4]?this.prerelease=l[4].split(`.`).map(e=>{if(/^[0-9]+$/.test(e)){let t=+e;if(t>=0&&t<i)return t}return e}):this.prerelease=[],this.build=l[5]?l[5].split(`.`):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(`.`)}`),this.version}toString(){return this.version}compare(t){if(n(`SemVer.compare`,this.version,this.options,t),!(t instanceof e)){if(typeof t==`string`&&t===this.version)return 0;t=new e(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return t instanceof e||(t=new e(t,this.options)),this.major<t.major?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:this.patch>t.patch?1:0}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let e=this.prerelease[r],i=t.prerelease[r];if(n(`prerelease compare`,r,e,i),e===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(e===void 0)return-1;if(e===i)continue;return c(e,i)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let e=this.build[r],i=t.build[r];if(n(`build compare`,r,e,i),e===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(e===void 0)return-1;if(e===i)continue;return c(e,i)}while(++r)}inc(e,t,n){if(e.startsWith(`pre`)){if(!t&&n===!1)throw Error(`invalid increment argument: identifier is empty`);if(t){let e=`-${t}`.match(this.options.loose?a[o.PRERELEASELOOSE]:a[o.PRERELEASE]);if(!e||e[1]!==t)throw Error(`invalid identifier: ${t}`)}}switch(e){case`premajor`:this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc(`pre`,t,n);break;case`preminor`:this.prerelease.length=0,this.patch=0,this.minor++,this.inc(`pre`,t,n);break;case`prepatch`:this.prerelease.length=0,this.inc(`patch`,t,n),this.inc(`pre`,t,n);break;case`prerelease`:this.prerelease.length===0&&this.inc(`patch`,t,n),this.inc(`pre`,t,n);break;case`release`:if(this.prerelease.length===0)throw Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case`major`:(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case`minor`:(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case`patch`:this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case`pre`:{let e=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[e];else{let r=this.prerelease.length;for(;--r>=0;)typeof this.prerelease[r]==`number`&&(this.prerelease[r]++,r=-2);if(r===-1){if(t===this.prerelease.join(`.`)&&n===!1)throw Error(`invalid increment argument: identifier already exists`);this.prerelease.push(e)}}if(t){let r=[t,e];n===!1&&(r=[t]),c(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=r):this.prerelease=r}break}default:throw Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(`.`)}`),this}}})),Dp=o(((e,t)=>{let n=Ep();t.exports=(e,t,r=!1)=>{if(e instanceof n)return e;try{return new n(e,t)}catch(e){if(!r)return null;throw e}}})),Op=o(((e,t)=>{let n=Dp();t.exports=(e,t)=>{let r=n(e,t);return r?r.version:null}})),kp=o(((e,t)=>{let n=Dp();t.exports=(e,t)=>{let r=n(e.trim().replace(/^[=v]+/,``),t);return r?r.version:null}})),Ap=o(((e,t)=>{let n=Ep();t.exports=(e,t,r,i,a)=>{typeof r==`string`&&(a=i,i=r,r=void 0);try{return new n(e instanceof n?e.version:e,r).inc(t,i,a).version}catch{return null}}})),jp=o(((e,t)=>{let n=Dp();t.exports=(e,t)=>{let r=n(e,null,!0),i=n(t,null,!0),a=r.compare(i);if(a===0)return null;let o=a>0,s=o?r:i,c=o?i:r,l=!!s.prerelease.length;if(c.prerelease.length&&!l){if(!c.patch&&!c.minor)return`major`;if(c.compareMain(s)===0)return c.minor&&!c.patch?`minor`:`patch`}let u=l?`pre`:``;return r.major===i.major?r.minor===i.minor?r.patch===i.patch?`prerelease`:u+`patch`:u+`minor`:u+`major`}})),Mp=o(((e,t)=>{let n=Ep();t.exports=(e,t)=>new n(e,t).major})),Np=o(((e,t)=>{let n=Ep();t.exports=(e,t)=>new n(e,t).minor})),Pp=o(((e,t)=>{let n=Ep();t.exports=(e,t)=>new n(e,t).patch})),Fp=o(((e,t)=>{let n=Dp();t.exports=(e,t)=>{let r=n(e,t);return r&&r.prerelease.length?r.prerelease:null}})),Ip=o(((e,t)=>{let n=Ep();t.exports=(e,t,r)=>new n(e,r).compare(new n(t,r))})),Lp=o(((e,t)=>{let n=Ip();t.exports=(e,t,r)=>n(t,e,r)})),Rp=o(((e,t)=>{let n=Ip();t.exports=(e,t)=>n(e,t,!0)})),zp=o(((e,t)=>{let n=Ep();t.exports=(e,t,r)=>{let i=new n(e,r),a=new n(t,r);return i.compare(a)||i.compareBuild(a)}})),Bp=o(((e,t)=>{let n=zp();t.exports=(e,t)=>e.sort((e,r)=>n(e,r,t))})),Vp=o(((e,t)=>{let n=zp();t.exports=(e,t)=>e.sort((e,r)=>n(r,e,t))})),Hp=o(((e,t)=>{let n=Ip();t.exports=(e,t,r)=>n(e,t,r)>0})),Up=o(((e,t)=>{let n=Ip();t.exports=(e,t,r)=>n(e,t,r)<0})),Wp=o(((e,t)=>{let n=Ip();t.exports=(e,t,r)=>n(e,t,r)===0})),Gp=o(((e,t)=>{let n=Ip();t.exports=(e,t,r)=>n(e,t,r)!==0})),Kp=o(((e,t)=>{let n=Ip();t.exports=(e,t,r)=>n(e,t,r)>=0})),qp=o(((e,t)=>{let n=Ip();t.exports=(e,t,r)=>n(e,t,r)<=0})),Jp=o(((e,t)=>{let n=Wp(),r=Gp(),i=Hp(),a=Kp(),o=Up(),s=qp();t.exports=(e,t,c,l)=>{switch(t){case`===`:return typeof e==`object`&&(e=e.version),typeof c==`object`&&(c=c.version),e===c;case`!==`:return typeof e==`object`&&(e=e.version),typeof c==`object`&&(c=c.version),e!==c;case``:case`=`:case`==`:return n(e,c,l);case`!=`:return r(e,c,l);case`>`:return i(e,c,l);case`>=`:return a(e,c,l);case`<`:return o(e,c,l);case`<=`:return s(e,c,l);default:throw TypeError(`Invalid operator: ${t}`)}}})),Yp=o(((e,t)=>{let n=Ep(),r=Dp(),{safeRe:i,t:a}=Cp();t.exports=(e,t)=>{if(e instanceof n)return e;if(typeof e==`number`&&(e=String(e)),typeof e!=`string`)return null;t||={};let o=null;if(!t.rtl)o=e.match(t.includePrerelease?i[a.COERCEFULL]:i[a.COERCE]);else{let n=t.includePrerelease?i[a.COERCERTLFULL]:i[a.COERCERTL],r;for(;(r=n.exec(e))&&(!o||o.index+o[0].length!==e.length);)(!o||r.index+r[0].length!==o.index+o[0].length)&&(o=r),n.lastIndex=r.index+r[1].length+r[2].length;n.lastIndex=-1}if(o===null)return null;let s=o[2];return r(`${s}.${o[3]||`0`}.${o[4]||`0`}${t.includePrerelease&&o[5]?`-${o[5]}`:``}${t.includePrerelease&&o[6]?`+${o[6]}`:``}`,t)}})),Xp=o(((e,t)=>{t.exports=class{constructor(){this.max=1e3,this.map=new Map}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){let e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}}})),Zp=o(((e,t)=>{let n=/\s+/g;t.exports=class e{constructor(t,r){if(r=i(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof a)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=t.trim().replace(n,` `),this.set=this.raw.split(`||`).map(e=>this.parseRange(e.trim())).filter(e=>e.length),!this.set.length)throw TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let e=this.set[0];if(this.set=this.set.filter(e=>!h(e[0])),this.set.length===0)this.set=[e];else if(this.set.length>1){for(let e of this.set)if(e.length===1&&g(e[0])){this.set=[e];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted=``;for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+=`||`);let t=this.set[e];for(let e=0;e<t.length;e++)e>0&&(this.formatted+=` `),this.formatted+=t[e].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let t=((this.options.includePrerelease&&p)|(this.options.loose&&m))+`:`+e,n=r.get(t);if(n)return n;let i=this.options.loose,s=i?c[l.HYPHENRANGELOOSE]:c[l.HYPHENRANGE];e=e.replace(s,O(this.options.includePrerelease)),o(`hyphen replace`,e),e=e.replace(c[l.COMPARATORTRIM],u),o(`comparator trim`,e),e=e.replace(c[l.TILDETRIM],d),o(`tilde trim`,e),e=e.replace(c[l.CARETTRIM],f),o(`caret trim`,e);let g=e.split(` `).map(e=>v(e,this.options)).join(` `).split(/\s+/).map(e=>D(e,this.options));i&&(g=g.filter(e=>(o(`loose invalid filter`,e,this.options),!!e.match(c[l.COMPARATORLOOSE])))),o(`range list`,g);let _=new Map,y=g.map(e=>new a(e,this.options));for(let e of y){if(h(e))return[e];_.set(e.value,e)}_.size>1&&_.has(``)&&_.delete(``);let b=[..._.values()];return r.set(t,b),b}intersects(t,n){if(!(t instanceof e))throw TypeError(`a Range is required`);return this.set.some(e=>_(e,n)&&t.set.some(t=>_(t,n)&&e.every(e=>t.every(t=>e.intersects(t,n)))))}test(e){if(!e)return!1;if(typeof e==`string`)try{e=new s(e,this.options)}catch{return!1}for(let t=0;t<this.set.length;t++)if(k(this.set[t],e,this.options))return!0;return!1}};let r=new(Xp()),i=wp(),a=Qp(),o=Sp(),s=Ep(),{safeRe:c,t:l,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:f}=Cp(),{FLAG_INCLUDE_PRERELEASE:p,FLAG_LOOSE:m}=xp(),h=e=>e.value===`<0.0.0-0`,g=e=>e.value===``,_=(e,t)=>{let n=!0,r=e.slice(),i=r.pop();for(;n&&r.length;)n=r.every(e=>i.intersects(e,t)),i=r.pop();return n},v=(e,t)=>(e=e.replace(c[l.BUILD],``),o(`comp`,e,t),e=S(e,t),o(`caret`,e),e=b(e,t),o(`tildes`,e),e=w(e,t),o(`xrange`,e),e=E(e,t),o(`stars`,e),e),y=e=>!e||e.toLowerCase()===`x`||e===`*`,b=(e,t)=>e.trim().split(/\s+/).map(e=>x(e,t)).join(` `),x=(e,t)=>{let n=t.loose?c[l.TILDELOOSE]:c[l.TILDE];return e.replace(n,(t,n,r,i,a)=>{o(`tilde`,e,t,n,r,i,a);let s;return y(n)?s=``:y(r)?s=`>=${n}.0.0 <${+n+1}.0.0-0`:y(i)?s=`>=${n}.${r}.0 <${n}.${+r+1}.0-0`:a?(o(`replaceTilde pr`,a),s=`>=${n}.${r}.${i}-${a} <${n}.${+r+1}.0-0`):s=`>=${n}.${r}.${i} <${n}.${+r+1}.0-0`,o(`tilde return`,s),s})},S=(e,t)=>e.trim().split(/\s+/).map(e=>C(e,t)).join(` `),C=(e,t)=>{o(`caret`,e,t);let n=t.loose?c[l.CARETLOOSE]:c[l.CARET],r=t.includePrerelease?`-0`:``;return e.replace(n,(t,n,i,a,s)=>{o(`caret`,e,t,n,i,a,s);let c;return y(n)?c=``:y(i)?c=`>=${n}.0.0${r} <${+n+1}.0.0-0`:y(a)?c=n===`0`?`>=${n}.${i}.0${r} <${n}.${+i+1}.0-0`:`>=${n}.${i}.0${r} <${+n+1}.0.0-0`:s?(o(`replaceCaret pr`,s),c=n===`0`?i===`0`?`>=${n}.${i}.${a}-${s} <${n}.${i}.${+a+1}-0`:`>=${n}.${i}.${a}-${s} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${a}-${s} <${+n+1}.0.0-0`):(o(`no pr`),c=n===`0`?i===`0`?`>=${n}.${i}.${a}${r} <${n}.${i}.${+a+1}-0`:`>=${n}.${i}.${a}${r} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${a} <${+n+1}.0.0-0`),o(`caret return`,c),c})},w=(e,t)=>(o(`replaceXRanges`,e,t),e.split(/\s+/).map(e=>T(e,t)).join(` `)),T=(e,t)=>{e=e.trim();let n=t.loose?c[l.XRANGELOOSE]:c[l.XRANGE];return e.replace(n,(n,r,i,a,s,c)=>{o(`xRange`,e,n,r,i,a,s,c);let l=y(i),u=l||y(a),d=u||y(s),f=d;return r===`=`&&f&&(r=``),c=t.includePrerelease?`-0`:``,l?n=r===`>`||r===`<`?`<0.0.0-0`:`*`:r&&f?(u&&(a=0),s=0,r===`>`?(r=`>=`,u?(i=+i+1,a=0,s=0):(a=+a+1,s=0)):r===`<=`&&(r=`<`,u?i=+i+1:a=+a+1),r===`<`&&(c=`-0`),n=`${r+i}.${a}.${s}${c}`):u?n=`>=${i}.0.0${c} <${+i+1}.0.0-0`:d&&(n=`>=${i}.${a}.0${c} <${i}.${+a+1}.0-0`),o(`xRange return`,n),n})},E=(e,t)=>(o(`replaceStars`,e,t),e.trim().replace(c[l.STAR],``)),D=(e,t)=>(o(`replaceGTE0`,e,t),e.trim().replace(c[t.includePrerelease?l.GTE0PRE:l.GTE0],``)),O=e=>(t,n,r,i,a,o,s,c,l,u,d,f)=>(n=y(r)?``:y(i)?`>=${r}.0.0${e?`-0`:``}`:y(a)?`>=${r}.${i}.0${e?`-0`:``}`:o?`>=${n}`:`>=${n}${e?`-0`:``}`,c=y(l)?``:y(u)?`<${+l+1}.0.0-0`:y(d)?`<${l}.${+u+1}.0-0`:f?`<=${l}.${u}.${d}-${f}`:e?`<${l}.${u}.${+d+1}-0`:`<=${c}`,`${n} ${c}`.trim()),k=(e,t,n)=>{for(let n=0;n<e.length;n++)if(!e[n].test(t))return!1;if(t.prerelease.length&&!n.includePrerelease){for(let n=0;n<e.length;n++)if(o(e[n].semver),e[n].semver!==a.ANY&&e[n].semver.prerelease.length>0){let r=e[n].semver;if(r.major===t.major&&r.minor===t.minor&&r.patch===t.patch)return!0}return!1}return!0}})),Qp=o(((e,t)=>{let n=Symbol(`SemVer ANY`);t.exports=class e{static get ANY(){return n}constructor(t,i){if(i=r(i),t instanceof e){if(t.loose===!!i.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(` `),s(`comparator`,t,i),this.options=i,this.loose=!!i.loose,this.parse(t),this.semver===n?this.value=``:this.value=this.operator+this.semver.version,s(`comp`,this)}parse(e){let t=this.options.loose?i[a.COMPARATORLOOSE]:i[a.COMPARATOR],r=e.match(t);if(!r)throw TypeError(`Invalid comparator: ${e}`);this.operator=r[1]===void 0?``:r[1],this.operator===`=`&&(this.operator=``),r[2]?this.semver=new c(r[2],this.options.loose):this.semver=n}toString(){return this.value}test(e){if(s(`Comparator.test`,e,this.options.loose),this.semver===n||e===n)return!0;if(typeof e==`string`)try{e=new c(e,this.options)}catch{return!1}return o(e,this.operator,this.semver,this.options)}intersects(t,n){if(!(t instanceof e))throw TypeError(`a Comparator is required`);return this.operator===``?this.value===``?!0:new l(t.value,n).test(this.value):t.operator===``?t.value===``?!0:new l(this.value,n).test(t.semver):(n=r(n),n.includePrerelease&&(this.value===`<0.0.0-0`||t.value===`<0.0.0-0`)||!n.includePrerelease&&(this.value.startsWith(`<0.0.0`)||t.value.startsWith(`<0.0.0`))?!1:!!(this.operator.startsWith(`>`)&&t.operator.startsWith(`>`)||this.operator.startsWith(`<`)&&t.operator.startsWith(`<`)||this.semver.version===t.semver.version&&this.operator.includes(`=`)&&t.operator.includes(`=`)||o(this.semver,`<`,t.semver,n)&&this.operator.startsWith(`>`)&&t.operator.startsWith(`<`)||o(this.semver,`>`,t.semver,n)&&this.operator.startsWith(`<`)&&t.operator.startsWith(`>`)))}};let r=wp(),{safeRe:i,t:a}=Cp(),o=Jp(),s=Sp(),c=Ep(),l=Zp()})),$p=o(((e,t)=>{let n=Zp();t.exports=(e,t,r)=>{try{t=new n(t,r)}catch{return!1}return t.test(e)}})),em=o(((e,t)=>{let n=Zp();t.exports=(e,t)=>new n(e,t).set.map(e=>e.map(e=>e.value).join(` `).trim().split(` `))})),tm=o(((e,t)=>{let n=Ep(),r=Zp();t.exports=(e,t,i)=>{let a=null,o=null,s=null;try{s=new r(t,i)}catch{return null}return e.forEach(e=>{s.test(e)&&(!a||o.compare(e)===-1)&&(a=e,o=new n(a,i))}),a}})),nm=o(((e,t)=>{let n=Ep(),r=Zp();t.exports=(e,t,i)=>{let a=null,o=null,s=null;try{s=new r(t,i)}catch{return null}return e.forEach(e=>{s.test(e)&&(!a||o.compare(e)===1)&&(a=e,o=new n(a,i))}),a}})),rm=o(((e,t)=>{let n=Ep(),r=Zp(),i=Hp();t.exports=(e,t)=>{e=new r(e,t);let a=new n(`0.0.0`);if(e.test(a)||(a=new n(`0.0.0-0`),e.test(a)))return a;a=null;for(let t=0;t<e.set.length;++t){let r=e.set[t],o=null;r.forEach(e=>{let t=new n(e.semver.version);switch(e.operator){case`>`:t.prerelease.length===0?t.patch++:t.prerelease.push(0),t.raw=t.format();case``:case`>=`:(!o||i(t,o))&&(o=t);break;case`<`:case`<=`:break;default:throw Error(`Unexpected operation: ${e.operator}`)}}),o&&(!a||i(a,o))&&(a=o)}return a&&e.test(a)?a:null}})),im=o(((e,t)=>{let n=Zp();t.exports=(e,t)=>{try{return new n(e,t).range||`*`}catch{return null}}})),am=o(((e,t)=>{let n=Ep(),r=Qp(),{ANY:i}=r,a=Zp(),o=$p(),s=Hp(),c=Up(),l=qp(),u=Kp();t.exports=(e,t,d,f)=>{e=new n(e,f),t=new a(t,f);let p,m,h,g,_;switch(d){case`>`:p=s,m=l,h=c,g=`>`,_=`>=`;break;case`<`:p=c,m=u,h=s,g=`<`,_=`<=`;break;default:throw TypeError(`Must provide a hilo val of "<" or ">"`)}if(o(e,t,f))return!1;for(let n=0;n<t.set.length;++n){let a=t.set[n],o=null,s=null;if(a.forEach(e=>{e.semver===i&&(e=new r(`>=0.0.0`)),o||=e,s||=e,p(e.semver,o.semver,f)?o=e:h(e.semver,s.semver,f)&&(s=e)}),o.operator===g||o.operator===_||(!s.operator||s.operator===g)&&m(e,s.semver)||s.operator===_&&h(e,s.semver))return!1}return!0}})),om=o(((e,t)=>{let n=am();t.exports=(e,t,r)=>n(e,t,`>`,r)})),sm=o(((e,t)=>{let n=am();t.exports=(e,t,r)=>n(e,t,`<`,r)})),cm=o(((e,t)=>{let n=Zp();t.exports=(e,t,r)=>(e=new n(e,r),t=new n(t,r),e.intersects(t,r))})),lm=o(((e,t)=>{let n=$p(),r=Ip();t.exports=(e,t,i)=>{let a=[],o=null,s=null,c=e.sort((e,t)=>r(e,t,i));for(let e of c)n(e,t,i)?(s=e,o||=e):(s&&a.push([o,s]),s=null,o=null);o&&a.push([o,null]);let l=[];for(let[e,t]of a)e===t?l.push(e):!t&&e===c[0]?l.push(`*`):t?e===c[0]?l.push(`<=${t}`):l.push(`${e} - ${t}`):l.push(`>=${e}`);let u=l.join(` || `),d=typeof t.raw==`string`?t.raw:String(t);return u.length<d.length?u:t}})),um=o(((e,t)=>{let n=Zp(),r=Qp(),{ANY:i}=r,a=$p(),o=Ip(),s=(e,t,r={})=>{if(e===t)return!0;e=new n(e,r),t=new n(t,r);let i=!1;OUTER:for(let n of e.set){for(let e of t.set){let t=u(n,e,r);if(i||=t!==null,t)continue OUTER}if(i)return!1}return!0},c=[new r(`>=0.0.0-0`)],l=[new r(`>=0.0.0`)],u=(e,t,n)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===i){if(t.length===1&&t[0].semver===i)return!0;e=n.includePrerelease?c:l}if(t.length===1&&t[0].semver===i){if(n.includePrerelease)return!0;t=l}let r=new Set,s,u;for(let t of e)t.operator===`>`||t.operator===`>=`?s=d(s,t,n):t.operator===`<`||t.operator===`<=`?u=f(u,t,n):r.add(t.semver);if(r.size>1)return null;let p;if(s&&u&&(p=o(s.semver,u.semver,n),p>0||p===0&&(s.operator!==`>=`||u.operator!==`<=`)))return null;for(let e of r){if(s&&!a(e,String(s),n)||u&&!a(e,String(u),n))return null;for(let r of t)if(!a(e,String(r),n))return!1;return!0}let m,h,g,_,v=u&&!n.includePrerelease&&u.semver.prerelease.length?u.semver:!1,y=s&&!n.includePrerelease&&s.semver.prerelease.length?s.semver:!1;v&&v.prerelease.length===1&&u.operator===`<`&&v.prerelease[0]===0&&(v=!1);for(let e of t){if(_=_||e.operator===`>`||e.operator===`>=`,g=g||e.operator===`<`||e.operator===`<=`,s){if(y&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===y.major&&e.semver.minor===y.minor&&e.semver.patch===y.patch&&(y=!1),e.operator===`>`||e.operator===`>=`){if(m=d(s,e,n),m===e&&m!==s)return!1}else if(s.operator===`>=`&&!a(s.semver,String(e),n))return!1}if(u){if(v&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===v.major&&e.semver.minor===v.minor&&e.semver.patch===v.patch&&(v=!1),e.operator===`<`||e.operator===`<=`){if(h=f(u,e,n),h===e&&h!==u)return!1}else if(u.operator===`<=`&&!a(u.semver,String(e),n))return!1}if(!e.operator&&(u||s)&&p!==0)return!1}return!(s&&g&&!u&&p!==0||u&&_&&!s&&p!==0||y||v)},d=(e,t,n)=>{if(!e)return t;let r=o(e.semver,t.semver,n);return r>0?e:r<0||t.operator===`>`&&e.operator===`>=`?t:e},f=(e,t,n)=>{if(!e)return t;let r=o(e.semver,t.semver,n);return r<0?e:r>0||t.operator===`<`&&e.operator===`<=`?t:e};t.exports=s})),dm=o(((e,t)=>{let n=Cp(),r=xp(),i=Ep(),a=Tp();t.exports={parse:Dp(),valid:Op(),clean:kp(),inc:Ap(),diff:jp(),major:Mp(),minor:Np(),patch:Pp(),prerelease:Fp(),compare:Ip(),rcompare:Lp(),compareLoose:Rp(),compareBuild:zp(),sort:Bp(),rsort:Vp(),gt:Hp(),lt:Up(),eq:Wp(),neq:Gp(),gte:Kp(),lte:qp(),cmp:Jp(),coerce:Yp(),Comparator:Qp(),Range:Zp(),satisfies:$p(),toComparators:em(),maxSatisfying:tm(),minSatisfying:nm(),minVersion:rm(),validRange:im(),outside:am(),gtr:om(),ltr:sm(),intersects:cm(),simplifyRange:lm(),subset:um(),SemVer:i,re:n.re,src:n.src,tokens:n.t,SEMVER_SPEC_VERSION:r.SEMVER_SPEC_VERSION,RELEASE_TYPES:r.RELEASE_TYPES,compareIdentifiers:a.compareIdentifiers,rcompareIdentifiers:a.rcompareIdentifiers}})),fm=o(((e,t)=>{let n=dm(),r=require(`node:assert`),i=Symbol.for(`registered-plugin`),{kTestInternals:a}=du(),{exist:o,existReply:s,existRequest:c}=sd(),{FST_ERR_PLUGIN_VERSION_MISMATCH:l,FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE:u,FST_ERR_PLUGIN_INVALID_ASYNC_HANDLER:d}=mu(),f=/-(?:rc|pre|alpha).+$/u;function p(e){return e[Symbol.for(`plugin-meta`)]}function m(e){let t=g(e);if(t)return t;let n=require.cache;if(n){let t=Object.keys(n);for(let r=0;r<t.length;r++){let i=t[r];if(n[i].exports===e)return i}}return e.name?e.name:null}function h(e){return e.toString().split(`
|
|
431
|
+
`,2).map(e=>e.trim()).join(` -- `)}function g(e){return e[Symbol.for(`fastify.display-name`)]}function _(e){return!!e[Symbol.for(`skip-override`)]}function v(e){let t=p(e);if(!t)return;let n=t.dependencies;n&&(r(Array.isArray(n),`The dependencies should be an array of strings`),n.forEach(e=>{r(this[i].indexOf(e)>-1,`The dependency '${e}' of plugin '${t.name}' is not registered`)}))}function y(e){let t=p(e);if(!t)return;let{decorators:n,name:r}=t;n&&(n.fastify&&x(this,`Fastify`,n.fastify,r),n.reply&&x(this,`Reply`,n.reply,r),n.request&&x(this,`Request`,n.request,r))}let b={Fastify:o,Request:c,Reply:s};function x(e,t,n,i){r(Array.isArray(n),`The decorators should be an array of strings`),n.forEach(n=>{let r=typeof i==`string`?` required by '${i}'`:``;if(!b[t].call(e,n))throw new u(n,r,t)})}function S(e){let t=p(e);if(t?.fastify==null)return;let r=t.fastify,i=f.test(this.version);if(!(i===!0&&n.gt(this.version,n.coerce(r))===!0)&&r&&n.satisfies(this.version,r,{includePrerelease:i})===!1)throw new l(t.name,r,this.version)}function C(e){let t=p(e);if(!t)return;let n=t.name;if(n)return this[i].push(n),n}function w(e,t){if(e.constructor.name===`AsyncFunction`&&e.length===3)throw new d(t)}function T(e){let t=C.call(this,e)||m(e);return w.call(this,e,t),S.call(this,e),y.call(this,e),v.call(this,e),_(e)}t.exports={getPluginName:m,getFuncPreview:h,kRegisteredPlugins:i,getDisplayName:g,registerPlugin:T},t.exports[a]={shouldSkipOverride:_,getMeta:p,checkDecorators:y,checkDependencies:v}})),pm=o(((e,t)=>{function n(e,t){let n=t||i();return e?a(e,n):n}function r(e,t){return e.genReqId(t)}function i(){let e=0;return function(){return e=e+1&2147483647,`req-${e.toString(36)}`}}function a(e,t){return function(n){return n.headers[e]||t(n)}}t.exports={getGenReqId:r,reqIdGenFactory:n}})),mm=o(((e,t)=>{var n=12,r=0,i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,7,7,7,7,7,7,7,7,7,7,7,7,8,7,7,10,9,9,9,11,4,4,4,4,4,4,4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,12,0,0,0,0,24,36,48,60,72,84,96,0,12,12,12,0,0,0,0,0,0,0,0,0,0,0,24,0,0,0,0,0,0,0,0,0,24,24,24,0,0,0,0,0,0,0,0,0,24,24,0,0,0,0,0,0,0,0,0,0,48,48,48,0,0,0,0,0,0,0,0,0,0,48,48,0,0,0,0,0,0,0,0,0,48,0,0,0,0,0,0,0,0,0,0,127,63,63,63,0,31,15,15,15,7,7,7];function a(e){var t=e.indexOf(`%`);if(t===-1)return e;for(var a=e.length,o=``,c=0,l=0,u=t,d=n;t>-1&&t<a;){var f=s(e[t+1],4)|s(e[t+2],0),p=i[f];if(d=i[256+d+p],l=l<<6|f&i[364+p],d===n)o+=e.slice(c,u),o+=l<=65535?String.fromCharCode(l):String.fromCharCode(55232+(l>>10),56320+(l&1023)),l=0,c=t+3,t=u=e.indexOf(`%`,c);else if(d===r)return null;else{if(t+=3,t<a&&e.charCodeAt(t)===37)continue;return null}}return o+e.slice(c)}var o={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};function s(e,t){var n=o[e];return n===void 0?255:n<<t}t.exports=a})),hm=o(((e,t)=>{let n=mm(),r=/\+/g,i=function(){};i.prototype=Object.create(null);function a(e){let t=new i;if(typeof e!=`string`)return t;let a=e.length,o=``,s=``,c=-1,l=-1,u=!1,d=!1,f=!1,p=!1,m=!1,h=0;for(let i=0;i<a+1;i++)if(h=i===a?38:e.charCodeAt(i),h===38){if(m=l>c,m||(l=i),o=e.slice(c+1,l),m||o.length>0){f&&(o=o.replace(r,` `)),u&&(o=n(o)||o),m&&(s=e.slice(l+1,i),p&&(s=s.replace(r,` `)),d&&(s=n(s)||s));let a=t[o];a===void 0?t[o]=s:a.pop?a.push(s):t[o]=[a,s]}s=``,c=i,l=i,u=!1,d=!1,f=!1,p=!1}else h===61?l<=c?l=i:d=!0:h===43?l>c?p=!0:f=!0:h===37&&(l>c?d=!0:u=!0);return t}t.exports=a})),gm=o(((e,t)=>{let n=Array.from({length:256},(e,t)=>`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase()),r=new Int8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,1,1,0,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,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,0,0,0,1,0,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,0,0,1,0]);function i(e){let t=e.length;if(t===0)return``;let i=``,a=0,o=0;outer:for(;o<t;o++){let s=e.charCodeAt(o);for(;s<128;){if(r[s]!==1&&(a<o&&(i+=e.slice(a,o)),a=o+1,i+=n[s]),++o===t)break outer;s=e.charCodeAt(o)}if(a<o&&(i+=e.slice(a,o)),s<2048){a=o+1,i+=n[192|s>>6]+n[128|s&63];continue}if(s<55296||s>=57344){a=o+1,i+=n[224|s>>12]+n[128|s>>6&63]+n[128|s&63];continue}if(++o,o>=t)throw Error(`URI malformed`);let c=e.charCodeAt(o)&1023;a=o+1,s=65536+((s&1023)<<10|c),i+=n[240|s>>18]+n[128|s>>12&63]+n[128|s>>6&63]+n[128|s&63]}return a===0?e:a<t?i+e.slice(a):i}t.exports={encodeString:i}})),_m=o(((e,t)=>{let{encodeString:n}=gm();function r(e){let t=typeof e;return t===`string`?n(e):t===`bigint`?e.toString():t===`boolean`?e?`true`:`false`:t===`number`&&Number.isFinite(e)?e<1e21?``+e:n(``+e):``}function i(e){let t=``;if(typeof e!=`object`||!e)return t;let i=Object.keys(e),a=i.length,o=0;for(let s=0;s<a;s++){let a=i[s],c=e[a],l=n(a)+`=`;if(s&&(t+=`&`),Array.isArray(c)){o=c.length;for(let e=0;e<o;e++)e&&(t+=`&`),t+=l,t+=r(c[e])}else t+=l,t+=r(c)}return t}t.exports=i})),vm=o(((e,t)=>{let n=hm(),r=_m(),i={parse:n,stringify:r};t.exports=i,t.exports.default=i,t.exports.parse=n,t.exports.stringify=r})),ym=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0})})),bm=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.types=void 0,(function(e){e[e.ROOT=0]=`ROOT`,e[e.GROUP=1]=`GROUP`,e[e.POSITION=2]=`POSITION`,e[e.SET=3]=`SET`,e[e.RANGE=4]=`RANGE`,e[e.REPETITION=5]=`REPETITION`,e[e.REFERENCE=6]=`REFERENCE`,e[e.CHAR=7]=`CHAR`})(e.types||={})})),xm=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0})})),Sm=o((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!==`default`&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,`__esModule`,{value:!0}),n(ym(),e),n(bm(),e),n(xm(),e)})),Cm=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.anyChar=e.notWhitespace=e.whitespace=e.notInts=e.ints=e.notWords=e.words=void 0;let t=Sm(),n=()=>[{type:t.types.RANGE,from:48,to:57}],r=()=>[{type:t.types.CHAR,value:95},{type:t.types.RANGE,from:97,to:122},{type:t.types.RANGE,from:65,to:90},{type:t.types.RANGE,from:48,to:57}],i=()=>[{type:t.types.CHAR,value:9},{type:t.types.CHAR,value:10},{type:t.types.CHAR,value:11},{type:t.types.CHAR,value:12},{type:t.types.CHAR,value:13},{type:t.types.CHAR,value:32},{type:t.types.CHAR,value:160},{type:t.types.CHAR,value:5760},{type:t.types.RANGE,from:8192,to:8202},{type:t.types.CHAR,value:8232},{type:t.types.CHAR,value:8233},{type:t.types.CHAR,value:8239},{type:t.types.CHAR,value:8287},{type:t.types.CHAR,value:12288},{type:t.types.CHAR,value:65279}],a=()=>[{type:t.types.CHAR,value:10},{type:t.types.CHAR,value:13},{type:t.types.CHAR,value:8232},{type:t.types.CHAR,value:8233}];e.words=()=>({type:t.types.SET,set:r(),not:!1}),e.notWords=()=>({type:t.types.SET,set:r(),not:!0}),e.ints=()=>({type:t.types.SET,set:n(),not:!1}),e.notInts=()=>({type:t.types.SET,set:n(),not:!0}),e.whitespace=()=>({type:t.types.SET,set:i(),not:!1}),e.notWhitespace=()=>({type:t.types.SET,set:i(),not:!0}),e.anyChar=()=>({type:t.types.SET,set:a(),not:!0})})),wm=o((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,`__esModule`,{value:!0}),e.tokenizeClass=e.strToChars=void 0;let i=Sm(),a=r(Cm());e.strToChars=e=>e.replace(/(\[\\b\])|(\\)?\\(?:u([A-F0-9]{4})|x([A-F0-9]{2})|c([@A-Z[\\\]^?])|([0tnvfr]))/g,(e,t,n,r,i,a,o)=>{if(n)return e;let s=t?8:r?parseInt(r,16):i?parseInt(i,16):a?`@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?`.indexOf(a):{0:0,t:9,n:10,v:11,f:12,r:13}[o],c=String.fromCharCode(s);return/[[\]{}^$.|?*+()]/.test(c)?`\\${c}`:c}),e.tokenizeClass=(e,t)=>{let n=[],r,o,s=/\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(((?:\\)])|(((?:\\)?([^\]])))))|(\])|(?:\\)?([^])/g;for(;(r=s.exec(e))!==null;){let e=(r[1]&&a.words())??(r[2]&&a.ints())??(r[3]&&a.whitespace())??(r[4]&&a.notWords())??(r[5]&&a.notInts())??(r[6]&&a.notWhitespace())??(r[7]&&{type:i.types.RANGE,from:(r[8]||r[9]).charCodeAt(0),to:(o=r[10]).charCodeAt(o.length-1)})??((o=r[16])&&{type:i.types.CHAR,value:o.charCodeAt(0)});if(e)n.push(e);else return[n,s.lastIndex]}throw SyntaxError(`Invalid regular expression: /${t}/: Unterminated character class`)}})),Tm=o((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,`__esModule`,{value:!0}),e.tokenizer=void 0;let i=r(wm()),a=Sm(),o=r(Cm()),s=/^[a-zA-Z_$]$/i,c=/^[a-zA-Z0-9_$]$/i,l=/\d/;e.tokenizer=e=>{let t=0,n,r={type:a.types.ROOT,stack:[]},d=r,f=r.stack,p=[],m=[],h=0,g=t=>{throw SyntaxError(`Invalid regular expression: /${e}/: Nothing to repeat at column ${t-1}`)},_=i.strToChars(e);for(;t<_.length;)switch(n=_[t++]){case`\\`:if(t===_.length)throw SyntaxError(`Invalid regular expression: /${e}/: \\ at end of pattern`);switch(n=_[t++]){case`b`:f.push({type:a.types.POSITION,value:`b`});break;case`B`:f.push({type:a.types.POSITION,value:`B`});break;case`w`:f.push(o.words());break;case`W`:f.push(o.notWords());break;case`d`:f.push(o.ints());break;case`D`:f.push(o.notInts());break;case`s`:f.push(o.whitespace());break;case`S`:f.push(o.notWhitespace());break;default:if(l.test(n)){let e=n;for(;t<_.length&&l.test(_[t]);)e+=_[t++];let r=parseInt(e,10),i={type:a.types.REFERENCE,value:r};f.push(i),m.push({reference:i,stack:f,index:f.length-1})}else f.push({type:a.types.CHAR,value:n.charCodeAt(0)})}break;case`^`:f.push({type:a.types.POSITION,value:`^`});break;case`$`:f.push({type:a.types.POSITION,value:`$`});break;case`[`:{let n;_[t]===`^`?(n=!0,t++):n=!1;let r=i.tokenizeClass(_.slice(t),e);t+=r[1],f.push({type:a.types.SET,set:r[0],not:n});break}case`.`:f.push(o.anyChar());break;case`(`:{let r={type:a.types.GROUP,stack:[],remember:!0};if(_[t]===`?`)if(n=_[t+1],t+=2,n===`=`)r.followedBy=!0,r.remember=!1;else if(n===`!`)r.notFollowedBy=!0,r.remember=!1;else if(n===`<`){let n=``;if(s.test(_[t]))n+=_[t],t++;else throw SyntaxError(`Invalid regular expression: /${e}/: Invalid capture group name, character '${_[t]}' after '<' at column ${t+1}`);for(;t<_.length&&c.test(_[t]);)n+=_[t],t++;if(!n)throw SyntaxError(`Invalid regular expression: /${e}/: Invalid capture group name, character '${_[t]}' after '<' at column ${t+1}`);if(_[t]!==`>`)throw SyntaxError(`Invalid regular expression: /${e}/: Unclosed capture group name, expected '>', found '${_[t]}' at column ${t+1}`);r.name=n,t++}else if(n===`:`)r.remember=!1;else throw SyntaxError(`Invalid regular expression: /${e}/: Invalid group, character '${n}' after '?' at column ${t-1}`);else h+=1;f.push(r),p.push(d),d=r,f=r.stack;break}case`)`:if(p.length===0)throw SyntaxError(`Invalid regular expression: /${e}/: Unmatched ) at column ${t-1}`);d=p.pop(),f=d.options?d.options[d.options.length-1]:d.stack;break;case`|`:{d.options||(d.options=[d.stack],delete d.stack);let e=[];d.options.push(e),f=e;break}case`{`:{let e=/^(\d+)(,(\d+)?)?\}/.exec(_.slice(t)),n,r;e===null?f.push({type:a.types.CHAR,value:123}):(f.length===0&&g(t),n=parseInt(e[1],10),r=e[2]?e[3]?parseInt(e[3],10):1/0:n,t+=e[0].length,f.push({type:a.types.REPETITION,min:n,max:r,value:f.pop()}));break}case`?`:f.length===0&&g(t),f.push({type:a.types.REPETITION,min:0,max:1,value:f.pop()});break;case`+`:f.length===0&&g(t),f.push({type:a.types.REPETITION,min:1,max:1/0,value:f.pop()});break;case`*`:f.length===0&&g(t),f.push({type:a.types.REPETITION,min:0,max:1/0,value:f.pop()});break;default:f.push({type:a.types.CHAR,value:n.charCodeAt(0)})}if(p.length!==0)throw SyntaxError(`Invalid regular expression: /${e}/: Unterminated group`);return u(m,h),r};function u(e,t){for(let n of e.reverse())if(t<n.reference.value){n.reference.type=a.types.CHAR;let e=n.reference.value.toString();if(n.reference.value=parseInt(e,8),!/^[0-7]+$/.test(e)){let t=0;for(;e[t]!==`8`&&e[t]!==`9`;)t+=1;if(t===0?(n.reference.value=e.charCodeAt(0),t+=1):n.reference.value=parseInt(e.slice(0,t),8),e.length>t){let r=n.stack.splice(n.index+1);for(let r of e.slice(t))n.stack.push({type:a.types.CHAR,value:r.charCodeAt(0)});n.stack.push(...r)}}}}})),Em=o((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,`__esModule`,{value:!0}),e.NOTANYCHAR=e.WHITESPACE=e.WORDS=e.INTS=void 0;let i=r(Cm()),a=Sm();function o(e){let t={},n=0;for(let r of e)r.type===a.types.CHAR&&(t[r.value]=!0),r.type===a.types.RANGE&&(t[`${r.from}-${r.to}`]=!0),n+=1;return{lookup:()=>Object.assign({},t),len:n}}e.INTS=o(i.ints().set),e.WORDS=o(i.words().set),e.WHITESPACE=o(i.whitespace().set),e.NOTANYCHAR=o(i.anyChar().set)})),Dm=o((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,`__esModule`,{value:!0}),e.writeSetTokens=e.setChar=void 0;let i=Sm(),a=r(Em());function o(e){return e===94?`\\^`:e===92?`\\\\`:e===93?`\\]`:e===45?`\\-`:String.fromCharCode(e)}e.setChar=o;function s(e,{lookup:t,len:n}){if(n!==e.length)return!1;let r=t();for(let t of e){if(t.type===i.types.SET)return!1;let e=t.type===i.types.CHAR?t.value:`${t.from}-${t.to}`;if(r[e])r[e]=!1;else return!1}return!0}function c(e,t=!1){if(s(e.set,a.INTS))return e.not?`\\D`:`\\d`;if(s(e.set,a.WORDS))return e.not?`\\W`:`\\w`;if(e.not&&s(e.set,a.NOTANYCHAR))return`.`;if(s(e.set,a.WHITESPACE))return e.not?`\\S`:`\\s`;let n=``;for(let t=0;t<e.set.length;t++){let r=e.set[t];n+=l(r)}let r=`${e.not?`^`:``}${n}`;return t?r:`[${r}]`}e.writeSetTokens=c;function l(e){return e.type===i.types.CHAR?o(e.value):e.type===i.types.RANGE?`${o(e.from)}-${o(e.to)}`:c(e,!0)}})),Om=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.reconstruct=void 0;let t=Sm(),n=Dm(),r=t=>t.map(e.reconstruct).join(``),i=e=>{if(`options`in e)return e.options.map(r).join(`|`);if(`stack`in e)return r(e.stack);throw Error(`options or stack must be Root or Group token`)};e.reconstruct=r=>{switch(r.type){case t.types.ROOT:return i(r);case t.types.CHAR:{let e=String.fromCharCode(r.value);return(/[[\\{}$^.|?*+()]/.test(e)?`\\`:``)+e}case t.types.POSITION:return r.value===`^`||r.value===`$`?r.value:`\\${r.value}`;case t.types.REFERENCE:return`\\${r.value}`;case t.types.SET:return n.writeSetTokens(r);case t.types.GROUP:return`(${r.name?`?<${r.name}>`:r.remember?``:r.followedBy?`?=`:r.notFollowedBy?`?!`:`?:`}${i(r)})`;case t.types.REPETITION:{let{min:t,max:n}=r,i;return i=t===0&&n===1?`?`:t===1&&n===1/0?`+`:t===0&&n===1/0?`*`:n===1/0?`{${t},}`:t===n?`{${t}}`:`{${t},${n}}`,`${e.reconstruct(r.value)}${i}`}case t.types.RANGE:return`${n.setChar(r.from)}-${n.setChar(r.to)}`;default:throw Error(`Invalid token type ${r}`)}}})),km=o(((e,t)=>{var n=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),r=e&&e.__exportStar||function(e,t){for(var r in e)r!==`default`&&!Object.prototype.hasOwnProperty.call(t,r)&&n(t,e,r)};Object.defineProperty(e,`__esModule`,{value:!0}),e.types=void 0;let i=Sm();Object.defineProperty(e,`types`,{enumerable:!0,get:function(){return i.types}}),r(Tm(),e),r(Om(),e);let a=Tm(),o=Om();r(Sm(),e),e.default=a.tokenizer,t.exports=a.tokenizer,t.exports.types=i.types,t.exports.reconstruct=o.reconstruct})),Am=o(((e,t)=>{let n=km(),r=n.types;function i(e,t){t||={};let i=t.limit===void 0?25:t.limit;a(e)?e=e.source:typeof e!=`string`&&(e=String(e));try{e=n(e)}catch{return!1}let o=0;return(function e(t,n){let a,s,c;if(t.type===r.REPETITION&&(n++,o++,n>1||o>i))return!1;if(t.options){for(a=0,c=t.options.length;a<c;a++)if(s=e({stack:t.options[a]},n),!s)return!1}let l=t.stack||t.value?.stack;if(!l)return!0;for(a=0;a<l.length;a++)if(s=e(l[a],n),!s)return!1;return!0})(e,0)}function a(e){return{}.toString.call(e)===`[object RegExp]`}t.exports=i,t.exports.default=i,t.exports.safeRegex=i})),jm=o(((e,t)=>{t.exports={name:`__fmw_internal_strategy_merged_tree_http_method__`,storage:function(){let e=new Map;return{get:t=>e.get(t)||null,set:(t,n)=>{e.set(t,n)}}},deriveConstraint:e=>e.method,mustMatchWhenDerived:!0}})),Mm=o(((e,t)=>{let n=Ad(),r=jm(),i=Symbol(`treeData`);function a(e,t=``){let n=``,r=Object.keys(e);for(let o=0;o<r.length;o++){let s=r[o],c=e[s],l=o===r.length-1,u=l?`└── `:`├── `,d=l?` `:`│ `,f=(c[i]||``).replaceAll(`
|
|
432
432
|
`,`
|
|
433
433
|
`+t+d);n+=t+u+s+f+`
|
|
434
|
-
`,n+=a(c,t+d)}return n}function o(e){let t=e.name||``;return t=t.replace(`bound`,``).trim(),t=(t||`anonymous`)+`()`,t}function s(e){return Array.isArray(e)?e.map(e=>s(e)):typeof e==`symbol`?e.toString():typeof e==`function`?o(e):e}function c(e,t){if(!t.includeMeta)return{};let n=t.buildPrettyMeta(e),r={},i=t.includeMeta;Array.isArray(i)||(i=Reflect.ownKeys(n));for(let e of i){if(!Object.prototype.hasOwnProperty.call(n,e))continue;let t=e.toString(),i=n[e];i!=null&&(r[t]=JSON.stringify(s(i)))}return r}function l(e){let t=``;for(let[n,r]of Object.entries(e))t+=`\n• (${n}) ${r}`;return t}function u(e){let t={...e.opts.constraints},n=t[r.name];return delete t[r.name],{...e,method:n,opts:{constraints:t}}}function d(e){let t=` (${e.method})`,n=e.opts.constraints||{};return Object.keys(n).length!==0&&(t+=` `+JSON.stringify(n)),t+=l(e.metaData),t}function f(e){return e.reduce((e,t)=>{for(let r of e)if(n(t.opts.constraints,r.opts.constraints)&&n(t.metaData,r.metaData))return r.method+=`, `+t.method,e;return e.push(t),e},[])}function p(e,t,n){let r=e.routes;return n.method===void 0&&(r=r.map(u)),r=r.map(e=>(e.metaData=c(e,n),e)),n.method===void 0&&(r=f(r)),r.map(d).join(`\n${t}`)}function m(e,t,n,r){if((e.isLeafNode||r.commonPrefix!==!1)&&(n||=`(empty root node)`,t=t[n]={},e.isLeafNode&&(t[i]=p(e,n,r)),n=``),e.staticChildren)for(let i of Object.values(e.staticChildren))m(i,t,n+i.prefix,r);if(e.parametricChildren)for(let i of Object.values(e.parametricChildren)){let e=Array.from(i.nodePaths).join(`|`);m(i,t,n+e,r)}e.wildcardChild&&m(e.wildcardChild,t,`*`,r)}function h(e,t){let n={};return m(e,n,e.prefix,t),a(n)}t.exports={prettyPrintTree:h}})),
|
|
434
|
+
`,n+=a(c,t+d)}return n}function o(e){let t=e.name||``;return t=t.replace(`bound`,``).trim(),t=(t||`anonymous`)+`()`,t}function s(e){return Array.isArray(e)?e.map(e=>s(e)):typeof e==`symbol`?e.toString():typeof e==`function`?o(e):e}function c(e,t){if(!t.includeMeta)return{};let n=t.buildPrettyMeta(e),r={},i=t.includeMeta;Array.isArray(i)||(i=Reflect.ownKeys(n));for(let e of i){if(!Object.prototype.hasOwnProperty.call(n,e))continue;let t=e.toString(),i=n[e];i!=null&&(r[t]=JSON.stringify(s(i)))}return r}function l(e){let t=``;for(let[n,r]of Object.entries(e))t+=`\n• (${n}) ${r}`;return t}function u(e){let t={...e.opts.constraints},n=t[r.name];return delete t[r.name],{...e,method:n,opts:{constraints:t}}}function d(e){let t=` (${e.method})`,n=e.opts.constraints||{};return Object.keys(n).length!==0&&(t+=` `+JSON.stringify(n)),t+=l(e.metaData),t}function f(e){return e.reduce((e,t)=>{for(let r of e)if(n(t.opts.constraints,r.opts.constraints)&&n(t.metaData,r.metaData))return r.method+=`, `+t.method,e;return e.push(t),e},[])}function p(e,t,n){let r=e.routes;return n.method===void 0&&(r=r.map(u)),r=r.map(e=>(e.metaData=c(e,n),e)),n.method===void 0&&(r=f(r)),r.map(d).join(`\n${t}`)}function m(e,t,n,r){if((e.isLeafNode||r.commonPrefix!==!1)&&(n||=`(empty root node)`,t=t[n]={},e.isLeafNode&&(t[i]=p(e,n,r)),n=``),e.staticChildren)for(let i of Object.values(e.staticChildren))m(i,t,n+i.prefix,r);if(e.parametricChildren)for(let i of Object.values(e.parametricChildren)){let e=Array.from(i.nodePaths).join(`|`);m(i,t,n+e,r)}e.wildcardChild&&m(e.wildcardChild,t,`*`,r)}function h(e,t){let n={};return m(e,n,e.prefix,t),a(n)}t.exports={prettyPrintTree:h}})),Nm=o(((e,t)=>{let n=function(){};n.prototype=Object.create(null),t.exports={NullObject:n}})),Pm=o(((e,t)=>{let{NullObject:n}=Nm(),r=jm();t.exports=class{constructor(){this.unconstrainedHandler=null,this.constraints=[],this.handlers=[],this.constrainedHandlerStores=null}getMatchingHandler(e){return e===void 0?this.unconstrainedHandler:this._getHandlerMatchingConstraints(e)}addHandler(e,t){let n=t.params,i=t.opts.constraints||{},a={params:n,constraints:i,handler:t.handler,store:t.store||null,_createParamsObject:this._compileCreateParamsObject(n)},o=Object.keys(i);o.length===0&&(this.unconstrainedHandler=a);for(let e of o)this.constraints.includes(e)||(e===`version`?this.constraints.unshift(e):this.constraints.push(e));let s=o.includes(r.name);if(!s&&this.handlers.length>=31)throw Error(`find-my-way supports a maximum of 31 route handlers per node when there are constraints, limit reached`);this.handlers.push(a),this.handlers.sort((e,t)=>Object.keys(e.constraints).length-Object.keys(t.constraints).length),s||this._compileGetHandlerMatchingConstraints(e,i)}_compileCreateParamsObject(e){let t=[];t.push(`const fn = function _createParamsObject (paramsArray) {`),t.push(`const params = new NullObject()`);for(let n=0;n<e.length;n++)t.push(`params['${e[n]}'] = paramsArray[${n}]`);return t.push(`return params`),t.push(`}`),t.push(`return fn`),Function(`NullObject`,t.join(`
|
|
435
435
|
`))(n)}_getHandlerMatchingConstraints(){return null}_buildConstraintStore(e,t){for(let n=0;n<this.handlers.length;n++){let r=this.handlers[n].constraints[t];if(r!==void 0){let t=e.get(r)||0;t|=1<<n,e.set(r,t)}}}_constrainedIndexBitmask(e){let t=0;for(let n=0;n<this.handlers.length;n++)this.handlers[n].constraints[e]!==void 0&&(t|=1<<n);return~t}_compileGetHandlerMatchingConstraints(e){this.constrainedHandlerStores={};for(let t of this.constraints){let n=e.newStoreForConstraint(t);this.constrainedHandlerStores[t]=n,this._buildConstraintStore(n,t)}let t=[];t.push(`
|
|
436
436
|
let candidates = ${(1<<this.handlers.length)-1}
|
|
437
437
|
let mask, matches
|
|
@@ -447,41 +447,42 @@ const asInteger = serializer.asInteger.bind(serializer)
|
|
|
447
447
|
}
|
|
448
448
|
if (candidates === 0) return null;
|
|
449
449
|
`)}for(let n in e.strategies)e.strategies[n].mustMatchWhenDerived&&!this.constraints.includes(n)&&t.push(`if (derivedConstraints.${n} !== undefined) return null`);t.push(`return this.handlers[Math.floor(Math.log2(candidates))]`),this._getHandlerMatchingConstraints=Function(`derivedConstraints`,t.join(`
|
|
450
|
-
`))}}})),
|
|
451
|
-
`)).bind(this)}}})),Rm=o(((e,t)=>{t.exports=`ACL.BIND.CHECKOUT.CONNECT.COPY.DELETE.GET.HEAD.LINK.LOCK.M-SEARCH.MERGE.MKACTIVITY.MKCALENDAR.MKCOL.MOVE.NOTIFY.OPTIONS.PATCH.POST.PROPFIND.PROPPATCH.PURGE.PUT.QUERY.REBIND.REPORT.SEARCH.SOURCE.SUBSCRIBE.TRACE.UNBIND.UNLINK.UNLOCK.UNSUBSCRIBE`.split(`.`)})),zm=o(((e,t)=>{function n(e,t){return e===50?t===53?`%`:t===51?`#`:t===52?`$`:t===54?`&`:t===66||t===98?`+`:t===67||t===99?`,`:t===70||t===102?`/`:null:e===51?t===65||t===97?`:`:t===66||t===98?`;`:t===68||t===100?`=`:t===70||t===102?`?`:null:e===52&&t===48?`@`:null}function r(e,t){let r=!1,i=!1,a=``;for(let o=1;o<e.length;o++){let s=e.charCodeAt(o);if(s===37){let t=e.charCodeAt(o+1),a=e.charCodeAt(o+2);n(t,a)===null?r=!0:(i=!0,t===50&&a===53&&(r=!0,e=e.slice(0,o+1)+`25`+e.slice(o+1),o+=2),o+=2)}else if(s===63||s===35||s===59&&t){a=e.slice(o+1),e=e.slice(0,o);break}}return{path:r?decodeURI(e):e,querystring:a,shouldDecodeParam:i}}function i(e){let t=e.indexOf(`%`);if(t===-1)return e;let r=``,i=t;for(let a=t;a<e.length;a++)if(e.charCodeAt(a)===37){let t=n(e.charCodeAt(a+1),e.charCodeAt(a+2));r+=e.slice(i,a)+t,i=a+3}return e.slice(0,t)+r+e.slice(i)}t.exports={safeDecodeURI:r,safeDecodeURIComponent:i}})),Bm=o(((e,t)=>{let n=require(`node:assert`),r=_m(),i=km(),a=kd(),{prettyPrintTree:o}=jm(),{StaticNode:s,NODE_TYPES:c}=Pm(),l=Lm(),u=Rm(),d=Am(),{safeDecodeURI:f,safeDecodeURIComponent:p}=zm(),m=/^https?:\/\/.*?\//,h=/(\/:[^/()]*?)\?(\/?)/,g=/[.*+?^${}()|[\]\\]/g,_=/\/\/+/g;if(!i(m))throw Error(`the FULL_PATH_REGEXP is not safe, update this module`);if(!i(h))throw Error(`the OPTIONAL_PARAM_REGEXP is not safe, update this module`);if(!i(g))throw Error(`the ESCAPE_REGEXP is not safe, update this module`);if(!i(_))throw Error(`the REMOVE_DUPLICATE_SLASHES_REGEXP is not safe, update this module`);function v(e){if(!(this instanceof v))return new v(e);e||={},this._opts=e,e.defaultRoute?(n(typeof e.defaultRoute==`function`,`The default route must be a function`),this.defaultRoute=e.defaultRoute):this.defaultRoute=null,e.onBadUrl?(n(typeof e.onBadUrl==`function`,`The bad url handler must be a function`),this.onBadUrl=e.onBadUrl):this.onBadUrl=null,e.buildPrettyMeta?(n(typeof e.buildPrettyMeta==`function`,`buildPrettyMeta must be a function`),this.buildPrettyMeta=e.buildPrettyMeta):this.buildPrettyMeta=w,e.querystringParser?(n(typeof e.querystringParser==`function`,`querystringParser must be a function`),this.querystringParser=e.querystringParser):this.querystringParser=e=>e.length===0?{}:r.parse(e),this.caseSensitive=e.caseSensitive===void 0?!0:e.caseSensitive,this.ignoreTrailingSlash=e.ignoreTrailingSlash||!1,this.ignoreDuplicateSlashes=e.ignoreDuplicateSlashes||!1,this.maxParamLength=e.maxParamLength||100,this.allowUnsafeRegex=e.allowUnsafeRegex||!1,this.constrainer=new l(e.constraints),this.useSemicolonDelimiter=e.useSemicolonDelimiter||!1,this.routes=[],this.trees={}}v.prototype.on=function(e,t,r,i,a){typeof r==`function`&&(i!==void 0&&(a=i),i=r,r={}),n(typeof t==`string`,`Path should be a string`),n(t.length>0,`The path could not be empty`),n(t[0]===`/`||t[0]===`*`,"The first character of a path should be `/` or `*`"),n(typeof i==`function`,`Handler should be a function`);let o=t.match(h);if(o){n(t.length===o.index+o[0].length,`Optional Parameter needs to be the last parameter of the path`);let s=t.replace(h,`$1$2`),c=t.replace(h,`$2`)||`/`;this.on(e,s,r,i,a),this.on(e,c,r,i,a);return}let s=t;this.ignoreDuplicateSlashes&&(t=b(t)),this.ignoreTrailingSlash&&(t=x(t));let c=Array.isArray(e)?e:[e];for(let e of c)n(typeof e==`string`,`Method should be a string`),n(u.includes(e),`Method '${e}' is not an http method.`),this._on(e,t,r,i,a,s)},v.prototype._on=function(e,t,r,o,c){let l={};r.constraints!==void 0&&(n(typeof r.constraints==`object`&&r.constraints!==null,`Constraints should be an object`),Object.keys(r.constraints).length!==0&&(l=r.constraints)),this.constrainer.validateConstraints(l),this.constrainer.noteUsage(l),this.trees[e]===void 0&&(this.trees[e]=new s(`/`));let u=t;if(u===`*`&&this.trees[e].prefix.length!==0){let t=this.trees[e];this.trees[e]=new s(``),this.trees[e].staticChildren[`/`]=t}let d=this.trees[e],f=d.prefix.length,p=[];for(let e=0;e<=u.length;e++){if(u.charCodeAt(e)===58&&u.charCodeAt(e+1)===58){e++;continue}let t=u.charCodeAt(e)===58&&u.charCodeAt(e+1)!==58,r=u.charCodeAt(e)===42;if(t||r||e===u.length&&e!==f){let t=u.slice(f,e);this.caseSensitive||(t=t.toLowerCase()),t=t.replaceAll(`::`,`:`),t=t.replaceAll(`%`,`%25`),d=d.createStaticChild(t)}if(t){let t=!1,r=!0,a=``,o=[],s=e+1;for(let c=s;;c++){let l=u.charCodeAt(c),m=l===40,h=l===45||l===46,g=l===47||c===u.length;if(m||h||g){let l=u.slice(s,c);if(p.push(l),t=t||m||h,m){let e=C(u,c),t=u.slice(c,e+1);this.allowUnsafeRegex||n(i(new RegExp(t)),`The regex '${t}' is not safe!`),o.push(S(t)),c=e+1,r=!0}else o.push(r?`(.*?)`:`(${a}|(?:(?!${a}).)*)`),r=!1;let _=c;for(;c<u.length;c++){let e=u.charCodeAt(c);if(e===47)break;if(e===58)if(u.charCodeAt(c+1)===58)c++;else break}let v=u.slice(_,c);if(v&&(v=v.replaceAll(`::`,`:`),v=v.replaceAll(`%`,`%25`),o.push(a=y(v))),s=c+1,g||u.charCodeAt(c)===47||c===u.length){let n=t?`()`+v:v,r=u.slice(e,c);u=u.slice(0,e+1)+n+u.slice(c),e+=n.length;let i=t?RegExp(`^`+o.join(``)+`$`):null;d=d.createParametricChild(i,v||null,r),f=e+1;break}}}}else if(r&&(p.push(`*`),d=d.createWildcardChild(),f=e+1,e!==u.length-1))throw Error(`Wildcard must be the last character in the route`)}this.caseSensitive||(u=u.toLowerCase()),u===`*`&&(u=`/*`);for(let t of this.routes){let n=t.opts.constraints||{};if(t.method===e&&t.pattern===u&&a(n,l))throw Error(`Method '${e}' already declared for route '${u}' with constraints '${JSON.stringify(l)}'`)}let m={method:e,path:t,pattern:u,params:p,opts:r,handler:o,store:c};this.routes.push(m),d.addRoute(m,this.constrainer)},v.prototype.hasRoute=function(e,t,n){return this.findRoute(e,t,n)!==null},v.prototype.findRoute=function(e,t,r={}){if(this.trees[e]===void 0)return null;let o=t,s=this.trees[e],c=s.prefix.length,l=[];for(let e=0;e<=o.length;e++){if(o.charCodeAt(e)===58&&o.charCodeAt(e+1)===58){e++;continue}let t=o.charCodeAt(e)===58&&o.charCodeAt(e+1)!==58,r=o.charCodeAt(e)===42;if(t||r||e===o.length&&e!==c){let t=o.slice(c,e);if(this.caseSensitive||(t=t.toLowerCase()),t=t.replaceAll(`::`,`:`),t=t.replaceAll(`%`,`%25`),s=s.getStaticChild(t),s===null)return null}if(t){let t=!1,r=!0,a=``,u=[],d=e+1;for(let f=d;;f++){let p=o.charCodeAt(f),m=p===40,h=p===45||p===46,g=p===47||f===o.length;if(m||h||g){let p=o.slice(d,f);if(l.push(p),t=t||m||h,m){let e=C(o,f),t=o.slice(f,e+1);this.allowUnsafeRegex||n(i(new RegExp(t)),`The regex '${t}' is not safe!`),u.push(S(t)),f=e+1,r=!1}else u.push(r?`(.*?)`:`(${a}|(?:(?!${a}).)*)`),r=!1;let _=f;for(;f<o.length;f++){let e=o.charCodeAt(f);if(e===47)break;if(e===58)if(o.charCodeAt(f+1)===58)f++;else break}let v=o.slice(_,f);if(v&&(v=v.replaceAll(`::`,`:`),v=v.replaceAll(`%`,`%25`),u.push(a=y(v))),d=f+1,g||o.charCodeAt(f)===47||f===o.length){let n=t?`()`+v:v,r=o.slice(e,f);o=o.slice(0,e+1)+n+o.slice(f),e+=n.length;let i=t?RegExp(`^`+u.join(``)+`$`):null;if(s=s.getParametricChild(i,v||null,r),s===null)return null;c=e+1;break}}}}else if(r&&(l.push(`*`),s=s.getWildcardChild(),c=e+1,e!==o.length-1))throw Error(`Wildcard must be the last character in the route`)}this.caseSensitive||(o=o.toLowerCase());for(let t of this.routes){let n=t.opts.constraints||{};if(t.method===e&&t.pattern===o&&a(n,r))return{handler:t.handler,store:t.store,params:t.params}}return null},v.prototype.hasConstraintStrategy=function(e){return this.constrainer.hasConstraintStrategy(e)},v.prototype.addConstraintStrategy=function(e){this.constrainer.addConstraintStrategy(e),this._rebuild(this.routes)},v.prototype.reset=function(){this.trees={},this.routes=[]},v.prototype.off=function(e,t,r){n(typeof t==`string`,`Path should be a string`),n(t.length>0,`The path could not be empty`),n(t[0]===`/`||t[0]===`*`,"The first character of a path should be `/` or `*`"),n(r===void 0||typeof r==`object`&&!Array.isArray(r)&&r!==null,`Constraints should be an object or undefined.`);let i=t.match(h);if(i){n(t.length===i.index+i[0].length,`Optional Parameter needs to be the last parameter of the path`);let a=t.replace(h,`$1$2`),o=t.replace(h,`$2`);this.off(e,a,r),this.off(e,o,r);return}this.ignoreDuplicateSlashes&&(t=b(t)),this.ignoreTrailingSlash&&(t=x(t));let a=Array.isArray(e)?e:[e];for(let e of a)this._off(e,t,r)},v.prototype._off=function(e,t,r){n(typeof e==`string`,`Method should be a string`),n(u.includes(e),`Method '${e}' is not an http method.`);function i(n){return e!==n.method||t!==n.path}function o(e){return i(e)||!a(r,e.opts.constraints||{})}let s=r?o:i,c=this.routes.filter(s);this._rebuild(c)},v.prototype.lookup=function(e,t,n,r){if(typeof n==`function`&&(r=n,n=void 0),r===void 0){let r=this.constrainer.deriveConstraints(e,n),i=this.find(e.method,e.url,r);return this.callHandler(i,e,t,n)}this.constrainer.deriveConstraints(e,n,(i,a)=>{if(i!==null){r(i);return}try{let i=this.find(e.method,e.url,a),o=this.callHandler(i,e,t,n);r(null,o)}catch(e){r(e)}})},v.prototype.callHandler=function(e,t,n,r){return e===null?this._defaultRoute(t,n,r):r===void 0?e.handler(t,n,e.params,e.store,e.searchParams):e.handler.call(r,t,n,e.params,e.store,e.searchParams)},v.prototype.find=function(e,t,n){let r=this.trees[e];if(r===void 0)return null;t.charCodeAt(0)!==47&&(t=t.replace(m,`/`)),this.ignoreDuplicateSlashes&&(t=b(t));let i,a,o;try{i=f(t,this.useSemicolonDelimiter),t=i.path,a=i.querystring,o=i.shouldDecodeParam}catch{return this._onBadUrl(t)}this.ignoreTrailingSlash&&(t=x(t));let s=t;this.caseSensitive===!1&&(t=t.toLowerCase());let l=this.maxParamLength,u=r.prefix.length,d=[],h=t.length,g=[];for(;;){if(u===h&&r.isLeafNode){let e=r.handlerStorage.getMatchingHandler(n);if(e!==null)return{handler:e.handler,store:e.store,params:e._createParamsObject(d),searchParams:this.querystringParser(a)}}let e=r.getNextNode(t,u,g,d.length);if(e===null){if(g.length===0)return null;let t=g.pop();u=t.brotherPathIndex,d.splice(t.paramsCount),e=t.brotherNode}if(r=e,r.kind===c.STATIC){u+=r.prefix.length;continue}if(r.kind===c.WILDCARD){let e=s.slice(u);o&&(e=p(e)),d.push(e),u=h;continue}let i=s.indexOf(`/`,u);i===-1&&(i=h);let f=s.slice(u,i);if(o&&(f=p(f)),r.isRegex){let e=r.regex.exec(f);if(e===null)continue;for(let t=1;t<e.length;t++){let n=e[t];if(n.length>l)return null;d.push(n)}}else{if(f.length>l)return null;d.push(f)}u=i}},v.prototype._rebuild=function(e){this.reset();for(let t of e){let{method:e,path:n,opts:r,handler:i,store:a}=t;this._on(e,n,r,i,a)}},v.prototype._defaultRoute=function(e,t,n){if(this.defaultRoute!==null)return n===void 0?this.defaultRoute(e,t):this.defaultRoute.call(n,e,t);t.statusCode=404,t.end()},v.prototype._onBadUrl=function(e){if(this.onBadUrl===null)return null;let t=this.onBadUrl;return{handler:(n,r,i)=>t(e,n,r),params:{},store:null}},v.prototype.prettyPrint=function(e={}){let t=e.method;e.buildPrettyMeta=this.buildPrettyMeta.bind(this);let n=null;if(t===void 0){let{version:e,host:t,...r}=this.constrainer.strategies;r[d.name]=d;let i=new v({...this._opts,constraints:r}),a=this.routes.map(e=>{let t={...e.opts.constraints,[d.name]:e.method};return{...e,method:`MERGED`,opts:{constraints:t}}});i._rebuild(a),n=i.trees.MERGED}else n=this.trees[t];return n==null?`(empty tree)`:o(n,e)};for(let e in u){if(!u.hasOwnProperty(e))continue;let t=u[e],n=t.toLowerCase();v.prototype[n]=function(e,n,r){return this.on(t,e,n,r)}}v.prototype.all=function(e,t,n){this.on(u,e,t,n)},v.sanitizeUrlPath=function(e,t){let n=f(e,t);return n.shouldDecodeParam?p(n.path):n.path},t.exports=v;function y(e){return e.replace(g,`\\$&`)}function b(e){return e.indexOf(`//`)===-1?e:e.replace(_,`/`)}function x(e){return e.length>1&&e.charCodeAt(e.length-1)===47?e.slice(0,-1):e}function S(e){return e.charCodeAt(1)===94&&(e=e.slice(0,1)+e.slice(2)),e.charCodeAt(e.length-2)===36&&(e=e.slice(0,e.length-2)+e.slice(e.length-1)),e}function C(e,t){let n=1;for(;t<e.length;){if(t++,e.charCodeAt(t)===92){t++;continue}if(e.charCodeAt(t)===41?n--:e.charCodeAt(t)===40&&n++,!n)return t}throw TypeError(`Invalid regexp expression in "`+e+`"`)}function w(e){return!e||!e.store?{}:Object.assign({},e.store)}})),Vm=o(((e,t)=>{function n(e,t,n,r){if(n===void 0){t.header(`content-length`,`0`),r(null,null);return}if(typeof n.resume==`function`){n.on(`error`,e=>{t.log.error({err:e},`Error on Stream found for HEAD route`)}),n.resume(),r(null,null);return}if(typeof n.getReader==`function`){n.cancel(`Stream cancelled by HEAD route`).catch(e=>{t.log.error({err:e},`Error on Stream found for HEAD route`)}),r(null,null);return}let i=``+Buffer.byteLength(n);t.header(`content-length`,i),r(null,null)}function r(e){return e==null?n:Array.isArray(e)?[...e,n]:[e,n]}t.exports={parseHeadOnSendHandlers:r}})),Hm=o(((e,t)=>{let n=Bm(),r=pd(),i=Cu(),{onRequestAbortHookRunner:a,lifecycleHooks:o,preParsingHookRunner:s,onTimeoutHookRunner:c,onRequestHookRunner:l}=hu(),{normalizeSchema:u}=rd(),{parseHeadOnSendHandlers:d}=Vm(),{compileSchemasForValidation:f,compileSchemasForSerialization:p}=Su(),{FST_ERR_SCH_VALIDATION_BUILD:m,FST_ERR_SCH_SERIALIZATION_BUILD:h,FST_ERR_DUPLICATED_ROUTE:g,FST_ERR_INVALID_URL:_,FST_ERR_HOOK_INVALID_HANDLER:v,FST_ERR_ROUTE_OPTIONS_NOT_OBJ:y,FST_ERR_ROUTE_DUPLICATED_HANDLER:b,FST_ERR_ROUTE_HANDLER_NOT_FN:x,FST_ERR_ROUTE_MISSING_HANDLER:S,FST_ERR_ROUTE_METHOD_NOT_SUPPORTED:C,FST_ERR_ROUTE_METHOD_INVALID:w,FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED:T,FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INT:E,FST_ERR_HOOK_INVALID_ASYNC_HANDLER:D}=mu(),{kRoutePrefix:O,kSupportedHTTPMethods:k,kLogLevel:A,kLogSerializers:j,kHooks:M,kSchemaController:ee,kOptions:N,kReplySerializerDefault:te,kReplyIsError:P,kRequestPayloadStream:ne,kDisableRequestLogging:F,kSchemaErrorFormatter:I,kErrorHandler:re,kHasBeenDecorated:L,kRequestAcceptVersion:ie,kRouteByFastify:ae,kRouteContext:R}=du(),{buildErrorHandler:oe}=od(),{createChildLogger:se}=td(),{getGenReqId:ce}=fm(),{FSTDEP022:le}=pu(),ue=[`allowUnsafeRegex`,`buildPrettyMeta`,`caseSensitive`,`constraints`,`defaultRoute`,`ignoreDuplicateSlashes`,`ignoreTrailingSlash`,`maxParamLength`,`onBadUrl`,`querystringParser`,`useSemicolonDelimiter`];function de(e){let t=n(e),i,s,c,C,w,T,E,k,P,ne,R,le,ue,de=!1;return{setup(e,t){i=t.avvio,s=t.fourOhFour,c=e.logger,C=t.hasLogger,w=t.setupResponseListeners,T=t.throwIfAlreadyStarted,le=e.exposeHeadRoutes,E=e.disableRequestLogging,typeof E==`function`&&(k=e.disableRequestLogging),P=e.routerOptions.ignoreTrailingSlash,ne=e.routerOptions.ignoreDuplicateSlashes,R=Object.hasOwn(e,`return503OnClosing`)?e.return503OnClosing:!0,ue=t.keepAliveConnections},routing:t.lookup.bind(t),route:we,hasRoute:Se,prepareRoute:xe,routeHandler:Te,closeRoutes:()=>{de=!0},printRoutes:t.prettyPrint.bind(t),addConstraintStrategy:_e,hasConstraintStrategy:ye,isAsyncConstraint:be,findRoute:Ce};function _e(e){return T(`Cannot add constraint strategy!`),t.addConstraintStrategy(e)}function ye(e){return t.hasConstraintStrategy(e)}function be(){return t.constrainer.asyncStrategiesInUse.size>0}function xe({method:e,url:t,options:n,handler:r,isFastify:i}){if(typeof t!=`string`)throw new _(typeof t);if(!r&&typeof n==`function`)r=n,n={};else if(r&&typeof r==`function`){if(Object.prototype.toString.call(n)!==`[object Object]`)throw new y(e,t);if(n.handler)throw typeof n.handler==`function`?new b(e,t):new x(e,t)}return n=Object.assign({},n,{method:e,url:t,path:t,handler:r||n&&n.handler}),we.call(this,{options:n,isFastify:i})}function Se({options:e}){let n=e.method?.toUpperCase()??``;return t.hasRoute(n,e.url||``,e.constraints)}function Ce(e){let n=t.find(e.method,e.url||``,e.constraints);return n?{handler:n.handler,params:n.params,searchParams:n.searchParams}:null}function we({options:e,isFastify:n}){T(`Cannot add route!`);let a={...e},c=a.url||a.path||``;if(!a.handler)throw new S(a.method,c);if(a.errorHandler!==void 0&&typeof a.errorHandler!=`function`)throw new x(a.method,c);he(a.bodyLimit);let l=a.exposeHeadRoute??le,_=!1,y=!1;if(Array.isArray(a.method))for(let e=0;e<a.method.length;++e)a.method[e]=pe.call(this,a.method[e]),me.call(this,a.method[e],c,a.schema),_=a.method.includes(`GET`),y=a.method.includes(`HEAD`);else a.method=pe.call(this,a.method),me.call(this,a.method,c,a.schema),_=a.method===`GET`,y=a.method===`HEAD`;let b=l&&_?{...e}:null,C=this[O];if(c===`/`&&C.length>0&&a.method!==`HEAD`)switch(a.prefixTrailingSlash){case`slash`:w.call(this,{path:c,isFastify:n});break;case`no-slash`:w.call(this,{path:``,isFastify:n});break;default:w.call(this,{path:``,isFastify:n}),P!==!0&&(ne!==!0||!C.endsWith(`/`))&&w.call(this,{path:c,prefixing:!0,isFastify:n})}else c[0]===`/`&&C.endsWith(`/`)?w.call(this,{path:c.slice(1),isFastify:n}):w.call(this,{path:c,isFastify:n});return this;function w({path:e,prefixing:n=!1,isFastify:c=!1}){let x=C+e;if(a.url=x,a.path=x,a.routePath=e,a.prefix=C,a.logLevel=a.logLevel||this[A],(this[j]||a.logSerializers)&&(a.logSerializers=Object.assign(Object.create(this[j]),a.logSerializers)),a.attachValidation??=!1,n===!1)for(let e of this[M].onRoute)e.call(this,a);for(let e of o)if(a&&e in a){if(Array.isArray(a[e]))for(let t of a[e]){if(typeof t!=`function`)throw new v(e,Object.prototype.toString.call(t));if(e===`onSend`||e===`preSerialization`||e===`onError`||e===`preParsing`){if(t.constructor.name===`AsyncFunction`&&t.length===4)throw new D}else if(e===`onRequestAbort`){if(t.constructor.name===`AsyncFunction`&&t.length!==1)throw new D}else if(t.constructor.name===`AsyncFunction`&&t.length===3)throw new D}else if(a[e]!==void 0&&typeof a[e]!=`function`)throw new v(e,Object.prototype.toString.call(a[e]))}let S=a.constraints||{},w={...a.config,url:x,method:a.method},T=new r({schema:a.schema,handler:a.handler.bind(this),config:w,errorHandler:a.errorHandler,childLoggerFactory:a.childLoggerFactory,bodyLimit:a.bodyLimit,logLevel:a.logLevel,logSerializers:a.logSerializers,attachValidation:a.attachValidation,schemaErrorFormatter:a.schemaErrorFormatter,replySerializer:this[te],validatorCompiler:a.validatorCompiler,serializerCompiler:a.serializerCompiler,exposeHeadRoute:l,prefixTrailingSlash:a.prefixTrailingSlash||`both`,server:this,isFastify:c}),E=t.findRoute(`HEAD`,a.url,S)!==null;try{t.on(a.method,a.url,{constraints:S},Te,T)}catch(e){if(!T[ae])throw e.message.includes(`Method '${a.method}' already declared for route`)?new g(a.method,a.url):e}if(this.after((e,t)=>{T.errorHandler=a.errorHandler?oe(this[re],a.errorHandler):this[re],T._parserOptions.limit=a.bodyLimit||null,T.logLevel=a.logLevel,T.logSerializers=a.logSerializers,T.attachValidation=a.attachValidation,T[te]=this[te],T.schemaErrorFormatter=a.schemaErrorFormatter||this[I]||T.schemaErrorFormatter,i.once(`preReady`,()=>{for(let e of o){let t=this[M][e].concat(a[e]||[]).map(e=>e.bind(this));T[e]=t.length?t:null}for(;!T.Request[L]&&T.Request.parent;)T.Request=T.Request.parent;for(;!T.Reply[L]&&T.Reply.parent;)T.Reply=T.Reply.parent;if(s.setContext(this,T),a.schema){T.schema=u(T.schema,this.initialConfig);let e=this[ee],t=a.schema.body||a.schema.headers||a.schema.querystring||a.schema.params;!a.validatorCompiler&&t&&e.setupValidator(this[N]);try{let t=typeof a?.validatorCompiler==`function`||e.isCustomValidatorCompiler;f(T,a.validatorCompiler||e.validatorCompiler,t)}catch(e){throw new m(a.method,x,e.message)}a.schema.response&&!a.serializerCompiler&&e.setupSerializer(this[N]);try{p(T,a.serializerCompiler||e.serializerCompiler)}catch(e){throw new h(a.method,x,e.message)}}}),t(e)}),l&&_&&!y&&!E){let t=d(b.onSend);xe.call(this,{method:`HEAD`,url:e,options:{...b,onSend:t},isFastify:!0})}}}function Te(e,t,n,r,i){let o=ce(r.server,e),s={level:r.logLevel};r.logSerializers&&(s.serializers=r.logSerializers);let u=se(r,c,e,o,s);if(u[F]=k?!1:E,de===!0&&(e.httpVersionMajor!==2&&t.setHeader(`Connection`,`close`),R)){t.writeHead(503,{"Content-Type":`application/json`,"Content-Length":`80`}),t.end(`{"error":"Service Unavailable","message":"Service Unavailable","statusCode":503}`),u.info({res:{statusCode:503}},`request aborted - refusing to accept new requests as server is closing`);return}String.prototype.toLowerCase.call(e.headers.connection||``)===`keep-alive`&&ue.has(e.socket)===!1&&(ue.add(e.socket),e.socket.on(`close`,ve.bind({keepAliveConnections:ue,socket:e.socket}))),e.headers[ie]!==void 0&&(e.headers[`accept-version`]=e.headers[ie],e.headers[ie]=void 0);let d=new r.Request(o,n,e,i,u,r),f=new r.Reply(t,d,u),p=k?k(d):E;u[F]=p,p===!1&&u.info({req:d},`incoming request`),(C===!0||r.onResponse!==null)&&w(f),r.onRequest===null?ge(null,d,f):l(r.onRequest,d,f,ge),r.onRequestAbort!==null&&e.on(`close`,()=>{e.aborted&&a(r.onRequestAbort,d,z.bind(null,f))}),r.onTimeout!==null&&(d.raw.socket._meta||d.raw.socket.on(`timeout`,fe),d.raw.socket._meta={context:r,request:d,reply:f})}}function z(e,t){t&&e.log.error({err:t},`onRequestAborted hook failed`)}function fe(){let{context:e,request:t,reply:n}=this._meta;c(e.onTimeout,t,n,ye)}function pe(e){if(typeof e!=`string`)throw new w;if(e=e.toUpperCase(),!this[k].bodyless.has(e)&&!this[k].bodywith.has(e))throw new C(e);return e}function me(e,t,n){if(this[k].bodyless.has(e)&&n?.body)throw new T(e,t)}function he(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw new E(e)}function ge(e,t,n){if(n.sent!==!0){if(e!=null){n[P]=!0,n.send(e);return}t[ne]=t.raw,t[R].preParsing===null?i.call(t.server,null,t,n):s(t[R].preParsing,t,n,i.bind(t.server))}}function _e(e,t){let n=e.routerOptions||Object.create(null),r=ue.filter(t=>Object.hasOwn(e,t));r.length>0&&le(r.join(`, `));for(let r of ue)Object.hasOwn(n,r)||(n[r]=e[r]??t[r]);return n}function ve(){this.keepAliveConnections.delete(this.socket)}function ye(){}t.exports={buildRouting:de,validateBodyLimitOption:he,buildRouterOptions:_e}})),Um=o(((e,t)=>{let n=Bm(),r=cd(),i=fd(),a=pd(),{kRoutePrefix:o,kCanSetNotFoundHandler:s,kFourOhFourLevelInstance:c,kFourOhFourContext:l,kHooks:u,kErrorHandler:d}=du(),{lifecycleHooks:f}=hu(),{buildErrorHandler:p}=od(),{FST_ERR_NOT_FOUND:m}=mu(),{createChildLogger:h}=td(),{getGenReqId:g}=fm();function _(e){let{logger:t,disableRequestLogging:_}=e,v=n({onBadUrl:S(),defaultRoute:E}),y=null;return{router:v,setNotFoundHandler:w,setContext:C,arrange404:b};function b(e){e[c]=e,e[s]=!0,v.onBadUrl=v.onBadUrl.bind(e),v.defaultRoute=v.defaultRoute.bind(e)}function x(e,t){let{url:n,method:r}=e.raw,i=`Route ${r}:${n} not found`;(typeof _==`function`?_(e.raw):_)||e.log.info(i),t.code(404).send({message:i,error:`Not Found`,statusCode:404})}function S(){return function(e,n,a){let o=this[c][l],s=g(o.server,n),u=h(o,t,n,s),d=new i(s,null,n,null,u,o),f=new r(a,d,u);y(d,f)}}function C(e,t){let n=Object.assign({},e[l]);n.onSend=t.onSend,t[l]=n}function w(e,t,n,r){this[s]===void 0&&(this[s]=!0),this[l]===void 0&&(this[l]=null);let i=this,a=this[o]||`/`;if(this[s]===!1)throw Error(`Not found handler already set for Fastify instance with prefix: '${a}'`);typeof e==`object`&&(e.preHandler&&(Array.isArray(e.preHandler)?e.preHandler=e.preHandler.map(e=>e.bind(i)):e.preHandler=e.preHandler.bind(i)),e.preValidation&&(Array.isArray(e.preValidation)?e.preValidation=e.preValidation.map(e=>e.bind(i)):e.preValidation=e.preValidation.bind(i))),typeof e==`function`&&(t=e,e=void 0),e||={},t?(this[c][s]=!1,t=t.bind(this),y=t):(t=x,y=x),this.after((i,o)=>{T.call(this,a,e,t,n,r),o(i)})}function T(e,t,n,r,i){let o=new a({schema:t.schema,handler:n,config:t.config||{},server:this});if(r.once(`preReady`,()=>{let e=this[l];for(let n of f){let r=this[u][n].concat(t[n]||[]).map(e=>e.bind(this));e[n]=r.length?r:null}e.errorHandler=t.errorHandler?p(this[d],t.errorHandler):this[d]}),this[l]!==null&&e===`/`){Object.assign(this[l],o);return}this[c][l]=o,v.all(e+(e.endsWith(`/`)?`*`:`/*`),i,o),v.all(e,i,o)}function E(e,n){let a=this[c][l],o=g(a.server,e),s=h(a,t,e,o);s.info({req:e},`incoming request`);let u=new i(o,null,e,null,s,a),d=new r(n,u,s);u.log.warn(`the default handler for 404 did not catch this, this is likely a fastify bug, please report it`),u.log.warn(v.prettyPrint()),d.code(404).send(new m)}}t.exports=_})),Wm=o(((e,t)=>{t.exports=a,t.exports.default=a;let n={type:`object`,additionalProperties:!1,properties:{connectionTimeout:{type:`integer`,default:0},keepAliveTimeout:{type:`integer`,default:72e3},forceCloseConnections:{oneOf:[{type:`string`,pattern:`idle`},{type:`boolean`}]},maxRequestsPerSocket:{type:`integer`,default:0,nullable:!0},requestTimeout:{type:`integer`,default:0},bodyLimit:{type:`integer`,default:1048576},caseSensitive:{type:`boolean`,default:!0},allowUnsafeRegex:{type:`boolean`,default:!1},http2:{type:`boolean`},https:{if:{not:{oneOf:[{type:`boolean`},{type:`null`},{type:`object`,additionalProperties:!1,required:[`allowHTTP1`],properties:{allowHTTP1:{type:`boolean`}}}]}},then:{setDefaultValue:!0}},ignoreTrailingSlash:{type:`boolean`,default:!1},ignoreDuplicateSlashes:{type:`boolean`,default:!1},disableRequestLogging:{default:!1},maxParamLength:{type:`integer`,default:100},onProtoPoisoning:{type:`string`,default:`error`},onConstructorPoisoning:{type:`string`,default:`error`},pluginTimeout:{type:`integer`,default:1e4},requestIdHeader:{anyOf:[{type:`boolean`},{type:`string`}],default:!1},requestIdLogLabel:{type:`string`,default:`reqId`},http2SessionTimeout:{type:`integer`,default:72e3},exposeHeadRoutes:{type:`boolean`,default:!0},useSemicolonDelimiter:{type:`boolean`,default:!1},routerOptions:{type:`object`,additionalProperties:!0,properties:{ignoreTrailingSlash:{type:`boolean`,default:!1},ignoreDuplicateSlashes:{type:`boolean`,default:!1},maxParamLength:{type:`integer`,default:100},allowUnsafeRegex:{type:`boolean`,default:!1},useSemicolonDelimiter:{type:`boolean`,default:!1}}},constraints:{type:`object`,additionalProperties:{type:`object`,required:[`name`,`storage`,`validate`,`deriveConstraint`],additionalProperties:!0,properties:{name:{type:`string`},storage:{},validate:{},deriveConstraint:{}}}}}},r=Object.prototype.hasOwnProperty,i=RegExp(`idle`,`u`);function a(e,{instancePath:t=``,parentData:o,parentDataProperty:s,rootData:c=e}={}){let l=null,u=0;if(u===0)if(e&&typeof e==`object`&&!Array.isArray(e)){e.connectionTimeout===void 0&&(e.connectionTimeout=0),e.keepAliveTimeout===void 0&&(e.keepAliveTimeout=72e3),e.maxRequestsPerSocket===void 0&&(e.maxRequestsPerSocket=0),e.requestTimeout===void 0&&(e.requestTimeout=0),e.bodyLimit===void 0&&(e.bodyLimit=1048576),e.caseSensitive===void 0&&(e.caseSensitive=!0),e.allowUnsafeRegex===void 0&&(e.allowUnsafeRegex=!1),e.ignoreTrailingSlash===void 0&&(e.ignoreTrailingSlash=!1),e.ignoreDuplicateSlashes===void 0&&(e.ignoreDuplicateSlashes=!1),e.disableRequestLogging===void 0&&(e.disableRequestLogging=!1),e.maxParamLength===void 0&&(e.maxParamLength=100),e.onProtoPoisoning===void 0&&(e.onProtoPoisoning=`error`),e.onConstructorPoisoning===void 0&&(e.onConstructorPoisoning=`error`),e.pluginTimeout===void 0&&(e.pluginTimeout=1e4),e.requestIdHeader===void 0&&(e.requestIdHeader=!1),e.requestIdLogLabel===void 0&&(e.requestIdLogLabel=`reqId`),e.http2SessionTimeout===void 0&&(e.http2SessionTimeout=72e3),e.exposeHeadRoutes===void 0&&(e.exposeHeadRoutes=!0),e.useSemicolonDelimiter===void 0&&(e.useSemicolonDelimiter=!1);let o=u;for(let t in e)r.call(n.properties,t)||delete e[t];if(o===u){let n=e.connectionTimeout,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else return a.errors=[{instancePath:t+`/connectionTimeout`,schemaPath:`#/properties/connectionTimeout/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.connectionTimeout=i))}var d=r===u;if(d){let n=e.keepAliveTimeout,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else return a.errors=[{instancePath:t+`/keepAliveTimeout`,schemaPath:`#/properties/keepAliveTimeout/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.keepAliveTimeout=i))}var d=r===u;if(d){if(e.forceCloseConnections!==void 0){let n=e.forceCloseConnections,r=u,o=u,s=!1,c=null,p=u;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else{let e={instancePath:t+`/forceCloseConnections`,schemaPath:`#/properties/forceCloseConnections/oneOf/0/type`,keyword:`type`,params:{type:`string`},message:`must be string`};l===null?l=[e]:l.push(e),u++}i!==void 0&&(n=i,e!==void 0&&(e.forceCloseConnections=i))}if(u===p&&typeof n==`string`&&!i.test(n)){let e={instancePath:t+`/forceCloseConnections`,schemaPath:`#/properties/forceCloseConnections/oneOf/0/pattern`,keyword:`pattern`,params:{pattern:`idle`},message:`must match pattern "idle"`};l===null?l=[e]:l.push(e),u++}var f=p===u;f&&(s=!0,c=0);let m=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else{let e={instancePath:t+`/forceCloseConnections`,schemaPath:`#/properties/forceCloseConnections/oneOf/1/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`};l===null?l=[e]:l.push(e),u++}r!==void 0&&(n=r,e!==void 0&&(e.forceCloseConnections=r))}var f=m===u;if(f&&s?(s=!1,c=[c,1]):f&&(s=!0,c=1),s)u=o,l!==null&&(o?l.length=o:l=null);else{let e={instancePath:t+`/forceCloseConnections`,schemaPath:`#/properties/forceCloseConnections/oneOf`,keyword:`oneOf`,params:{passingSchemas:c},message:`must match exactly one schema in oneOf`};return l===null?l=[e]:l.push(e),u++,a.errors=l,!1}var d=r===u}else var d=!0;if(d){let n=e.maxRequestsPerSocket,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))&&n!==null){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else if(n===``||n===0||n===!1)i=null;else return a.errors=[{instancePath:t+`/maxRequestsPerSocket`,schemaPath:`#/properties/maxRequestsPerSocket/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.maxRequestsPerSocket=i))}var d=r===u;if(d){let n=e.requestTimeout,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else return a.errors=[{instancePath:t+`/requestTimeout`,schemaPath:`#/properties/requestTimeout/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.requestTimeout=i))}var d=r===u;if(d){let n=e.bodyLimit,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else return a.errors=[{instancePath:t+`/bodyLimit`,schemaPath:`#/properties/bodyLimit/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.bodyLimit=i))}var d=r===u;if(d){let n=e.caseSensitive,r=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else return a.errors=[{instancePath:t+`/caseSensitive`,schemaPath:`#/properties/caseSensitive/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(n=r,e!==void 0&&(e.caseSensitive=r))}var d=r===u;if(d){let n=e.allowUnsafeRegex,r=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else return a.errors=[{instancePath:t+`/allowUnsafeRegex`,schemaPath:`#/properties/allowUnsafeRegex/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(n=r,e!==void 0&&(e.allowUnsafeRegex=r))}var d=r===u;if(d){if(e.http2!==void 0){let n=e.http2,r=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else return a.errors=[{instancePath:t+`/http2`,schemaPath:`#/properties/http2/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(n=r,e!==void 0&&(e.http2=r))}var d=r===u}else var d=!0;if(d){if(e.https!==void 0){let n=e.https,r=u,i=u,o=!0,s=u,c=u,f=u,h=u,g=!1,_=null,v=u;if(typeof n!=`boolean`){let t;if(t===void 0)if(n===`false`||n===0||n===null)t=!1;else if(n===`true`||n===1)t=!0;else{let e={};l===null?l=[e]:l.push(e),u++}t!==void 0&&(n=t,e!==void 0&&(e.https=t))}var p=v===u;p&&(g=!0,_=0);let y=u;if(n!==null){let t;if(t===void 0)if(n===``||n===0||n===!1)t=null;else{let e={};l===null?l=[e]:l.push(e),u++}t!==void 0&&(n=t,e!==void 0&&(e.https=t))}var p=y===u;if(p&&g)g=!1,_=[_,1];else{p&&(g=!0,_=1);let e=u;if(u===e)if(n&&typeof n==`object`&&!Array.isArray(n))if(n.allowHTTP1===void 0){let e={};l===null?l=[e]:l.push(e),u++}else{let e=u;for(let e in n)e!==`allowHTTP1`&&delete n[e];if(e===u&&n.allowHTTP1!==void 0){let e=n.allowHTTP1;if(typeof e!=`boolean`){let t;if(t===void 0)if(e===`false`||e===0||e===null)t=!1;else if(e===`true`||e===1)t=!0;else{let e={};l===null?l=[e]:l.push(e),u++}t!==void 0&&(e=t,n!==void 0&&(n.allowHTTP1=t))}}}else{let e={};l===null?l=[e]:l.push(e),u++}var p=e===u;p&&g?(g=!1,_=[_,2]):p&&(g=!0,_=2)}if(g)u=h,l!==null&&(h?l.length=h:l=null);else{let e={};l===null?l=[e]:l.push(e),u++}if(f===u){let e={};l===null?l=[e]:l.push(e),u++}else u=c,l!==null&&(c?l.length=c:l=null);var m=s===u;if(u=i,l!==null&&(i?l.length=i:l=null),m){let t=u;e.https=!0;var m=t===u;o=m}if(!o){let e={instancePath:t+`/https`,schemaPath:`#/properties/https/if`,keyword:`if`,params:{failingKeyword:`then`},message:`must match "then" schema`};return l===null?l=[e]:l.push(e),u++,a.errors=l,!1}var d=r===u}else var d=!0;if(d){let n=e.ignoreTrailingSlash,r=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else return a.errors=[{instancePath:t+`/ignoreTrailingSlash`,schemaPath:`#/properties/ignoreTrailingSlash/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(n=r,e!==void 0&&(e.ignoreTrailingSlash=r))}var d=r===u;if(d){let n=e.ignoreDuplicateSlashes,r=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else return a.errors=[{instancePath:t+`/ignoreDuplicateSlashes`,schemaPath:`#/properties/ignoreDuplicateSlashes/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(n=r,e!==void 0&&(e.ignoreDuplicateSlashes=r))}var d=r===u;if(d){let n=e.maxParamLength,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else return a.errors=[{instancePath:t+`/maxParamLength`,schemaPath:`#/properties/maxParamLength/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.maxParamLength=i))}var d=r===u;if(d){let n=e.onProtoPoisoning,r=u;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else return a.errors=[{instancePath:t+`/onProtoPoisoning`,schemaPath:`#/properties/onProtoPoisoning/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.onProtoPoisoning=i))}var d=r===u;if(d){let n=e.onConstructorPoisoning,r=u;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else return a.errors=[{instancePath:t+`/onConstructorPoisoning`,schemaPath:`#/properties/onConstructorPoisoning/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.onConstructorPoisoning=i))}var d=r===u;if(d){let n=e.pluginTimeout,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else return a.errors=[{instancePath:t+`/pluginTimeout`,schemaPath:`#/properties/pluginTimeout/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.pluginTimeout=i))}var d=r===u;if(d){let n=e.requestIdHeader,r=u,i=u,o=!1,s=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else{let e={instancePath:t+`/requestIdHeader`,schemaPath:`#/properties/requestIdHeader/anyOf/0/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`};l===null?l=[e]:l.push(e),u++}r!==void 0&&(n=r,e!==void 0&&(e.requestIdHeader=r))}var h=s===u;if(o||=h,!o){let r=u;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else{let e={instancePath:t+`/requestIdHeader`,schemaPath:`#/properties/requestIdHeader/anyOf/1/type`,keyword:`type`,params:{type:`string`},message:`must be string`};l===null?l=[e]:l.push(e),u++}i!==void 0&&(n=i,e!==void 0&&(e.requestIdHeader=i))}var h=r===u;o||=h}if(o)u=i,l!==null&&(i?l.length=i:l=null);else{let e={instancePath:t+`/requestIdHeader`,schemaPath:`#/properties/requestIdHeader/anyOf`,keyword:`anyOf`,params:{},message:`must match a schema in anyOf`};return l===null?l=[e]:l.push(e),u++,a.errors=l,!1}var d=r===u;if(d){let n=e.requestIdLogLabel,r=u;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else return a.errors=[{instancePath:t+`/requestIdLogLabel`,schemaPath:`#/properties/requestIdLogLabel/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.requestIdLogLabel=i))}var d=r===u;if(d){let n=e.http2SessionTimeout,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else return a.errors=[{instancePath:t+`/http2SessionTimeout`,schemaPath:`#/properties/http2SessionTimeout/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.http2SessionTimeout=i))}var d=r===u;if(d){let n=e.exposeHeadRoutes,r=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else return a.errors=[{instancePath:t+`/exposeHeadRoutes`,schemaPath:`#/properties/exposeHeadRoutes/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(n=r,e!==void 0&&(e.exposeHeadRoutes=r))}var d=r===u;if(d){let n=e.useSemicolonDelimiter,r=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else return a.errors=[{instancePath:t+`/useSemicolonDelimiter`,schemaPath:`#/properties/useSemicolonDelimiter/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(n=r,e!==void 0&&(e.useSemicolonDelimiter=r))}var d=r===u;if(d){if(e.routerOptions!==void 0){let n=e.routerOptions,r=u;if(u===r)if(n&&typeof n==`object`&&!Array.isArray(n)){n.ignoreTrailingSlash===void 0&&(n.ignoreTrailingSlash=!1),n.ignoreDuplicateSlashes===void 0&&(n.ignoreDuplicateSlashes=!1),n.maxParamLength===void 0&&(n.maxParamLength=100),n.allowUnsafeRegex===void 0&&(n.allowUnsafeRegex=!1),n.useSemicolonDelimiter===void 0&&(n.useSemicolonDelimiter=!1);let e=n.ignoreTrailingSlash,r=u;if(typeof e!=`boolean`){let r;if(r===void 0)if(e===`false`||e===0||e===null)r=!1;else if(e===`true`||e===1)r=!0;else return a.errors=[{instancePath:t+`/routerOptions/ignoreTrailingSlash`,schemaPath:`#/properties/routerOptions/properties/ignoreTrailingSlash/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(e=r,n!==void 0&&(n.ignoreTrailingSlash=r))}var g=r===u;if(g){let e=n.ignoreDuplicateSlashes,r=u;if(typeof e!=`boolean`){let r;if(r===void 0)if(e===`false`||e===0||e===null)r=!1;else if(e===`true`||e===1)r=!0;else return a.errors=[{instancePath:t+`/routerOptions/ignoreDuplicateSlashes`,schemaPath:`#/properties/routerOptions/properties/ignoreDuplicateSlashes/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(e=r,n!==void 0&&(n.ignoreDuplicateSlashes=r))}var g=r===u;if(g){let e=n.maxParamLength,r=u;if(!(typeof e==`number`&&!(e%1)&&!isNaN(e)&&isFinite(e))){let r=typeof e,i;if(i===void 0)if(r===`boolean`||e===null||r===`string`&&e&&e==+e&&!(e%1))i=+e;else return a.errors=[{instancePath:t+`/routerOptions/maxParamLength`,schemaPath:`#/properties/routerOptions/properties/maxParamLength/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(e=i,n!==void 0&&(n.maxParamLength=i))}var g=r===u;if(g){let e=n.allowUnsafeRegex,r=u;if(typeof e!=`boolean`){let r;if(r===void 0)if(e===`false`||e===0||e===null)r=!1;else if(e===`true`||e===1)r=!0;else return a.errors=[{instancePath:t+`/routerOptions/allowUnsafeRegex`,schemaPath:`#/properties/routerOptions/properties/allowUnsafeRegex/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(e=r,n!==void 0&&(n.allowUnsafeRegex=r))}var g=r===u;if(g){let e=n.useSemicolonDelimiter,r=u;if(typeof e!=`boolean`){let r;if(r===void 0)if(e===`false`||e===0||e===null)r=!1;else if(e===`true`||e===1)r=!0;else return a.errors=[{instancePath:t+`/routerOptions/useSemicolonDelimiter`,schemaPath:`#/properties/routerOptions/properties/useSemicolonDelimiter/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(e=r,n!==void 0&&(n.useSemicolonDelimiter=r))}var g=r===u}}}}}else return a.errors=[{instancePath:t+`/routerOptions`,schemaPath:`#/properties/routerOptions/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var d=r===u}else var d=!0;if(d)if(e.constraints!==void 0){let n=e.constraints,r=u;if(u===r)if(n&&typeof n==`object`&&!Array.isArray(n))for(let e in n){let r=n[e],i=u;if(u===i)if(r&&typeof r==`object`&&!Array.isArray(r)){let n;if(r.name===void 0&&(n=`name`)||r.storage===void 0&&(n=`storage`)||r.validate===void 0&&(n=`validate`)||r.deriveConstraint===void 0&&(n=`deriveConstraint`))return a.errors=[{instancePath:t+`/constraints/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),schemaPath:`#/properties/constraints/additionalProperties/required`,keyword:`required`,params:{missingProperty:n},message:`must have required property '`+n+`'`}],!1;if(r.name!==void 0){let n=r.name;if(typeof n!=`string`){let i=typeof n,o;if(o===void 0)if(i==`number`||i==`boolean`)o=``+n;else if(n===null)o=``;else return a.errors=[{instancePath:t+`/constraints/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`)+`/name`,schemaPath:`#/properties/constraints/additionalProperties/properties/name/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;o!==void 0&&(n=o,r!==void 0&&(r.name=o))}}}else return a.errors=[{instancePath:t+`/constraints/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),schemaPath:`#/properties/constraints/additionalProperties/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;if(i!==u)break}else return a.errors=[{instancePath:t+`/constraints`,schemaPath:`#/properties/constraints/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var d=r===u}else var d=!0}}}}}}}}}}}}}}}}}}}}}}}else return a.errors=[{instancePath:t,schemaPath:`#/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;return a.errors=l,u===0}t.exports.defaultInitOptions={connectionTimeout:0,keepAliveTimeout:72e3,maxRequestsPerSocket:0,requestTimeout:0,bodyLimit:1048576,caseSensitive:!0,allowUnsafeRegex:!1,disableRequestLogging:!1,ignoreTrailingSlash:!1,ignoreDuplicateSlashes:!1,maxParamLength:100,onProtoPoisoning:`error`,onConstructorPoisoning:`error`,pluginTimeout:1e4,requestIdHeader:!1,requestIdLogLabel:`reqId`,http2SessionTimeout:72e3,exposeHeadRoutes:!0,useSemicolonDelimiter:!1,allowErrorHandlerOverride:!0,routerOptions:{ignoreTrailingSlash:!1,ignoreDuplicateSlashes:!1,maxParamLength:100,allowUnsafeRegex:!1,useSemicolonDelimiter:!1}}})),Gm=o(((e,t)=>{let n=Wm(),r=nd()({circles:!0,proto:!1}),{FST_ERR_INIT_OPTS_INVALID:i}=mu();function a(e){let t=r(e);if(!n(t)){let e=new i(JSON.stringify(n.errors.map(e=>e.message)));throw e.errors=n.errors,e}return o(t)}function o(e){let t=Object.getOwnPropertyNames(e);for(let n of t){let t=e[n];ArrayBuffer.isView(t)&&!(t instanceof DataView)||(e[n]=t&&typeof t==`object`?o(t):t)}return Object.freeze(e)}t.exports=a,t.exports.defaultInitOptions=n.defaultInitOptions,t.exports.utils={deepFreezeObject:o}})),Km=o(((e,t)=>{let{kAvvioBoot:n,kChildren:r,kRoutePrefix:i,kLogLevel:a,kLogSerializers:o,kHooks:s,kSchemaController:c,kContentTypeParser:l,kReply:u,kRequest:d,kFourOhFour:f,kPluginNameChain:p,kErrorHandlerAlreadySet:m}=du(),h=cd(),g=fd(),_=yp(),v=gd(),{buildHooks:y}=hu(),b=dm();t.exports=function(e,t,S){let C=b.registerPlugin.call(e,t),w=b.getPluginName(t)||b.getFuncPreview(t);if(C)return e[p].push(w),e;let T=Object.create(e);e[r].push(T),T.ready=e[n].bind(T),T[r]=[],T[u]=h.buildReply(T[u]),T[d]=g.buildRequest(T[d]),T[l]=v.helpers.buildContentTypeParser(T[l]),T[s]=y(T[s]),T[i]=x(T[i],S.prefix),T[a]=S.logLevel||T[a],T[c]=_.buildSchemaController(e[c]),T.getSchema=T[c].getSchema.bind(T[c]),T.getSchemas=T[c].getSchemas.bind(T[c]),T[b.kRegisteredPlugins]=Object.create(T[b.kRegisteredPlugins]),T[p]=[w],T[m]=!1,(T[o]||S.logSerializers)&&(T[o]=Object.assign(Object.create(T[o]),S.logSerializers)),S.prefix&&T[f].arrange404(T);for(let t of T[s].onRegister)t.call(e,T,S);return T};function x(e,t){return t?(e.endsWith(`/`)&&t[0]===`/`?t=t.slice(1):t[0]!==`/`&&(t=`/`+t),e+t):e}})),qm=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.parseCookie=c,e.parse=c,e.stringifyCookie=l,e.stringifySetCookie=u,e.serialize=u,e.parseSetCookie=d,e.stringifySetCookie=u,e.serialize=u;let t=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,n=/^[\u0021-\u003A\u003C-\u007E]*$/,r=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,i=/^[\u0020-\u003A\u003D-\u007E]*$/,a=/^-?\d+$/,o=Object.prototype.toString,s=(()=>{let e=function(){};return e.prototype=Object.create(null),e})();function c(e,t){let n=new s,r=e.length;if(r<2)return n;let i=t?.decode||h,a=0;do{let t=p(e,a,r);if(t===-1)break;let o=f(e,a,r);if(t>o){a=e.lastIndexOf(`;`,t-1)+1;continue}let s=m(e,a,t);n[s]===void 0&&(n[s]=i(m(e,t+1,o))),a=o+1}while(a<r);return n}function l(e,r){let i=r?.encode||encodeURIComponent,a=[];for(let r of Object.keys(e)){let o=e[r];if(o===void 0)continue;if(!t.test(r))throw TypeError(`cookie name is invalid: ${r}`);let s=i(o);if(!n.test(s))throw TypeError(`cookie val is invalid: ${o}`);a.push(`${r}=${s}`)}return a.join(`; `)}function u(e,a,o){let s=typeof e==`object`?e:{...o,name:e,value:String(a)},c=(typeof a==`object`?a:o)?.encode||encodeURIComponent;if(!t.test(s.name))throw TypeError(`argument name is invalid: ${s.name}`);let l=s.value?c(s.value):``;if(!n.test(l))throw TypeError(`argument val is invalid: ${s.value}`);let u=s.name+`=`+l;if(s.maxAge!==void 0){if(!Number.isInteger(s.maxAge))throw TypeError(`option maxAge is invalid: ${s.maxAge}`);u+=`; Max-Age=`+s.maxAge}if(s.domain){if(!r.test(s.domain))throw TypeError(`option domain is invalid: ${s.domain}`);u+=`; Domain=`+s.domain}if(s.path){if(!i.test(s.path))throw TypeError(`option path is invalid: ${s.path}`);u+=`; Path=`+s.path}if(s.expires){if(!g(s.expires)||!Number.isFinite(s.expires.valueOf()))throw TypeError(`option expires is invalid: ${s.expires}`);u+=`; Expires=`+s.expires.toUTCString()}if(s.httpOnly&&(u+=`; HttpOnly`),s.secure&&(u+=`; Secure`),s.partitioned&&(u+=`; Partitioned`),s.priority)switch(typeof s.priority==`string`?s.priority.toLowerCase():void 0){case`low`:u+=`; Priority=Low`;break;case`medium`:u+=`; Priority=Medium`;break;case`high`:u+=`; Priority=High`;break;default:throw TypeError(`option priority is invalid: ${s.priority}`)}if(s.sameSite)switch(typeof s.sameSite==`string`?s.sameSite.toLowerCase():s.sameSite){case!0:case`strict`:u+=`; SameSite=Strict`;break;case`lax`:u+=`; SameSite=Lax`;break;case`none`:u+=`; SameSite=None`;break;default:throw TypeError(`option sameSite is invalid: ${s.sameSite}`)}return u}function d(e,t){let n=t?.decode||h,r=e.length,i=f(e,0,r),o=p(e,0,i),s=o===-1?{name:``,value:n(m(e,0,i))}:{name:m(e,0,o),value:n(m(e,o+1,i))},c=i+1;for(;c<r;){let t=f(e,c,r),n=p(e,c,t),i=n===-1?m(e,c,t):m(e,c,n),o=n===-1?void 0:m(e,n+1,t);switch(i.toLowerCase()){case`httponly`:s.httpOnly=!0;break;case`secure`:s.secure=!0;break;case`partitioned`:s.partitioned=!0;break;case`domain`:s.domain=o;break;case`path`:s.path=o;break;case`max-age`:o&&a.test(o)&&(s.maxAge=Number(o));break;case`expires`:if(!o)break;let e=new Date(o);Number.isFinite(e.valueOf())&&(s.expires=e);break;case`priority`:if(!o)break;let t=o.toLowerCase();(t===`low`||t===`medium`||t===`high`)&&(s.priority=t);break;case`samesite`:if(!o)break;let n=o.toLowerCase();(n===`lax`||n===`strict`||n===`none`)&&(s.sameSite=n);break}c=t+1}return s}function f(e,t,n){let r=e.indexOf(`;`,t);return r===-1?n:r}function p(e,t,n){let r=e.indexOf(`=`,t);return r<n?r:-1}function m(e,t,n){let r=t,i=n;do{let t=e.charCodeAt(r);if(t!==32&&t!==9)break}while(++r<i);for(;i>r;){let t=e.charCodeAt(i-1);if(t!==32&&t!==9)break;i--}return e.slice(r,i)}function h(e){if(e.indexOf(`%`)===-1)return e;try{return decodeURIComponent(e)}catch{return e}}function g(e){return o.call(e)===`[object Date]`}})),Jm=o(((e,t)=>{let{format:n}=require(`node:util`);function r(e){return i({...e,name:`DeprecationWarning`})}function i({name:e,code:t,message:r,unlimited:i=!1}={}){if(!e)throw Error(`Warning name must not be empty`);if(!t)throw Error(`Warning code must not be empty`);if(!r)throw Error(`Warning message must not be empty`);if(typeof i!=`boolean`)throw Error(`Warning opts.unlimited must be a boolean`);t=t.toUpperCase();let a={[e]:function(e,t,n){o.emitted===!0&&o.unlimited!==!0||(o.emitted=!0,process.emitWarning(o.format(e,t,n),o.name,o.code))}};i&&(a={[e]:function(e,t,n){o.emitted=!0,process.emitWarning(o.format(e,t,n),o.name,o.code)}});let o=a[e];return o.emitted=!1,o.message=r,o.unlimited=i,o.code=t,o.format=function(e,t,i){let a;return a=e&&t&&i?n(r,e,t,i):e&&t?n(r,e,t):e?n(r,e):r,a},o}let a={createWarning:i,createDeprecation:r};t.exports=a,t.exports.default=a,t.exports.processWarning=a})),Ym=o(((e,t)=>{let{URL:n}=require(`node:url`),r=`http://localhost`;t.exports=function(e,t){(typeof e==`string`||Object.prototype.toString.call(e)===`[object String]`)&&e.startsWith(`//`)&&(e=r+e);let i=typeof e==`object`?Object.assign(new n(r),e):new n(e,r);if(typeof t==`string`){t=new URLSearchParams(t);for(let e of t.keys()){i.searchParams.delete(e);for(let n of t.getAll(e))i.searchParams.append(e,n)}}else{let n=Object.assign({},e.query,t);for(let e in n){let t=n[e];if(Array.isArray(t)){i.searchParams.delete(e);for(let n of t)i.searchParams.append(e,n)}else i.searchParams.set(e,t)}}return i}})),Xm=o(((e,t)=>{let{randomUUID:n}=require(`node:crypto`),{Readable:r}=require(`node:stream`),i;function a(e){return e&&typeof e==`object`&&typeof e.append==`function`&&typeof e.delete==`function`&&typeof e.get==`function`&&typeof e.getAll==`function`&&typeof e.has==`function`&&typeof e.set==`function`&&e[Symbol.toStringTag]===`FormData`}function o(e){i??=new TextEncoder;let t=`----formdata-${n()}`,a=`--${t}\r\nContent-Disposition: form-data`,o=e=>e.replace(/\n/g,`%0A`).replace(/\r/g,`%0D`).replace(/"/g,`%22`),s=e=>e.replace(/\r?\n|\r/g,`\r
|
|
452
|
-
`),c=new Uint8Array([13,10]);async function*l(){for(let[t,n]of e)if(typeof n==`string`)yield i.encode(`${a}; name="${o(s(t))}"\r\n\r\n`),yield i.encode(`${s(n)}\r\n`);else{let e=`${a}; name="${o(s(t))}"`;n.name&&(e+=`; filename="${o(n.name)}"`),e+=`\r\nContent-Type: ${n.type||`application/octet-stream`}\r\n\r\n`,yield i.encode(e),n.stream?yield*n.stream():yield n,yield c}yield i.encode(`--${t}--`)}return{stream:r.from(l()),contentType:`multipart/form-data; boundary=${t}`}}t.exports.isFormDataLike=a,t.exports.formDataToStream=o})),Zm=o(((e,t)=>{let{Readable:n,addAbortSignal:r}=require(`node:stream`),i=require(`node:util`),a=qm(),o=require(`node:assert`),{createDeprecation:s}=Jm(),c=Ym(),{isFormDataLike:l,formDataToStream:u}=Xm(),{EventEmitter:d}=require(`node:events`),f=s({name:`FastifyDeprecationLightMyRequest`,code:`FST_LIGHTMYREQUEST_DEP01`,message:`You are accessing "request.connection", use "request.socket" instead.`});function p(e){return e.port?e.host:e.hostname+(e.protocol===`https:`?`:443`:`:80`)}var m=class extends d{constructor(e){super(),this.remoteAddress=e}};function h(e){return new t(this);function t(t){g.call(t,{...e,Request:void 0}),Object.assign(this,t);for(let e of Object.keys(g.prototype))this.constructor.prototype[e]=g.prototype[e];return i.inherits(this.constructor,e.Request),this}}function g(e){n.call(this,{autoDestroy:!1});let t=c(e.url||e.path,e.query);this.url=t.pathname+t.search,this.aborted=!1,this.httpVersionMajor=1,this.httpVersionMinor=1,this.httpVersion=`1.1`,this.method=e.method?e.method.toUpperCase():`GET`,this.headers={},this.rawHeaders=[];let i=e.headers||{};for(let e in i){let t=e.toLowerCase();if((t===`user-agent`||t===`content-type`)&&i[e]===void 0){this.headers[t]=void 0;continue}let n=i[e];o(n!==void 0,`invalid value "undefined" for header `+e),this.headers[t]=``+n}if(`user-agent`in this.headers||(this.headers[`user-agent`]=`lightMyRequest`),this.headers.host=this.headers.host||e.authority||p(t),e.cookies){let{cookies:t}=e,n=Object.keys(t).map(e=>a.serialize(e,t[e]));this.headers.cookie&&n.unshift(this.headers.cookie),this.headers.cookie=n.join(`; `)}this.socket=new m(e.remoteAddress||`127.0.0.1`),Object.defineProperty(this,`connection`,{get(){return f(),this.socket},configurable:!0});let s=e.payload||e.body||null,d=s&&typeof s.resume==`function`;if(l(s)){let e=u(s);s=e.stream,d=!0,this.headers[`content-type`]=e.contentType,this.headers[`transfer-encoding`]=`chunked`}s&&typeof s!=`string`&&!d&&!Buffer.isBuffer(s)&&(s=JSON.stringify(s),`content-type`in this.headers||(this.headers[`content-type`]=`application/json`)),s&&!d&&!Object.hasOwn(this.headers,`content-length`)&&(this.headers[`content-length`]=(Buffer.isBuffer(s)?s.length:Buffer.byteLength(s)).toString());for(let e of Object.keys(this.headers))this.rawHeaders.push(e,this.headers[e]);this._lightMyRequest={payload:s,isDone:!1,simulate:e.simulate||{},payloadAsStream:e.payloadAsStream,signal:e.signal};let h=e.signal;h&&r(h,this);{let e=this._lightMyRequest.payload;e?._readableState?(this._read=_,e.on(`error`,e=>{this.destroy(e)}),e.on(`end`,()=>{this.push(null)})):this._read=v}return this}function _(){let e=this._lightMyRequest.payload,t=!0,n=!1,r;for(;t&&(r=e.read());)n=!0,t=this.push(r);t&&!n&&this._lightMyRequest.payload.once(`readable`,this._read.bind(this))}function v(){setImmediate(()=>{if(this._lightMyRequest.isDone){this._lightMyRequest.simulate.end!==!1&&this.push(null);return}this._lightMyRequest.isDone=!0,this._lightMyRequest.payload&&(this._lightMyRequest.simulate.split?(this.push(this._lightMyRequest.payload.slice(0,1)),this.push(this._lightMyRequest.payload.slice(1))):this.push(this._lightMyRequest.payload)),this._lightMyRequest.simulate.error&&this.emit(`error`,Error(`Simulated`)),this._lightMyRequest.simulate.close&&this.emit(`close`),this._lightMyRequest.simulate.end!==!1&&this.push(null)})}i.inherits(g,n),i.inherits(h,g),g.prototype.destroy=function(e){this.destroyed||this._lightMyRequest.isDone||(this.destroyed=!0,e&&(this._error=!0,process.nextTick(()=>this.emit(`error`,e))),process.nextTick(()=>this.emit(`close`)))},t.exports=g,t.exports.Request=g,t.exports.CustomRequest=h})),Qm=o(((e,t)=>{var n={decodeValues:!0,map:!1,silent:!1};function r(e){return typeof e!=`string`||e in{}}function i(){return Object.create(null)}function a(e){return typeof e==`string`&&!!e.trim()}function o(e,t){var o=e.split(`;`).filter(a),c=s(o.shift()),l=c.name,u=c.value;if(t=t?Object.assign({},n,t):n,r(l))return null;try{u=t.decodeValues?decodeURIComponent(u):u}catch(e){console.error(`set-cookie-parser: failed to decode cookie value. Set options.decodeValues=false to disable decoding.`,e)}var d=i();return d.name=l,d.value=u,o.forEach(function(e){var t=e.split(`=`),n=t.shift().trimLeft().toLowerCase();if(!r(n)){var i=t.join(`=`);if(n===`expires`)d.expires=new Date(i);else if(n===`max-age`){var a=parseInt(i,10);Number.isNaN(a)||(d.maxAge=a)}else n===`secure`?d.secure=!0:n===`httponly`?d.httpOnly=!0:n===`samesite`?d.sameSite=i:n===`partitioned`?d.partitioned=!0:n&&(d[n]=i)}}),d}function s(e){var t=``,n=``,r=e.split(`=`);return r.length>1?(t=r.shift(),n=r.join(`=`)):n=e,{name:t,value:n}}function c(e,t){if(t=t?Object.assign({},n,t):n,!e)return t.map?i():[];if(e.headers)if(typeof e.headers.getSetCookie==`function`)e=e.headers.getSetCookie();else if(e.headers[`set-cookie`])e=e.headers[`set-cookie`];else{var s=e.headers[Object.keys(e.headers).find(function(e){return e.toLowerCase()===`set-cookie`})];!s&&e.headers.cookie&&!t.silent&&console.warn(`Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning.`),e=s}if(Array.isArray(e)||(e=[e]),t.map){var c=i();return e.filter(a).reduce(function(e,n){var i=o(n,t);return i&&!r(i.name)&&(e[i.name]=i),e},c)}else return e.filter(a).map(function(e){return o(e,t)}).filter(Boolean)}function l(e){if(Array.isArray(e))return e;if(typeof e!=`string`)return[];var t=[],n=0,r,i,a,o,s;function c(){for(;n<e.length&&/\s/.test(e.charAt(n));)n+=1;return n<e.length}function l(){return i=e.charAt(n),i!==`=`&&i!==`;`&&i!==`,`}for(;n<e.length;){for(r=n,s=!1;c();)if(i=e.charAt(n),i===`,`){for(a=n,n+=1,c(),o=n;n<e.length&&l();)n+=1;n<e.length&&e.charAt(n)===`=`?(s=!0,n=o,t.push(e.substring(r,a)),r=n):n=a+1}else n+=1;(!s||n>=e.length)&&t.push(e.substring(r,e.length))}return t}t.exports=c,t.exports.parse=c,t.exports.parseString=o,t.exports.splitCookiesString=l})),$m=o(((e,t)=>{let n=require(`node:http`),{Writable:r,Readable:i,addAbortSignal:a}=require(`node:stream`),o=require(`node:util`),s=Qm();function c(e,t,r){if(n.ServerResponse.call(this,e),e._lightMyRequest?.payloadAsStream){this._lightMyRequest={headers:null,trailers:{},stream:new i({read:this.emit.bind(this,`drain`)})};let t=e._lightMyRequest.signal;t&&a(t,this._lightMyRequest.stream)}else this._lightMyRequest={headers:null,trailers:{},payloadChunks:[]};this.setHeader(`foo`,`bar`),this.removeHeader(`foo`),this.assignSocket(u()),this._promiseCallback=typeof r==`function`;let o=!1,s=e=>{if(!o){if(o=!0,this._promiseCallback)return process.nextTick(()=>t(e));process.nextTick(()=>t(null,e))}};this._lightMyRequest.onEndSuccess=s;let c=!1,d=e=>{if(o){this._lightMyRequest.stream&&!c&&(e||(e=Error(`response destroyed before completion`),e.code=`LIGHT_ECONNRESET`),this._lightMyRequest.stream.destroy(e),this._lightMyRequest.stream.on(`error`,()=>{}));return}if(o=!0,e||(e=Error(`response destroyed before completion`),e.code=`LIGHT_ECONNRESET`),this._promiseCallback)return process.nextTick(()=>r(e));process.nextTick(()=>t(e,null))};this._lightMyRequest.stream?this.once(`finish`,()=>{c=!0,this._lightMyRequest.stream.push(null)}):this.once(`finish`,()=>{let t=l(this);t.raw.req=e,s(t)}),this.connection.once(`error`,d),this.once(`error`,d),this.once(`close`,d)}o.inherits(c,n.ServerResponse),c.prototype.setTimeout=function(e,t){return this.timeoutHandle=setTimeout(()=>{this.emit(`timeout`)},e),this.on(`timeout`,t),this},c.prototype.writeHead=function(){let e=n.ServerResponse.prototype.writeHead.apply(this,arguments);return f(this),this._lightMyRequest.stream&&this._lightMyRequest.onEndSuccess(l(this)),e},c.prototype.write=function(e,t,r){return this.timeoutHandle&&clearTimeout(this.timeoutHandle),n.ServerResponse.prototype.write.call(this,e,t,r),this._lightMyRequest.stream?this._lightMyRequest.stream.push(Buffer.from(e,t)):(this._lightMyRequest.payloadChunks.push(Buffer.from(e,t)),!0)},c.prototype.end=function(e,t,r){e&&this.write(e,t),n.ServerResponse.prototype.end.call(this,r),this.emit(`finish`),this.destroy()},c.prototype.destroy=function(e){this.destroyed||(this.destroyed=!0,e&&process.nextTick(()=>this.emit(`error`,e)),process.nextTick(()=>this.emit(`close`)))},c.prototype.addTrailers=function(e){for(let t in e)this._lightMyRequest.trailers[t.toLowerCase().trim()]=e[t].toString().trim()};function l(e){e._lightMyRequest.headers===null&&f(e),d(e);let t={raw:{res:e},headers:e._lightMyRequest.headers,statusCode:e.statusCode,statusMessage:e.statusMessage,trailers:{},get cookies(){return s.parse(this)}};if(t.trailers=e._lightMyRequest.trailers,e._lightMyRequest.payloadChunks){let n=Buffer.concat(e._lightMyRequest.payloadChunks);t.rawPayload=n,t.payload=n.toString(),t.body=t.payload,t.json=function(){return JSON.parse(t.payload)}}else t.json=function(){throw Error(`Response payload is not available with payloadAsStream: true`)};return t.stream=function(){return e._lightMyRequest.stream?e._lightMyRequest.stream:i.from(e._lightMyRequest.payloadChunks)},t}function u(){return new r({write(e,t,n){setImmediate(n)}})}function d(e){let t=e._lightMyRequest.headers;for(let e of Object.keys(t)){let n=t[e];Array.isArray(n)?t[e]=n.map(e=>``+e):t[e]=``+n}}function f(e){e._lightMyRequest.headers=Object.assign({},e.getHeaders()),[`Date`,`Connection`,`Transfer-Encoding`].forEach(t=>{let n=RegExp(`\\r\\n`+t+`: ([^\\r]*)\\r\\n`),r=e._header?.match(n);r&&(e._lightMyRequest.headers[t.toLowerCase()]=r[1])})}t.exports=c})),eh=o(((e,t)=>{t.exports=r,t.exports.default=r;let n={type:`object`,properties:{url:{oneOf:[{type:`string`},{type:`object`,properties:{protocol:{type:`string`},hostname:{type:`string`},pathname:{type:`string`}},additionalProperties:!0,required:[`pathname`]}]},path:{oneOf:[{type:`string`},{type:`object`,properties:{protocol:{type:`string`},hostname:{type:`string`},pathname:{type:`string`}},additionalProperties:!0,required:[`pathname`]}]},cookies:{type:`object`,additionalProperties:!0},headers:{type:`object`,additionalProperties:!0},query:{anyOf:[{type:`object`,additionalProperties:!0},{type:`string`}]},simulate:{type:`object`,properties:{end:{type:`boolean`},split:{type:`boolean`},error:{type:`boolean`},close:{type:`boolean`}}},authority:{type:`string`},remoteAddress:{type:`string`},method:{type:`string`,enum:`ACL.BIND.CHECKOUT.CONNECT.COPY.DELETE.GET.HEAD.LINK.LOCK.M-SEARCH.MERGE.MKACTIVITY.MKCALENDAR.MKCOL.MOVE.NOTIFY.OPTIONS.PATCH.POST.PROPFIND.PROPPATCH.PURGE.PUT.QUERY.REBIND.REPORT.SEARCH.SOURCE.SUBSCRIBE.TRACE.UNBIND.UNLINK.UNLOCK.UNSUBSCRIBE.acl.bind.checkout.connect.copy.delete.get.head.link.lock.m-search.merge.mkactivity.mkcalendar.mkcol.move.notify.options.patch.post.propfind.proppatch.purge.put.query.rebind.report.search.source.subscribe.trace.unbind.unlink.unlock.unsubscribe`.split(`.`)},validate:{type:`boolean`}},additionalProperties:!0,oneOf:[{required:[`url`]},{required:[`path`]}]};function r(e,{instancePath:t=``,parentData:i,parentDataProperty:a,rootData:o=e}={}){let s=null,c=0,l=c,u=!1,d=null,f=c;if(e&&typeof e==`object`&&!Array.isArray(e)){let n;if(e.url===void 0&&(n=`url`)){let e={instancePath:t,schemaPath:`#/oneOf/0/required`,keyword:`required`,params:{missingProperty:n},message:`must have required property '`+n+`'`};s===null?s=[e]:s.push(e),c++}}var p=f===c;p&&(u=!0,d=0);let m=c;if(e&&typeof e==`object`&&!Array.isArray(e)){let n;if(e.path===void 0&&(n=`path`)){let e={instancePath:t,schemaPath:`#/oneOf/1/required`,keyword:`required`,params:{missingProperty:n},message:`must have required property '`+n+`'`};s===null?s=[e]:s.push(e),c++}}var p=m===c;if(p&&u?(u=!1,d=[d,1]):p&&(u=!0,d=1),u)c=l,s!==null&&(l?s.length=l:s=null);else{let e={instancePath:t,schemaPath:`#/oneOf`,keyword:`oneOf`,params:{passingSchemas:d},message:`must match exactly one schema in oneOf`};return s===null?s=[e]:s.push(e),c++,r.errors=s,!1}if(c===0)if(e&&typeof e==`object`&&!Array.isArray(e)){if(e.url!==void 0){let n=e.url,i=c,a=c,o=!1,l=null,u=c;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else{let e={instancePath:t+`/url`,schemaPath:`#/properties/url/oneOf/0/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(n=i,e!==void 0&&(e.url=i))}var h=u===c;h&&(o=!0,l=0);let d=c;if(c===d)if(n&&typeof n==`object`&&!Array.isArray(n)){let e;if(n.pathname===void 0&&(e=`pathname`)){let n={instancePath:t+`/url`,schemaPath:`#/properties/url/oneOf/1/required`,keyword:`required`,params:{missingProperty:e},message:`must have required property '`+e+`'`};s===null?s=[n]:s.push(n),c++}else{if(n.protocol!==void 0){let e=n.protocol,r=c;if(typeof e!=`string`){let r=typeof e,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+e;else if(e===null)i=``;else{let e={instancePath:t+`/url/protocol`,schemaPath:`#/properties/url/oneOf/1/properties/protocol/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(e=i,n!==void 0&&(n.protocol=i))}var g=r===c}else var g=!0;if(g){if(n.hostname!==void 0){let e=n.hostname,r=c;if(typeof e!=`string`){let r=typeof e,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+e;else if(e===null)i=``;else{let e={instancePath:t+`/url/hostname`,schemaPath:`#/properties/url/oneOf/1/properties/hostname/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(e=i,n!==void 0&&(n.hostname=i))}var g=r===c}else var g=!0;if(g)if(n.pathname!==void 0){let e=n.pathname,r=c;if(typeof e!=`string`){let r=typeof e,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+e;else if(e===null)i=``;else{let e={instancePath:t+`/url/pathname`,schemaPath:`#/properties/url/oneOf/1/properties/pathname/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(e=i,n!==void 0&&(n.pathname=i))}var g=r===c}else var g=!0}}}else{let e={instancePath:t+`/url`,schemaPath:`#/properties/url/oneOf/1/type`,keyword:`type`,params:{type:`object`},message:`must be object`};s===null?s=[e]:s.push(e),c++}var h=d===c;if(h&&o?(o=!1,l=[l,1]):h&&(o=!0,l=1),o)c=a,s!==null&&(a?s.length=a:s=null);else{let e={instancePath:t+`/url`,schemaPath:`#/properties/url/oneOf`,keyword:`oneOf`,params:{passingSchemas:l},message:`must match exactly one schema in oneOf`};return s===null?s=[e]:s.push(e),c++,r.errors=s,!1}var _=i===c}else var _=!0;if(_){if(e.path!==void 0){let n=e.path,i=c,a=c,o=!1,l=null,u=c;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else{let e={instancePath:t+`/path`,schemaPath:`#/properties/path/oneOf/0/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(n=i,e!==void 0&&(e.path=i))}var v=u===c;v&&(o=!0,l=0);let d=c;if(c===d)if(n&&typeof n==`object`&&!Array.isArray(n)){let e;if(n.pathname===void 0&&(e=`pathname`)){let n={instancePath:t+`/path`,schemaPath:`#/properties/path/oneOf/1/required`,keyword:`required`,params:{missingProperty:e},message:`must have required property '`+e+`'`};s===null?s=[n]:s.push(n),c++}else{if(n.protocol!==void 0){let e=n.protocol,r=c;if(typeof e!=`string`){let r=typeof e,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+e;else if(e===null)i=``;else{let e={instancePath:t+`/path/protocol`,schemaPath:`#/properties/path/oneOf/1/properties/protocol/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(e=i,n!==void 0&&(n.protocol=i))}var y=r===c}else var y=!0;if(y){if(n.hostname!==void 0){let e=n.hostname,r=c;if(typeof e!=`string`){let r=typeof e,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+e;else if(e===null)i=``;else{let e={instancePath:t+`/path/hostname`,schemaPath:`#/properties/path/oneOf/1/properties/hostname/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(e=i,n!==void 0&&(n.hostname=i))}var y=r===c}else var y=!0;if(y)if(n.pathname!==void 0){let e=n.pathname,r=c;if(typeof e!=`string`){let r=typeof e,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+e;else if(e===null)i=``;else{let e={instancePath:t+`/path/pathname`,schemaPath:`#/properties/path/oneOf/1/properties/pathname/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(e=i,n!==void 0&&(n.pathname=i))}var y=r===c}else var y=!0}}}else{let e={instancePath:t+`/path`,schemaPath:`#/properties/path/oneOf/1/type`,keyword:`type`,params:{type:`object`},message:`must be object`};s===null?s=[e]:s.push(e),c++}var v=d===c;if(v&&o?(o=!1,l=[l,1]):v&&(o=!0,l=1),o)c=a,s!==null&&(a?s.length=a:s=null);else{let e={instancePath:t+`/path`,schemaPath:`#/properties/path/oneOf`,keyword:`oneOf`,params:{passingSchemas:l},message:`must match exactly one schema in oneOf`};return s===null?s=[e]:s.push(e),c++,r.errors=s,!1}var _=i===c}else var _=!0;if(_){if(e.cookies!==void 0){let n=e.cookies,i=c;if(c===i&&!(n&&typeof n==`object`&&!Array.isArray(n)))return r.errors=[{instancePath:t+`/cookies`,schemaPath:`#/properties/cookies/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var _=i===c}else var _=!0;if(_){if(e.headers!==void 0){let n=e.headers,i=c;if(c===i&&!(n&&typeof n==`object`&&!Array.isArray(n)))return r.errors=[{instancePath:t+`/headers`,schemaPath:`#/properties/headers/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var _=i===c}else var _=!0;if(_){if(e.query!==void 0){let n=e.query,i=c,a=c,o=!1,l=c;if(c===l&&!(n&&typeof n==`object`&&!Array.isArray(n))){let e={instancePath:t+`/query`,schemaPath:`#/properties/query/anyOf/0/type`,keyword:`type`,params:{type:`object`},message:`must be object`};s===null?s=[e]:s.push(e),c++}var b=l===c;if(o||=b,!o){let r=c;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else{let e={instancePath:t+`/query`,schemaPath:`#/properties/query/anyOf/1/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(n=i,e!==void 0&&(e.query=i))}var b=r===c;o||=b}if(o)c=a,s!==null&&(a?s.length=a:s=null);else{let e={instancePath:t+`/query`,schemaPath:`#/properties/query/anyOf`,keyword:`anyOf`,params:{},message:`must match a schema in anyOf`};return s===null?s=[e]:s.push(e),c++,r.errors=s,!1}var _=i===c}else var _=!0;if(_){if(e.simulate!==void 0){let n=e.simulate,i=c;if(c===i)if(n&&typeof n==`object`&&!Array.isArray(n)){if(n.end!==void 0){let e=n.end,i=c;if(typeof e!=`boolean`){let i;if(i===void 0)if(e===`false`||e===0||e===null)i=!1;else if(e===`true`||e===1)i=!0;else return r.errors=[{instancePath:t+`/simulate/end`,schemaPath:`#/properties/simulate/properties/end/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;i!==void 0&&(e=i,n!==void 0&&(n.end=i))}var x=i===c}else var x=!0;if(x){if(n.split!==void 0){let e=n.split,i=c;if(typeof e!=`boolean`){let i;if(i===void 0)if(e===`false`||e===0||e===null)i=!1;else if(e===`true`||e===1)i=!0;else return r.errors=[{instancePath:t+`/simulate/split`,schemaPath:`#/properties/simulate/properties/split/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;i!==void 0&&(e=i,n!==void 0&&(n.split=i))}var x=i===c}else var x=!0;if(x){if(n.error!==void 0){let e=n.error,i=c;if(typeof e!=`boolean`){let i;if(i===void 0)if(e===`false`||e===0||e===null)i=!1;else if(e===`true`||e===1)i=!0;else return r.errors=[{instancePath:t+`/simulate/error`,schemaPath:`#/properties/simulate/properties/error/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;i!==void 0&&(e=i,n!==void 0&&(n.error=i))}var x=i===c}else var x=!0;if(x)if(n.close!==void 0){let e=n.close,i=c;if(typeof e!=`boolean`){let i;if(i===void 0)if(e===`false`||e===0||e===null)i=!1;else if(e===`true`||e===1)i=!0;else return r.errors=[{instancePath:t+`/simulate/close`,schemaPath:`#/properties/simulate/properties/close/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;i!==void 0&&(e=i,n!==void 0&&(n.close=i))}var x=i===c}else var x=!0}}}else return r.errors=[{instancePath:t+`/simulate`,schemaPath:`#/properties/simulate/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var _=i===c}else var _=!0;if(_){if(e.authority!==void 0){let n=e.authority,i=c;if(typeof n!=`string`){let i=typeof n,a;if(a===void 0)if(i==`number`||i==`boolean`)a=``+n;else if(n===null)a=``;else return r.errors=[{instancePath:t+`/authority`,schemaPath:`#/properties/authority/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;a!==void 0&&(n=a,e!==void 0&&(e.authority=a))}var _=i===c}else var _=!0;if(_){if(e.remoteAddress!==void 0){let n=e.remoteAddress,i=c;if(typeof n!=`string`){let i=typeof n,a;if(a===void 0)if(i==`number`||i==`boolean`)a=``+n;else if(n===null)a=``;else return r.errors=[{instancePath:t+`/remoteAddress`,schemaPath:`#/properties/remoteAddress/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;a!==void 0&&(n=a,e!==void 0&&(e.remoteAddress=a))}var _=i===c}else var _=!0;if(_){if(e.method!==void 0){let i=e.method,a=c;if(typeof i!=`string`){let n=typeof i,a;if(a===void 0)if(n==`number`||n==`boolean`)a=``+i;else if(i===null)a=``;else return r.errors=[{instancePath:t+`/method`,schemaPath:`#/properties/method/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;a!==void 0&&(i=a,e!==void 0&&(e.method=a))}if(!(i===`ACL`||i===`BIND`||i===`CHECKOUT`||i===`CONNECT`||i===`COPY`||i===`DELETE`||i===`GET`||i===`HEAD`||i===`LINK`||i===`LOCK`||i===`M-SEARCH`||i===`MERGE`||i===`MKACTIVITY`||i===`MKCALENDAR`||i===`MKCOL`||i===`MOVE`||i===`NOTIFY`||i===`OPTIONS`||i===`PATCH`||i===`POST`||i===`PROPFIND`||i===`PROPPATCH`||i===`PURGE`||i===`PUT`||i===`QUERY`||i===`REBIND`||i===`REPORT`||i===`SEARCH`||i===`SOURCE`||i===`SUBSCRIBE`||i===`TRACE`||i===`UNBIND`||i===`UNLINK`||i===`UNLOCK`||i===`UNSUBSCRIBE`||i===`acl`||i===`bind`||i===`checkout`||i===`connect`||i===`copy`||i===`delete`||i===`get`||i===`head`||i===`link`||i===`lock`||i===`m-search`||i===`merge`||i===`mkactivity`||i===`mkcalendar`||i===`mkcol`||i===`move`||i===`notify`||i===`options`||i===`patch`||i===`post`||i===`propfind`||i===`proppatch`||i===`purge`||i===`put`||i===`query`||i===`rebind`||i===`report`||i===`search`||i===`source`||i===`subscribe`||i===`trace`||i===`unbind`||i===`unlink`||i===`unlock`||i===`unsubscribe`))return r.errors=[{instancePath:t+`/method`,schemaPath:`#/properties/method/enum`,keyword:`enum`,params:{allowedValues:n.properties.method.enum},message:`must be equal to one of the allowed values`}],!1;var _=a===c}else var _=!0;if(_)if(e.validate!==void 0){let n=e.validate,i=c;if(typeof n!=`boolean`){let i;if(i===void 0)if(n===`false`||n===0||n===null)i=!1;else if(n===`true`||n===1)i=!0;else return r.errors=[{instancePath:t+`/validate`,schemaPath:`#/properties/validate/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.validate=i))}var _=i===c}else var _=!0}}}}}}}}}else return r.errors=[{instancePath:t,schemaPath:`#/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;return r.errors=s,c===0}})),th=o(((e,t)=>{let n=require(`node:assert`),r=Zm(),i=$m(),a=`The dispatch function has already been invoked`,o=eh();function s(e,t,n){return n===void 0?new d(e,t):u(e,t,n)}function c(e,t){let n=e._lightMyRequest.payload;if(!n||n._readableState||typeof n.resume!=`function`)return t();let r=[];n.on(`data`,e=>r.push(Buffer.from(e))),n.on(`end`,()=>{let n=Buffer.concat(r);return e.headers[`content-length`]=e.headers[`content-length`]||``+n.length,delete e.headers[`transfer-encoding`],e._lightMyRequest.payload=n,t()}),n.resume()}function l(e,t,n,r){return n.once(`error`,function(e){this.destroyed&&r.destroy(e)}),n.once(`close`,function(){this.destroyed&&!this._error&&r.destroy()}),c(n,()=>e.call(t,n,r))}function u(e,t,a){if(t=typeof t==`string`?{url:t}:t,t.validate!==!1&&(n(typeof e==`function`,`dispatchFunc should be a function`),!o(t)))throw Error(o.errors.map(e=>e.message));let s=t.server||{},c=t.Request?r.CustomRequest:r;if(e.request&&e.request.app===e&&(Object.setPrototypeOf(Object.getPrototypeOf(e.request),c.prototype),Object.setPrototypeOf(Object.getPrototypeOf(e.response),i.prototype)),typeof a==`function`){let n=new c(t);return l(e,s,n,new i(n,a))}else return new Promise((n,r)=>{let a=new c(t);l(e,s,a,new i(a,n,r))})}function d(e,t){typeof t==`string`?this.option={url:t}:this.option=Object.assign({},t),this.dispatch=e,this._hasInvoked=!1,this._promise=null,this.option.autoStart!==!1&&process.nextTick(()=>{this._hasInvoked||this.end()})}[`delete`,`get`,`head`,`options`,`patch`,`post`,`put`,`trace`].forEach(e=>{d.prototype[e]=function(t){if(this._hasInvoked===!0||this._promise)throw Error(a);return this.option.url=t,this.option.method=e.toUpperCase(),this}}),[`body`,`cookies`,`headers`,`payload`,`query`].forEach(e=>{d.prototype[e]=function(t){if(this._hasInvoked===!0||this._promise)throw Error(a);return this.option[e]=t,this}}),d.prototype.end=function(e){if(this._hasInvoked===!0||this._promise)throw Error(a);if(this._hasInvoked=!0,typeof e==`function`)u(this.dispatch,this.option,e);else return this._promise=u(this.dispatch,this.option),this._promise},Object.getOwnPropertyNames(Promise.prototype).forEach(e=>{e!==`constructor`&&(d.prototype[e]=function(...t){if(!this._promise){if(this._hasInvoked===!0)throw Error(a);this._hasInvoked=!0,this._promise=u(this.dispatch,this.option)}return this._promise[e](...t)})});function f(e){return e instanceof r||e instanceof i||e?.constructor?.name===`_CustomLMRRequest`}t.exports=s,t.exports.default=s,t.exports.inject=s,t.exports.isInjection=f})),nh=o(((e,t)=>{let n=uu(),r=require(`node:http`),i=require(`node:diagnostics_channel`),a,{kAvvioBoot:o,kChildren:s,kServerBindings:c,kBodyLimit:l,kSupportedHTTPMethods:u,kRoutePrefix:d,kLogLevel:f,kLogSerializers:p,kHooks:m,kSchemaController:h,kRequestAcceptVersion:g,kReplySerializerDefault:_,kContentTypeParser:v,kReply:y,kRequest:b,kFourOhFour:x,kState:S,kOptions:C,kPluginNameChain:w,kSchemaErrorFormatter:T,kErrorHandler:E,kKeepAliveConnections:D,kChildLoggerFactory:O,kGenReqId:k,kErrorHandlerAlreadySet:A}=du(),{createServer:j}=vu(),M=cd(),ee=fd(),N=pd(),te=sd(),P=gd(),ne=yp(),{Hooks:F,hookRunnerApplication:I,supportedHooks:re}=hu(),{createChildLogger:L,defaultChildLoggerFactory:ie,createLogger:ae}=td(),R=dm(),{getGenReqId:oe,reqIdGenFactory:se}=fm(),{buildRouting:ce,validateBodyLimitOption:le,buildRouterOptions:ue}=Hm(),de=Um(),z=Gm(),fe=Km(),{appendStackTrace:pe,AVVIO_ERRORS_MAP:me,...he}=mu(),ge=_u(),{defaultInitOptions:_e}=z,{FST_ERR_ASYNC_CONSTRAINT:ve,FST_ERR_BAD_URL:ye,FST_ERR_OPTIONS_NOT_OBJ:be,FST_ERR_QSP_NOT_FN:xe,FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN:Se,FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ:Ce,FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR:we,FST_ERR_INSTANCE_ALREADY_LISTENING:Te,FST_ERR_REOPENED_CLOSE_SERVER:Ee,FST_ERR_ROUTE_REWRITE_NOT_STR:De,FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN:Oe,FST_ERR_ERROR_HANDLER_NOT_FN:ke,FST_ERR_ERROR_HANDLER_ALREADY_SET:Ae,FST_ERR_ROUTE_METHOD_INVALID:je}=he,{buildErrorHandler:Me}=od(),{FSTWRN004:Ne}=pu(),Pe=i.channel(`fastify.initialization`);function Fe(e){let{options:t,genReqId:i,disableRequestLogging:ae,hasLogger:le,initialConfig:ue}=Ie(e,Xe,Ze),z=ce(t.routerOptions),be=de(t),xe=ct(z,t),{server:Se,listen:Ce,forceCloseConnections:we,serverHasCloseAllConnections:Oe,serverHasCloseHttp2Sessions:Fe,keepAliveConnections:Le}=j(t,xe),Re=M.setupResponseListeners,Be=ne.buildSchemaController(null,t.schemaController),B={[S]:{listening:!1,closing:!1,started:!1,ready:!1,booting:!1,aborted:!1,readyResolver:null},[D]:Le,[u]:{bodyless:new Set([`GET`,`HEAD`,`TRACE`]),bodywith:new Set([`DELETE`,`OPTIONS`,`PATCH`,`PUT`,`POST`])},[C]:t,[s]:[],[c]:[],[l]:t.bodyLimit,[d]:``,[f]:``,[p]:null,[m]:new F,[h]:Be,[T]:null,[E]:Me(),[A]:!1,[O]:t.childLoggerFactory||ie,[_]:null,[v]:new P(t.bodyLimit,t.onProtoPoisoning||_e.onProtoPoisoning,t.onConstructorPoisoning||_e.onConstructorPoisoning),[y]:M.buildReply(M),[b]:ee.buildRequest(ee,t.trustProxy),[x]:be,[R.kRegisteredPlugins]:[],[w]:[`fastify`],[o]:null,[k]:i,routing:xe,delete:function(e,t,n){return z.prepareRoute.call(this,{method:`DELETE`,url:e,options:t,handler:n})},get:function(e,t,n){return z.prepareRoute.call(this,{method:`GET`,url:e,options:t,handler:n})},head:function(e,t,n){return z.prepareRoute.call(this,{method:`HEAD`,url:e,options:t,handler:n})},trace:function(e,t,n){return z.prepareRoute.call(this,{method:`TRACE`,url:e,options:t,handler:n})},patch:function(e,t,n){return z.prepareRoute.call(this,{method:`PATCH`,url:e,options:t,handler:n})},post:function(e,t,n){return z.prepareRoute.call(this,{method:`POST`,url:e,options:t,handler:n})},put:function(e,t,n){return z.prepareRoute.call(this,{method:`PUT`,url:e,options:t,handler:n})},options:function(e,t,n){return z.prepareRoute.call(this,{method:`OPTIONS`,url:e,options:t,handler:n})},all:function(e,t,n){return z.prepareRoute.call(this,{method:this.supportedMethods,url:e,options:t,handler:n})},route:function(e){return z.route.call(this,{options:e})},hasRoute:function(e){return z.hasRoute.call(this,{options:e})},findRoute:function(e){return z.findRoute(e)},log:t.logger,withTypeProvider:qe,addHook:Je,addSchema:Ye,getSchema:Be.getSchema.bind(Be),getSchemas:Be.getSchemas.bind(Be),setValidatorCompiler:et,setSerializerCompiler:nt,setSchemaController:rt,setReplySerializer:it,setSchemaErrorFormatter:tt,setGenReqId:lt,addContentTypeParser:P.helpers.addContentTypeParser,hasContentTypeParser:P.helpers.hasContentTypeParser,getDefaultJsonParser:P.defaultParsers.getDefaultJsonParser,defaultTextParser:P.defaultParsers.defaultTextParser,removeContentTypeParser:P.helpers.removeContentTypeParser,removeAllContentTypeParsers:P.helpers.removeAllContentTypeParsers,register:null,after:null,ready:null,onClose:null,close:null,printPlugins:null,hasPlugin:function(e){return this[R.kRegisteredPlugins].includes(e)||this[w].includes(e)},listen:Ce,server:Se,addresses:function(){let e=this[c].map(e=>e.address());return e.push(this.server.address()),e.filter(e=>e)},decorate:te.add,hasDecorator:te.exist,decorateReply:te.decorateReply,decorateRequest:te.decorateRequest,hasRequestDecorator:te.existRequest,hasReplyDecorator:te.existReply,getDecorator:te.getInstanceDecorator,addHttpMethod:ut,inject:Ge,printRoutes:st,setNotFoundHandler:$e,setErrorHandler:at,setChildLoggerFactory:ot,initialConfig:ue,addConstraintStrategy:z.addConstraintStrategy.bind(z),hasConstraintStrategy:z.hasConstraintStrategy.bind(z)};Object.defineProperties(B,{listeningOrigin:{get(){let e=this.addresses().slice(-1).pop();if(typeof e==`string`)return e;let t=e.family===`IPv6`?`[${e.address}]`:e.address;return`${this[C].https?`https`:`http`}://${t}:${e.port}`}},pluginName:{configurable:!0,get(){return this[w].length>1?this[w].join(` -> `):this[w][0]}},prefix:{configurable:!0,get(){return this[d]}},validatorCompiler:{configurable:!0,get(){return this[h].getValidatorCompiler()}},serializerCompiler:{configurable:!0,get(){return this[h].getSerializerCompiler()}},childLoggerFactory:{configurable:!0,get(){return this[O]}},version:{configurable:!0,get(){return`5.7.4`}},errorHandler:{configurable:!0,get(){return this[E].func}},genReqId:{configurable:!0,get(){return this[k]}},supportedMethods:{configurable:!1,get(){return[...this[u].bodyless,...this[u].bodywith]}}}),t.schemaErrorFormatter&&(ze(t.schemaErrorFormatter),B[T]=t.schemaErrorFormatter.bind(B));let Ve=Number(t.pluginTimeout),He=n(B,{autostart:!1,timeout:isNaN(Ve)===!1?Ve:_e.pluginTimeout,expose:{use:`register`}});He.override=fe,He.on(`start`,()=>B[S].started=!0),B[o]=B.ready,B.ready=Ke,B.printPlugins=He.prettyPrint.bind(He),He.once(`preReady`,()=>{B.onClose((e,n)=>{B[S].closing=!0,z.closeRoutes(),I(`preClose`,B[o],B,function(){if(B[S].listening){if(we===`idle`)e.server.closeIdleConnections();else if(Oe&&we)e.server.closeAllConnections();else if(we===!0)for(let e of B[D])e.destroy(),B[D].delete(e)}Fe&&e.server.closeHttp2Sessions(),!t.serverFactory||B[S].listening?e.server.close(function(e){e&&e.code!==`ERR_SERVER_NOT_RUNNING`?n(null):n()}):process.nextTick(n,null)})})});let Ue=new N({server:B,config:{}});return B.setNotFoundHandler(),be.arrange404(B),z.setup(t,{avvio:He,fourOhFour:be,hasLogger:le,setupResponseListeners:Re,throwIfAlreadyStarted:We,keepAliveConnections:Le}),Se.on(`clientError`,t.clientErrorHandler.bind(B)),Pe.hasSubscribers&&Pe.publish({fastify:B}),`asyncDispose`in Symbol&&(B[Symbol.asyncDispose]=function(){return B.close()}),B;function We(e){if(B[S].started)throw new Te(e)}function Ge(e,t){if(a===void 0&&(a=th()),B[S].started){if(B[S].closing){let e=new Ee;if(t){t(e);return}else return Promise.reject(e)}return a(xe,e,t)}if(t)this.ready(n=>{n?t(n,null):a(xe,e,t)});else return a((e,t)=>{this.ready(function(n){if(n){t.emit(`error`,n);return}xe(e,t)})},e)}function Ke(e){if(this[S].readyResolver!==null){if(e!=null){this[S].readyResolver.promise.then(()=>e(null,B),e);return}return this[S].readyResolver.promise}if(process.nextTick(t),this[S].readyResolver=ge.withResolvers(),e)this[S].readyResolver.promise.then(()=>e(null,B),e);else return this[S].readyResolver.promise;function t(){B[o]((e,t)=>{e||B[S].started||B[S].ready||B[S].booting?n(e):(B[S].booting=!0,I(`onReady`,B[o],B,n)),t()})}function n(e){if(e=e!=null&&me[e.code]!=null?pe(e,new me[e.code](e.message)):e,e)return B[S].readyResolver.reject(e);B[S].readyResolver.resolve(B),B[S].booting=!1,B[S].ready=!0,B[S].readyResolver=null}}function qe(){return this}function Je(e,t){if(We(`Cannot call "addHook"!`),t==null)throw new he.FST_ERR_HOOK_INVALID_HANDLER(e,t);if(e===`onSend`||e===`preSerialization`||e===`onError`||e===`preParsing`){if(t.constructor.name===`AsyncFunction`&&t.length===4)throw new he.FST_ERR_HOOK_INVALID_ASYNC_HANDLER}else if(e===`onReady`||e===`onListen`){if(t.constructor.name===`AsyncFunction`&&t.length!==0)throw new he.FST_ERR_HOOK_INVALID_ASYNC_HANDLER}else if(e===`onRequestAbort`){if(t.constructor.name===`AsyncFunction`&&t.length!==1)throw new he.FST_ERR_HOOK_INVALID_ASYNC_HANDLER}else if(t.constructor.name===`AsyncFunction`&&t.length===3)throw new he.FST_ERR_HOOK_INVALID_ASYNC_HANDLER;return e===`onClose`?this.onClose(t.bind(this)):e===`onReady`||e===`onListen`||e===`onRoute`?this[m].add(e,t):this.after((r,i)=>{try{n.call(this,e,t),i(r)}catch(e){i(e)}}),this;function n(e,t){this[m].add(e,t),this[s].forEach(r=>n.call(r,e,t))}}function Ye(e){return We(`Cannot call "addSchema"!`),this[h].add(e),this[s].forEach(t=>t.addSchema(e)),this}function Xe(e,t){e.headers[`accept-version`]!==void 0&&(e.headers[g]=e.headers[`accept-version`],e.headers[`accept-version`]=void 0),be.router.lookup(e,t)}function Ze(e,n,r){if(t.frameworkErrors){let i=oe(Ue.server,n),a=L(Ue,t.logger,n,i),o=new ee(i,null,n,null,a,Ue),s=new M(r,o,a);return(typeof ae==`function`?ae(n):ae)===!1&&a.info({req:o},`incoming request`),t.frameworkErrors(new ye(e),o,s)}let i=JSON.stringify({error:`Bad Request`,code:`FST_ERR_BAD_URL`,message:`'${e}' is not a valid url component`,statusCode:400});r.writeHead(400,{"Content-Type":`application/json`,"Content-Length":Buffer.byteLength(i)}),r.end(i)}function Qe(e,n,r){if(e!==!1)return function(e){if(e){if(t.frameworkErrors){let e=oe(Ue.server,n),i=L(Ue,t.logger,n,e),a=new ee(e,null,n,null,i,Ue),o=new M(r,a,i);return(typeof ae==`function`?ae(n):ae)===!1&&i.info({req:a},`incoming request`),t.frameworkErrors(new ve,a,o)}r.writeHead(500,{"Content-Type":`application/json`,"Content-Length":101}),r.end(`{"error":"Internal Server Error","message":"Unexpected error from async constraint","statusCode":500}`)}}}function $e(e,t){return We(`Cannot call "setNotFoundHandler"!`),be.setNotFoundHandler.call(this,e,t,He,z.routeHandler),this}function et(e){return We(`Cannot call "setValidatorCompiler"!`),this[h].setValidatorCompiler(e),this}function tt(e){return We(`Cannot call "setSchemaErrorFormatter"!`),ze(e),this[T]=e.bind(this),this}function nt(e){return We(`Cannot call "setSerializerCompiler"!`),this[h].setSerializerCompiler(e),this}function rt(e){We(`Cannot call "setSchemaController"!`);let t=this[h],n=ne.buildSchemaController(t,Object.assign({},t.opts,e));return this[h]=n,this.getSchema=n.getSchema.bind(n),this.getSchemas=n.getSchemas.bind(n),this}function it(e){return We(`Cannot call "setReplySerializer"!`),this[_]=e,this}function at(e){if(We(`Cannot call "setErrorHandler"!`),typeof e!=`function`)throw new ke;if(!t.allowErrorHandlerOverride&&this[A])throw new Ae;return this[A]&&Ne(`To disable this behavior, set 'allowErrorHandlerOverride' to false or ignore this message. For more information, visit: https://fastify.dev/docs/latest/Reference/Server/#allowerrorhandleroverride`),this[A]=!0,this[E]=Me(this[E],e.bind(this)),this}function ot(e){return We(`Cannot call "setChildLoggerFactory"!`),this[O]=e,this}function st(e={}){return e.includeMeta=e.includeHooks?e.includeMeta?re.concat(e.includeMeta):re:e.includeMeta,z.printRoutes(e)}function ct(e,{rewriteUrl:t,logger:n}){let r;return function(n,i){if(r===void 0&&(r=e.isAsyncConstraint()),t){n.originalUrl=n.url;let e=t.call(B,n);if(typeof e==`string`)n.url=e;else{let t=new De(n.url,typeof e);n.destroy(t)}}e.routing(n,i,Qe(r,n,i))}}function lt(e){return We(`Cannot call "setGenReqId"!`),this[k]=se(this[C].requestIdHeader,e),this}function ut(e,{hasBody:t=!1}={}){if(typeof e!=`string`||r.METHODS.indexOf(e)===-1)throw new je;t===!0?(this[u].bodywith.add(e),this[u].bodyless.delete(e)):(this[u].bodywith.delete(e),this[u].bodyless.add(e));let n=e.toLowerCase();return this.hasDecorator(n)||this.decorate(n,function(t,n,r){return z.prepareRoute.call(this,{method:e,url:t,options:n,handler:r})}),this}}function Ie(e,t,n){if(e&&typeof e!=`object`)throw new be;if(e=Object.assign({},e),e.querystringParser&&typeof e.querystringParser!=`function`||e.routerOptions?.querystringParser&&typeof e.routerOptions.querystringParser!=`function`)throw new xe(typeof(e.querystringParser??e.routerOptions.querystringParser));if(e.schemaController&&e.schemaController.bucket&&typeof e.schemaController.bucket!=`function`)throw new Se(typeof e.schemaController.bucket);le(e.bodyLimit);let r=typeof e.requestIdHeader==`string`&&e.requestIdHeader.length!==0?e.requestIdHeader.toLowerCase():e.requestIdHeader===!0&&`request-id`,i=se(r,e.genReqId),a=e.requestIdLogLabel||`reqId`;e.bodyLimit=e.bodyLimit||_e.bodyLimit;let o=e.disableRequestLogging||!1,s=Object.assign({customOptions:{},plugins:[]},e.ajv);if(!s.customOptions||Object.prototype.toString.call(s.customOptions)!==`[object Object]`)throw new Ce(typeof s.customOptions);if(!s.plugins||!Array.isArray(s.plugins))throw new we(typeof s.plugins);let{logger:c,hasLogger:l}=ae(e);e.connectionTimeout=e.connectionTimeout||_e.connectionTimeout,e.keepAliveTimeout=e.keepAliveTimeout||_e.keepAliveTimeout,e.maxRequestsPerSocket=e.maxRequestsPerSocket||_e.maxRequestsPerSocket,e.requestTimeout=e.requestTimeout||_e.requestTimeout,e.logger=c,e.requestIdHeader=r,e.requestIdLogLabel=a,e.disableRequestLogging=o,e.ajv=s,e.clientErrorHandler=e.clientErrorHandler||Re,e.allowErrorHandlerOverride=e.allowErrorHandlerOverride??_e.allowErrorHandlerOverride;let u=z(e);return e.exposeHeadRoutes=u.exposeHeadRoutes,e.http2SessionTimeout=u.http2SessionTimeout,e.routerOptions=ue(e,{defaultRoute:t,onBadUrl:n,ignoreTrailingSlash:_e.ignoreTrailingSlash,ignoreDuplicateSlashes:_e.ignoreDuplicateSlashes,maxParamLength:_e.maxParamLength,allowUnsafeRegex:_e.allowUnsafeRegex,buildPrettyMeta:Le,useSemicolonDelimiter:_e.useSemicolonDelimiter}),{options:e,genReqId:i,disableRequestLogging:o,hasLogger:l,initialConfig:u}}function Le(e){let t={};return[`errorHandler`,`logLevel`,`logSerializers`].concat(re).forEach(n=>{t[n]=e.store[n]}),Object.assign({},t)}function Re(e,t){if(e.code===`ECONNRESET`||t.destroyed)return;let n,i,a,o;e.code===`ERR_HTTP_REQUEST_TIMEOUT`?(i=`408`,a=r.STATUS_CODES[i],n=`{"error":"${a}","message":"Client Timeout","statusCode":408}`,o=`timeout`):e.code===`HPE_HEADER_OVERFLOW`?(i=`431`,a=r.STATUS_CODES[i],n=`{"error":"${a}","message":"Exceeded maximum allowed HTTP header size","statusCode":431}`,o=`header_overflow`):(i=`400`,a=r.STATUS_CODES[i],n=`{"error":"${a}","message":"Client Error","statusCode":400}`,o=`error`),this.log.trace({err:e},`client ${o}`),t.writable&&t.write(`HTTP/1.1 ${i} ${a}\r\nContent-Length: ${n.length}\r\nContent-Type: application/json\r\n\r\n${n}`),t.destroy(e)}function ze(e){if(typeof e!=`function`)throw new Oe(typeof e);if(e.constructor.name===`AsyncFunction`)throw new Oe(`AsyncFunction`)}t.exports=Fe,t.exports.errorCodes=he,t.exports.fastify=Fe,t.exports.default=Fe})),rh=o(((e,t)=>{let n=/at\s(?:.*\.)?plugin\s.*\n\s*(.*)/,r=/(\w*(\.\w*)*)\..*/;t.exports=function(e){if(e.name.length>0)return e.name;let t=Error.stackTraceLimit;Error.stackTraceLimit=10;try{throw Error(`anonymous function`)}catch(e){return Error.stackTraceLimit=t,i(e.stack)}};function i(e){let t=e.match(n);return t?t[1].split(/[/\\]/).slice(-1)[0].match(r)[1]:`anonymous`}t.exports.extractPluginName=i})),ih=o(((e,t)=>{t.exports=function(e){return e[0]===`@`&&(e=e.slice(1).replace(`/`,`-`)),e.replace(/-(.)/g,function(e,t){return t.toUpperCase()})}})),ah=o(((e,t)=>{let n=rh(),r=ih(),i=0;function a(e,t={}){let a=!1;if(e.default!==void 0&&(e=e.default),typeof e!=`function`)throw TypeError(`fastify-plugin expects a function, instead got a '${typeof e}'`);if(typeof t==`string`&&(t={fastify:t}),typeof t!=`object`||Array.isArray(t)||t===null)throw TypeError(`The options object should be an object`);if(t.fastify!==void 0&&typeof t.fastify!=`string`)throw TypeError(`fastify-plugin expects a version string, instead got '${typeof t.fastify}'`);t.name||(a=!0,t.name=n(e)+`-auto-`+ i++),e[Symbol.for(`skip-override`)]=t.encapsulate!==!0,e[Symbol.for(`fastify.display-name`)]=t.name,e[Symbol.for(`plugin-meta`)]=t,e.default||=e;let o=r(t.name);return!a&&!e[o]&&(e[o]=e),e}t.exports=a,t.exports.default=a,t.exports.fastifyPlugin=a})),oh=o(((e,t)=>{function n(e){if(typeof e!=`function`)throw Error(`obliterator/iterator: expecting a function!`);this.next=e}typeof Symbol<`u`&&(n.prototype[Symbol.iterator]=function(){return this}),n.of=function(){var e=arguments,t=e.length,r=0;return new n(function(){return r>=t?{done:!0}:{done:!1,value:e[r++]}})},n.empty=function(){return new n(function(){return{done:!0}})},n.fromSequence=function(e){var t=0,r=e.length;return new n(function(){return t>=r?{done:!0}:{done:!1,value:e[t++]}})},n.is=function(e){return e instanceof n?!0:typeof e==`object`&&!!e&&typeof e.next==`function`},t.exports=n})),sh=o((e=>{e.ARRAY_BUFFER_SUPPORT=typeof ArrayBuffer<`u`,e.SYMBOL_SUPPORT=typeof Symbol<`u`})),ch=o(((e,t)=>{var n=sh(),r=n.ARRAY_BUFFER_SUPPORT,i=n.SYMBOL_SUPPORT;t.exports=function(e,t){var n,a,o,s,c;if(!e)throw Error(`obliterator/forEach: invalid iterable.`);if(typeof t!=`function`)throw Error(`obliterator/forEach: expecting a callback.`);if(Array.isArray(e)||r&&ArrayBuffer.isView(e)||typeof e==`string`||e.toString()===`[object Arguments]`){for(o=0,s=e.length;o<s;o++)t(e[o],o);return}if(typeof e.forEach==`function`){e.forEach(t);return}if(i&&Symbol.iterator in e&&typeof e.next!=`function`&&(e=e[Symbol.iterator]()),typeof e.next==`function`){for(n=e,o=0;c=n.next(),c.done!==!0;)t(c.value,o),o++;return}for(a in e)e.hasOwnProperty(a)&&t(e[a],a)}})),lh=o((e=>{var t=2**8-1,n=2**16-1,r=2**32-1,i=2**7-1,a=2**15-1,o=2**31-1;e.getPointerArray=function(e){var i=e-1;if(i<=t)return Uint8Array;if(i<=n)return Uint16Array;if(i<=r)return Uint32Array;throw Error(`mnemonist: Pointer Array of size > 4294967295 is not supported.`)},e.getSignedPointerArray=function(e){var t=e-1;return t<=i?Int8Array:t<=a?Int16Array:t<=o?Int32Array:Float64Array},e.getNumberType=function(e){return e===(e|0)?Math.sign(e)===-1?e<=127&&e>=-128?Int8Array:e<=32767&&e>=-32768?Int16Array:Int32Array:e<=255?Uint8Array:e<=65535?Uint16Array:Uint32Array:Float64Array};var s={Uint8Array:1,Int8Array:2,Uint16Array:3,Int16Array:4,Uint32Array:5,Int32Array:6,Float32Array:7,Float64Array:8};e.getMinimalRepresentation=function(t,n){var r=null,i=0,a,o,c,l,u;for(l=0,u=t.length;l<u;l++)c=n?n(t[l]):t[l],o=e.getNumberType(c),a=s[o.name],a>i&&(i=a,r=o);return r},e.isTypedArray=function(e){return typeof ArrayBuffer<`u`&&ArrayBuffer.isView(e)},e.concat=function(){var e=0,t,n,r;for(t=0,r=arguments.length;t<r;t++)e+=arguments[t].length;var i=new arguments[0].constructor(e);for(t=0,n=0;t<r;t++)i.set(arguments[t],n),n+=arguments[t].length;return i},e.indices=function(t){for(var n=new(e.getPointerArray(t))(t),r=0;r<t;r++)n[r]=r;return n}})),uh=o((e=>{var t=ch(),n=lh();function r(e){return Array.isArray(e)||n.isTypedArray(e)}function i(e){if(typeof e.length==`number`)return e.length;if(typeof e.size==`number`)return e.size}function a(e){var n=i(e),r=typeof n==`number`?Array(n):[],a=0;return t(e,function(e){r[a++]=e}),r}function o(e){var r=i(e),a=typeof r==`number`?n.getPointerArray(r):Array,o=typeof r==`number`?Array(r):[],s=typeof r==`number`?new a(r):[],c=0;return t(e,function(e){o[c]=e,s[c]=c++}),[o,s]}e.isArrayLike=r,e.guessLength=i,e.toArray=a,e.toArrayWithIndices=o})),dh=o(((e,t)=>{var n=oh(),r=ch(),i=lh(),a=uh();function o(e,t,n){if(arguments.length<2&&(n=e,e=null,t=null),this.capacity=n,typeof this.capacity!=`number`||this.capacity<=0)throw Error(`mnemonist/lru-cache: capacity should be positive number.`);if(!isFinite(this.capacity)||Math.floor(this.capacity)!==this.capacity)throw Error(`mnemonist/lru-cache: capacity should be a finite positive integer.`);var r=i.getPointerArray(n);this.forward=new r(n),this.backward=new r(n),this.K=typeof e==`function`?new e(n):Array(n),this.V=typeof t==`function`?new t(n):Array(n),this.size=0,this.head=0,this.tail=0,this.items={}}o.prototype.clear=function(){this.size=0,this.head=0,this.tail=0,this.items={}},o.prototype.splayOnTop=function(e){var t=this.head;if(this.head===e)return this;var n=this.backward[e],r=this.forward[e];return this.tail===e?this.tail=n:this.backward[r]=n,this.forward[n]=r,this.backward[t]=e,this.head=e,this.forward[e]=t,this},o.prototype.set=function(e,t){var n=this.items[e];if(n!==void 0){this.splayOnTop(n),this.V[n]=t;return}this.size<this.capacity?n=this.size++:(n=this.tail,this.tail=this.backward[n],delete this.items[this.K[n]]),this.items[e]=n,this.K[n]=e,this.V[n]=t,this.forward[n]=this.head,this.backward[this.head]=n,this.head=n},o.prototype.setpop=function(e,t){var n=null,r=null,i=this.items[e];return i===void 0?(this.size<this.capacity?i=this.size++:(i=this.tail,this.tail=this.backward[i],n=this.V[i],r=this.K[i],delete this.items[r]),this.items[e]=i,this.K[i]=e,this.V[i]=t,this.forward[i]=this.head,this.backward[this.head]=i,this.head=i,r?{evicted:!0,key:r,value:n}:null):(this.splayOnTop(i),n=this.V[i],this.V[i]=t,{evicted:!1,key:e,value:n})},o.prototype.has=function(e){return e in this.items},o.prototype.get=function(e){var t=this.items[e];if(t!==void 0)return this.splayOnTop(t),this.V[t]},o.prototype.peek=function(e){var t=this.items[e];if(t!==void 0)return this.V[t]},o.prototype.forEach=function(e,t){t=arguments.length>1?t:this;for(var n=0,r=this.size,i=this.head,a=this.K,o=this.V,s=this.forward;n<r;)e.call(t,o[i],a[i],this),i=s[i],n++},o.prototype.keys=function(){var e=0,t=this.size,r=this.head,i=this.K,a=this.forward;return new n(function(){if(e>=t)return{done:!0};var n=i[r];return e++,e<t&&(r=a[r]),{done:!1,value:n}})},o.prototype.values=function(){var e=0,t=this.size,r=this.head,i=this.V,a=this.forward;return new n(function(){if(e>=t)return{done:!0};var n=i[r];return e++,e<t&&(r=a[r]),{done:!1,value:n}})},o.prototype.entries=function(){var e=0,t=this.size,r=this.head,i=this.K,a=this.V,o=this.forward;return new n(function(){if(e>=t)return{done:!0};var n=i[r],s=a[r];return e++,e<t&&(r=o[r]),{done:!1,value:[n,s]}})},typeof Symbol<`u`&&(o.prototype[Symbol.iterator]=o.prototype.entries),o.prototype.inspect=function(){for(var e=new Map,t=this.entries(),n;n=t.next(),!n.done;)e.set(n.value[0],n.value[1]);return Object.defineProperty(e,`constructor`,{value:o,enumerable:!1}),e},typeof Symbol<`u`&&(o.prototype[Symbol.for(`nodejs.util.inspect.custom`)]=o.prototype.inspect),o.from=function(e,t,n,i){if(arguments.length<2){if(i=a.guessLength(e),typeof i!=`number`)throw Error(`mnemonist/lru-cache.from: could not guess iterable length. Please provide desired capacity as last argument.`)}else arguments.length===2&&(i=t,t=null,n=null);var s=new o(t,n,i);return r(e,function(e,t){s.set(t,e)}),s},t.exports=o})),fh=o(((e,t)=>{let n=dh(),r=/^[!#$%&'*+\-.^\w`|~]+$/u;function i(e){if(r.test(e)===!1)throw TypeError(`Fieldname contains invalid characters.`)}function a(e){e=e.trim().toLowerCase();let t=[];if(e.length!==0)if(e.indexOf(`,`)===-1)t.push(e);else{let n=e.length,r=0,i=0,a;for(;r<n;++r)a=e[r],a===` `?i=r+1:a===`,`&&(i!==r&&t.push(e.slice(i,r)),i=r+1);i!==r&&t.push(e.slice(i,r))}return t}function o(e){let t=new n(1e3);return i(e),function(n){let r=n.getHeader(`Vary`);if(!r){n.header(`Vary`,e);return}if(r===`*`)return;if(e===`*`){n.header(`Vary`,`*`);return}if(Array.isArray(r)&&(r=r.join(`, `)),!t.has(r)){let n=a(r);n.indexOf(`*`)===-1?n.indexOf(e.toLowerCase())===-1?t.set(r,r+`, `+e):t.set(r,null):t.set(r,`*`)}let i=t.get(r);i!==null&&n.header(`Vary`,i)}}t.exports.createAddFieldnameToVary=o,t.exports.addOriginToVaryHeader=o(`Origin`),t.exports.addAccessControlRequestHeadersToVaryHeader=o(`Access-Control-Request-Headers`),t.exports.parse=a})),ph=o(((e,t)=>{let n=ah(),{addAccessControlRequestHeadersToVaryHeader:r,addOriginToVaryHeader:i}=fh(),a={origin:`*`,methods:`GET,HEAD,PUT,PATCH,POST,DELETE`,hook:`onRequest`,preflightContinue:!1,optionsSuccessStatus:204,credentials:!1,exposedHeaders:null,allowedHeaders:null,maxAge:null,preflight:!0,strictPreflight:!0},o=[`onRequest`,`preParsing`,`preValidation`,`preHandler`,`preSerialization`,`onSend`],s=[`preSerialization`,`preParsing`,`onSend`];function c(e,t){o.indexOf(e)===-1&&t(TypeError(`@fastify/cors: Invalid hook option provided.`))}function l(e,t,n){e.decorateRequest(`corsPreflightEnabled`,!1);let r=!0;if(typeof t==`function`)u(t,e,{hook:a.hook},n);else if(t.delegator){let{delegator:r,...i}=t;u(r,e,i,n)}else{t.hideOptionsRoute!==void 0&&(r=t.hideOptionsRoute);let i=f(t);c(i.hook,n),s.indexOf(i.hook)===-1?e.addHook(i.hook,function(t,n,r){p(e,i,t,n,r)}):e.addHook(i.hook,function(t,n,r,a){p(e,i,t,n,a)})}e.options(`*`,{schema:{hide:r}},(e,t)=>{if(!e.corsPreflightEnabled){t.callNotFound();return}t.send()}),n()}function u(e,t,n,r){let i=n?.hook||a.hook;c(i,r),e.length===2?s.indexOf(i)===-1?t.addHook(i,function(n,r,i){d(e,t,n,r,i)}):t.addHook(i,function(n,r,i,a){d(e,t,n,r,a)}):s.indexOf(i)===-1?t.addHook(i,function(n,r,i){let a=e(n);if(a&&typeof a.then==`function`){a.then(e=>p(t,f(e,!0),n,r,i)).catch(i);return}i(Error(`Invalid CORS origin option`))}):t.addHook(i,function(n,r,i,a){let o=e(n);if(o&&typeof o.then==`function`){o.then(e=>p(t,f(e,!0),n,r,a)).catch(a);return}a(Error(`Invalid CORS origin option`))})}function d(e,t,n,r,i){e(n,(e,a)=>{e?i(e):p(t,f(a,!0),n,r,i)})}function f(e,t){let n={...a,...e};return Array.isArray(e.origin)&&e.origin.indexOf(`*`)!==-1&&(n.origin=`*`),Number.isInteger(n.cacheControl)?n.cacheControl=`max-age=${n.cacheControl}`:typeof n.cacheControl!=`string`&&(n.cacheControl=null),n.dynamic=t||!1,n}function p(e,t,n,r,a){(typeof t.origin!=`string`&&t.origin!==!1||t.dynamic)&&i(r),(typeof t.origin==`function`?g(e,t.origin):(e,n)=>n(null,t.origin))(n,(e,i)=>{if(e!==null)return a(e);if(i===!1||n.routeOptions.config?.cors===!1)return a();if(!i)return a(Error(`Invalid CORS origin option`));if(m(n,r,i,t),n.raw.method===`OPTIONS`&&t.preflight===!0){if(t.strictPreflight===!0&&(!n.headers.origin||!n.headers[`access-control-request-method`])){r.status(400).type(`text/plain`).send(`Invalid Preflight Request`);return}if(n.corsPreflightEnabled=!0,h(n,r,t),!t.preflightContinue){r.code(t.optionsSuccessStatus).header(`Content-Length`,`0`).send();return}}return a()})}function m(e,t,n,r){let i=_(e.headers.origin,n);i&&t.header(`Access-Control-Allow-Origin`,i),r.credentials&&t.header(`Access-Control-Allow-Credentials`,`true`),r.exposedHeaders!==null&&t.header(`Access-Control-Expose-Headers`,Array.isArray(r.exposedHeaders)?r.exposedHeaders.join(`, `):r.exposedHeaders)}function h(e,t,n){if(t.header(`Access-Control-Allow-Methods`,Array.isArray(n.methods)?n.methods.join(`, `):n.methods),n.allowedHeaders===null){r(t);let n=e.headers[`access-control-request-headers`];n!==void 0&&t.header(`Access-Control-Allow-Headers`,n)}else t.header(`Access-Control-Allow-Headers`,Array.isArray(n.allowedHeaders)?n.allowedHeaders.join(`, `):n.allowedHeaders);n.maxAge!==null&&t.header(`Access-Control-Max-Age`,String(n.maxAge)),n.cacheControl&&t.header(`Cache-Control`,n.cacheControl)}function g(e,t){return function(n,r){let i=t.call(e,n.headers.origin,r);i&&typeof i.then==`function`&&i.then(e=>r(null,e),r)}}function _(e,t){return typeof t==`string`?t:v(e,t)?e:!1}function v(e,t){if(Array.isArray(t)){for(let n=0;n<t.length;++n)if(v(e,t[n]))return!0;return!1}else if(typeof t==`string`)return e===t;else if(t instanceof RegExp)return t.lastIndex=0,t.test(e);else return!!t}let y=n(l,{fastify:`5.x`,name:`@fastify/cors`});t.exports=y,t.exports.fastifyCors=y,t.exports.default=y})),mh=o(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),hh=o(((e,t)=>{let{EMPTY_BUFFER:n}=mh(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}if(t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=require(`bufferutil`);t.exports.mask=function(t,n,r,i,o){o<48?a(t,n,r,i,o):e.mask(t,n,r,i,o)},t.exports.unmask=function(t,n){t.length<32?o(t,n):e.unmask(t,n)}}catch{}})),gh=o(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),_h=o(((e,t)=>{let n=require(`zlib`),r=hh(),i=gh(),{kStatusCode:a}=mh(),o=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),c=Symbol(`permessage-deflate`),l=Symbol(`total-length`),u=Symbol(`callback`),d=Symbol(`buffers`),f=Symbol(`error`),p;t.exports=class{constructor(e,t,n){this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,p||=new i(this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit)}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){p.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){p.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on(`error`,g),this._inflate.on(`data`,h)}this._inflate[u]=i,this._inflate.write(e),t&&this._inflate.write(s),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on(`data`,m)}this._deflate[u]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[d],this._deflate[l]);t&&(e=new o(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(e){if(this[l]+=e.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(e);return}this[f]=RangeError(`Max payload size exceeded`),this[f].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[f][a]=1009,this.removeListener(`data`,h),this.reset()}function g(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})),vh=o(((e,t)=>{let{isUtf8:n}=require(`buffer`),{hasBlob:r}=mh(),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,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,0,0,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,0,1,0];function a(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function o(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function s(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:s,isValidStatusCode:a,isValidUTF8:o,tokenChars:i},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=require(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})),yh=o(((e,t)=>{let{Writable:n}=require(`stream`),r=_h(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=mh(),{concat:c,toArrayBuffer:l,unmask:u}=hh(),{isValidStatusCode:d,isValidUTF8:f}=vh(),p=Buffer[Symbol.species];t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[s]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new p(t.buffer,t.byteOffset+e,t.length-e),new p(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new p(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=a;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?c(n,t):this._binaryType===`arraybuffer`?l(c(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=c(n,t);if(!this._skipUTF8Validation&&!f(r)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,a),this.end();else{let n=e.readUInt16BE(0);if(!d(n)){t(this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let r=new p(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(r)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o]=r,a}}})),bh=o(((e,t)=>{let{Duplex:n}=require(`stream`),{randomFillSync:r}=require(`crypto`),i=_h(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=mh(),{isBlob:c,isValidStatusCode:l}=vh(),{mask:u,toBuffer:d}=hh(),f=Symbol(`kByteLength`),p=Buffer.alloc(4),m=8*1024,h,g=m;t.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=s,this[o]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||p,t.generateMask?t.generateMask(n):(g===m&&(h===void 0&&(h=Buffer.alloc(m)),r(h,0,m),g=0),n[0]=h[g++],n[1]=h[g++],n[2]=h[g++],n[3]=h[g++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[f]!==void 0?s=t[f]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:i?(u(e,n,l,a,s),[l]):(u(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=a;else if(typeof t!=`number`||!l(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`?o.write(n,2):o.set(n,2)}let s={[f]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,s),i):this.enqueue([this.dispatch,o,!1,s,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[i.extensionName],a=t.binary?2:1,o=t.compress,s,l;typeof e==`string`?(s=Buffer.byteLength(e),l=!1):c(e)?(s=e.size,l=!1):(e=d(e),s=e.length,l=d.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,a=0),t.fin&&(this._firstFragment=!0);let u={[f]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:l,rsv1:o};c(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[f],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(_,this,e,i);return}this._bufferedBytes-=r[f];let a=d(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(v,this,e,i)})}dispatch(t,n,r,a){if(!n){this.sendFrame(e.frame(t,r),a);return}let o=this._extensions[i.extensionName];this._bufferedBytes+=r[f],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){_(this,Error(`The socket was closed while data was being compressed`),a);return}this._bufferedBytes-=r[f],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),a),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function _(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function v(e,t,n){_(e,t,n),e.onerror(t)}})),xh=o(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=mh(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,`target`,{enumerable:!0}),Object.defineProperty(f.prototype,`type`,{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,`code`,{enumerable:!0}),Object.defineProperty(p.prototype,`reason`,{enumerable:!0}),Object.defineProperty(p.prototype,`wasClean`,{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,`error`,{enumerable:!0}),Object.defineProperty(m.prototype,`message`,{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),Sh=o(((e,t)=>{let{tokenChars:n}=vh();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),Ch=o(((e,t)=>{let n=require(`events`),r=require(`https`),i=require(`http`),a=require(`net`),o=require(`tls`),{randomBytes:s,createHash:c}=require(`crypto`),{Duplex:l,Readable:u}=require(`stream`),{URL:d}=require(`url`),f=_h(),p=yh(),m=bh(),{isBlob:h}=vh(),{BINARY_TYPES:g,CLOSE_TIMEOUT:_,EMPTY_BUFFER:v,GUID:y,kForOnEventAttribute:b,kListener:x,kStatusCode:S,kWebSocket:C,NOOP:w}=mh(),{EventTarget:{addEventListener:T,removeEventListener:E}}=xh(),{format:D,parse:O}=Sh(),{toBuffer:k}=hh(),A=Symbol(`kAborted`),j=[8,13],M=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],ee=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var N=class e extends n{constructor(t,n,r){super(),this._binaryType=g[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=v,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),te(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){g.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new p({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new m(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[C]=this,a[C]=this,t[C]=this,i.on(`conclude`,L),i.on(`drain`,ie),i.on(`error`,ae),i.on(`message`,oe),i.on(`ping`,se),i.on(`pong`,ce),a.onerror=ue,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,z),t.on(`data`,fe),t.on(`end`,pe),t.on(`error`,me),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[f.extensionName]&&this._extensions[f.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){I(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),de(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){re(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||v,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){re(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||v,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){re(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[f.extensionName]||(i.compress=!1),this._sender.send(t||v,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){I(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(N,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(N.prototype,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(N,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(N.prototype,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(N,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(N.prototype,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(N,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),Object.defineProperty(N.prototype,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(N.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(N.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[b])return t[x];return null},set(t){for(let t of this.listeners(e))if(t[b]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[b]:!0})}})}),N.prototype.addEventListener=T,N.prototype.removeEventListener=E,t.exports=N;function te(e,t,n,a){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_,protocolVersion:j[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!j.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${j.join(`, `)})`);let l;if(t instanceof d)l=t;else try{l=new d(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}l.protocol===`http:`?l.protocol=`ws:`:l.protocol===`https:`&&(l.protocol=`wss:`),e._url=l.href;let u=l.protocol===`wss:`,p=l.protocol===`ws+unix:`,m;if(l.protocol!==`ws:`&&!u&&!p?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?m=`The URL's pathname is empty`:l.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;P(e,t);return}let h=u?443:80,g=s(16).toString(`base64`),v=u?r.request:i.request,b=new Set,x;if(o.createConnection=o.createConnection||(u?F:ne),o.defaultPort=o.defaultPort||h,o.port=l.port||h,o.host=l.hostname.startsWith(`[`)?l.hostname.slice(1,-1):l.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=l.pathname+l.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(x=new f(o.perMessageDeflate===!0?{}:o.perMessageDeflate,!1,o.maxPayload),o.headers[`Sec-WebSocket-Extensions`]=D({[f.extensionName]:x.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!ee.test(e)||b.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);b.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(l.username||l.password)&&(o.auth=`${l.username}:${l.password}`),p){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let S;if(o.followRedirects){if(e._redirects===0){e._originalIpc=p,e._originalSecure=u,e._originalHostOrSocketPath=p?o.socketPath:l.host;let t=a&&a.headers;if(a={...a,headers:{}},t)for(let[e,n]of Object.entries(t))a.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=p?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:l.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!a.headers.authorization&&(a.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),S=e._req=v(o),e._redirects&&e.emit(`redirect`,e.url,S)}else S=e._req=v(o);o.timeout&&S.on(`timeout`,()=>{I(e,S,`Opening handshake has timed out`)}),S.on(`error`,t=>{S===null||S[A]||(S=e._req=null,P(e,t))}),S.on(`response`,r=>{let i=r.headers.location,s=r.statusCode;if(i&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){I(e,S,`Maximum redirects exceeded`);return}S.abort();let r;try{r=new d(i,t)}catch{P(e,SyntaxError(`Invalid URL: ${i}`));return}te(e,r,n,a)}else e.emit(`unexpected-response`,S,r)||I(e,S,`Unexpected server response: ${r.statusCode}`)}),S.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==N.CONNECTING)return;S=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){I(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+y).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){I(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],l;if(s===void 0?b.size&&(l=`Server sent no subprotocol`):b.size?b.has(s)||(l=`Server sent an invalid subprotocol`):l=`Server sent a subprotocol but none was requested`,l){I(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!x){I(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=O(u)}catch{I(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){I(e,n,`Server indicated an extension that was not requested`);return}try{x.accept(t[f.extensionName])}catch{I(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[f.extensionName]=x}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(S,e):S.end()}function P(e,t){e._readyState=N.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function ne(e){return e.path=e.socketPath,a.connect(e)}function F(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function I(e,t,n){e._readyState=N.CLOSING;let r=Error(n);Error.captureStackTrace(r,I),t.setHeader?(t[A]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(P,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function re(e,t,n){if(t){let n=h(t)?t.size:k(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${M[e.readyState]})`);process.nextTick(n,t)}}function L(e,t){let n=this[C];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[C]!==void 0&&(n._socket.removeListener(`data`,fe),process.nextTick(le,n._socket),e===1005?n.close():n.close(e,t))}function ie(){let e=this[C];e.isPaused||e._socket.resume()}function ae(e){let t=this[C];t._socket[C]!==void 0&&(t._socket.removeListener(`data`,fe),process.nextTick(le,t._socket),t.close(e[S])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function R(){this[C].emitClose()}function oe(e,t){this[C].emit(`message`,e,t)}function se(e){let t=this[C];t._autoPong&&t.pong(e,!this._isServer,w),t.emit(`ping`,e)}function ce(e){this[C].emit(`pong`,e)}function le(e){e.resume()}function ue(e){let t=this[C];t.readyState!==N.CLOSED&&(t.readyState===N.OPEN&&(t._readyState=N.CLOSING,de(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function de(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function z(){let e=this[C];if(this.removeListener(`close`,z),this.removeListener(`data`,fe),this.removeListener(`end`,pe),e._readyState=N.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[C]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,R),e._receiver.on(`finish`,R))}function fe(e){this[C]._receiver.write(e)||this.pause()}function pe(){let e=this[C];e._readyState=N.CLOSING,e._receiver.end(),this.end()}function me(){let e=this[C];this.removeListener(`error`,me),this.on(`error`,w),e&&(e._readyState=N.CLOSING,this.destroy())}})),wh=o(((e,t)=>{Ch();let{Duplex:n}=require(`stream`);function r(e){e.emit(`close`)}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function a(e){this.removeListener(`error`,a),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function o(e,t){let o=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(o=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let i=!1;e.once(`error`,function(e){i=!0,n(e)}),e.once(`close`,function(){i||n(t),process.nextTick(r,s)}),o&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,i),s.on(`error`,a),s}t.exports=o})),Th=o(((e,t)=>{let{tokenChars:n}=vh();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),Eh=o(((e,t)=>{let n=require(`events`),r=require(`http`),{Duplex:i}=require(`stream`),{createHash:a}=require(`crypto`),o=Sh(),s=_h(),c=Th(),l=Ch(),{CLOSE_TIMEOUT:u,GUID:d,kWebSocket:f}=mh(),p=/^[+/0-9A-Za-z]{22}==$/;t.exports=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:u,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=m(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(h,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(h,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{h(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,g);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){v(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){v(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!p.test(i)){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){_(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{v(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&f!==void 0){let n=new s(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=o.parse(f);e[s.extensionName]&&(n.accept(e[s.extensionName]),m[s.extensionName]=n)}catch{v(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${l===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return _(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return _(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,c,l){if(!i.readable||!i.writable)return i.destroy();if(i[f])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return _(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${a(`sha1`).update(t+d).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[s.extensionName]){let t=e[s.extensionName].params,n=o.format({[s.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
|
|
450
|
+
`))}}})),Fm=o(((e,t)=>{let n=Pm(),r={STATIC:0,PARAMETRIC:1,WILDCARD:2};var i=class{constructor(){this.isLeafNode=!1,this.routes=null,this.handlerStorage=null}addRoute(e,t){this.routes===null&&(this.routes=[]),this.handlerStorage===null&&(this.handlerStorage=new n),this.isLeafNode=!0,this.routes.push(e),this.handlerStorage.addHandler(t,e)}},a=class extends i{constructor(){super(),this.staticChildren={}}findStaticMatchingChild(e,t){let n=this.staticChildren[e.charAt(t)];return n===void 0||!n.matchPrefix(e,t)?null:n}getStaticChild(e,t=0){if(e.length===t)return this;let n=this.findStaticMatchingChild(e,t);return n?n.getStaticChild(e,t+n.prefix.length):null}createStaticChild(e){if(e.length===0)return this;let t=this.staticChildren[e.charAt(0)];if(t){let n=1;for(;n<t.prefix.length;n++)if(e.charCodeAt(n)!==t.prefix.charCodeAt(n)){t=t.split(this,n);break}return t.createStaticChild(e.slice(n))}let n=e.charAt(0);return this.staticChildren[n]=new o(e),this.staticChildren[n]}},o=class e extends a{constructor(e){super(),this.prefix=e,this.wildcardChild=null,this.parametricChildren=[],this.kind=r.STATIC,this._compilePrefixMatch()}getParametricChild(e){let t=e&&e.source;return this.parametricChildren.find(e=>(e.regex&&e.regex.source)===t)||null}createParametricChild(e,t,n){let r=this.getParametricChild(e);return r?(r.nodePaths.add(n),r):(r=new s(e,t,n),this.parametricChildren.push(r),this.parametricChildren.sort((e,t)=>e.isRegex?t.isRegex?e.staticSuffix===null?1:t.staticSuffix===null?-1:t.staticSuffix.endsWith(e.staticSuffix)?1:e.staticSuffix.endsWith(t.staticSuffix)?-1:0:-1:1),r)}getWildcardChild(){return this.wildcardChild}createWildcardChild(){return this.wildcardChild=this.getWildcardChild()||new c,this.wildcardChild}split(t,n){let r=this.prefix.slice(0,n),i=this.prefix.slice(n);this.prefix=i,this._compilePrefixMatch();let a=new e(r);return a.staticChildren[i.charAt(0)]=this,t.staticChildren[r.charAt(0)]=a,a}getNextNode(e,t,n,r){let i=this.findStaticMatchingChild(e,t),a=0;if(i===null){if(this.parametricChildren.length===0)return this.wildcardChild;i=this.parametricChildren[0],a=1}this.wildcardChild!==null&&n.push({paramsCount:r,brotherPathIndex:t,brotherNode:this.wildcardChild});for(let e=this.parametricChildren.length-1;e>=a;e--)n.push({paramsCount:r,brotherPathIndex:t,brotherNode:this.parametricChildren[e]});return i}_compilePrefixMatch(){if(this.prefix.length===1){this.matchPrefix=()=>!0;return}let e=[];for(let t=1;t<this.prefix.length;t++){let n=this.prefix.charCodeAt(t);e.push(`path.charCodeAt(i + ${t}) === ${n}`)}this.matchPrefix=Function(`path`,`i`,`return ${e.join(` && `)}`)}},s=class extends a{constructor(e,t,n){super(),this.isRegex=!!e,this.regex=e||null,this.staticSuffix=t||null,this.kind=r.PARAMETRIC,this.nodePaths=new Set([n])}getNextNode(e,t){return this.findStaticMatchingChild(e,t)}},c=class extends i{constructor(){super(),this.kind=r.WILDCARD}getNextNode(){return null}};t.exports={StaticNode:o,ParametricNode:s,WildcardNode:c,NODE_TYPES:r}})),Im=o(((e,t)=>{let n=require(`node:assert`);function r(){if(!(this instanceof r))return new r;this.store=new Map,this.maxMajor=0,this.maxMinors={},this.maxPatches={}}r.prototype.set=function(e,t){if(typeof e!=`string`)throw TypeError(`Version should be a string`);let[n,r,i]=e.split(`.`,3);if(isNaN(n))throw TypeError(`Major version must be a numeric value`);return n=Number(n),r=Number(r)||0,i=Number(i)||0,n>=this.maxMajor&&(this.maxMajor=n,this.store.set(`x`,t),this.store.set(`*`,t),this.store.set(`x.x`,t),this.store.set(`x.x.x`,t)),r>=(this.maxMinors[n]||0)&&(this.maxMinors[n]=r,this.store.set(`${n}.x`,t),this.store.set(`${n}.x.x`,t)),i>=(this.maxPatches[`${n}.${r}`]||0)&&(this.maxPatches[`${n}.${r}`]=i,this.store.set(`${n}.${r}.x`,t)),this.store.set(`${n}.${r}.${i}`,t),this},r.prototype.get=function(e){return this.store.get(e)},t.exports={name:`version`,mustMatchWhenDerived:!0,storage:r,validate(e){n(typeof e==`string`,`Version should be a string`)}}})),Lm=o(((e,t)=>{let n=require(`node:assert`);function r(){let e=new Map,t=[];return{get:n=>{let r=e.get(n);if(r)return r;for(let e of t)if(e.host.test(n))return e.value},set:(n,r)=>{n instanceof RegExp?t.push({host:n,value:r}):e.set(n,r)}}}t.exports={name:`host`,mustMatchWhenDerived:!1,storage:r,validate(e){n(typeof e==`string`||Object.prototype.toString.call(e)===`[object RegExp]`,`Host should be a string or a RegExp`)}}})),Rm=o(((e,t)=>{let n=Im(),r=Lm(),i=require(`node:assert`);t.exports=class{constructor(e){if(this.strategies={version:n,host:r},this.strategiesInUse=new Set,this.asyncStrategiesInUse=new Set,e)for(let t of Object.values(e))this.addConstraintStrategy(t)}isStrategyUsed(e){return this.strategiesInUse.has(e)||this.asyncStrategiesInUse.has(e)}hasConstraintStrategy(e){let t=this.strategies[e];return t===void 0?!1:t.isCustom||this.isStrategyUsed(e)}addConstraintStrategy(e){if(i(typeof e.name==`string`&&e.name!==``,`strategy.name is required.`),i(e.storage&&typeof e.storage==`function`,`strategy.storage function is required.`),i(e.deriveConstraint&&typeof e.deriveConstraint==`function`,`strategy.deriveConstraint function is required.`),this.strategies[e.name]&&this.strategies[e.name].isCustom)throw Error(`There already exists a custom constraint with the name ${e.name}.`);if(this.isStrategyUsed(e.name))throw Error(`There already exists a route with ${e.name} constraint.`);e.isCustom=!0,e.isAsync=e.deriveConstraint.length===3,this.strategies[e.name]=e,e.mustMatchWhenDerived&&this.noteUsage({[e.name]:e})}deriveConstraints(e,t,n){let r=this.deriveSyncConstraints(e,t);if(n===void 0)return r;this.deriveAsyncConstraints(r,e,t,n)}deriveSyncConstraints(e,t){}noteUsage(e){if(e){let t=this.strategiesInUse.size;for(let t in e)this.strategies[t].isAsync?this.asyncStrategiesInUse.add(t):this.strategiesInUse.add(t);t!==this.strategiesInUse.size&&this._buildDeriveConstraints()}}newStoreForConstraint(e){if(!this.strategies[e])throw Error(`No strategy registered for constraint key ${e}`);return this.strategies[e].storage()}validateConstraints(e){for(let t in e){let n=e[t];if(n===void 0)throw Error(`Can't pass an undefined constraint value, must pass null or no key at all`);let r=this.strategies[t];if(!r)throw Error(`No strategy registered for constraint key ${t}`);r.validate&&r.validate(n)}}deriveAsyncConstraints(e,t,n,r){let i=this.asyncStrategiesInUse.size;if(i===0){r(null,e);return}e||={};for(let a of this.asyncStrategiesInUse)this.strategies[a].deriveConstraint(t,n,(t,n)=>{if(t!==null){r(t);return}e[a]=n,--i===0&&r(null,e)})}_buildDeriveConstraints(){if(this.strategiesInUse.size===0)return;let e=[`return {`];for(let t of this.strategiesInUse){let n=this.strategies[t];n.isCustom?e.push(` ${n.name}: this.strategies.${t}.deriveConstraint(req, ctx),`):t===`version`?e.push(` version: req.headers['accept-version'],`):e.push(` host: req.headers.host || req.headers[':authority'],`)}e.push(`}`),this.deriveSyncConstraints=Function(`req`,`ctx`,e.join(`
|
|
451
|
+
`)).bind(this)}}})),zm=o(((e,t)=>{t.exports=`ACL.BIND.CHECKOUT.CONNECT.COPY.DELETE.GET.HEAD.LINK.LOCK.M-SEARCH.MERGE.MKACTIVITY.MKCALENDAR.MKCOL.MOVE.NOTIFY.OPTIONS.PATCH.POST.PROPFIND.PROPPATCH.PURGE.PUT.QUERY.REBIND.REPORT.SEARCH.SOURCE.SUBSCRIBE.TRACE.UNBIND.UNLINK.UNLOCK.UNSUBSCRIBE`.split(`.`)})),Bm=o(((e,t)=>{function n(e,t){return e===50?t===53?`%`:t===51?`#`:t===52?`$`:t===54?`&`:t===66||t===98?`+`:t===67||t===99?`,`:t===70||t===102?`/`:null:e===51?t===65||t===97?`:`:t===66||t===98?`;`:t===68||t===100?`=`:t===70||t===102?`?`:null:e===52&&t===48?`@`:null}function r(e,t){let r=!1,i=!1,a=``;for(let o=1;o<e.length;o++){let s=e.charCodeAt(o);if(s===37){let t=e.charCodeAt(o+1),a=e.charCodeAt(o+2);n(t,a)===null?r=!0:(i=!0,t===50&&a===53&&(r=!0,e=e.slice(0,o+1)+`25`+e.slice(o+1),o+=2),o+=2)}else if(s===63||s===35||s===59&&t){a=e.slice(o+1),e=e.slice(0,o);break}}return{path:r?decodeURI(e):e,querystring:a,shouldDecodeParam:i}}function i(e){let t=e.indexOf(`%`);if(t===-1)return e;let r=``,i=t;for(let a=t;a<e.length;a++)if(e.charCodeAt(a)===37){let t=n(e.charCodeAt(a+1),e.charCodeAt(a+2));r+=e.slice(i,a)+t,i=a+3}return e.slice(0,t)+r+e.slice(i)}t.exports={safeDecodeURI:r,safeDecodeURIComponent:i}})),Vm=o(((e,t)=>{let n=require(`node:assert`),r=vm(),i=Am(),a=Ad(),{prettyPrintTree:o}=Mm(),{StaticNode:s,NODE_TYPES:c}=Fm(),l=Rm(),u=zm(),d=jm(),{safeDecodeURI:f,safeDecodeURIComponent:p}=Bm(),m=/^https?:\/\/.*?\//,h=/(\/:[^/()]*?)\?(\/?)/,g=/[.*+?^${}()|[\]\\]/g,_=/\/\/+/g;if(!i(m))throw Error(`the FULL_PATH_REGEXP is not safe, update this module`);if(!i(h))throw Error(`the OPTIONAL_PARAM_REGEXP is not safe, update this module`);if(!i(g))throw Error(`the ESCAPE_REGEXP is not safe, update this module`);if(!i(_))throw Error(`the REMOVE_DUPLICATE_SLASHES_REGEXP is not safe, update this module`);function v(e){if(!(this instanceof v))return new v(e);e||={},this._opts=e,e.defaultRoute?(n(typeof e.defaultRoute==`function`,`The default route must be a function`),this.defaultRoute=e.defaultRoute):this.defaultRoute=null,e.onBadUrl?(n(typeof e.onBadUrl==`function`,`The bad url handler must be a function`),this.onBadUrl=e.onBadUrl):this.onBadUrl=null,e.buildPrettyMeta?(n(typeof e.buildPrettyMeta==`function`,`buildPrettyMeta must be a function`),this.buildPrettyMeta=e.buildPrettyMeta):this.buildPrettyMeta=w,e.querystringParser?(n(typeof e.querystringParser==`function`,`querystringParser must be a function`),this.querystringParser=e.querystringParser):this.querystringParser=e=>e.length===0?{}:r.parse(e),this.caseSensitive=e.caseSensitive===void 0?!0:e.caseSensitive,this.ignoreTrailingSlash=e.ignoreTrailingSlash||!1,this.ignoreDuplicateSlashes=e.ignoreDuplicateSlashes||!1,this.maxParamLength=e.maxParamLength||100,this.allowUnsafeRegex=e.allowUnsafeRegex||!1,this.constrainer=new l(e.constraints),this.useSemicolonDelimiter=e.useSemicolonDelimiter||!1,this.routes=[],this.trees={}}v.prototype.on=function(e,t,r,i,a){typeof r==`function`&&(i!==void 0&&(a=i),i=r,r={}),n(typeof t==`string`,`Path should be a string`),n(t.length>0,`The path could not be empty`),n(t[0]===`/`||t[0]===`*`,"The first character of a path should be `/` or `*`"),n(typeof i==`function`,`Handler should be a function`);let o=t.match(h);if(o){n(t.length===o.index+o[0].length,`Optional Parameter needs to be the last parameter of the path`);let s=t.replace(h,`$1$2`),c=t.replace(h,`$2`)||`/`;this.on(e,s,r,i,a),this.on(e,c,r,i,a);return}let s=t;this.ignoreDuplicateSlashes&&(t=b(t)),this.ignoreTrailingSlash&&(t=x(t));let c=Array.isArray(e)?e:[e];for(let e of c)n(typeof e==`string`,`Method should be a string`),n(u.includes(e),`Method '${e}' is not an http method.`),this._on(e,t,r,i,a,s)},v.prototype._on=function(e,t,r,o,c){let l={};r.constraints!==void 0&&(n(typeof r.constraints==`object`&&r.constraints!==null,`Constraints should be an object`),Object.keys(r.constraints).length!==0&&(l=r.constraints)),this.constrainer.validateConstraints(l),this.constrainer.noteUsage(l),this.trees[e]===void 0&&(this.trees[e]=new s(`/`));let u=t;if(u===`*`&&this.trees[e].prefix.length!==0){let t=this.trees[e];this.trees[e]=new s(``),this.trees[e].staticChildren[`/`]=t}let d=this.trees[e],f=d.prefix.length,p=[];for(let e=0;e<=u.length;e++){if(u.charCodeAt(e)===58&&u.charCodeAt(e+1)===58){e++;continue}let t=u.charCodeAt(e)===58&&u.charCodeAt(e+1)!==58,r=u.charCodeAt(e)===42;if(t||r||e===u.length&&e!==f){let t=u.slice(f,e);this.caseSensitive||(t=t.toLowerCase()),t=t.replaceAll(`::`,`:`),t=t.replaceAll(`%`,`%25`),d=d.createStaticChild(t)}if(t){let t=!1,r=!0,a=``,o=[],s=e+1;for(let c=s;;c++){let l=u.charCodeAt(c),m=l===40,h=l===45||l===46,g=l===47||c===u.length;if(m||h||g){let l=u.slice(s,c);if(p.push(l),t=t||m||h,m){let e=C(u,c),t=u.slice(c,e+1);this.allowUnsafeRegex||n(i(new RegExp(t)),`The regex '${t}' is not safe!`),o.push(S(t)),c=e+1,r=!0}else o.push(r?`(.*?)`:`(${a}|(?:(?!${a}).)*)`),r=!1;let _=c;for(;c<u.length;c++){let e=u.charCodeAt(c);if(e===47)break;if(e===58)if(u.charCodeAt(c+1)===58)c++;else break}let v=u.slice(_,c);if(v&&(v=v.replaceAll(`::`,`:`),v=v.replaceAll(`%`,`%25`),o.push(a=y(v))),s=c+1,g||u.charCodeAt(c)===47||c===u.length){let n=t?`()`+v:v,r=u.slice(e,c);u=u.slice(0,e+1)+n+u.slice(c),e+=n.length;let i=t?RegExp(`^`+o.join(``)+`$`):null;d=d.createParametricChild(i,v||null,r),f=e+1;break}}}}else if(r&&(p.push(`*`),d=d.createWildcardChild(),f=e+1,e!==u.length-1))throw Error(`Wildcard must be the last character in the route`)}this.caseSensitive||(u=u.toLowerCase()),u===`*`&&(u=`/*`);for(let t of this.routes){let n=t.opts.constraints||{};if(t.method===e&&t.pattern===u&&a(n,l))throw Error(`Method '${e}' already declared for route '${u}' with constraints '${JSON.stringify(l)}'`)}let m={method:e,path:t,pattern:u,params:p,opts:r,handler:o,store:c};this.routes.push(m),d.addRoute(m,this.constrainer)},v.prototype.hasRoute=function(e,t,n){return this.findRoute(e,t,n)!==null},v.prototype.findRoute=function(e,t,r={}){if(this.trees[e]===void 0)return null;let o=t,s=this.trees[e],c=s.prefix.length,l=[];for(let e=0;e<=o.length;e++){if(o.charCodeAt(e)===58&&o.charCodeAt(e+1)===58){e++;continue}let t=o.charCodeAt(e)===58&&o.charCodeAt(e+1)!==58,r=o.charCodeAt(e)===42;if(t||r||e===o.length&&e!==c){let t=o.slice(c,e);if(this.caseSensitive||(t=t.toLowerCase()),t=t.replaceAll(`::`,`:`),t=t.replaceAll(`%`,`%25`),s=s.getStaticChild(t),s===null)return null}if(t){let t=!1,r=!0,a=``,u=[],d=e+1;for(let f=d;;f++){let p=o.charCodeAt(f),m=p===40,h=p===45||p===46,g=p===47||f===o.length;if(m||h||g){let p=o.slice(d,f);if(l.push(p),t=t||m||h,m){let e=C(o,f),t=o.slice(f,e+1);this.allowUnsafeRegex||n(i(new RegExp(t)),`The regex '${t}' is not safe!`),u.push(S(t)),f=e+1,r=!1}else u.push(r?`(.*?)`:`(${a}|(?:(?!${a}).)*)`),r=!1;let _=f;for(;f<o.length;f++){let e=o.charCodeAt(f);if(e===47)break;if(e===58)if(o.charCodeAt(f+1)===58)f++;else break}let v=o.slice(_,f);if(v&&(v=v.replaceAll(`::`,`:`),v=v.replaceAll(`%`,`%25`),u.push(a=y(v))),d=f+1,g||o.charCodeAt(f)===47||f===o.length){let n=t?`()`+v:v,r=o.slice(e,f);o=o.slice(0,e+1)+n+o.slice(f),e+=n.length;let i=t?RegExp(`^`+u.join(``)+`$`):null;if(s=s.getParametricChild(i,v||null,r),s===null)return null;c=e+1;break}}}}else if(r&&(l.push(`*`),s=s.getWildcardChild(),c=e+1,e!==o.length-1))throw Error(`Wildcard must be the last character in the route`)}this.caseSensitive||(o=o.toLowerCase());for(let t of this.routes){let n=t.opts.constraints||{};if(t.method===e&&t.pattern===o&&a(n,r))return{handler:t.handler,store:t.store,params:t.params}}return null},v.prototype.hasConstraintStrategy=function(e){return this.constrainer.hasConstraintStrategy(e)},v.prototype.addConstraintStrategy=function(e){this.constrainer.addConstraintStrategy(e),this._rebuild(this.routes)},v.prototype.reset=function(){this.trees={},this.routes=[]},v.prototype.off=function(e,t,r){n(typeof t==`string`,`Path should be a string`),n(t.length>0,`The path could not be empty`),n(t[0]===`/`||t[0]===`*`,"The first character of a path should be `/` or `*`"),n(r===void 0||typeof r==`object`&&!Array.isArray(r)&&r!==null,`Constraints should be an object or undefined.`);let i=t.match(h);if(i){n(t.length===i.index+i[0].length,`Optional Parameter needs to be the last parameter of the path`);let a=t.replace(h,`$1$2`),o=t.replace(h,`$2`);this.off(e,a,r),this.off(e,o,r);return}this.ignoreDuplicateSlashes&&(t=b(t)),this.ignoreTrailingSlash&&(t=x(t));let a=Array.isArray(e)?e:[e];for(let e of a)this._off(e,t,r)},v.prototype._off=function(e,t,r){n(typeof e==`string`,`Method should be a string`),n(u.includes(e),`Method '${e}' is not an http method.`);function i(n){return e!==n.method||t!==n.path}function o(e){return i(e)||!a(r,e.opts.constraints||{})}let s=r?o:i,c=this.routes.filter(s);this._rebuild(c)},v.prototype.lookup=function(e,t,n,r){if(typeof n==`function`&&(r=n,n=void 0),r===void 0){let r=this.constrainer.deriveConstraints(e,n),i=this.find(e.method,e.url,r);return this.callHandler(i,e,t,n)}this.constrainer.deriveConstraints(e,n,(i,a)=>{if(i!==null){r(i);return}try{let i=this.find(e.method,e.url,a),o=this.callHandler(i,e,t,n);r(null,o)}catch(e){r(e)}})},v.prototype.callHandler=function(e,t,n,r){return e===null?this._defaultRoute(t,n,r):r===void 0?e.handler(t,n,e.params,e.store,e.searchParams):e.handler.call(r,t,n,e.params,e.store,e.searchParams)},v.prototype.find=function(e,t,n){let r=this.trees[e];if(r===void 0)return null;t.charCodeAt(0)!==47&&(t=t.replace(m,`/`)),this.ignoreDuplicateSlashes&&(t=b(t));let i,a,o;try{i=f(t,this.useSemicolonDelimiter),t=i.path,a=i.querystring,o=i.shouldDecodeParam}catch{return this._onBadUrl(t)}this.ignoreTrailingSlash&&(t=x(t));let s=t;this.caseSensitive===!1&&(t=t.toLowerCase());let l=this.maxParamLength,u=r.prefix.length,d=[],h=t.length,g=[];for(;;){if(u===h&&r.isLeafNode){let e=r.handlerStorage.getMatchingHandler(n);if(e!==null)return{handler:e.handler,store:e.store,params:e._createParamsObject(d),searchParams:this.querystringParser(a)}}let e=r.getNextNode(t,u,g,d.length);if(e===null){if(g.length===0)return null;let t=g.pop();u=t.brotherPathIndex,d.splice(t.paramsCount),e=t.brotherNode}if(r=e,r.kind===c.STATIC){u+=r.prefix.length;continue}if(r.kind===c.WILDCARD){let e=s.slice(u);o&&(e=p(e)),d.push(e),u=h;continue}let i=s.indexOf(`/`,u);i===-1&&(i=h);let f=s.slice(u,i);if(o&&(f=p(f)),r.isRegex){let e=r.regex.exec(f);if(e===null)continue;for(let t=1;t<e.length;t++){let n=e[t];if(n.length>l)return null;d.push(n)}}else{if(f.length>l)return null;d.push(f)}u=i}},v.prototype._rebuild=function(e){this.reset();for(let t of e){let{method:e,path:n,opts:r,handler:i,store:a}=t;this._on(e,n,r,i,a)}},v.prototype._defaultRoute=function(e,t,n){if(this.defaultRoute!==null)return n===void 0?this.defaultRoute(e,t):this.defaultRoute.call(n,e,t);t.statusCode=404,t.end()},v.prototype._onBadUrl=function(e){if(this.onBadUrl===null)return null;let t=this.onBadUrl;return{handler:(n,r,i)=>t(e,n,r),params:{},store:null}},v.prototype.prettyPrint=function(e={}){let t=e.method;e.buildPrettyMeta=this.buildPrettyMeta.bind(this);let n=null;if(t===void 0){let{version:e,host:t,...r}=this.constrainer.strategies;r[d.name]=d;let i=new v({...this._opts,constraints:r}),a=this.routes.map(e=>{let t={...e.opts.constraints,[d.name]:e.method};return{...e,method:`MERGED`,opts:{constraints:t}}});i._rebuild(a),n=i.trees.MERGED}else n=this.trees[t];return n==null?`(empty tree)`:o(n,e)};for(let e in u){if(!u.hasOwnProperty(e))continue;let t=u[e],n=t.toLowerCase();v.prototype[n]=function(e,n,r){return this.on(t,e,n,r)}}v.prototype.all=function(e,t,n){this.on(u,e,t,n)},v.sanitizeUrlPath=function(e,t){let n=f(e,t);return n.shouldDecodeParam?p(n.path):n.path},t.exports=v;function y(e){return e.replace(g,`\\$&`)}function b(e){return e.indexOf(`//`)===-1?e:e.replace(_,`/`)}function x(e){return e.length>1&&e.charCodeAt(e.length-1)===47?e.slice(0,-1):e}function S(e){return e.charCodeAt(1)===94&&(e=e.slice(0,1)+e.slice(2)),e.charCodeAt(e.length-2)===36&&(e=e.slice(0,e.length-2)+e.slice(e.length-1)),e}function C(e,t){let n=1;for(;t<e.length;){if(t++,e.charCodeAt(t)===92){t++;continue}if(e.charCodeAt(t)===41?n--:e.charCodeAt(t)===40&&n++,!n)return t}throw TypeError(`Invalid regexp expression in "`+e+`"`)}function w(e){return!e||!e.store?{}:Object.assign({},e.store)}})),Hm=o(((e,t)=>{function n(e,t,n,r){if(n===void 0){t.header(`content-length`,`0`),r(null,null);return}if(typeof n.resume==`function`){n.on(`error`,e=>{t.log.error({err:e},`Error on Stream found for HEAD route`)}),n.resume(),r(null,null);return}if(typeof n.getReader==`function`){n.cancel(`Stream cancelled by HEAD route`).catch(e=>{t.log.error({err:e},`Error on Stream found for HEAD route`)}),r(null,null);return}let i=``+Buffer.byteLength(n);t.header(`content-length`,i),r(null,null)}function r(e){return e==null?n:Array.isArray(e)?[...e,n]:[e,n]}t.exports={parseHeadOnSendHandlers:r}})),Um=o(((e,t)=>{let n=Vm(),r=pd(),i=Cu(),{onRequestAbortHookRunner:a,lifecycleHooks:o,preParsingHookRunner:s,onTimeoutHookRunner:c,onRequestHookRunner:l}=hu(),{normalizeSchema:u}=rd(),{parseHeadOnSendHandlers:d}=Hm(),{compileSchemasForValidation:f,compileSchemasForSerialization:p}=Su(),{FST_ERR_SCH_VALIDATION_BUILD:m,FST_ERR_SCH_SERIALIZATION_BUILD:h,FST_ERR_DUPLICATED_ROUTE:g,FST_ERR_INVALID_URL:_,FST_ERR_HOOK_INVALID_HANDLER:v,FST_ERR_ROUTE_OPTIONS_NOT_OBJ:y,FST_ERR_ROUTE_DUPLICATED_HANDLER:b,FST_ERR_ROUTE_HANDLER_NOT_FN:x,FST_ERR_ROUTE_MISSING_HANDLER:S,FST_ERR_ROUTE_METHOD_NOT_SUPPORTED:C,FST_ERR_ROUTE_METHOD_INVALID:w,FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED:T,FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INT:E,FST_ERR_HOOK_INVALID_ASYNC_HANDLER:D}=mu(),{kRoutePrefix:O,kSupportedHTTPMethods:k,kLogLevel:A,kLogSerializers:j,kHooks:M,kSchemaController:ee,kOptions:N,kReplySerializerDefault:te,kReplyIsError:P,kRequestPayloadStream:ne,kDisableRequestLogging:F,kSchemaErrorFormatter:I,kErrorHandler:re,kHasBeenDecorated:L,kRequestAcceptVersion:ie,kRouteByFastify:ae,kRouteContext:R}=du(),{buildErrorHandler:oe}=od(),{createChildLogger:se}=td(),{getGenReqId:ce}=pm(),{FSTDEP022:le}=pu(),ue=[`allowUnsafeRegex`,`buildPrettyMeta`,`caseSensitive`,`constraints`,`defaultRoute`,`ignoreDuplicateSlashes`,`ignoreTrailingSlash`,`maxParamLength`,`onBadUrl`,`querystringParser`,`useSemicolonDelimiter`];function de(e){let t=n(e),i,s,c,C,w,T,E,k,P,ne,R,le,ue,de=!1;return{setup(e,t){i=t.avvio,s=t.fourOhFour,c=e.logger,C=t.hasLogger,w=t.setupResponseListeners,T=t.throwIfAlreadyStarted,le=e.exposeHeadRoutes,E=e.disableRequestLogging,typeof E==`function`&&(k=e.disableRequestLogging),P=e.routerOptions.ignoreTrailingSlash,ne=e.routerOptions.ignoreDuplicateSlashes,R=Object.hasOwn(e,`return503OnClosing`)?e.return503OnClosing:!0,ue=t.keepAliveConnections},routing:t.lookup.bind(t),route:we,hasRoute:Se,prepareRoute:xe,routeHandler:Te,closeRoutes:()=>{de=!0},printRoutes:t.prettyPrint.bind(t),addConstraintStrategy:_e,hasConstraintStrategy:ye,isAsyncConstraint:be,findRoute:Ce};function _e(e){return T(`Cannot add constraint strategy!`),t.addConstraintStrategy(e)}function ye(e){return t.hasConstraintStrategy(e)}function be(){return t.constrainer.asyncStrategiesInUse.size>0}function xe({method:e,url:t,options:n,handler:r,isFastify:i}){if(typeof t!=`string`)throw new _(typeof t);if(!r&&typeof n==`function`)r=n,n={};else if(r&&typeof r==`function`){if(Object.prototype.toString.call(n)!==`[object Object]`)throw new y(e,t);if(n.handler)throw typeof n.handler==`function`?new b(e,t):new x(e,t)}return n=Object.assign({},n,{method:e,url:t,path:t,handler:r||n&&n.handler}),we.call(this,{options:n,isFastify:i})}function Se({options:e}){let n=e.method?.toUpperCase()??``;return t.hasRoute(n,e.url||``,e.constraints)}function Ce(e){let n=t.find(e.method,e.url||``,e.constraints);return n?{handler:n.handler,params:n.params,searchParams:n.searchParams}:null}function we({options:e,isFastify:n}){T(`Cannot add route!`);let a={...e},c=a.url||a.path||``;if(!a.handler)throw new S(a.method,c);if(a.errorHandler!==void 0&&typeof a.errorHandler!=`function`)throw new x(a.method,c);he(a.bodyLimit);let l=a.exposeHeadRoute??le,_=!1,y=!1;if(Array.isArray(a.method))for(let e=0;e<a.method.length;++e)a.method[e]=pe.call(this,a.method[e]),me.call(this,a.method[e],c,a.schema),_=a.method.includes(`GET`),y=a.method.includes(`HEAD`);else a.method=pe.call(this,a.method),me.call(this,a.method,c,a.schema),_=a.method===`GET`,y=a.method===`HEAD`;let b=l&&_?{...e}:null,C=this[O];if(c===`/`&&C.length>0&&a.method!==`HEAD`)switch(a.prefixTrailingSlash){case`slash`:w.call(this,{path:c,isFastify:n});break;case`no-slash`:w.call(this,{path:``,isFastify:n});break;default:w.call(this,{path:``,isFastify:n}),P!==!0&&(ne!==!0||!C.endsWith(`/`))&&w.call(this,{path:c,prefixing:!0,isFastify:n})}else c[0]===`/`&&C.endsWith(`/`)?w.call(this,{path:c.slice(1),isFastify:n}):w.call(this,{path:c,isFastify:n});return this;function w({path:e,prefixing:n=!1,isFastify:c=!1}){let x=C+e;if(a.url=x,a.path=x,a.routePath=e,a.prefix=C,a.logLevel=a.logLevel||this[A],(this[j]||a.logSerializers)&&(a.logSerializers=Object.assign(Object.create(this[j]),a.logSerializers)),a.attachValidation??=!1,n===!1)for(let e of this[M].onRoute)e.call(this,a);for(let e of o)if(a&&e in a){if(Array.isArray(a[e]))for(let t of a[e]){if(typeof t!=`function`)throw new v(e,Object.prototype.toString.call(t));if(e===`onSend`||e===`preSerialization`||e===`onError`||e===`preParsing`){if(t.constructor.name===`AsyncFunction`&&t.length===4)throw new D}else if(e===`onRequestAbort`){if(t.constructor.name===`AsyncFunction`&&t.length!==1)throw new D}else if(t.constructor.name===`AsyncFunction`&&t.length===3)throw new D}else if(a[e]!==void 0&&typeof a[e]!=`function`)throw new v(e,Object.prototype.toString.call(a[e]))}let S=a.constraints||{},w={...a.config,url:x,method:a.method},T=new r({schema:a.schema,handler:a.handler.bind(this),config:w,errorHandler:a.errorHandler,childLoggerFactory:a.childLoggerFactory,bodyLimit:a.bodyLimit,logLevel:a.logLevel,logSerializers:a.logSerializers,attachValidation:a.attachValidation,schemaErrorFormatter:a.schemaErrorFormatter,replySerializer:this[te],validatorCompiler:a.validatorCompiler,serializerCompiler:a.serializerCompiler,exposeHeadRoute:l,prefixTrailingSlash:a.prefixTrailingSlash||`both`,server:this,isFastify:c}),E=t.findRoute(`HEAD`,a.url,S)!==null;try{t.on(a.method,a.url,{constraints:S},Te,T)}catch(e){if(!T[ae])throw e.message.includes(`Method '${a.method}' already declared for route`)?new g(a.method,a.url):e}if(this.after((e,t)=>{T.errorHandler=a.errorHandler?oe(this[re],a.errorHandler):this[re],T._parserOptions.limit=a.bodyLimit||null,T.logLevel=a.logLevel,T.logSerializers=a.logSerializers,T.attachValidation=a.attachValidation,T[te]=this[te],T.schemaErrorFormatter=a.schemaErrorFormatter||this[I]||T.schemaErrorFormatter,i.once(`preReady`,()=>{for(let e of o){let t=this[M][e].concat(a[e]||[]).map(e=>e.bind(this));T[e]=t.length?t:null}for(;!T.Request[L]&&T.Request.parent;)T.Request=T.Request.parent;for(;!T.Reply[L]&&T.Reply.parent;)T.Reply=T.Reply.parent;if(s.setContext(this,T),a.schema){T.schema=u(T.schema,this.initialConfig);let e=this[ee],t=a.schema.body||a.schema.headers||a.schema.querystring||a.schema.params;!a.validatorCompiler&&t&&e.setupValidator(this[N]);try{let t=typeof a?.validatorCompiler==`function`||e.isCustomValidatorCompiler;f(T,a.validatorCompiler||e.validatorCompiler,t)}catch(e){throw new m(a.method,x,e.message)}a.schema.response&&!a.serializerCompiler&&e.setupSerializer(this[N]);try{p(T,a.serializerCompiler||e.serializerCompiler)}catch(e){throw new h(a.method,x,e.message)}}}),t(e)}),l&&_&&!y&&!E){let t=d(b.onSend);xe.call(this,{method:`HEAD`,url:e,options:{...b,onSend:t},isFastify:!0})}}}function Te(e,t,n,r,i){let o=ce(r.server,e),s={level:r.logLevel};r.logSerializers&&(s.serializers=r.logSerializers);let u=se(r,c,e,o,s);if(u[F]=k?!1:E,de===!0&&(e.httpVersionMajor!==2&&t.setHeader(`Connection`,`close`),R)){t.writeHead(503,{"Content-Type":`application/json`,"Content-Length":`80`}),t.end(`{"error":"Service Unavailable","message":"Service Unavailable","statusCode":503}`),u.info({res:{statusCode:503}},`request aborted - refusing to accept new requests as server is closing`);return}String.prototype.toLowerCase.call(e.headers.connection||``)===`keep-alive`&&ue.has(e.socket)===!1&&(ue.add(e.socket),e.socket.on(`close`,ve.bind({keepAliveConnections:ue,socket:e.socket}))),e.headers[ie]!==void 0&&(e.headers[`accept-version`]=e.headers[ie],e.headers[ie]=void 0);let d=new r.Request(o,n,e,i,u,r),f=new r.Reply(t,d,u),p=k?k(d):E;u[F]=p,p===!1&&u.info({req:d},`incoming request`),(C===!0||r.onResponse!==null)&&w(f),r.onRequest===null?ge(null,d,f):l(r.onRequest,d,f,ge),r.onRequestAbort!==null&&e.on(`close`,()=>{e.aborted&&a(r.onRequestAbort,d,z.bind(null,f))}),r.onTimeout!==null&&(d.raw.socket._meta||d.raw.socket.on(`timeout`,fe),d.raw.socket._meta={context:r,request:d,reply:f})}}function z(e,t){t&&e.log.error({err:t},`onRequestAborted hook failed`)}function fe(){let{context:e,request:t,reply:n}=this._meta;c(e.onTimeout,t,n,ye)}function pe(e){if(typeof e!=`string`)throw new w;if(e=e.toUpperCase(),!this[k].bodyless.has(e)&&!this[k].bodywith.has(e))throw new C(e);return e}function me(e,t,n){if(this[k].bodyless.has(e)&&n?.body)throw new T(e,t)}function he(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw new E(e)}function ge(e,t,n){if(n.sent!==!0){if(e!=null){n[P]=!0,n.send(e);return}t[ne]=t.raw,t[R].preParsing===null?i.call(t.server,null,t,n):s(t[R].preParsing,t,n,i.bind(t.server))}}function _e(e,t){let n=e.routerOptions||Object.create(null),r=ue.filter(t=>Object.hasOwn(e,t));r.length>0&&le(r.join(`, `));for(let r of ue)Object.hasOwn(n,r)||(n[r]=e[r]??t[r]);return n}function ve(){this.keepAliveConnections.delete(this.socket)}function ye(){}t.exports={buildRouting:de,validateBodyLimitOption:he,buildRouterOptions:_e}})),Wm=o(((e,t)=>{let n=Vm(),r=cd(),i=fd(),a=pd(),{kRoutePrefix:o,kCanSetNotFoundHandler:s,kFourOhFourLevelInstance:c,kFourOhFourContext:l,kHooks:u,kErrorHandler:d}=du(),{lifecycleHooks:f}=hu(),{buildErrorHandler:p}=od(),{FST_ERR_NOT_FOUND:m}=mu(),{createChildLogger:h}=td(),{getGenReqId:g}=pm();function _(e){let{logger:t,disableRequestLogging:_}=e,v=n({onBadUrl:S(),defaultRoute:E}),y=null;return{router:v,setNotFoundHandler:w,setContext:C,arrange404:b};function b(e){e[c]=e,e[s]=!0,v.onBadUrl=v.onBadUrl.bind(e),v.defaultRoute=v.defaultRoute.bind(e)}function x(e,t){let{url:n,method:r}=e.raw,i=`Route ${r}:${n} not found`;(typeof _==`function`?_(e.raw):_)||e.log.info(i),t.code(404).send({message:i,error:`Not Found`,statusCode:404})}function S(){return function(e,n,a){let o=this[c][l],s=g(o.server,n),u=h(o,t,n,s),d=new i(s,null,n,null,u,o),f=new r(a,d,u);y(d,f)}}function C(e,t){let n=Object.assign({},e[l]);n.onSend=t.onSend,t[l]=n}function w(e,t,n,r){this[s]===void 0&&(this[s]=!0),this[l]===void 0&&(this[l]=null);let i=this,a=this[o]||`/`;if(this[s]===!1)throw Error(`Not found handler already set for Fastify instance with prefix: '${a}'`);typeof e==`object`&&(e.preHandler&&(Array.isArray(e.preHandler)?e.preHandler=e.preHandler.map(e=>e.bind(i)):e.preHandler=e.preHandler.bind(i)),e.preValidation&&(Array.isArray(e.preValidation)?e.preValidation=e.preValidation.map(e=>e.bind(i)):e.preValidation=e.preValidation.bind(i))),typeof e==`function`&&(t=e,e=void 0),e||={},t?(this[c][s]=!1,t=t.bind(this),y=t):(t=x,y=x),this.after((i,o)=>{T.call(this,a,e,t,n,r),o(i)})}function T(e,t,n,r,i){let o=new a({schema:t.schema,handler:n,config:t.config||{},server:this});if(r.once(`preReady`,()=>{let e=this[l];for(let n of f){let r=this[u][n].concat(t[n]||[]).map(e=>e.bind(this));e[n]=r.length?r:null}e.errorHandler=t.errorHandler?p(this[d],t.errorHandler):this[d]}),this[l]!==null&&e===`/`){Object.assign(this[l],o);return}this[c][l]=o,v.all(e+(e.endsWith(`/`)?`*`:`/*`),i,o),v.all(e,i,o)}function E(e,n){let a=this[c][l],o=g(a.server,e),s=h(a,t,e,o);s.info({req:e},`incoming request`);let u=new i(o,null,e,null,s,a),d=new r(n,u,s);u.log.warn(`the default handler for 404 did not catch this, this is likely a fastify bug, please report it`),u.log.warn(v.prettyPrint()),d.code(404).send(new m)}}t.exports=_})),Gm=o(((e,t)=>{t.exports=a,t.exports.default=a;let n={type:`object`,additionalProperties:!1,properties:{connectionTimeout:{type:`integer`,default:0},keepAliveTimeout:{type:`integer`,default:72e3},forceCloseConnections:{oneOf:[{type:`string`,pattern:`idle`},{type:`boolean`}]},maxRequestsPerSocket:{type:`integer`,default:0,nullable:!0},requestTimeout:{type:`integer`,default:0},bodyLimit:{type:`integer`,default:1048576},caseSensitive:{type:`boolean`,default:!0},allowUnsafeRegex:{type:`boolean`,default:!1},http2:{type:`boolean`},https:{if:{not:{oneOf:[{type:`boolean`},{type:`null`},{type:`object`,additionalProperties:!1,required:[`allowHTTP1`],properties:{allowHTTP1:{type:`boolean`}}}]}},then:{setDefaultValue:!0}},ignoreTrailingSlash:{type:`boolean`,default:!1},ignoreDuplicateSlashes:{type:`boolean`,default:!1},disableRequestLogging:{default:!1},maxParamLength:{type:`integer`,default:100},onProtoPoisoning:{type:`string`,default:`error`},onConstructorPoisoning:{type:`string`,default:`error`},pluginTimeout:{type:`integer`,default:1e4},requestIdHeader:{anyOf:[{type:`boolean`},{type:`string`}],default:!1},requestIdLogLabel:{type:`string`,default:`reqId`},http2SessionTimeout:{type:`integer`,default:72e3},exposeHeadRoutes:{type:`boolean`,default:!0},useSemicolonDelimiter:{type:`boolean`,default:!1},routerOptions:{type:`object`,additionalProperties:!0,properties:{ignoreTrailingSlash:{type:`boolean`,default:!1},ignoreDuplicateSlashes:{type:`boolean`,default:!1},maxParamLength:{type:`integer`,default:100},allowUnsafeRegex:{type:`boolean`,default:!1},useSemicolonDelimiter:{type:`boolean`,default:!1}}},constraints:{type:`object`,additionalProperties:{type:`object`,required:[`name`,`storage`,`validate`,`deriveConstraint`],additionalProperties:!0,properties:{name:{type:`string`},storage:{},validate:{},deriveConstraint:{}}}}}},r=Object.prototype.hasOwnProperty,i=RegExp(`idle`,`u`);function a(e,{instancePath:t=``,parentData:o,parentDataProperty:s,rootData:c=e}={}){let l=null,u=0;if(u===0)if(e&&typeof e==`object`&&!Array.isArray(e)){e.connectionTimeout===void 0&&(e.connectionTimeout=0),e.keepAliveTimeout===void 0&&(e.keepAliveTimeout=72e3),e.maxRequestsPerSocket===void 0&&(e.maxRequestsPerSocket=0),e.requestTimeout===void 0&&(e.requestTimeout=0),e.bodyLimit===void 0&&(e.bodyLimit=1048576),e.caseSensitive===void 0&&(e.caseSensitive=!0),e.allowUnsafeRegex===void 0&&(e.allowUnsafeRegex=!1),e.ignoreTrailingSlash===void 0&&(e.ignoreTrailingSlash=!1),e.ignoreDuplicateSlashes===void 0&&(e.ignoreDuplicateSlashes=!1),e.disableRequestLogging===void 0&&(e.disableRequestLogging=!1),e.maxParamLength===void 0&&(e.maxParamLength=100),e.onProtoPoisoning===void 0&&(e.onProtoPoisoning=`error`),e.onConstructorPoisoning===void 0&&(e.onConstructorPoisoning=`error`),e.pluginTimeout===void 0&&(e.pluginTimeout=1e4),e.requestIdHeader===void 0&&(e.requestIdHeader=!1),e.requestIdLogLabel===void 0&&(e.requestIdLogLabel=`reqId`),e.http2SessionTimeout===void 0&&(e.http2SessionTimeout=72e3),e.exposeHeadRoutes===void 0&&(e.exposeHeadRoutes=!0),e.useSemicolonDelimiter===void 0&&(e.useSemicolonDelimiter=!1);let o=u;for(let t in e)r.call(n.properties,t)||delete e[t];if(o===u){let n=e.connectionTimeout,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else return a.errors=[{instancePath:t+`/connectionTimeout`,schemaPath:`#/properties/connectionTimeout/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.connectionTimeout=i))}var d=r===u;if(d){let n=e.keepAliveTimeout,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else return a.errors=[{instancePath:t+`/keepAliveTimeout`,schemaPath:`#/properties/keepAliveTimeout/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.keepAliveTimeout=i))}var d=r===u;if(d){if(e.forceCloseConnections!==void 0){let n=e.forceCloseConnections,r=u,o=u,s=!1,c=null,p=u;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else{let e={instancePath:t+`/forceCloseConnections`,schemaPath:`#/properties/forceCloseConnections/oneOf/0/type`,keyword:`type`,params:{type:`string`},message:`must be string`};l===null?l=[e]:l.push(e),u++}i!==void 0&&(n=i,e!==void 0&&(e.forceCloseConnections=i))}if(u===p&&typeof n==`string`&&!i.test(n)){let e={instancePath:t+`/forceCloseConnections`,schemaPath:`#/properties/forceCloseConnections/oneOf/0/pattern`,keyword:`pattern`,params:{pattern:`idle`},message:`must match pattern "idle"`};l===null?l=[e]:l.push(e),u++}var f=p===u;f&&(s=!0,c=0);let m=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else{let e={instancePath:t+`/forceCloseConnections`,schemaPath:`#/properties/forceCloseConnections/oneOf/1/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`};l===null?l=[e]:l.push(e),u++}r!==void 0&&(n=r,e!==void 0&&(e.forceCloseConnections=r))}var f=m===u;if(f&&s?(s=!1,c=[c,1]):f&&(s=!0,c=1),s)u=o,l!==null&&(o?l.length=o:l=null);else{let e={instancePath:t+`/forceCloseConnections`,schemaPath:`#/properties/forceCloseConnections/oneOf`,keyword:`oneOf`,params:{passingSchemas:c},message:`must match exactly one schema in oneOf`};return l===null?l=[e]:l.push(e),u++,a.errors=l,!1}var d=r===u}else var d=!0;if(d){let n=e.maxRequestsPerSocket,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))&&n!==null){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else if(n===``||n===0||n===!1)i=null;else return a.errors=[{instancePath:t+`/maxRequestsPerSocket`,schemaPath:`#/properties/maxRequestsPerSocket/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.maxRequestsPerSocket=i))}var d=r===u;if(d){let n=e.requestTimeout,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else return a.errors=[{instancePath:t+`/requestTimeout`,schemaPath:`#/properties/requestTimeout/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.requestTimeout=i))}var d=r===u;if(d){let n=e.bodyLimit,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else return a.errors=[{instancePath:t+`/bodyLimit`,schemaPath:`#/properties/bodyLimit/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.bodyLimit=i))}var d=r===u;if(d){let n=e.caseSensitive,r=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else return a.errors=[{instancePath:t+`/caseSensitive`,schemaPath:`#/properties/caseSensitive/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(n=r,e!==void 0&&(e.caseSensitive=r))}var d=r===u;if(d){let n=e.allowUnsafeRegex,r=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else return a.errors=[{instancePath:t+`/allowUnsafeRegex`,schemaPath:`#/properties/allowUnsafeRegex/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(n=r,e!==void 0&&(e.allowUnsafeRegex=r))}var d=r===u;if(d){if(e.http2!==void 0){let n=e.http2,r=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else return a.errors=[{instancePath:t+`/http2`,schemaPath:`#/properties/http2/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(n=r,e!==void 0&&(e.http2=r))}var d=r===u}else var d=!0;if(d){if(e.https!==void 0){let n=e.https,r=u,i=u,o=!0,s=u,c=u,f=u,h=u,g=!1,_=null,v=u;if(typeof n!=`boolean`){let t;if(t===void 0)if(n===`false`||n===0||n===null)t=!1;else if(n===`true`||n===1)t=!0;else{let e={};l===null?l=[e]:l.push(e),u++}t!==void 0&&(n=t,e!==void 0&&(e.https=t))}var p=v===u;p&&(g=!0,_=0);let y=u;if(n!==null){let t;if(t===void 0)if(n===``||n===0||n===!1)t=null;else{let e={};l===null?l=[e]:l.push(e),u++}t!==void 0&&(n=t,e!==void 0&&(e.https=t))}var p=y===u;if(p&&g)g=!1,_=[_,1];else{p&&(g=!0,_=1);let e=u;if(u===e)if(n&&typeof n==`object`&&!Array.isArray(n))if(n.allowHTTP1===void 0){let e={};l===null?l=[e]:l.push(e),u++}else{let e=u;for(let e in n)e!==`allowHTTP1`&&delete n[e];if(e===u&&n.allowHTTP1!==void 0){let e=n.allowHTTP1;if(typeof e!=`boolean`){let t;if(t===void 0)if(e===`false`||e===0||e===null)t=!1;else if(e===`true`||e===1)t=!0;else{let e={};l===null?l=[e]:l.push(e),u++}t!==void 0&&(e=t,n!==void 0&&(n.allowHTTP1=t))}}}else{let e={};l===null?l=[e]:l.push(e),u++}var p=e===u;p&&g?(g=!1,_=[_,2]):p&&(g=!0,_=2)}if(g)u=h,l!==null&&(h?l.length=h:l=null);else{let e={};l===null?l=[e]:l.push(e),u++}if(f===u){let e={};l===null?l=[e]:l.push(e),u++}else u=c,l!==null&&(c?l.length=c:l=null);var m=s===u;if(u=i,l!==null&&(i?l.length=i:l=null),m){let t=u;e.https=!0;var m=t===u;o=m}if(!o){let e={instancePath:t+`/https`,schemaPath:`#/properties/https/if`,keyword:`if`,params:{failingKeyword:`then`},message:`must match "then" schema`};return l===null?l=[e]:l.push(e),u++,a.errors=l,!1}var d=r===u}else var d=!0;if(d){let n=e.ignoreTrailingSlash,r=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else return a.errors=[{instancePath:t+`/ignoreTrailingSlash`,schemaPath:`#/properties/ignoreTrailingSlash/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(n=r,e!==void 0&&(e.ignoreTrailingSlash=r))}var d=r===u;if(d){let n=e.ignoreDuplicateSlashes,r=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else return a.errors=[{instancePath:t+`/ignoreDuplicateSlashes`,schemaPath:`#/properties/ignoreDuplicateSlashes/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(n=r,e!==void 0&&(e.ignoreDuplicateSlashes=r))}var d=r===u;if(d){let n=e.maxParamLength,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else return a.errors=[{instancePath:t+`/maxParamLength`,schemaPath:`#/properties/maxParamLength/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.maxParamLength=i))}var d=r===u;if(d){let n=e.onProtoPoisoning,r=u;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else return a.errors=[{instancePath:t+`/onProtoPoisoning`,schemaPath:`#/properties/onProtoPoisoning/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.onProtoPoisoning=i))}var d=r===u;if(d){let n=e.onConstructorPoisoning,r=u;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else return a.errors=[{instancePath:t+`/onConstructorPoisoning`,schemaPath:`#/properties/onConstructorPoisoning/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.onConstructorPoisoning=i))}var d=r===u;if(d){let n=e.pluginTimeout,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else return a.errors=[{instancePath:t+`/pluginTimeout`,schemaPath:`#/properties/pluginTimeout/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.pluginTimeout=i))}var d=r===u;if(d){let n=e.requestIdHeader,r=u,i=u,o=!1,s=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else{let e={instancePath:t+`/requestIdHeader`,schemaPath:`#/properties/requestIdHeader/anyOf/0/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`};l===null?l=[e]:l.push(e),u++}r!==void 0&&(n=r,e!==void 0&&(e.requestIdHeader=r))}var h=s===u;if(o||=h,!o){let r=u;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else{let e={instancePath:t+`/requestIdHeader`,schemaPath:`#/properties/requestIdHeader/anyOf/1/type`,keyword:`type`,params:{type:`string`},message:`must be string`};l===null?l=[e]:l.push(e),u++}i!==void 0&&(n=i,e!==void 0&&(e.requestIdHeader=i))}var h=r===u;o||=h}if(o)u=i,l!==null&&(i?l.length=i:l=null);else{let e={instancePath:t+`/requestIdHeader`,schemaPath:`#/properties/requestIdHeader/anyOf`,keyword:`anyOf`,params:{},message:`must match a schema in anyOf`};return l===null?l=[e]:l.push(e),u++,a.errors=l,!1}var d=r===u;if(d){let n=e.requestIdLogLabel,r=u;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else return a.errors=[{instancePath:t+`/requestIdLogLabel`,schemaPath:`#/properties/requestIdLogLabel/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.requestIdLogLabel=i))}var d=r===u;if(d){let n=e.http2SessionTimeout,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else return a.errors=[{instancePath:t+`/http2SessionTimeout`,schemaPath:`#/properties/http2SessionTimeout/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.http2SessionTimeout=i))}var d=r===u;if(d){let n=e.exposeHeadRoutes,r=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else return a.errors=[{instancePath:t+`/exposeHeadRoutes`,schemaPath:`#/properties/exposeHeadRoutes/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(n=r,e!==void 0&&(e.exposeHeadRoutes=r))}var d=r===u;if(d){let n=e.useSemicolonDelimiter,r=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else return a.errors=[{instancePath:t+`/useSemicolonDelimiter`,schemaPath:`#/properties/useSemicolonDelimiter/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(n=r,e!==void 0&&(e.useSemicolonDelimiter=r))}var d=r===u;if(d){if(e.routerOptions!==void 0){let n=e.routerOptions,r=u;if(u===r)if(n&&typeof n==`object`&&!Array.isArray(n)){n.ignoreTrailingSlash===void 0&&(n.ignoreTrailingSlash=!1),n.ignoreDuplicateSlashes===void 0&&(n.ignoreDuplicateSlashes=!1),n.maxParamLength===void 0&&(n.maxParamLength=100),n.allowUnsafeRegex===void 0&&(n.allowUnsafeRegex=!1),n.useSemicolonDelimiter===void 0&&(n.useSemicolonDelimiter=!1);let e=n.ignoreTrailingSlash,r=u;if(typeof e!=`boolean`){let r;if(r===void 0)if(e===`false`||e===0||e===null)r=!1;else if(e===`true`||e===1)r=!0;else return a.errors=[{instancePath:t+`/routerOptions/ignoreTrailingSlash`,schemaPath:`#/properties/routerOptions/properties/ignoreTrailingSlash/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(e=r,n!==void 0&&(n.ignoreTrailingSlash=r))}var g=r===u;if(g){let e=n.ignoreDuplicateSlashes,r=u;if(typeof e!=`boolean`){let r;if(r===void 0)if(e===`false`||e===0||e===null)r=!1;else if(e===`true`||e===1)r=!0;else return a.errors=[{instancePath:t+`/routerOptions/ignoreDuplicateSlashes`,schemaPath:`#/properties/routerOptions/properties/ignoreDuplicateSlashes/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(e=r,n!==void 0&&(n.ignoreDuplicateSlashes=r))}var g=r===u;if(g){let e=n.maxParamLength,r=u;if(!(typeof e==`number`&&!(e%1)&&!isNaN(e)&&isFinite(e))){let r=typeof e,i;if(i===void 0)if(r===`boolean`||e===null||r===`string`&&e&&e==+e&&!(e%1))i=+e;else return a.errors=[{instancePath:t+`/routerOptions/maxParamLength`,schemaPath:`#/properties/routerOptions/properties/maxParamLength/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(e=i,n!==void 0&&(n.maxParamLength=i))}var g=r===u;if(g){let e=n.allowUnsafeRegex,r=u;if(typeof e!=`boolean`){let r;if(r===void 0)if(e===`false`||e===0||e===null)r=!1;else if(e===`true`||e===1)r=!0;else return a.errors=[{instancePath:t+`/routerOptions/allowUnsafeRegex`,schemaPath:`#/properties/routerOptions/properties/allowUnsafeRegex/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(e=r,n!==void 0&&(n.allowUnsafeRegex=r))}var g=r===u;if(g){let e=n.useSemicolonDelimiter,r=u;if(typeof e!=`boolean`){let r;if(r===void 0)if(e===`false`||e===0||e===null)r=!1;else if(e===`true`||e===1)r=!0;else return a.errors=[{instancePath:t+`/routerOptions/useSemicolonDelimiter`,schemaPath:`#/properties/routerOptions/properties/useSemicolonDelimiter/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(e=r,n!==void 0&&(n.useSemicolonDelimiter=r))}var g=r===u}}}}}else return a.errors=[{instancePath:t+`/routerOptions`,schemaPath:`#/properties/routerOptions/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var d=r===u}else var d=!0;if(d)if(e.constraints!==void 0){let n=e.constraints,r=u;if(u===r)if(n&&typeof n==`object`&&!Array.isArray(n))for(let e in n){let r=n[e],i=u;if(u===i)if(r&&typeof r==`object`&&!Array.isArray(r)){let n;if(r.name===void 0&&(n=`name`)||r.storage===void 0&&(n=`storage`)||r.validate===void 0&&(n=`validate`)||r.deriveConstraint===void 0&&(n=`deriveConstraint`))return a.errors=[{instancePath:t+`/constraints/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),schemaPath:`#/properties/constraints/additionalProperties/required`,keyword:`required`,params:{missingProperty:n},message:`must have required property '`+n+`'`}],!1;if(r.name!==void 0){let n=r.name;if(typeof n!=`string`){let i=typeof n,o;if(o===void 0)if(i==`number`||i==`boolean`)o=``+n;else if(n===null)o=``;else return a.errors=[{instancePath:t+`/constraints/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`)+`/name`,schemaPath:`#/properties/constraints/additionalProperties/properties/name/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;o!==void 0&&(n=o,r!==void 0&&(r.name=o))}}}else return a.errors=[{instancePath:t+`/constraints/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),schemaPath:`#/properties/constraints/additionalProperties/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;if(i!==u)break}else return a.errors=[{instancePath:t+`/constraints`,schemaPath:`#/properties/constraints/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var d=r===u}else var d=!0}}}}}}}}}}}}}}}}}}}}}}}else return a.errors=[{instancePath:t,schemaPath:`#/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;return a.errors=l,u===0}t.exports.defaultInitOptions={connectionTimeout:0,keepAliveTimeout:72e3,maxRequestsPerSocket:0,requestTimeout:0,bodyLimit:1048576,caseSensitive:!0,allowUnsafeRegex:!1,disableRequestLogging:!1,ignoreTrailingSlash:!1,ignoreDuplicateSlashes:!1,maxParamLength:100,onProtoPoisoning:`error`,onConstructorPoisoning:`error`,pluginTimeout:1e4,requestIdHeader:!1,requestIdLogLabel:`reqId`,http2SessionTimeout:72e3,exposeHeadRoutes:!0,useSemicolonDelimiter:!1,allowErrorHandlerOverride:!0,routerOptions:{ignoreTrailingSlash:!1,ignoreDuplicateSlashes:!1,maxParamLength:100,allowUnsafeRegex:!1,useSemicolonDelimiter:!1}}})),Km=o(((e,t)=>{let n=Gm(),r=nd()({circles:!0,proto:!1}),{FST_ERR_INIT_OPTS_INVALID:i}=mu();function a(e){let t=r(e);if(!n(t)){let e=new i(JSON.stringify(n.errors.map(e=>e.message)));throw e.errors=n.errors,e}return o(t)}function o(e){let t=Object.getOwnPropertyNames(e);for(let n of t){let t=e[n];ArrayBuffer.isView(t)&&!(t instanceof DataView)||(e[n]=t&&typeof t==`object`?o(t):t)}return Object.freeze(e)}t.exports=a,t.exports.defaultInitOptions=n.defaultInitOptions,t.exports.utils={deepFreezeObject:o}})),qm=o(((e,t)=>{let{kAvvioBoot:n,kChildren:r,kRoutePrefix:i,kLogLevel:a,kLogSerializers:o,kHooks:s,kSchemaController:c,kContentTypeParser:l,kReply:u,kRequest:d,kFourOhFour:f,kPluginNameChain:p,kErrorHandlerAlreadySet:m}=du(),h=cd(),g=fd(),_=bp(),v=gd(),{buildHooks:y}=hu(),b=fm();t.exports=function(e,t,S){let C=b.registerPlugin.call(e,t),w=b.getPluginName(t)||b.getFuncPreview(t);if(C)return e[p].push(w),e;let T=Object.create(e);e[r].push(T),T.ready=e[n].bind(T),T[r]=[],T[u]=h.buildReply(T[u]),T[d]=g.buildRequest(T[d]),T[l]=v.helpers.buildContentTypeParser(T[l]),T[s]=y(T[s]),T[i]=x(T[i],S.prefix),T[a]=S.logLevel||T[a],T[c]=_.buildSchemaController(e[c]),T.getSchema=T[c].getSchema.bind(T[c]),T.getSchemas=T[c].getSchemas.bind(T[c]),T[b.kRegisteredPlugins]=Object.create(T[b.kRegisteredPlugins]),T[p]=[w],T[m]=!1,(T[o]||S.logSerializers)&&(T[o]=Object.assign(Object.create(T[o]),S.logSerializers)),S.prefix&&T[f].arrange404(T);for(let t of T[s].onRegister)t.call(e,T,S);return T};function x(e,t){return t?(e.endsWith(`/`)&&t[0]===`/`?t=t.slice(1):t[0]!==`/`&&(t=`/`+t),e+t):e}})),Jm=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.parseCookie=c,e.parse=c,e.stringifyCookie=l,e.stringifySetCookie=u,e.serialize=u,e.parseSetCookie=d,e.stringifySetCookie=u,e.serialize=u;let t=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,n=/^[\u0021-\u003A\u003C-\u007E]*$/,r=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,i=/^[\u0020-\u003A\u003D-\u007E]*$/,a=/^-?\d+$/,o=Object.prototype.toString,s=(()=>{let e=function(){};return e.prototype=Object.create(null),e})();function c(e,t){let n=new s,r=e.length;if(r<2)return n;let i=t?.decode||h,a=0;do{let t=p(e,a,r);if(t===-1)break;let o=f(e,a,r);if(t>o){a=e.lastIndexOf(`;`,t-1)+1;continue}let s=m(e,a,t);n[s]===void 0&&(n[s]=i(m(e,t+1,o))),a=o+1}while(a<r);return n}function l(e,r){let i=r?.encode||encodeURIComponent,a=[];for(let r of Object.keys(e)){let o=e[r];if(o===void 0)continue;if(!t.test(r))throw TypeError(`cookie name is invalid: ${r}`);let s=i(o);if(!n.test(s))throw TypeError(`cookie val is invalid: ${o}`);a.push(`${r}=${s}`)}return a.join(`; `)}function u(e,a,o){let s=typeof e==`object`?e:{...o,name:e,value:String(a)},c=(typeof a==`object`?a:o)?.encode||encodeURIComponent;if(!t.test(s.name))throw TypeError(`argument name is invalid: ${s.name}`);let l=s.value?c(s.value):``;if(!n.test(l))throw TypeError(`argument val is invalid: ${s.value}`);let u=s.name+`=`+l;if(s.maxAge!==void 0){if(!Number.isInteger(s.maxAge))throw TypeError(`option maxAge is invalid: ${s.maxAge}`);u+=`; Max-Age=`+s.maxAge}if(s.domain){if(!r.test(s.domain))throw TypeError(`option domain is invalid: ${s.domain}`);u+=`; Domain=`+s.domain}if(s.path){if(!i.test(s.path))throw TypeError(`option path is invalid: ${s.path}`);u+=`; Path=`+s.path}if(s.expires){if(!g(s.expires)||!Number.isFinite(s.expires.valueOf()))throw TypeError(`option expires is invalid: ${s.expires}`);u+=`; Expires=`+s.expires.toUTCString()}if(s.httpOnly&&(u+=`; HttpOnly`),s.secure&&(u+=`; Secure`),s.partitioned&&(u+=`; Partitioned`),s.priority)switch(typeof s.priority==`string`?s.priority.toLowerCase():void 0){case`low`:u+=`; Priority=Low`;break;case`medium`:u+=`; Priority=Medium`;break;case`high`:u+=`; Priority=High`;break;default:throw TypeError(`option priority is invalid: ${s.priority}`)}if(s.sameSite)switch(typeof s.sameSite==`string`?s.sameSite.toLowerCase():s.sameSite){case!0:case`strict`:u+=`; SameSite=Strict`;break;case`lax`:u+=`; SameSite=Lax`;break;case`none`:u+=`; SameSite=None`;break;default:throw TypeError(`option sameSite is invalid: ${s.sameSite}`)}return u}function d(e,t){let n=t?.decode||h,r=e.length,i=f(e,0,r),o=p(e,0,i),s=o===-1?{name:``,value:n(m(e,0,i))}:{name:m(e,0,o),value:n(m(e,o+1,i))},c=i+1;for(;c<r;){let t=f(e,c,r),n=p(e,c,t),i=n===-1?m(e,c,t):m(e,c,n),o=n===-1?void 0:m(e,n+1,t);switch(i.toLowerCase()){case`httponly`:s.httpOnly=!0;break;case`secure`:s.secure=!0;break;case`partitioned`:s.partitioned=!0;break;case`domain`:s.domain=o;break;case`path`:s.path=o;break;case`max-age`:o&&a.test(o)&&(s.maxAge=Number(o));break;case`expires`:if(!o)break;let e=new Date(o);Number.isFinite(e.valueOf())&&(s.expires=e);break;case`priority`:if(!o)break;let t=o.toLowerCase();(t===`low`||t===`medium`||t===`high`)&&(s.priority=t);break;case`samesite`:if(!o)break;let n=o.toLowerCase();(n===`lax`||n===`strict`||n===`none`)&&(s.sameSite=n);break}c=t+1}return s}function f(e,t,n){let r=e.indexOf(`;`,t);return r===-1?n:r}function p(e,t,n){let r=e.indexOf(`=`,t);return r<n?r:-1}function m(e,t,n){let r=t,i=n;do{let t=e.charCodeAt(r);if(t!==32&&t!==9)break}while(++r<i);for(;i>r;){let t=e.charCodeAt(i-1);if(t!==32&&t!==9)break;i--}return e.slice(r,i)}function h(e){if(e.indexOf(`%`)===-1)return e;try{return decodeURIComponent(e)}catch{return e}}function g(e){return o.call(e)===`[object Date]`}})),Ym=o(((e,t)=>{let{format:n}=require(`node:util`);function r(e){return i({...e,name:`DeprecationWarning`})}function i({name:e,code:t,message:r,unlimited:i=!1}={}){if(!e)throw Error(`Warning name must not be empty`);if(!t)throw Error(`Warning code must not be empty`);if(!r)throw Error(`Warning message must not be empty`);if(typeof i!=`boolean`)throw Error(`Warning opts.unlimited must be a boolean`);t=t.toUpperCase();let a={[e]:function(e,t,n){o.emitted===!0&&o.unlimited!==!0||(o.emitted=!0,process.emitWarning(o.format(e,t,n),o.name,o.code))}};i&&(a={[e]:function(e,t,n){o.emitted=!0,process.emitWarning(o.format(e,t,n),o.name,o.code)}});let o=a[e];return o.emitted=!1,o.message=r,o.unlimited=i,o.code=t,o.format=function(e,t,i){let a;return a=e&&t&&i?n(r,e,t,i):e&&t?n(r,e,t):e?n(r,e):r,a},o}let a={createWarning:i,createDeprecation:r};t.exports=a,t.exports.default=a,t.exports.processWarning=a})),Xm=o(((e,t)=>{let{URL:n}=require(`node:url`),r=`http://localhost`;t.exports=function(e,t){(typeof e==`string`||Object.prototype.toString.call(e)===`[object String]`)&&e.startsWith(`//`)&&(e=r+e);let i=typeof e==`object`?Object.assign(new n(r),e):new n(e,r);if(typeof t==`string`){t=new URLSearchParams(t);for(let e of t.keys()){i.searchParams.delete(e);for(let n of t.getAll(e))i.searchParams.append(e,n)}}else{let n=Object.assign({},e.query,t);for(let e in n){let t=n[e];if(Array.isArray(t)){i.searchParams.delete(e);for(let n of t)i.searchParams.append(e,n)}else i.searchParams.set(e,t)}}return i}})),Zm=o(((e,t)=>{let{randomUUID:n}=require(`node:crypto`),{Readable:r}=require(`node:stream`),i;function a(e){return e&&typeof e==`object`&&typeof e.append==`function`&&typeof e.delete==`function`&&typeof e.get==`function`&&typeof e.getAll==`function`&&typeof e.has==`function`&&typeof e.set==`function`&&e[Symbol.toStringTag]===`FormData`}function o(e){i??=new TextEncoder;let t=`----formdata-${n()}`,a=`--${t}\r\nContent-Disposition: form-data`,o=e=>e.replace(/\n/g,`%0A`).replace(/\r/g,`%0D`).replace(/"/g,`%22`),s=e=>e.replace(/\r?\n|\r/g,`\r
|
|
452
|
+
`),c=new Uint8Array([13,10]);async function*l(){for(let[t,n]of e)if(typeof n==`string`)yield i.encode(`${a}; name="${o(s(t))}"\r\n\r\n`),yield i.encode(`${s(n)}\r\n`);else{let e=`${a}; name="${o(s(t))}"`;n.name&&(e+=`; filename="${o(n.name)}"`),e+=`\r\nContent-Type: ${n.type||`application/octet-stream`}\r\n\r\n`,yield i.encode(e),n.stream?yield*n.stream():yield n,yield c}yield i.encode(`--${t}--`)}return{stream:r.from(l()),contentType:`multipart/form-data; boundary=${t}`}}t.exports.isFormDataLike=a,t.exports.formDataToStream=o})),Qm=o(((e,t)=>{let{Readable:n,addAbortSignal:r}=require(`node:stream`),i=require(`node:util`),a=Jm(),o=require(`node:assert`),{createDeprecation:s}=Ym(),c=Xm(),{isFormDataLike:l,formDataToStream:u}=Zm(),{EventEmitter:d}=require(`node:events`),f=s({name:`FastifyDeprecationLightMyRequest`,code:`FST_LIGHTMYREQUEST_DEP01`,message:`You are accessing "request.connection", use "request.socket" instead.`});function p(e){return e.port?e.host:e.hostname+(e.protocol===`https:`?`:443`:`:80`)}var m=class extends d{constructor(e){super(),this.remoteAddress=e}};function h(e){return new t(this);function t(t){g.call(t,{...e,Request:void 0}),Object.assign(this,t);for(let e of Object.keys(g.prototype))this.constructor.prototype[e]=g.prototype[e];return i.inherits(this.constructor,e.Request),this}}function g(e){n.call(this,{autoDestroy:!1});let t=c(e.url||e.path,e.query);this.url=t.pathname+t.search,this.aborted=!1,this.httpVersionMajor=1,this.httpVersionMinor=1,this.httpVersion=`1.1`,this.method=e.method?e.method.toUpperCase():`GET`,this.headers={},this.rawHeaders=[];let i=e.headers||{};for(let e in i){let t=e.toLowerCase();if((t===`user-agent`||t===`content-type`)&&i[e]===void 0){this.headers[t]=void 0;continue}let n=i[e];o(n!==void 0,`invalid value "undefined" for header `+e),this.headers[t]=``+n}if(`user-agent`in this.headers||(this.headers[`user-agent`]=`lightMyRequest`),this.headers.host=this.headers.host||e.authority||p(t),e.cookies){let{cookies:t}=e,n=Object.keys(t).map(e=>a.serialize(e,t[e]));this.headers.cookie&&n.unshift(this.headers.cookie),this.headers.cookie=n.join(`; `)}this.socket=new m(e.remoteAddress||`127.0.0.1`),Object.defineProperty(this,`connection`,{get(){return f(),this.socket},configurable:!0});let s=e.payload||e.body||null,d=s&&typeof s.resume==`function`;if(l(s)){let e=u(s);s=e.stream,d=!0,this.headers[`content-type`]=e.contentType,this.headers[`transfer-encoding`]=`chunked`}s&&typeof s!=`string`&&!d&&!Buffer.isBuffer(s)&&(s=JSON.stringify(s),`content-type`in this.headers||(this.headers[`content-type`]=`application/json`)),s&&!d&&!Object.hasOwn(this.headers,`content-length`)&&(this.headers[`content-length`]=(Buffer.isBuffer(s)?s.length:Buffer.byteLength(s)).toString());for(let e of Object.keys(this.headers))this.rawHeaders.push(e,this.headers[e]);this._lightMyRequest={payload:s,isDone:!1,simulate:e.simulate||{},payloadAsStream:e.payloadAsStream,signal:e.signal};let h=e.signal;h&&r(h,this);{let e=this._lightMyRequest.payload;e?._readableState?(this._read=_,e.on(`error`,e=>{this.destroy(e)}),e.on(`end`,()=>{this.push(null)})):this._read=v}return this}function _(){let e=this._lightMyRequest.payload,t=!0,n=!1,r;for(;t&&(r=e.read());)n=!0,t=this.push(r);t&&!n&&this._lightMyRequest.payload.once(`readable`,this._read.bind(this))}function v(){setImmediate(()=>{if(this._lightMyRequest.isDone){this._lightMyRequest.simulate.end!==!1&&this.push(null);return}this._lightMyRequest.isDone=!0,this._lightMyRequest.payload&&(this._lightMyRequest.simulate.split?(this.push(this._lightMyRequest.payload.slice(0,1)),this.push(this._lightMyRequest.payload.slice(1))):this.push(this._lightMyRequest.payload)),this._lightMyRequest.simulate.error&&this.emit(`error`,Error(`Simulated`)),this._lightMyRequest.simulate.close&&this.emit(`close`),this._lightMyRequest.simulate.end!==!1&&this.push(null)})}i.inherits(g,n),i.inherits(h,g),g.prototype.destroy=function(e){this.destroyed||this._lightMyRequest.isDone||(this.destroyed=!0,e&&(this._error=!0,process.nextTick(()=>this.emit(`error`,e))),process.nextTick(()=>this.emit(`close`)))},t.exports=g,t.exports.Request=g,t.exports.CustomRequest=h})),$m=o(((e,t)=>{var n={decodeValues:!0,map:!1,silent:!1};function r(e){return typeof e!=`string`||e in{}}function i(){return Object.create(null)}function a(e){return typeof e==`string`&&!!e.trim()}function o(e,t){var o=e.split(`;`).filter(a),c=s(o.shift()),l=c.name,u=c.value;if(t=t?Object.assign({},n,t):n,r(l))return null;try{u=t.decodeValues?decodeURIComponent(u):u}catch(e){console.error(`set-cookie-parser: failed to decode cookie value. Set options.decodeValues=false to disable decoding.`,e)}var d=i();return d.name=l,d.value=u,o.forEach(function(e){var t=e.split(`=`),n=t.shift().trimLeft().toLowerCase();if(!r(n)){var i=t.join(`=`);if(n===`expires`)d.expires=new Date(i);else if(n===`max-age`){var a=parseInt(i,10);Number.isNaN(a)||(d.maxAge=a)}else n===`secure`?d.secure=!0:n===`httponly`?d.httpOnly=!0:n===`samesite`?d.sameSite=i:n===`partitioned`?d.partitioned=!0:n&&(d[n]=i)}}),d}function s(e){var t=``,n=``,r=e.split(`=`);return r.length>1?(t=r.shift(),n=r.join(`=`)):n=e,{name:t,value:n}}function c(e,t){if(t=t?Object.assign({},n,t):n,!e)return t.map?i():[];if(e.headers)if(typeof e.headers.getSetCookie==`function`)e=e.headers.getSetCookie();else if(e.headers[`set-cookie`])e=e.headers[`set-cookie`];else{var s=e.headers[Object.keys(e.headers).find(function(e){return e.toLowerCase()===`set-cookie`})];!s&&e.headers.cookie&&!t.silent&&console.warn(`Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning.`),e=s}if(Array.isArray(e)||(e=[e]),t.map){var c=i();return e.filter(a).reduce(function(e,n){var i=o(n,t);return i&&!r(i.name)&&(e[i.name]=i),e},c)}else return e.filter(a).map(function(e){return o(e,t)}).filter(Boolean)}function l(e){if(Array.isArray(e))return e;if(typeof e!=`string`)return[];var t=[],n=0,r,i,a,o,s;function c(){for(;n<e.length&&/\s/.test(e.charAt(n));)n+=1;return n<e.length}function l(){return i=e.charAt(n),i!==`=`&&i!==`;`&&i!==`,`}for(;n<e.length;){for(r=n,s=!1;c();)if(i=e.charAt(n),i===`,`){for(a=n,n+=1,c(),o=n;n<e.length&&l();)n+=1;n<e.length&&e.charAt(n)===`=`?(s=!0,n=o,t.push(e.substring(r,a)),r=n):n=a+1}else n+=1;(!s||n>=e.length)&&t.push(e.substring(r,e.length))}return t}t.exports=c,t.exports.parse=c,t.exports.parseString=o,t.exports.splitCookiesString=l})),eh=o(((e,t)=>{let n=require(`node:http`),{Writable:r,Readable:i,addAbortSignal:a}=require(`node:stream`),o=require(`node:util`),s=$m();function c(e,t,r){if(n.ServerResponse.call(this,e),e._lightMyRequest?.payloadAsStream){this._lightMyRequest={headers:null,trailers:{},stream:new i({read:this.emit.bind(this,`drain`)})};let t=e._lightMyRequest.signal;t&&a(t,this._lightMyRequest.stream)}else this._lightMyRequest={headers:null,trailers:{},payloadChunks:[]};this.setHeader(`foo`,`bar`),this.removeHeader(`foo`),this.assignSocket(u()),this._promiseCallback=typeof r==`function`;let o=!1,s=e=>{if(!o){if(o=!0,this._promiseCallback)return process.nextTick(()=>t(e));process.nextTick(()=>t(null,e))}};this._lightMyRequest.onEndSuccess=s;let c=!1,d=e=>{if(o){this._lightMyRequest.stream&&!c&&(e||(e=Error(`response destroyed before completion`),e.code=`LIGHT_ECONNRESET`),this._lightMyRequest.stream.destroy(e),this._lightMyRequest.stream.on(`error`,()=>{}));return}if(o=!0,e||(e=Error(`response destroyed before completion`),e.code=`LIGHT_ECONNRESET`),this._promiseCallback)return process.nextTick(()=>r(e));process.nextTick(()=>t(e,null))};this._lightMyRequest.stream?this.once(`finish`,()=>{c=!0,this._lightMyRequest.stream.push(null)}):this.once(`finish`,()=>{let t=l(this);t.raw.req=e,s(t)}),this.connection.once(`error`,d),this.once(`error`,d),this.once(`close`,d)}o.inherits(c,n.ServerResponse),c.prototype.setTimeout=function(e,t){return this.timeoutHandle=setTimeout(()=>{this.emit(`timeout`)},e),this.on(`timeout`,t),this},c.prototype.writeHead=function(){let e=n.ServerResponse.prototype.writeHead.apply(this,arguments);return f(this),this._lightMyRequest.stream&&this._lightMyRequest.onEndSuccess(l(this)),e},c.prototype.write=function(e,t,r){return this.timeoutHandle&&clearTimeout(this.timeoutHandle),n.ServerResponse.prototype.write.call(this,e,t,r),this._lightMyRequest.stream?this._lightMyRequest.stream.push(Buffer.from(e,t)):(this._lightMyRequest.payloadChunks.push(Buffer.from(e,t)),!0)},c.prototype.end=function(e,t,r){e&&this.write(e,t),n.ServerResponse.prototype.end.call(this,r),this.emit(`finish`),this.destroy()},c.prototype.destroy=function(e){this.destroyed||(this.destroyed=!0,e&&process.nextTick(()=>this.emit(`error`,e)),process.nextTick(()=>this.emit(`close`)))},c.prototype.addTrailers=function(e){for(let t in e)this._lightMyRequest.trailers[t.toLowerCase().trim()]=e[t].toString().trim()};function l(e){e._lightMyRequest.headers===null&&f(e),d(e);let t={raw:{res:e},headers:e._lightMyRequest.headers,statusCode:e.statusCode,statusMessage:e.statusMessage,trailers:{},get cookies(){return s.parse(this)}};if(t.trailers=e._lightMyRequest.trailers,e._lightMyRequest.payloadChunks){let n=Buffer.concat(e._lightMyRequest.payloadChunks);t.rawPayload=n,t.payload=n.toString(),t.body=t.payload,t.json=function(){return JSON.parse(t.payload)}}else t.json=function(){throw Error(`Response payload is not available with payloadAsStream: true`)};return t.stream=function(){return e._lightMyRequest.stream?e._lightMyRequest.stream:i.from(e._lightMyRequest.payloadChunks)},t}function u(){return new r({write(e,t,n){setImmediate(n)}})}function d(e){let t=e._lightMyRequest.headers;for(let e of Object.keys(t)){let n=t[e];Array.isArray(n)?t[e]=n.map(e=>``+e):t[e]=``+n}}function f(e){e._lightMyRequest.headers=Object.assign({},e.getHeaders()),[`Date`,`Connection`,`Transfer-Encoding`].forEach(t=>{let n=RegExp(`\\r\\n`+t+`: ([^\\r]*)\\r\\n`),r=e._header?.match(n);r&&(e._lightMyRequest.headers[t.toLowerCase()]=r[1])})}t.exports=c})),th=o(((e,t)=>{t.exports=r,t.exports.default=r;let n={type:`object`,properties:{url:{oneOf:[{type:`string`},{type:`object`,properties:{protocol:{type:`string`},hostname:{type:`string`},pathname:{type:`string`}},additionalProperties:!0,required:[`pathname`]}]},path:{oneOf:[{type:`string`},{type:`object`,properties:{protocol:{type:`string`},hostname:{type:`string`},pathname:{type:`string`}},additionalProperties:!0,required:[`pathname`]}]},cookies:{type:`object`,additionalProperties:!0},headers:{type:`object`,additionalProperties:!0},query:{anyOf:[{type:`object`,additionalProperties:!0},{type:`string`}]},simulate:{type:`object`,properties:{end:{type:`boolean`},split:{type:`boolean`},error:{type:`boolean`},close:{type:`boolean`}}},authority:{type:`string`},remoteAddress:{type:`string`},method:{type:`string`,enum:`ACL.BIND.CHECKOUT.CONNECT.COPY.DELETE.GET.HEAD.LINK.LOCK.M-SEARCH.MERGE.MKACTIVITY.MKCALENDAR.MKCOL.MOVE.NOTIFY.OPTIONS.PATCH.POST.PROPFIND.PROPPATCH.PURGE.PUT.QUERY.REBIND.REPORT.SEARCH.SOURCE.SUBSCRIBE.TRACE.UNBIND.UNLINK.UNLOCK.UNSUBSCRIBE.acl.bind.checkout.connect.copy.delete.get.head.link.lock.m-search.merge.mkactivity.mkcalendar.mkcol.move.notify.options.patch.post.propfind.proppatch.purge.put.query.rebind.report.search.source.subscribe.trace.unbind.unlink.unlock.unsubscribe`.split(`.`)},validate:{type:`boolean`}},additionalProperties:!0,oneOf:[{required:[`url`]},{required:[`path`]}]};function r(e,{instancePath:t=``,parentData:i,parentDataProperty:a,rootData:o=e}={}){let s=null,c=0,l=c,u=!1,d=null,f=c;if(e&&typeof e==`object`&&!Array.isArray(e)){let n;if(e.url===void 0&&(n=`url`)){let e={instancePath:t,schemaPath:`#/oneOf/0/required`,keyword:`required`,params:{missingProperty:n},message:`must have required property '`+n+`'`};s===null?s=[e]:s.push(e),c++}}var p=f===c;p&&(u=!0,d=0);let m=c;if(e&&typeof e==`object`&&!Array.isArray(e)){let n;if(e.path===void 0&&(n=`path`)){let e={instancePath:t,schemaPath:`#/oneOf/1/required`,keyword:`required`,params:{missingProperty:n},message:`must have required property '`+n+`'`};s===null?s=[e]:s.push(e),c++}}var p=m===c;if(p&&u?(u=!1,d=[d,1]):p&&(u=!0,d=1),u)c=l,s!==null&&(l?s.length=l:s=null);else{let e={instancePath:t,schemaPath:`#/oneOf`,keyword:`oneOf`,params:{passingSchemas:d},message:`must match exactly one schema in oneOf`};return s===null?s=[e]:s.push(e),c++,r.errors=s,!1}if(c===0)if(e&&typeof e==`object`&&!Array.isArray(e)){if(e.url!==void 0){let n=e.url,i=c,a=c,o=!1,l=null,u=c;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else{let e={instancePath:t+`/url`,schemaPath:`#/properties/url/oneOf/0/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(n=i,e!==void 0&&(e.url=i))}var h=u===c;h&&(o=!0,l=0);let d=c;if(c===d)if(n&&typeof n==`object`&&!Array.isArray(n)){let e;if(n.pathname===void 0&&(e=`pathname`)){let n={instancePath:t+`/url`,schemaPath:`#/properties/url/oneOf/1/required`,keyword:`required`,params:{missingProperty:e},message:`must have required property '`+e+`'`};s===null?s=[n]:s.push(n),c++}else{if(n.protocol!==void 0){let e=n.protocol,r=c;if(typeof e!=`string`){let r=typeof e,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+e;else if(e===null)i=``;else{let e={instancePath:t+`/url/protocol`,schemaPath:`#/properties/url/oneOf/1/properties/protocol/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(e=i,n!==void 0&&(n.protocol=i))}var g=r===c}else var g=!0;if(g){if(n.hostname!==void 0){let e=n.hostname,r=c;if(typeof e!=`string`){let r=typeof e,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+e;else if(e===null)i=``;else{let e={instancePath:t+`/url/hostname`,schemaPath:`#/properties/url/oneOf/1/properties/hostname/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(e=i,n!==void 0&&(n.hostname=i))}var g=r===c}else var g=!0;if(g)if(n.pathname!==void 0){let e=n.pathname,r=c;if(typeof e!=`string`){let r=typeof e,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+e;else if(e===null)i=``;else{let e={instancePath:t+`/url/pathname`,schemaPath:`#/properties/url/oneOf/1/properties/pathname/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(e=i,n!==void 0&&(n.pathname=i))}var g=r===c}else var g=!0}}}else{let e={instancePath:t+`/url`,schemaPath:`#/properties/url/oneOf/1/type`,keyword:`type`,params:{type:`object`},message:`must be object`};s===null?s=[e]:s.push(e),c++}var h=d===c;if(h&&o?(o=!1,l=[l,1]):h&&(o=!0,l=1),o)c=a,s!==null&&(a?s.length=a:s=null);else{let e={instancePath:t+`/url`,schemaPath:`#/properties/url/oneOf`,keyword:`oneOf`,params:{passingSchemas:l},message:`must match exactly one schema in oneOf`};return s===null?s=[e]:s.push(e),c++,r.errors=s,!1}var _=i===c}else var _=!0;if(_){if(e.path!==void 0){let n=e.path,i=c,a=c,o=!1,l=null,u=c;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else{let e={instancePath:t+`/path`,schemaPath:`#/properties/path/oneOf/0/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(n=i,e!==void 0&&(e.path=i))}var v=u===c;v&&(o=!0,l=0);let d=c;if(c===d)if(n&&typeof n==`object`&&!Array.isArray(n)){let e;if(n.pathname===void 0&&(e=`pathname`)){let n={instancePath:t+`/path`,schemaPath:`#/properties/path/oneOf/1/required`,keyword:`required`,params:{missingProperty:e},message:`must have required property '`+e+`'`};s===null?s=[n]:s.push(n),c++}else{if(n.protocol!==void 0){let e=n.protocol,r=c;if(typeof e!=`string`){let r=typeof e,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+e;else if(e===null)i=``;else{let e={instancePath:t+`/path/protocol`,schemaPath:`#/properties/path/oneOf/1/properties/protocol/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(e=i,n!==void 0&&(n.protocol=i))}var y=r===c}else var y=!0;if(y){if(n.hostname!==void 0){let e=n.hostname,r=c;if(typeof e!=`string`){let r=typeof e,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+e;else if(e===null)i=``;else{let e={instancePath:t+`/path/hostname`,schemaPath:`#/properties/path/oneOf/1/properties/hostname/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(e=i,n!==void 0&&(n.hostname=i))}var y=r===c}else var y=!0;if(y)if(n.pathname!==void 0){let e=n.pathname,r=c;if(typeof e!=`string`){let r=typeof e,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+e;else if(e===null)i=``;else{let e={instancePath:t+`/path/pathname`,schemaPath:`#/properties/path/oneOf/1/properties/pathname/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(e=i,n!==void 0&&(n.pathname=i))}var y=r===c}else var y=!0}}}else{let e={instancePath:t+`/path`,schemaPath:`#/properties/path/oneOf/1/type`,keyword:`type`,params:{type:`object`},message:`must be object`};s===null?s=[e]:s.push(e),c++}var v=d===c;if(v&&o?(o=!1,l=[l,1]):v&&(o=!0,l=1),o)c=a,s!==null&&(a?s.length=a:s=null);else{let e={instancePath:t+`/path`,schemaPath:`#/properties/path/oneOf`,keyword:`oneOf`,params:{passingSchemas:l},message:`must match exactly one schema in oneOf`};return s===null?s=[e]:s.push(e),c++,r.errors=s,!1}var _=i===c}else var _=!0;if(_){if(e.cookies!==void 0){let n=e.cookies,i=c;if(c===i&&!(n&&typeof n==`object`&&!Array.isArray(n)))return r.errors=[{instancePath:t+`/cookies`,schemaPath:`#/properties/cookies/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var _=i===c}else var _=!0;if(_){if(e.headers!==void 0){let n=e.headers,i=c;if(c===i&&!(n&&typeof n==`object`&&!Array.isArray(n)))return r.errors=[{instancePath:t+`/headers`,schemaPath:`#/properties/headers/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var _=i===c}else var _=!0;if(_){if(e.query!==void 0){let n=e.query,i=c,a=c,o=!1,l=c;if(c===l&&!(n&&typeof n==`object`&&!Array.isArray(n))){let e={instancePath:t+`/query`,schemaPath:`#/properties/query/anyOf/0/type`,keyword:`type`,params:{type:`object`},message:`must be object`};s===null?s=[e]:s.push(e),c++}var b=l===c;if(o||=b,!o){let r=c;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else{let e={instancePath:t+`/query`,schemaPath:`#/properties/query/anyOf/1/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(n=i,e!==void 0&&(e.query=i))}var b=r===c;o||=b}if(o)c=a,s!==null&&(a?s.length=a:s=null);else{let e={instancePath:t+`/query`,schemaPath:`#/properties/query/anyOf`,keyword:`anyOf`,params:{},message:`must match a schema in anyOf`};return s===null?s=[e]:s.push(e),c++,r.errors=s,!1}var _=i===c}else var _=!0;if(_){if(e.simulate!==void 0){let n=e.simulate,i=c;if(c===i)if(n&&typeof n==`object`&&!Array.isArray(n)){if(n.end!==void 0){let e=n.end,i=c;if(typeof e!=`boolean`){let i;if(i===void 0)if(e===`false`||e===0||e===null)i=!1;else if(e===`true`||e===1)i=!0;else return r.errors=[{instancePath:t+`/simulate/end`,schemaPath:`#/properties/simulate/properties/end/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;i!==void 0&&(e=i,n!==void 0&&(n.end=i))}var x=i===c}else var x=!0;if(x){if(n.split!==void 0){let e=n.split,i=c;if(typeof e!=`boolean`){let i;if(i===void 0)if(e===`false`||e===0||e===null)i=!1;else if(e===`true`||e===1)i=!0;else return r.errors=[{instancePath:t+`/simulate/split`,schemaPath:`#/properties/simulate/properties/split/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;i!==void 0&&(e=i,n!==void 0&&(n.split=i))}var x=i===c}else var x=!0;if(x){if(n.error!==void 0){let e=n.error,i=c;if(typeof e!=`boolean`){let i;if(i===void 0)if(e===`false`||e===0||e===null)i=!1;else if(e===`true`||e===1)i=!0;else return r.errors=[{instancePath:t+`/simulate/error`,schemaPath:`#/properties/simulate/properties/error/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;i!==void 0&&(e=i,n!==void 0&&(n.error=i))}var x=i===c}else var x=!0;if(x)if(n.close!==void 0){let e=n.close,i=c;if(typeof e!=`boolean`){let i;if(i===void 0)if(e===`false`||e===0||e===null)i=!1;else if(e===`true`||e===1)i=!0;else return r.errors=[{instancePath:t+`/simulate/close`,schemaPath:`#/properties/simulate/properties/close/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;i!==void 0&&(e=i,n!==void 0&&(n.close=i))}var x=i===c}else var x=!0}}}else return r.errors=[{instancePath:t+`/simulate`,schemaPath:`#/properties/simulate/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var _=i===c}else var _=!0;if(_){if(e.authority!==void 0){let n=e.authority,i=c;if(typeof n!=`string`){let i=typeof n,a;if(a===void 0)if(i==`number`||i==`boolean`)a=``+n;else if(n===null)a=``;else return r.errors=[{instancePath:t+`/authority`,schemaPath:`#/properties/authority/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;a!==void 0&&(n=a,e!==void 0&&(e.authority=a))}var _=i===c}else var _=!0;if(_){if(e.remoteAddress!==void 0){let n=e.remoteAddress,i=c;if(typeof n!=`string`){let i=typeof n,a;if(a===void 0)if(i==`number`||i==`boolean`)a=``+n;else if(n===null)a=``;else return r.errors=[{instancePath:t+`/remoteAddress`,schemaPath:`#/properties/remoteAddress/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;a!==void 0&&(n=a,e!==void 0&&(e.remoteAddress=a))}var _=i===c}else var _=!0;if(_){if(e.method!==void 0){let i=e.method,a=c;if(typeof i!=`string`){let n=typeof i,a;if(a===void 0)if(n==`number`||n==`boolean`)a=``+i;else if(i===null)a=``;else return r.errors=[{instancePath:t+`/method`,schemaPath:`#/properties/method/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;a!==void 0&&(i=a,e!==void 0&&(e.method=a))}if(!(i===`ACL`||i===`BIND`||i===`CHECKOUT`||i===`CONNECT`||i===`COPY`||i===`DELETE`||i===`GET`||i===`HEAD`||i===`LINK`||i===`LOCK`||i===`M-SEARCH`||i===`MERGE`||i===`MKACTIVITY`||i===`MKCALENDAR`||i===`MKCOL`||i===`MOVE`||i===`NOTIFY`||i===`OPTIONS`||i===`PATCH`||i===`POST`||i===`PROPFIND`||i===`PROPPATCH`||i===`PURGE`||i===`PUT`||i===`QUERY`||i===`REBIND`||i===`REPORT`||i===`SEARCH`||i===`SOURCE`||i===`SUBSCRIBE`||i===`TRACE`||i===`UNBIND`||i===`UNLINK`||i===`UNLOCK`||i===`UNSUBSCRIBE`||i===`acl`||i===`bind`||i===`checkout`||i===`connect`||i===`copy`||i===`delete`||i===`get`||i===`head`||i===`link`||i===`lock`||i===`m-search`||i===`merge`||i===`mkactivity`||i===`mkcalendar`||i===`mkcol`||i===`move`||i===`notify`||i===`options`||i===`patch`||i===`post`||i===`propfind`||i===`proppatch`||i===`purge`||i===`put`||i===`query`||i===`rebind`||i===`report`||i===`search`||i===`source`||i===`subscribe`||i===`trace`||i===`unbind`||i===`unlink`||i===`unlock`||i===`unsubscribe`))return r.errors=[{instancePath:t+`/method`,schemaPath:`#/properties/method/enum`,keyword:`enum`,params:{allowedValues:n.properties.method.enum},message:`must be equal to one of the allowed values`}],!1;var _=a===c}else var _=!0;if(_)if(e.validate!==void 0){let n=e.validate,i=c;if(typeof n!=`boolean`){let i;if(i===void 0)if(n===`false`||n===0||n===null)i=!1;else if(n===`true`||n===1)i=!0;else return r.errors=[{instancePath:t+`/validate`,schemaPath:`#/properties/validate/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.validate=i))}var _=i===c}else var _=!0}}}}}}}}}else return r.errors=[{instancePath:t,schemaPath:`#/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;return r.errors=s,c===0}})),nh=o(((e,t)=>{let n=require(`node:assert`),r=Qm(),i=eh(),a=`The dispatch function has already been invoked`,o=th();function s(e,t,n){return n===void 0?new d(e,t):u(e,t,n)}function c(e,t){let n=e._lightMyRequest.payload;if(!n||n._readableState||typeof n.resume!=`function`)return t();let r=[];n.on(`data`,e=>r.push(Buffer.from(e))),n.on(`end`,()=>{let n=Buffer.concat(r);return e.headers[`content-length`]=e.headers[`content-length`]||``+n.length,delete e.headers[`transfer-encoding`],e._lightMyRequest.payload=n,t()}),n.resume()}function l(e,t,n,r){return n.once(`error`,function(e){this.destroyed&&r.destroy(e)}),n.once(`close`,function(){this.destroyed&&!this._error&&r.destroy()}),c(n,()=>e.call(t,n,r))}function u(e,t,a){if(t=typeof t==`string`?{url:t}:t,t.validate!==!1&&(n(typeof e==`function`,`dispatchFunc should be a function`),!o(t)))throw Error(o.errors.map(e=>e.message));let s=t.server||{},c=t.Request?r.CustomRequest:r;if(e.request&&e.request.app===e&&(Object.setPrototypeOf(Object.getPrototypeOf(e.request),c.prototype),Object.setPrototypeOf(Object.getPrototypeOf(e.response),i.prototype)),typeof a==`function`){let n=new c(t);return l(e,s,n,new i(n,a))}else return new Promise((n,r)=>{let a=new c(t);l(e,s,a,new i(a,n,r))})}function d(e,t){typeof t==`string`?this.option={url:t}:this.option=Object.assign({},t),this.dispatch=e,this._hasInvoked=!1,this._promise=null,this.option.autoStart!==!1&&process.nextTick(()=>{this._hasInvoked||this.end()})}[`delete`,`get`,`head`,`options`,`patch`,`post`,`put`,`trace`].forEach(e=>{d.prototype[e]=function(t){if(this._hasInvoked===!0||this._promise)throw Error(a);return this.option.url=t,this.option.method=e.toUpperCase(),this}}),[`body`,`cookies`,`headers`,`payload`,`query`].forEach(e=>{d.prototype[e]=function(t){if(this._hasInvoked===!0||this._promise)throw Error(a);return this.option[e]=t,this}}),d.prototype.end=function(e){if(this._hasInvoked===!0||this._promise)throw Error(a);if(this._hasInvoked=!0,typeof e==`function`)u(this.dispatch,this.option,e);else return this._promise=u(this.dispatch,this.option),this._promise},Object.getOwnPropertyNames(Promise.prototype).forEach(e=>{e!==`constructor`&&(d.prototype[e]=function(...t){if(!this._promise){if(this._hasInvoked===!0)throw Error(a);this._hasInvoked=!0,this._promise=u(this.dispatch,this.option)}return this._promise[e](...t)})});function f(e){return e instanceof r||e instanceof i||e?.constructor?.name===`_CustomLMRRequest`}t.exports=s,t.exports.default=s,t.exports.inject=s,t.exports.isInjection=f})),rh=o(((e,t)=>{let n=uu(),r=require(`node:http`),i=require(`node:diagnostics_channel`),a,{kAvvioBoot:o,kChildren:s,kServerBindings:c,kBodyLimit:l,kSupportedHTTPMethods:u,kRoutePrefix:d,kLogLevel:f,kLogSerializers:p,kHooks:m,kSchemaController:h,kRequestAcceptVersion:g,kReplySerializerDefault:_,kContentTypeParser:v,kReply:y,kRequest:b,kFourOhFour:x,kState:S,kOptions:C,kPluginNameChain:w,kSchemaErrorFormatter:T,kErrorHandler:E,kKeepAliveConnections:D,kChildLoggerFactory:O,kGenReqId:k,kErrorHandlerAlreadySet:A}=du(),{createServer:j}=vu(),M=cd(),ee=fd(),N=pd(),te=sd(),P=gd(),ne=bp(),{Hooks:F,hookRunnerApplication:I,supportedHooks:re}=hu(),{createChildLogger:L,defaultChildLoggerFactory:ie,createLogger:ae}=td(),R=fm(),{getGenReqId:oe,reqIdGenFactory:se}=pm(),{buildRouting:ce,validateBodyLimitOption:le,buildRouterOptions:ue}=Um(),de=Wm(),z=Km(),fe=qm(),{appendStackTrace:pe,AVVIO_ERRORS_MAP:me,...he}=mu(),ge=_u(),{defaultInitOptions:_e}=z,{FST_ERR_ASYNC_CONSTRAINT:ve,FST_ERR_BAD_URL:ye,FST_ERR_OPTIONS_NOT_OBJ:be,FST_ERR_QSP_NOT_FN:xe,FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN:Se,FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ:Ce,FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR:we,FST_ERR_INSTANCE_ALREADY_LISTENING:Te,FST_ERR_REOPENED_CLOSE_SERVER:Ee,FST_ERR_ROUTE_REWRITE_NOT_STR:De,FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN:Oe,FST_ERR_ERROR_HANDLER_NOT_FN:ke,FST_ERR_ERROR_HANDLER_ALREADY_SET:Ae,FST_ERR_ROUTE_METHOD_INVALID:je}=he,{buildErrorHandler:Me}=od(),{FSTWRN004:Ne}=pu(),Pe=i.channel(`fastify.initialization`);function Fe(e){let{options:t,genReqId:i,disableRequestLogging:ae,hasLogger:le,initialConfig:ue}=Ie(e,Xe,Ze),z=ce(t.routerOptions),be=de(t),xe=ct(z,t),{server:Se,listen:Ce,forceCloseConnections:we,serverHasCloseAllConnections:Oe,serverHasCloseHttp2Sessions:Fe,keepAliveConnections:Le}=j(t,xe),Re=M.setupResponseListeners,Be=ne.buildSchemaController(null,t.schemaController),B={[S]:{listening:!1,closing:!1,started:!1,ready:!1,booting:!1,aborted:!1,readyResolver:null},[D]:Le,[u]:{bodyless:new Set([`GET`,`HEAD`,`TRACE`]),bodywith:new Set([`DELETE`,`OPTIONS`,`PATCH`,`PUT`,`POST`])},[C]:t,[s]:[],[c]:[],[l]:t.bodyLimit,[d]:``,[f]:``,[p]:null,[m]:new F,[h]:Be,[T]:null,[E]:Me(),[A]:!1,[O]:t.childLoggerFactory||ie,[_]:null,[v]:new P(t.bodyLimit,t.onProtoPoisoning||_e.onProtoPoisoning,t.onConstructorPoisoning||_e.onConstructorPoisoning),[y]:M.buildReply(M),[b]:ee.buildRequest(ee,t.trustProxy),[x]:be,[R.kRegisteredPlugins]:[],[w]:[`fastify`],[o]:null,[k]:i,routing:xe,delete:function(e,t,n){return z.prepareRoute.call(this,{method:`DELETE`,url:e,options:t,handler:n})},get:function(e,t,n){return z.prepareRoute.call(this,{method:`GET`,url:e,options:t,handler:n})},head:function(e,t,n){return z.prepareRoute.call(this,{method:`HEAD`,url:e,options:t,handler:n})},trace:function(e,t,n){return z.prepareRoute.call(this,{method:`TRACE`,url:e,options:t,handler:n})},patch:function(e,t,n){return z.prepareRoute.call(this,{method:`PATCH`,url:e,options:t,handler:n})},post:function(e,t,n){return z.prepareRoute.call(this,{method:`POST`,url:e,options:t,handler:n})},put:function(e,t,n){return z.prepareRoute.call(this,{method:`PUT`,url:e,options:t,handler:n})},options:function(e,t,n){return z.prepareRoute.call(this,{method:`OPTIONS`,url:e,options:t,handler:n})},all:function(e,t,n){return z.prepareRoute.call(this,{method:this.supportedMethods,url:e,options:t,handler:n})},route:function(e){return z.route.call(this,{options:e})},hasRoute:function(e){return z.hasRoute.call(this,{options:e})},findRoute:function(e){return z.findRoute(e)},log:t.logger,withTypeProvider:qe,addHook:Je,addSchema:Ye,getSchema:Be.getSchema.bind(Be),getSchemas:Be.getSchemas.bind(Be),setValidatorCompiler:et,setSerializerCompiler:nt,setSchemaController:rt,setReplySerializer:it,setSchemaErrorFormatter:tt,setGenReqId:lt,addContentTypeParser:P.helpers.addContentTypeParser,hasContentTypeParser:P.helpers.hasContentTypeParser,getDefaultJsonParser:P.defaultParsers.getDefaultJsonParser,defaultTextParser:P.defaultParsers.defaultTextParser,removeContentTypeParser:P.helpers.removeContentTypeParser,removeAllContentTypeParsers:P.helpers.removeAllContentTypeParsers,register:null,after:null,ready:null,onClose:null,close:null,printPlugins:null,hasPlugin:function(e){return this[R.kRegisteredPlugins].includes(e)||this[w].includes(e)},listen:Ce,server:Se,addresses:function(){let e=this[c].map(e=>e.address());return e.push(this.server.address()),e.filter(e=>e)},decorate:te.add,hasDecorator:te.exist,decorateReply:te.decorateReply,decorateRequest:te.decorateRequest,hasRequestDecorator:te.existRequest,hasReplyDecorator:te.existReply,getDecorator:te.getInstanceDecorator,addHttpMethod:ut,inject:Ge,printRoutes:st,setNotFoundHandler:$e,setErrorHandler:at,setChildLoggerFactory:ot,initialConfig:ue,addConstraintStrategy:z.addConstraintStrategy.bind(z),hasConstraintStrategy:z.hasConstraintStrategy.bind(z)};Object.defineProperties(B,{listeningOrigin:{get(){let e=this.addresses().slice(-1).pop();if(typeof e==`string`)return e;let t=e.family===`IPv6`?`[${e.address}]`:e.address;return`${this[C].https?`https`:`http`}://${t}:${e.port}`}},pluginName:{configurable:!0,get(){return this[w].length>1?this[w].join(` -> `):this[w][0]}},prefix:{configurable:!0,get(){return this[d]}},validatorCompiler:{configurable:!0,get(){return this[h].getValidatorCompiler()}},serializerCompiler:{configurable:!0,get(){return this[h].getSerializerCompiler()}},childLoggerFactory:{configurable:!0,get(){return this[O]}},version:{configurable:!0,get(){return`5.7.4`}},errorHandler:{configurable:!0,get(){return this[E].func}},genReqId:{configurable:!0,get(){return this[k]}},supportedMethods:{configurable:!1,get(){return[...this[u].bodyless,...this[u].bodywith]}}}),t.schemaErrorFormatter&&(ze(t.schemaErrorFormatter),B[T]=t.schemaErrorFormatter.bind(B));let Ve=Number(t.pluginTimeout),He=n(B,{autostart:!1,timeout:isNaN(Ve)===!1?Ve:_e.pluginTimeout,expose:{use:`register`}});He.override=fe,He.on(`start`,()=>B[S].started=!0),B[o]=B.ready,B.ready=Ke,B.printPlugins=He.prettyPrint.bind(He),He.once(`preReady`,()=>{B.onClose((e,n)=>{B[S].closing=!0,z.closeRoutes(),I(`preClose`,B[o],B,function(){if(B[S].listening){if(we===`idle`)e.server.closeIdleConnections();else if(Oe&&we)e.server.closeAllConnections();else if(we===!0)for(let e of B[D])e.destroy(),B[D].delete(e)}Fe&&e.server.closeHttp2Sessions(),!t.serverFactory||B[S].listening?e.server.close(function(e){e&&e.code!==`ERR_SERVER_NOT_RUNNING`?n(null):n()}):process.nextTick(n,null)})})});let Ue=new N({server:B,config:{}});return B.setNotFoundHandler(),be.arrange404(B),z.setup(t,{avvio:He,fourOhFour:be,hasLogger:le,setupResponseListeners:Re,throwIfAlreadyStarted:We,keepAliveConnections:Le}),Se.on(`clientError`,t.clientErrorHandler.bind(B)),Pe.hasSubscribers&&Pe.publish({fastify:B}),`asyncDispose`in Symbol&&(B[Symbol.asyncDispose]=function(){return B.close()}),B;function We(e){if(B[S].started)throw new Te(e)}function Ge(e,t){if(a===void 0&&(a=nh()),B[S].started){if(B[S].closing){let e=new Ee;if(t){t(e);return}else return Promise.reject(e)}return a(xe,e,t)}if(t)this.ready(n=>{n?t(n,null):a(xe,e,t)});else return a((e,t)=>{this.ready(function(n){if(n){t.emit(`error`,n);return}xe(e,t)})},e)}function Ke(e){if(this[S].readyResolver!==null){if(e!=null){this[S].readyResolver.promise.then(()=>e(null,B),e);return}return this[S].readyResolver.promise}if(process.nextTick(t),this[S].readyResolver=ge.withResolvers(),e)this[S].readyResolver.promise.then(()=>e(null,B),e);else return this[S].readyResolver.promise;function t(){B[o]((e,t)=>{e||B[S].started||B[S].ready||B[S].booting?n(e):(B[S].booting=!0,I(`onReady`,B[o],B,n)),t()})}function n(e){if(e=e!=null&&me[e.code]!=null?pe(e,new me[e.code](e.message)):e,e)return B[S].readyResolver.reject(e);B[S].readyResolver.resolve(B),B[S].booting=!1,B[S].ready=!0,B[S].readyResolver=null}}function qe(){return this}function Je(e,t){if(We(`Cannot call "addHook"!`),t==null)throw new he.FST_ERR_HOOK_INVALID_HANDLER(e,t);if(e===`onSend`||e===`preSerialization`||e===`onError`||e===`preParsing`){if(t.constructor.name===`AsyncFunction`&&t.length===4)throw new he.FST_ERR_HOOK_INVALID_ASYNC_HANDLER}else if(e===`onReady`||e===`onListen`){if(t.constructor.name===`AsyncFunction`&&t.length!==0)throw new he.FST_ERR_HOOK_INVALID_ASYNC_HANDLER}else if(e===`onRequestAbort`){if(t.constructor.name===`AsyncFunction`&&t.length!==1)throw new he.FST_ERR_HOOK_INVALID_ASYNC_HANDLER}else if(t.constructor.name===`AsyncFunction`&&t.length===3)throw new he.FST_ERR_HOOK_INVALID_ASYNC_HANDLER;return e===`onClose`?this.onClose(t.bind(this)):e===`onReady`||e===`onListen`||e===`onRoute`?this[m].add(e,t):this.after((r,i)=>{try{n.call(this,e,t),i(r)}catch(e){i(e)}}),this;function n(e,t){this[m].add(e,t),this[s].forEach(r=>n.call(r,e,t))}}function Ye(e){return We(`Cannot call "addSchema"!`),this[h].add(e),this[s].forEach(t=>t.addSchema(e)),this}function Xe(e,t){e.headers[`accept-version`]!==void 0&&(e.headers[g]=e.headers[`accept-version`],e.headers[`accept-version`]=void 0),be.router.lookup(e,t)}function Ze(e,n,r){if(t.frameworkErrors){let i=oe(Ue.server,n),a=L(Ue,t.logger,n,i),o=new ee(i,null,n,null,a,Ue),s=new M(r,o,a);return(typeof ae==`function`?ae(n):ae)===!1&&a.info({req:o},`incoming request`),t.frameworkErrors(new ye(e),o,s)}let i=JSON.stringify({error:`Bad Request`,code:`FST_ERR_BAD_URL`,message:`'${e}' is not a valid url component`,statusCode:400});r.writeHead(400,{"Content-Type":`application/json`,"Content-Length":Buffer.byteLength(i)}),r.end(i)}function Qe(e,n,r){if(e!==!1)return function(e){if(e){if(t.frameworkErrors){let e=oe(Ue.server,n),i=L(Ue,t.logger,n,e),a=new ee(e,null,n,null,i,Ue),o=new M(r,a,i);return(typeof ae==`function`?ae(n):ae)===!1&&i.info({req:a},`incoming request`),t.frameworkErrors(new ve,a,o)}r.writeHead(500,{"Content-Type":`application/json`,"Content-Length":101}),r.end(`{"error":"Internal Server Error","message":"Unexpected error from async constraint","statusCode":500}`)}}}function $e(e,t){return We(`Cannot call "setNotFoundHandler"!`),be.setNotFoundHandler.call(this,e,t,He,z.routeHandler),this}function et(e){return We(`Cannot call "setValidatorCompiler"!`),this[h].setValidatorCompiler(e),this}function tt(e){return We(`Cannot call "setSchemaErrorFormatter"!`),ze(e),this[T]=e.bind(this),this}function nt(e){return We(`Cannot call "setSerializerCompiler"!`),this[h].setSerializerCompiler(e),this}function rt(e){We(`Cannot call "setSchemaController"!`);let t=this[h],n=ne.buildSchemaController(t,Object.assign({},t.opts,e));return this[h]=n,this.getSchema=n.getSchema.bind(n),this.getSchemas=n.getSchemas.bind(n),this}function it(e){return We(`Cannot call "setReplySerializer"!`),this[_]=e,this}function at(e){if(We(`Cannot call "setErrorHandler"!`),typeof e!=`function`)throw new ke;if(!t.allowErrorHandlerOverride&&this[A])throw new Ae;return this[A]&&Ne(`To disable this behavior, set 'allowErrorHandlerOverride' to false or ignore this message. For more information, visit: https://fastify.dev/docs/latest/Reference/Server/#allowerrorhandleroverride`),this[A]=!0,this[E]=Me(this[E],e.bind(this)),this}function ot(e){return We(`Cannot call "setChildLoggerFactory"!`),this[O]=e,this}function st(e={}){return e.includeMeta=e.includeHooks?e.includeMeta?re.concat(e.includeMeta):re:e.includeMeta,z.printRoutes(e)}function ct(e,{rewriteUrl:t,logger:n}){let r;return function(n,i){if(r===void 0&&(r=e.isAsyncConstraint()),t){n.originalUrl=n.url;let e=t.call(B,n);if(typeof e==`string`)n.url=e;else{let t=new De(n.url,typeof e);n.destroy(t)}}e.routing(n,i,Qe(r,n,i))}}function lt(e){return We(`Cannot call "setGenReqId"!`),this[k]=se(this[C].requestIdHeader,e),this}function ut(e,{hasBody:t=!1}={}){if(typeof e!=`string`||r.METHODS.indexOf(e)===-1)throw new je;t===!0?(this[u].bodywith.add(e),this[u].bodyless.delete(e)):(this[u].bodywith.delete(e),this[u].bodyless.add(e));let n=e.toLowerCase();return this.hasDecorator(n)||this.decorate(n,function(t,n,r){return z.prepareRoute.call(this,{method:e,url:t,options:n,handler:r})}),this}}function Ie(e,t,n){if(e&&typeof e!=`object`)throw new be;if(e=Object.assign({},e),e.querystringParser&&typeof e.querystringParser!=`function`||e.routerOptions?.querystringParser&&typeof e.routerOptions.querystringParser!=`function`)throw new xe(typeof(e.querystringParser??e.routerOptions.querystringParser));if(e.schemaController&&e.schemaController.bucket&&typeof e.schemaController.bucket!=`function`)throw new Se(typeof e.schemaController.bucket);le(e.bodyLimit);let r=typeof e.requestIdHeader==`string`&&e.requestIdHeader.length!==0?e.requestIdHeader.toLowerCase():e.requestIdHeader===!0&&`request-id`,i=se(r,e.genReqId),a=e.requestIdLogLabel||`reqId`;e.bodyLimit=e.bodyLimit||_e.bodyLimit;let o=e.disableRequestLogging||!1,s=Object.assign({customOptions:{},plugins:[]},e.ajv);if(!s.customOptions||Object.prototype.toString.call(s.customOptions)!==`[object Object]`)throw new Ce(typeof s.customOptions);if(!s.plugins||!Array.isArray(s.plugins))throw new we(typeof s.plugins);let{logger:c,hasLogger:l}=ae(e);e.connectionTimeout=e.connectionTimeout||_e.connectionTimeout,e.keepAliveTimeout=e.keepAliveTimeout||_e.keepAliveTimeout,e.maxRequestsPerSocket=e.maxRequestsPerSocket||_e.maxRequestsPerSocket,e.requestTimeout=e.requestTimeout||_e.requestTimeout,e.logger=c,e.requestIdHeader=r,e.requestIdLogLabel=a,e.disableRequestLogging=o,e.ajv=s,e.clientErrorHandler=e.clientErrorHandler||Re,e.allowErrorHandlerOverride=e.allowErrorHandlerOverride??_e.allowErrorHandlerOverride;let u=z(e);return e.exposeHeadRoutes=u.exposeHeadRoutes,e.http2SessionTimeout=u.http2SessionTimeout,e.routerOptions=ue(e,{defaultRoute:t,onBadUrl:n,ignoreTrailingSlash:_e.ignoreTrailingSlash,ignoreDuplicateSlashes:_e.ignoreDuplicateSlashes,maxParamLength:_e.maxParamLength,allowUnsafeRegex:_e.allowUnsafeRegex,buildPrettyMeta:Le,useSemicolonDelimiter:_e.useSemicolonDelimiter}),{options:e,genReqId:i,disableRequestLogging:o,hasLogger:l,initialConfig:u}}function Le(e){let t={};return[`errorHandler`,`logLevel`,`logSerializers`].concat(re).forEach(n=>{t[n]=e.store[n]}),Object.assign({},t)}function Re(e,t){if(e.code===`ECONNRESET`||t.destroyed)return;let n,i,a,o;e.code===`ERR_HTTP_REQUEST_TIMEOUT`?(i=`408`,a=r.STATUS_CODES[i],n=`{"error":"${a}","message":"Client Timeout","statusCode":408}`,o=`timeout`):e.code===`HPE_HEADER_OVERFLOW`?(i=`431`,a=r.STATUS_CODES[i],n=`{"error":"${a}","message":"Exceeded maximum allowed HTTP header size","statusCode":431}`,o=`header_overflow`):(i=`400`,a=r.STATUS_CODES[i],n=`{"error":"${a}","message":"Client Error","statusCode":400}`,o=`error`),this.log.trace({err:e},`client ${o}`),t.writable&&t.write(`HTTP/1.1 ${i} ${a}\r\nContent-Length: ${n.length}\r\nContent-Type: application/json\r\n\r\n${n}`),t.destroy(e)}function ze(e){if(typeof e!=`function`)throw new Oe(typeof e);if(e.constructor.name===`AsyncFunction`)throw new Oe(`AsyncFunction`)}t.exports=Fe,t.exports.errorCodes=he,t.exports.fastify=Fe,t.exports.default=Fe})),ih=o(((e,t)=>{let n=/at\s(?:.*\.)?plugin\s.*\n\s*(.*)/,r=/(\w*(\.\w*)*)\..*/;t.exports=function(e){if(e.name.length>0)return e.name;let t=Error.stackTraceLimit;Error.stackTraceLimit=10;try{throw Error(`anonymous function`)}catch(e){return Error.stackTraceLimit=t,i(e.stack)}};function i(e){let t=e.match(n);return t?t[1].split(/[/\\]/).slice(-1)[0].match(r)[1]:`anonymous`}t.exports.extractPluginName=i})),ah=o(((e,t)=>{t.exports=function(e){return e[0]===`@`&&(e=e.slice(1).replace(`/`,`-`)),e.replace(/-(.)/g,function(e,t){return t.toUpperCase()})}})),oh=o(((e,t)=>{let n=ih(),r=ah(),i=0;function a(e,t={}){let a=!1;if(e.default!==void 0&&(e=e.default),typeof e!=`function`)throw TypeError(`fastify-plugin expects a function, instead got a '${typeof e}'`);if(typeof t==`string`&&(t={fastify:t}),typeof t!=`object`||Array.isArray(t)||t===null)throw TypeError(`The options object should be an object`);if(t.fastify!==void 0&&typeof t.fastify!=`string`)throw TypeError(`fastify-plugin expects a version string, instead got '${typeof t.fastify}'`);t.name||(a=!0,t.name=n(e)+`-auto-`+ i++),e[Symbol.for(`skip-override`)]=t.encapsulate!==!0,e[Symbol.for(`fastify.display-name`)]=t.name,e[Symbol.for(`plugin-meta`)]=t,e.default||=e;let o=r(t.name);return!a&&!e[o]&&(e[o]=e),e}t.exports=a,t.exports.default=a,t.exports.fastifyPlugin=a})),sh=o(((e,t)=>{function n(e){if(typeof e!=`function`)throw Error(`obliterator/iterator: expecting a function!`);this.next=e}typeof Symbol<`u`&&(n.prototype[Symbol.iterator]=function(){return this}),n.of=function(){var e=arguments,t=e.length,r=0;return new n(function(){return r>=t?{done:!0}:{done:!1,value:e[r++]}})},n.empty=function(){return new n(function(){return{done:!0}})},n.fromSequence=function(e){var t=0,r=e.length;return new n(function(){return t>=r?{done:!0}:{done:!1,value:e[t++]}})},n.is=function(e){return e instanceof n?!0:typeof e==`object`&&!!e&&typeof e.next==`function`},t.exports=n})),ch=o((e=>{e.ARRAY_BUFFER_SUPPORT=typeof ArrayBuffer<`u`,e.SYMBOL_SUPPORT=typeof Symbol<`u`})),lh=o(((e,t)=>{var n=ch(),r=n.ARRAY_BUFFER_SUPPORT,i=n.SYMBOL_SUPPORT;t.exports=function(e,t){var n,a,o,s,c;if(!e)throw Error(`obliterator/forEach: invalid iterable.`);if(typeof t!=`function`)throw Error(`obliterator/forEach: expecting a callback.`);if(Array.isArray(e)||r&&ArrayBuffer.isView(e)||typeof e==`string`||e.toString()===`[object Arguments]`){for(o=0,s=e.length;o<s;o++)t(e[o],o);return}if(typeof e.forEach==`function`){e.forEach(t);return}if(i&&Symbol.iterator in e&&typeof e.next!=`function`&&(e=e[Symbol.iterator]()),typeof e.next==`function`){for(n=e,o=0;c=n.next(),c.done!==!0;)t(c.value,o),o++;return}for(a in e)e.hasOwnProperty(a)&&t(e[a],a)}})),uh=o((e=>{var t=2**8-1,n=2**16-1,r=2**32-1,i=2**7-1,a=2**15-1,o=2**31-1;e.getPointerArray=function(e){var i=e-1;if(i<=t)return Uint8Array;if(i<=n)return Uint16Array;if(i<=r)return Uint32Array;throw Error(`mnemonist: Pointer Array of size > 4294967295 is not supported.`)},e.getSignedPointerArray=function(e){var t=e-1;return t<=i?Int8Array:t<=a?Int16Array:t<=o?Int32Array:Float64Array},e.getNumberType=function(e){return e===(e|0)?Math.sign(e)===-1?e<=127&&e>=-128?Int8Array:e<=32767&&e>=-32768?Int16Array:Int32Array:e<=255?Uint8Array:e<=65535?Uint16Array:Uint32Array:Float64Array};var s={Uint8Array:1,Int8Array:2,Uint16Array:3,Int16Array:4,Uint32Array:5,Int32Array:6,Float32Array:7,Float64Array:8};e.getMinimalRepresentation=function(t,n){var r=null,i=0,a,o,c,l,u;for(l=0,u=t.length;l<u;l++)c=n?n(t[l]):t[l],o=e.getNumberType(c),a=s[o.name],a>i&&(i=a,r=o);return r},e.isTypedArray=function(e){return typeof ArrayBuffer<`u`&&ArrayBuffer.isView(e)},e.concat=function(){var e=0,t,n,r;for(t=0,r=arguments.length;t<r;t++)e+=arguments[t].length;var i=new arguments[0].constructor(e);for(t=0,n=0;t<r;t++)i.set(arguments[t],n),n+=arguments[t].length;return i},e.indices=function(t){for(var n=new(e.getPointerArray(t))(t),r=0;r<t;r++)n[r]=r;return n}})),dh=o((e=>{var t=lh(),n=uh();function r(e){return Array.isArray(e)||n.isTypedArray(e)}function i(e){if(typeof e.length==`number`)return e.length;if(typeof e.size==`number`)return e.size}function a(e){var n=i(e),r=typeof n==`number`?Array(n):[],a=0;return t(e,function(e){r[a++]=e}),r}function o(e){var r=i(e),a=typeof r==`number`?n.getPointerArray(r):Array,o=typeof r==`number`?Array(r):[],s=typeof r==`number`?new a(r):[],c=0;return t(e,function(e){o[c]=e,s[c]=c++}),[o,s]}e.isArrayLike=r,e.guessLength=i,e.toArray=a,e.toArrayWithIndices=o})),fh=o(((e,t)=>{var n=sh(),r=lh(),i=uh(),a=dh();function o(e,t,n){if(arguments.length<2&&(n=e,e=null,t=null),this.capacity=n,typeof this.capacity!=`number`||this.capacity<=0)throw Error(`mnemonist/lru-cache: capacity should be positive number.`);if(!isFinite(this.capacity)||Math.floor(this.capacity)!==this.capacity)throw Error(`mnemonist/lru-cache: capacity should be a finite positive integer.`);var r=i.getPointerArray(n);this.forward=new r(n),this.backward=new r(n),this.K=typeof e==`function`?new e(n):Array(n),this.V=typeof t==`function`?new t(n):Array(n),this.size=0,this.head=0,this.tail=0,this.items={}}o.prototype.clear=function(){this.size=0,this.head=0,this.tail=0,this.items={}},o.prototype.splayOnTop=function(e){var t=this.head;if(this.head===e)return this;var n=this.backward[e],r=this.forward[e];return this.tail===e?this.tail=n:this.backward[r]=n,this.forward[n]=r,this.backward[t]=e,this.head=e,this.forward[e]=t,this},o.prototype.set=function(e,t){var n=this.items[e];if(n!==void 0){this.splayOnTop(n),this.V[n]=t;return}this.size<this.capacity?n=this.size++:(n=this.tail,this.tail=this.backward[n],delete this.items[this.K[n]]),this.items[e]=n,this.K[n]=e,this.V[n]=t,this.forward[n]=this.head,this.backward[this.head]=n,this.head=n},o.prototype.setpop=function(e,t){var n=null,r=null,i=this.items[e];return i===void 0?(this.size<this.capacity?i=this.size++:(i=this.tail,this.tail=this.backward[i],n=this.V[i],r=this.K[i],delete this.items[r]),this.items[e]=i,this.K[i]=e,this.V[i]=t,this.forward[i]=this.head,this.backward[this.head]=i,this.head=i,r?{evicted:!0,key:r,value:n}:null):(this.splayOnTop(i),n=this.V[i],this.V[i]=t,{evicted:!1,key:e,value:n})},o.prototype.has=function(e){return e in this.items},o.prototype.get=function(e){var t=this.items[e];if(t!==void 0)return this.splayOnTop(t),this.V[t]},o.prototype.peek=function(e){var t=this.items[e];if(t!==void 0)return this.V[t]},o.prototype.forEach=function(e,t){t=arguments.length>1?t:this;for(var n=0,r=this.size,i=this.head,a=this.K,o=this.V,s=this.forward;n<r;)e.call(t,o[i],a[i],this),i=s[i],n++},o.prototype.keys=function(){var e=0,t=this.size,r=this.head,i=this.K,a=this.forward;return new n(function(){if(e>=t)return{done:!0};var n=i[r];return e++,e<t&&(r=a[r]),{done:!1,value:n}})},o.prototype.values=function(){var e=0,t=this.size,r=this.head,i=this.V,a=this.forward;return new n(function(){if(e>=t)return{done:!0};var n=i[r];return e++,e<t&&(r=a[r]),{done:!1,value:n}})},o.prototype.entries=function(){var e=0,t=this.size,r=this.head,i=this.K,a=this.V,o=this.forward;return new n(function(){if(e>=t)return{done:!0};var n=i[r],s=a[r];return e++,e<t&&(r=o[r]),{done:!1,value:[n,s]}})},typeof Symbol<`u`&&(o.prototype[Symbol.iterator]=o.prototype.entries),o.prototype.inspect=function(){for(var e=new Map,t=this.entries(),n;n=t.next(),!n.done;)e.set(n.value[0],n.value[1]);return Object.defineProperty(e,`constructor`,{value:o,enumerable:!1}),e},typeof Symbol<`u`&&(o.prototype[Symbol.for(`nodejs.util.inspect.custom`)]=o.prototype.inspect),o.from=function(e,t,n,i){if(arguments.length<2){if(i=a.guessLength(e),typeof i!=`number`)throw Error(`mnemonist/lru-cache.from: could not guess iterable length. Please provide desired capacity as last argument.`)}else arguments.length===2&&(i=t,t=null,n=null);var s=new o(t,n,i);return r(e,function(e,t){s.set(t,e)}),s},t.exports=o})),ph=o(((e,t)=>{let n=fh(),r=/^[!#$%&'*+\-.^\w`|~]+$/u;function i(e){if(r.test(e)===!1)throw TypeError(`Fieldname contains invalid characters.`)}function a(e){e=e.trim().toLowerCase();let t=[];if(e.length!==0)if(e.indexOf(`,`)===-1)t.push(e);else{let n=e.length,r=0,i=0,a;for(;r<n;++r)a=e[r],a===` `?i=r+1:a===`,`&&(i!==r&&t.push(e.slice(i,r)),i=r+1);i!==r&&t.push(e.slice(i,r))}return t}function o(e){let t=new n(1e3);return i(e),function(n){let r=n.getHeader(`Vary`);if(!r){n.header(`Vary`,e);return}if(r===`*`)return;if(e===`*`){n.header(`Vary`,`*`);return}if(Array.isArray(r)&&(r=r.join(`, `)),!t.has(r)){let n=a(r);n.indexOf(`*`)===-1?n.indexOf(e.toLowerCase())===-1?t.set(r,r+`, `+e):t.set(r,null):t.set(r,`*`)}let i=t.get(r);i!==null&&n.header(`Vary`,i)}}t.exports.createAddFieldnameToVary=o,t.exports.addOriginToVaryHeader=o(`Origin`),t.exports.addAccessControlRequestHeadersToVaryHeader=o(`Access-Control-Request-Headers`),t.exports.parse=a})),mh=o(((e,t)=>{let n=oh(),{addAccessControlRequestHeadersToVaryHeader:r,addOriginToVaryHeader:i}=ph(),a={origin:`*`,methods:`GET,HEAD,PUT,PATCH,POST,DELETE`,hook:`onRequest`,preflightContinue:!1,optionsSuccessStatus:204,credentials:!1,exposedHeaders:null,allowedHeaders:null,maxAge:null,preflight:!0,strictPreflight:!0},o=[`onRequest`,`preParsing`,`preValidation`,`preHandler`,`preSerialization`,`onSend`],s=[`preSerialization`,`preParsing`,`onSend`];function c(e,t){o.indexOf(e)===-1&&t(TypeError(`@fastify/cors: Invalid hook option provided.`))}function l(e,t,n){e.decorateRequest(`corsPreflightEnabled`,!1);let r=!0;if(typeof t==`function`)u(t,e,{hook:a.hook},n);else if(t.delegator){let{delegator:r,...i}=t;u(r,e,i,n)}else{t.hideOptionsRoute!==void 0&&(r=t.hideOptionsRoute);let i=f(t);c(i.hook,n),s.indexOf(i.hook)===-1?e.addHook(i.hook,function(t,n,r){p(e,i,t,n,r)}):e.addHook(i.hook,function(t,n,r,a){p(e,i,t,n,a)})}e.options(`*`,{schema:{hide:r}},(e,t)=>{if(!e.corsPreflightEnabled){t.callNotFound();return}t.send()}),n()}function u(e,t,n,r){let i=n?.hook||a.hook;c(i,r),e.length===2?s.indexOf(i)===-1?t.addHook(i,function(n,r,i){d(e,t,n,r,i)}):t.addHook(i,function(n,r,i,a){d(e,t,n,r,a)}):s.indexOf(i)===-1?t.addHook(i,function(n,r,i){let a=e(n);if(a&&typeof a.then==`function`){a.then(e=>p(t,f(e,!0),n,r,i)).catch(i);return}i(Error(`Invalid CORS origin option`))}):t.addHook(i,function(n,r,i,a){let o=e(n);if(o&&typeof o.then==`function`){o.then(e=>p(t,f(e,!0),n,r,a)).catch(a);return}a(Error(`Invalid CORS origin option`))})}function d(e,t,n,r,i){e(n,(e,a)=>{e?i(e):p(t,f(a,!0),n,r,i)})}function f(e,t){let n={...a,...e};return Array.isArray(e.origin)&&e.origin.indexOf(`*`)!==-1&&(n.origin=`*`),Number.isInteger(n.cacheControl)?n.cacheControl=`max-age=${n.cacheControl}`:typeof n.cacheControl!=`string`&&(n.cacheControl=null),n.dynamic=t||!1,n}function p(e,t,n,r,a){(typeof t.origin!=`string`&&t.origin!==!1||t.dynamic)&&i(r),(typeof t.origin==`function`?g(e,t.origin):(e,n)=>n(null,t.origin))(n,(e,i)=>{if(e!==null)return a(e);if(i===!1||n.routeOptions.config?.cors===!1)return a();if(!i)return a(Error(`Invalid CORS origin option`));if(m(n,r,i,t),n.raw.method===`OPTIONS`&&t.preflight===!0){if(t.strictPreflight===!0&&(!n.headers.origin||!n.headers[`access-control-request-method`])){r.status(400).type(`text/plain`).send(`Invalid Preflight Request`);return}if(n.corsPreflightEnabled=!0,h(n,r,t),!t.preflightContinue){r.code(t.optionsSuccessStatus).header(`Content-Length`,`0`).send();return}}return a()})}function m(e,t,n,r){let i=_(e.headers.origin,n);i&&t.header(`Access-Control-Allow-Origin`,i),r.credentials&&t.header(`Access-Control-Allow-Credentials`,`true`),r.exposedHeaders!==null&&t.header(`Access-Control-Expose-Headers`,Array.isArray(r.exposedHeaders)?r.exposedHeaders.join(`, `):r.exposedHeaders)}function h(e,t,n){if(t.header(`Access-Control-Allow-Methods`,Array.isArray(n.methods)?n.methods.join(`, `):n.methods),n.allowedHeaders===null){r(t);let n=e.headers[`access-control-request-headers`];n!==void 0&&t.header(`Access-Control-Allow-Headers`,n)}else t.header(`Access-Control-Allow-Headers`,Array.isArray(n.allowedHeaders)?n.allowedHeaders.join(`, `):n.allowedHeaders);n.maxAge!==null&&t.header(`Access-Control-Max-Age`,String(n.maxAge)),n.cacheControl&&t.header(`Cache-Control`,n.cacheControl)}function g(e,t){return function(n,r){let i=t.call(e,n.headers.origin,r);i&&typeof i.then==`function`&&i.then(e=>r(null,e),r)}}function _(e,t){return typeof t==`string`?t:v(e,t)?e:!1}function v(e,t){if(Array.isArray(t)){for(let n=0;n<t.length;++n)if(v(e,t[n]))return!0;return!1}else if(typeof t==`string`)return e===t;else if(t instanceof RegExp)return t.lastIndex=0,t.test(e);else return!!t}let y=n(l,{fastify:`5.x`,name:`@fastify/cors`});t.exports=y,t.exports.fastifyCors=y,t.exports.default=y})),hh=o(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),gh=o(((e,t)=>{let{EMPTY_BUFFER:n}=hh(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}if(t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=require(`bufferutil`);t.exports.mask=function(t,n,r,i,o){o<48?a(t,n,r,i,o):e.mask(t,n,r,i,o)},t.exports.unmask=function(t,n){t.length<32?o(t,n):e.unmask(t,n)}}catch{}})),_h=o(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),vh=o(((e,t)=>{let n=require(`zlib`),r=gh(),i=_h(),{kStatusCode:a}=hh(),o=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),c=Symbol(`permessage-deflate`),l=Symbol(`total-length`),u=Symbol(`callback`),d=Symbol(`buffers`),f=Symbol(`error`),p;t.exports=class{constructor(e,t,n){this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,p||=new i(this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit)}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){p.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){p.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on(`error`,g),this._inflate.on(`data`,h)}this._inflate[u]=i,this._inflate.write(e),t&&this._inflate.write(s),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on(`data`,m)}this._deflate[u]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[d],this._deflate[l]);t&&(e=new o(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(e){if(this[l]+=e.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(e);return}this[f]=RangeError(`Max payload size exceeded`),this[f].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[f][a]=1009,this.removeListener(`data`,h),this.reset()}function g(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})),yh=o(((e,t)=>{let{isUtf8:n}=require(`buffer`),{hasBlob:r}=hh(),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,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,0,0,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,0,1,0];function a(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function o(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function s(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:s,isValidStatusCode:a,isValidUTF8:o,tokenChars:i},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=require(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})),bh=o(((e,t)=>{let{Writable:n}=require(`stream`),r=vh(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=hh(),{concat:c,toArrayBuffer:l,unmask:u}=gh(),{isValidStatusCode:d,isValidUTF8:f}=yh(),p=Buffer[Symbol.species];t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[s]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new p(t.buffer,t.byteOffset+e,t.length-e),new p(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new p(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=a;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?c(n,t):this._binaryType===`arraybuffer`?l(c(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=c(n,t);if(!this._skipUTF8Validation&&!f(r)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,a),this.end();else{let n=e.readUInt16BE(0);if(!d(n)){t(this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let r=new p(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(r)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o]=r,a}}})),xh=o(((e,t)=>{let{Duplex:n}=require(`stream`),{randomFillSync:r}=require(`crypto`),i=vh(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=hh(),{isBlob:c,isValidStatusCode:l}=yh(),{mask:u,toBuffer:d}=gh(),f=Symbol(`kByteLength`),p=Buffer.alloc(4),m=8*1024,h,g=m;t.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=s,this[o]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||p,t.generateMask?t.generateMask(n):(g===m&&(h===void 0&&(h=Buffer.alloc(m)),r(h,0,m),g=0),n[0]=h[g++],n[1]=h[g++],n[2]=h[g++],n[3]=h[g++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[f]!==void 0?s=t[f]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:i?(u(e,n,l,a,s),[l]):(u(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=a;else if(typeof t!=`number`||!l(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`?o.write(n,2):o.set(n,2)}let s={[f]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,s),i):this.enqueue([this.dispatch,o,!1,s,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[i.extensionName],a=t.binary?2:1,o=t.compress,s,l;typeof e==`string`?(s=Buffer.byteLength(e),l=!1):c(e)?(s=e.size,l=!1):(e=d(e),s=e.length,l=d.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,a=0),t.fin&&(this._firstFragment=!0);let u={[f]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:l,rsv1:o};c(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[f],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(_,this,e,i);return}this._bufferedBytes-=r[f];let a=d(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(v,this,e,i)})}dispatch(t,n,r,a){if(!n){this.sendFrame(e.frame(t,r),a);return}let o=this._extensions[i.extensionName];this._bufferedBytes+=r[f],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){_(this,Error(`The socket was closed while data was being compressed`),a);return}this._bufferedBytes-=r[f],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),a),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function _(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function v(e,t,n){_(e,t,n),e.onerror(t)}})),Sh=o(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=hh(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,`target`,{enumerable:!0}),Object.defineProperty(f.prototype,`type`,{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,`code`,{enumerable:!0}),Object.defineProperty(p.prototype,`reason`,{enumerable:!0}),Object.defineProperty(p.prototype,`wasClean`,{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,`error`,{enumerable:!0}),Object.defineProperty(m.prototype,`message`,{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),Ch=o(((e,t)=>{let{tokenChars:n}=yh();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),wh=o(((e,t)=>{let n=require(`events`),r=require(`https`),i=require(`http`),a=require(`net`),o=require(`tls`),{randomBytes:s,createHash:c}=require(`crypto`),{Duplex:l,Readable:u}=require(`stream`),{URL:d}=require(`url`),f=vh(),p=bh(),m=xh(),{isBlob:h}=yh(),{BINARY_TYPES:g,CLOSE_TIMEOUT:_,EMPTY_BUFFER:v,GUID:y,kForOnEventAttribute:b,kListener:x,kStatusCode:S,kWebSocket:C,NOOP:w}=hh(),{EventTarget:{addEventListener:T,removeEventListener:E}}=Sh(),{format:D,parse:O}=Ch(),{toBuffer:k}=gh(),A=Symbol(`kAborted`),j=[8,13],M=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],ee=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var N=class e extends n{constructor(t,n,r){super(),this._binaryType=g[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=v,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),te(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){g.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new p({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new m(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[C]=this,a[C]=this,t[C]=this,i.on(`conclude`,L),i.on(`drain`,ie),i.on(`error`,ae),i.on(`message`,oe),i.on(`ping`,se),i.on(`pong`,ce),a.onerror=ue,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,z),t.on(`data`,fe),t.on(`end`,pe),t.on(`error`,me),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[f.extensionName]&&this._extensions[f.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){I(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),de(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){re(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||v,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){re(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||v,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){re(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[f.extensionName]||(i.compress=!1),this._sender.send(t||v,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){I(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(N,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(N.prototype,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(N,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(N.prototype,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(N,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(N.prototype,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(N,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),Object.defineProperty(N.prototype,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(N.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(N.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[b])return t[x];return null},set(t){for(let t of this.listeners(e))if(t[b]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[b]:!0})}})}),N.prototype.addEventListener=T,N.prototype.removeEventListener=E,t.exports=N;function te(e,t,n,a){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_,protocolVersion:j[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!j.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${j.join(`, `)})`);let l;if(t instanceof d)l=t;else try{l=new d(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}l.protocol===`http:`?l.protocol=`ws:`:l.protocol===`https:`&&(l.protocol=`wss:`),e._url=l.href;let u=l.protocol===`wss:`,p=l.protocol===`ws+unix:`,m;if(l.protocol!==`ws:`&&!u&&!p?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?m=`The URL's pathname is empty`:l.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;P(e,t);return}let h=u?443:80,g=s(16).toString(`base64`),v=u?r.request:i.request,b=new Set,x;if(o.createConnection=o.createConnection||(u?F:ne),o.defaultPort=o.defaultPort||h,o.port=l.port||h,o.host=l.hostname.startsWith(`[`)?l.hostname.slice(1,-1):l.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=l.pathname+l.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(x=new f(o.perMessageDeflate===!0?{}:o.perMessageDeflate,!1,o.maxPayload),o.headers[`Sec-WebSocket-Extensions`]=D({[f.extensionName]:x.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!ee.test(e)||b.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);b.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(l.username||l.password)&&(o.auth=`${l.username}:${l.password}`),p){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let S;if(o.followRedirects){if(e._redirects===0){e._originalIpc=p,e._originalSecure=u,e._originalHostOrSocketPath=p?o.socketPath:l.host;let t=a&&a.headers;if(a={...a,headers:{}},t)for(let[e,n]of Object.entries(t))a.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=p?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:l.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!a.headers.authorization&&(a.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),S=e._req=v(o),e._redirects&&e.emit(`redirect`,e.url,S)}else S=e._req=v(o);o.timeout&&S.on(`timeout`,()=>{I(e,S,`Opening handshake has timed out`)}),S.on(`error`,t=>{S===null||S[A]||(S=e._req=null,P(e,t))}),S.on(`response`,r=>{let i=r.headers.location,s=r.statusCode;if(i&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){I(e,S,`Maximum redirects exceeded`);return}S.abort();let r;try{r=new d(i,t)}catch{P(e,SyntaxError(`Invalid URL: ${i}`));return}te(e,r,n,a)}else e.emit(`unexpected-response`,S,r)||I(e,S,`Unexpected server response: ${r.statusCode}`)}),S.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==N.CONNECTING)return;S=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){I(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+y).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){I(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],l;if(s===void 0?b.size&&(l=`Server sent no subprotocol`):b.size?b.has(s)||(l=`Server sent an invalid subprotocol`):l=`Server sent a subprotocol but none was requested`,l){I(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!x){I(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=O(u)}catch{I(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){I(e,n,`Server indicated an extension that was not requested`);return}try{x.accept(t[f.extensionName])}catch{I(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[f.extensionName]=x}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(S,e):S.end()}function P(e,t){e._readyState=N.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function ne(e){return e.path=e.socketPath,a.connect(e)}function F(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function I(e,t,n){e._readyState=N.CLOSING;let r=Error(n);Error.captureStackTrace(r,I),t.setHeader?(t[A]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(P,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function re(e,t,n){if(t){let n=h(t)?t.size:k(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${M[e.readyState]})`);process.nextTick(n,t)}}function L(e,t){let n=this[C];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[C]!==void 0&&(n._socket.removeListener(`data`,fe),process.nextTick(le,n._socket),e===1005?n.close():n.close(e,t))}function ie(){let e=this[C];e.isPaused||e._socket.resume()}function ae(e){let t=this[C];t._socket[C]!==void 0&&(t._socket.removeListener(`data`,fe),process.nextTick(le,t._socket),t.close(e[S])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function R(){this[C].emitClose()}function oe(e,t){this[C].emit(`message`,e,t)}function se(e){let t=this[C];t._autoPong&&t.pong(e,!this._isServer,w),t.emit(`ping`,e)}function ce(e){this[C].emit(`pong`,e)}function le(e){e.resume()}function ue(e){let t=this[C];t.readyState!==N.CLOSED&&(t.readyState===N.OPEN&&(t._readyState=N.CLOSING,de(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function de(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function z(){let e=this[C];if(this.removeListener(`close`,z),this.removeListener(`data`,fe),this.removeListener(`end`,pe),e._readyState=N.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[C]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,R),e._receiver.on(`finish`,R))}function fe(e){this[C]._receiver.write(e)||this.pause()}function pe(){let e=this[C];e._readyState=N.CLOSING,e._receiver.end(),this.end()}function me(){let e=this[C];this.removeListener(`error`,me),this.on(`error`,w),e&&(e._readyState=N.CLOSING,this.destroy())}})),Th=o(((e,t)=>{wh();let{Duplex:n}=require(`stream`);function r(e){e.emit(`close`)}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function a(e){this.removeListener(`error`,a),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function o(e,t){let o=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(o=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let i=!1;e.once(`error`,function(e){i=!0,n(e)}),e.once(`close`,function(){i||n(t),process.nextTick(r,s)}),o&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,i),s.on(`error`,a),s}t.exports=o})),Eh=o(((e,t)=>{let{tokenChars:n}=yh();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),Dh=o(((e,t)=>{let n=require(`events`),r=require(`http`),{Duplex:i}=require(`stream`),{createHash:a}=require(`crypto`),o=Ch(),s=vh(),c=Eh(),l=wh(),{CLOSE_TIMEOUT:u,GUID:d,kWebSocket:f}=hh(),p=/^[+/0-9A-Za-z]{22}==$/;t.exports=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:u,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=m(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(h,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(h,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{h(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,g);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){v(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){v(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!p.test(i)){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){_(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{v(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&f!==void 0){let n=new s(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=o.parse(f);e[s.extensionName]&&(n.accept(e[s.extensionName]),m[s.extensionName]=n)}catch{v(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${l===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return _(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return _(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,c,l){if(!i.readable||!i.writable)return i.destroy();if(i[f])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return _(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${a(`sha1`).update(t+d).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[s.extensionName]){let t=e[s.extensionName].params,n=o.format({[s.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
|
|
453
453
|
`).join(`\r
|
|
454
454
|
`)),i.removeListener(`error`,g),p.setSocket(i,c,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on(`close`,()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(h,this)})),l(p,r)}};function m(e,t){for(let n of Object.keys(t))e.on(n,t[n]);return function(){for(let n of Object.keys(t))e.removeListener(n,t[n])}}function h(e){e._state=2,e.emit(`close`)}function g(){this.destroy()}function _(e,t,n,i){n||=r.STATUS_CODES[t],i={Connection:`close`,"Content-Type":`text/html`,"Content-Length":Buffer.byteLength(n),...i},e.once(`finish`,e.destroy),e.end(`HTTP/1.1 ${t} ${r.STATUS_CODES[t]}\r\n`+Object.keys(i).map(e=>`${e}: ${i[e]}`).join(`\r
|
|
455
455
|
`)+`\r
|
|
456
456
|
\r
|
|
457
|
-
`+n)}function v(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,v),e.emit(`wsClientError`,r,n,t)}else _(n,r,i,a)}})),Dh=o(((e,t)=>{let n=Ch();n.createWebSocketStream=wh(),n.Server=Eh(),n.Receiver=yh(),n.Sender=bh(),n.WebSocket=n,n.WebSocketServer=n.Server,t.exports=n})),Oh=o(((e,t)=>{t.exports=require(`stream`)})),kh=o(((e,t)=>{function n(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function r(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]==null?{}:arguments[t];t%2?n(Object(r),!0).forEach(function(t){i(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):n(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function i(e,t,n){return t=c(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function o(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,c(r.key),r)}}function s(e,t,n){return t&&o(e.prototype,t),n&&o(e,n),Object.defineProperty(e,`prototype`,{writable:!1}),e}function c(e){var t=l(e,`string`);return typeof t==`symbol`?t:String(t)}function l(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var u=require(`buffer`).Buffer,d=require(`util`).inspect,f=d&&d.custom||`inspect`;function p(e,t,n){u.prototype.copy.call(e,t,n)}t.exports=function(){function e(){a(this,e),this.head=null,this.tail=null,this.length=0}return s(e,[{key:`push`,value:function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:`unshift`,value:function(e){var t={data:e,next:this.head};this.length===0&&(this.tail=t),this.head=t,++this.length}},{key:`shift`,value:function(){if(this.length!==0){var e=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,e}}},{key:`clear`,value:function(){this.head=this.tail=null,this.length=0}},{key:`join`,value:function(e){if(this.length===0)return``;for(var t=this.head,n=``+t.data;t=t.next;)n+=e+t.data;return n}},{key:`concat`,value:function(e){if(this.length===0)return u.alloc(0);for(var t=u.allocUnsafe(e>>>0),n=this.head,r=0;n;)p(n.data,t,r),r+=n.data.length,n=n.next;return t}},{key:`consume`,value:function(e,t){var n;return e<this.head.data.length?(n=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):n=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),n}},{key:`first`,value:function(){return this.head.data}},{key:`_getString`,value:function(e){var t=this.head,n=1,r=t.data;for(e-=r.length;t=t.next;){var i=t.data,a=e>i.length?i.length:e;if(a===i.length?r+=i:r+=i.slice(0,e),e-=a,e===0){a===i.length?(++n,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=i.slice(a));break}++n}return this.length-=n,r}},{key:`_getBuffer`,value:function(e){var t=u.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var i=n.data,a=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,a),e-=a,e===0){a===i.length?(++r,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=i.slice(a));break}++r}return this.length-=r,t}},{key:f,value:function(e,t){return d(this,r(r({},t),{},{depth:0,customInspect:!1}))}}]),e}()})),Ah=o(((e,t)=>{function n(e,t){var n=this,a=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return a||s?(t?t(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(o,this,e)):process.nextTick(o,this,e)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(e){!t&&e?n._writableState?n._writableState.errorEmitted?process.nextTick(i,n):(n._writableState.errorEmitted=!0,process.nextTick(r,n,e)):process.nextTick(r,n,e):t?(process.nextTick(i,n),t(e)):process.nextTick(i,n)}),this)}function r(e,t){o(e,t),i(e)}function i(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit(`close`)}function a(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function o(e,t){e.emit(`error`,t)}function s(e,t){var n=e._readableState,r=e._writableState;n&&n.autoDestroy||r&&r.autoDestroy?e.destroy(t):e.emit(`error`,t)}t.exports={destroy:n,undestroy:a,errorOrDestroy:s}})),jh=o(((e,t)=>{let n={};function r(e,t,r){r||=Error;function i(e,n,r){return typeof t==`string`?t:t(e,n,r)}class a extends r{constructor(e,t,n){super(i(e,t,n))}}a.prototype.name=r.name,a.prototype.code=e,n[e]=a}function i(e,t){if(Array.isArray(e)){let n=e.length;return e=e.map(e=>String(e)),n>2?`one of ${t} ${e.slice(0,n-1).join(`, `)}, or `+e[n-1]:n===2?`one of ${t} ${e[0]} or ${e[1]}`:`of ${t} ${e[0]}`}else return`of ${t} ${String(e)}`}function a(e,t,n){return e.substr(!n||n<0?0:+n,t.length)===t}function o(e,t,n){return(n===void 0||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}function s(e,t,n){return typeof n!=`number`&&(n=0),n+t.length>e.length?!1:e.indexOf(t,n)!==-1}r(`ERR_INVALID_OPT_VALUE`,function(e,t){return`The value "`+t+`" is invalid for option "`+e+`"`},TypeError),r(`ERR_INVALID_ARG_TYPE`,function(e,t,n){let r;typeof t==`string`&&a(t,`not `)?(r=`must not be`,t=t.replace(/^not /,``)):r=`must be`;let c;return c=o(e,` argument`)?`The ${e} ${r} ${i(t,`type`)}`:`The "${e}" ${s(e,`.`)?`property`:`argument`} ${r} ${i(t,`type`)}`,c+=`. Received type ${typeof n}`,c},TypeError),r(`ERR_STREAM_PUSH_AFTER_EOF`,`stream.push() after EOF`),r(`ERR_METHOD_NOT_IMPLEMENTED`,function(e){return`The `+e+` method is not implemented`}),r(`ERR_STREAM_PREMATURE_CLOSE`,`Premature close`),r(`ERR_STREAM_DESTROYED`,function(e){return`Cannot call `+e+` after a stream was destroyed`}),r(`ERR_MULTIPLE_CALLBACK`,`Callback called multiple times`),r(`ERR_STREAM_CANNOT_PIPE`,`Cannot pipe, not readable`),r(`ERR_STREAM_WRITE_AFTER_END`,`write after end`),r(`ERR_STREAM_NULL_VALUES`,`May not write null values to stream`,TypeError),r(`ERR_UNKNOWN_ENCODING`,function(e){return`Unknown encoding: `+e},TypeError),r(`ERR_STREAM_UNSHIFT_AFTER_END_EVENT`,`stream.unshift() after end event`),t.exports.codes=n})),Mh=o(((e,t)=>{var n=jh().codes.ERR_INVALID_OPT_VALUE;function r(e,t,n){return e.highWaterMark==null?t?e[n]:null:e.highWaterMark}function i(e,t,i,a){var o=r(t,a,i);if(o!=null){if(!(isFinite(o)&&Math.floor(o)===o)||o<0)throw new n(a?i:`highWaterMark`,o);return Math.floor(o)}return e.objectMode?16:16*1024}t.exports={getHighWaterMark:i}})),Nh=o(((e,t)=>{typeof Object.create==`function`?t.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:t.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}})),Ph=o(((e,t)=>{try{var n=require(`util`);if(typeof n.inherits!=`function`)throw``;t.exports=n.inherits}catch{t.exports=Nh()}})),Fh=o(((e,t)=>{t.exports=require(`util`).deprecate})),Ih=o(((e,t)=>{t.exports=T;function n(e){var t=this;this.next=null,this.entry=null,this.finish=function(){ie(t,e)}}var r;T.WritableState=C;var i={deprecate:Fh()},a=Oh(),o=require(`buffer`).Buffer,s=(typeof global<`u`?global:typeof window<`u`?window:typeof self<`u`?self:{}).Uint8Array||function(){};function c(e){return o.from(e)}function l(e){return o.isBuffer(e)||e instanceof s}var u=Ah(),d=Mh().getHighWaterMark,f=jh().codes,p=f.ERR_INVALID_ARG_TYPE,m=f.ERR_METHOD_NOT_IMPLEMENTED,h=f.ERR_MULTIPLE_CALLBACK,g=f.ERR_STREAM_CANNOT_PIPE,_=f.ERR_STREAM_DESTROYED,v=f.ERR_STREAM_NULL_VALUES,y=f.ERR_STREAM_WRITE_AFTER_END,b=f.ERR_UNKNOWN_ENCODING,x=u.errorOrDestroy;Ph()(T,a);function S(){}function C(e,t,i){r||=Lh(),e||={},typeof i!=`boolean`&&(i=t instanceof r),this.objectMode=!!e.objectMode,i&&(this.objectMode=this.objectMode||!!e.writableObjectMode),this.highWaterMark=d(this,e,`writableHighWaterMark`,i),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1,this.decodeStrings=e.decodeStrings!==!1,this.defaultEncoding=e.defaultEncoding||`utf8`,this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){ee(t,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=e.emitClose!==!1,this.autoDestroy=!!e.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new n(this)}C.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},(function(){try{Object.defineProperty(C.prototype,`buffer`,{get:i.deprecate(function(){return this.getBuffer()},`_writableState.buffer is deprecated. Use _writableState.getBuffer instead.`,`DEP0003`)})}catch{}})();var w;typeof Symbol==`function`&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==`function`?(w=Function.prototype[Symbol.hasInstance],Object.defineProperty(T,Symbol.hasInstance,{value:function(e){return w.call(this,e)?!0:this===T?e&&e._writableState instanceof C:!1}})):w=function(e){return e instanceof this};function T(e){r||=Lh();var t=this instanceof r;if(!t&&!w.call(T,this))return new T(e);this._writableState=new C(e,this,t),this.writable=!0,e&&(typeof e.write==`function`&&(this._write=e.write),typeof e.writev==`function`&&(this._writev=e.writev),typeof e.destroy==`function`&&(this._destroy=e.destroy),typeof e.final==`function`&&(this._final=e.final)),a.call(this)}T.prototype.pipe=function(){x(this,new g)};function E(e,t){var n=new y;x(e,n),process.nextTick(t,n)}function D(e,t,n,r){var i;return n===null?i=new v:typeof n!=`string`&&!t.objectMode&&(i=new p(`chunk`,[`string`,`Buffer`],n)),i?(x(e,i),process.nextTick(r,i),!1):!0}T.prototype.write=function(e,t,n){var r=this._writableState,i=!1,a=!r.objectMode&&l(e);return a&&!o.isBuffer(e)&&(e=c(e)),typeof t==`function`&&(n=t,t=null),a?t=`buffer`:t||=r.defaultEncoding,typeof n!=`function`&&(n=S),r.ending?E(this,n):(a||D(this,r,e,n))&&(r.pendingcb++,i=k(this,r,a,e,t,n)),i},T.prototype.cork=function(){this._writableState.corked++},T.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest&&P(this,e))},T.prototype.setDefaultEncoding=function(e){if(typeof e==`string`&&(e=e.toLowerCase()),!([`hex`,`utf8`,`utf-8`,`ascii`,`binary`,`base64`,`ucs2`,`ucs-2`,`utf16le`,`utf-16le`,`raw`].indexOf((e+``).toLowerCase())>-1))throw new b(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(T.prototype,`writableBuffer`,{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function O(e,t,n){return!e.objectMode&&e.decodeStrings!==!1&&typeof t==`string`&&(t=o.from(t,n)),t}Object.defineProperty(T.prototype,`writableHighWaterMark`,{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function k(e,t,n,r,i,a){if(!n){var o=O(t,r,i);r!==o&&(n=!0,i=`buffer`,r=o)}var s=t.objectMode?1:r.length;t.length+=s;var c=t.length<t.highWaterMark;if(c||(t.needDrain=!0),t.writing||t.corked){var l=t.lastBufferedRequest;t.lastBufferedRequest={chunk:r,encoding:i,isBuf:n,callback:a,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else A(e,t,!1,s,r,i,a);return c}function A(e,t,n,r,i,a,o){t.writelen=r,t.writecb=o,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new _(`write`)):n?e._writev(i,t.onwrite):e._write(i,a,t.onwrite),t.sync=!1}function j(e,t,n,r,i){--t.pendingcb,n?(process.nextTick(i,r),process.nextTick(re,e,t),e._writableState.errorEmitted=!0,x(e,r)):(i(r),e._writableState.errorEmitted=!0,x(e,r),re(e,t))}function M(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function ee(e,t){var n=e._writableState,r=n.sync,i=n.writecb;if(typeof i!=`function`)throw new h;if(M(n),t)j(e,n,r,t,i);else{var a=ne(n)||e.destroyed;!a&&!n.corked&&!n.bufferProcessing&&n.bufferedRequest&&P(e,n),r?process.nextTick(N,e,n,a,i):N(e,n,a,i)}}function N(e,t,n,r){n||te(e,t),t.pendingcb--,r(),re(e,t)}function te(e,t){t.length===0&&t.needDrain&&(t.needDrain=!1,e.emit(`drain`))}function P(e,t){t.bufferProcessing=!0;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var i=t.bufferedRequestCount,a=Array(i),o=t.corkedRequestsFree;o.entry=r;for(var s=0,c=!0;r;)a[s]=r,r.isBuf||(c=!1),r=r.next,s+=1;a.allBuffers=c,A(e,t,!0,t.length,a,``,o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new n(t),t.bufferedRequestCount=0}else{for(;r;){var l=r.chunk,u=r.encoding,d=r.callback;if(A(e,t,!1,t.objectMode?1:l.length,l,u,d),r=r.next,t.bufferedRequestCount--,t.writing)break}r===null&&(t.lastBufferedRequest=null)}t.bufferedRequest=r,t.bufferProcessing=!1}T.prototype._write=function(e,t,n){n(new m(`_write()`))},T.prototype._writev=null,T.prototype.end=function(e,t,n){var r=this._writableState;return typeof e==`function`?(n=e,e=null,t=null):typeof t==`function`&&(n=t,t=null),e!=null&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||L(this,r,n),this},Object.defineProperty(T.prototype,`writableLength`,{enumerable:!1,get:function(){return this._writableState.length}});function ne(e){return e.ending&&e.length===0&&e.bufferedRequest===null&&!e.finished&&!e.writing}function F(e,t){e._final(function(n){t.pendingcb--,n&&x(e,n),t.prefinished=!0,e.emit(`prefinish`),re(e,t)})}function I(e,t){!t.prefinished&&!t.finalCalled&&(typeof e._final==`function`&&!t.destroyed?(t.pendingcb++,t.finalCalled=!0,process.nextTick(F,e,t)):(t.prefinished=!0,e.emit(`prefinish`)))}function re(e,t){var n=ne(t);if(n&&(I(e,t),t.pendingcb===0&&(t.finished=!0,e.emit(`finish`),t.autoDestroy))){var r=e._readableState;(!r||r.autoDestroy&&r.endEmitted)&&e.destroy()}return n}function L(e,t,n){t.ending=!0,re(e,t),n&&(t.finished?process.nextTick(n):e.once(`finish`,n)),t.ended=!0,e.writable=!1}function ie(e,t,n){var r=e.entry;for(e.entry=null;r;){var i=r.callback;t.pendingcb--,i(n),r=r.next}t.corkedRequestsFree.next=e}Object.defineProperty(T.prototype,`destroyed`,{enumerable:!1,get:function(){return this._writableState===void 0?!1:this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),T.prototype.destroy=u.destroy,T.prototype._undestroy=u.undestroy,T.prototype._destroy=function(e,t){t(e)}})),Lh=o(((e,t)=>{var n=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=c;var r=Uh(),i=Ih();Ph()(c,r);for(var a=n(i.prototype),o=0;o<a.length;o++){var s=a[o];c.prototype[s]||(c.prototype[s]=i.prototype[s])}function c(e){if(!(this instanceof c))return new c(e);r.call(this,e),i.call(this,e),this.allowHalfOpen=!0,e&&(e.readable===!1&&(this.readable=!1),e.writable===!1&&(this.writable=!1),e.allowHalfOpen===!1&&(this.allowHalfOpen=!1,this.once(`end`,l)))}Object.defineProperty(c.prototype,`writableHighWaterMark`,{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(c.prototype,`writableBuffer`,{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(c.prototype,`writableLength`,{enumerable:!1,get:function(){return this._writableState.length}});function l(){this._writableState.ended||process.nextTick(u,this)}function u(e){e.end()}Object.defineProperty(c.prototype,`destroyed`,{enumerable:!1,get:function(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set:function(e){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=e,this._writableState.destroyed=e)}})})),Rh=o(((e,t)=>{
|
|
457
|
+
`+n)}function v(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,v),e.emit(`wsClientError`,r,n,t)}else _(n,r,i,a)}})),Oh=o(((e,t)=>{let n=wh();n.createWebSocketStream=Th(),n.Server=Dh(),n.Receiver=bh(),n.Sender=xh(),n.WebSocket=n,n.WebSocketServer=n.Server,t.exports=n})),kh=o(((e,t)=>{t.exports=require(`stream`)})),Ah=o(((e,t)=>{function n(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function r(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]==null?{}:arguments[t];t%2?n(Object(r),!0).forEach(function(t){i(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):n(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function i(e,t,n){return t=c(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function o(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,c(r.key),r)}}function s(e,t,n){return t&&o(e.prototype,t),n&&o(e,n),Object.defineProperty(e,`prototype`,{writable:!1}),e}function c(e){var t=l(e,`string`);return typeof t==`symbol`?t:String(t)}function l(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var u=require(`buffer`).Buffer,d=require(`util`).inspect,f=d&&d.custom||`inspect`;function p(e,t,n){u.prototype.copy.call(e,t,n)}t.exports=function(){function e(){a(this,e),this.head=null,this.tail=null,this.length=0}return s(e,[{key:`push`,value:function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:`unshift`,value:function(e){var t={data:e,next:this.head};this.length===0&&(this.tail=t),this.head=t,++this.length}},{key:`shift`,value:function(){if(this.length!==0){var e=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,e}}},{key:`clear`,value:function(){this.head=this.tail=null,this.length=0}},{key:`join`,value:function(e){if(this.length===0)return``;for(var t=this.head,n=``+t.data;t=t.next;)n+=e+t.data;return n}},{key:`concat`,value:function(e){if(this.length===0)return u.alloc(0);for(var t=u.allocUnsafe(e>>>0),n=this.head,r=0;n;)p(n.data,t,r),r+=n.data.length,n=n.next;return t}},{key:`consume`,value:function(e,t){var n;return e<this.head.data.length?(n=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):n=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),n}},{key:`first`,value:function(){return this.head.data}},{key:`_getString`,value:function(e){var t=this.head,n=1,r=t.data;for(e-=r.length;t=t.next;){var i=t.data,a=e>i.length?i.length:e;if(a===i.length?r+=i:r+=i.slice(0,e),e-=a,e===0){a===i.length?(++n,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=i.slice(a));break}++n}return this.length-=n,r}},{key:`_getBuffer`,value:function(e){var t=u.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var i=n.data,a=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,a),e-=a,e===0){a===i.length?(++r,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=i.slice(a));break}++r}return this.length-=r,t}},{key:f,value:function(e,t){return d(this,r(r({},t),{},{depth:0,customInspect:!1}))}}]),e}()})),jh=o(((e,t)=>{function n(e,t){var n=this,a=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return a||s?(t?t(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(o,this,e)):process.nextTick(o,this,e)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(e){!t&&e?n._writableState?n._writableState.errorEmitted?process.nextTick(i,n):(n._writableState.errorEmitted=!0,process.nextTick(r,n,e)):process.nextTick(r,n,e):t?(process.nextTick(i,n),t(e)):process.nextTick(i,n)}),this)}function r(e,t){o(e,t),i(e)}function i(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit(`close`)}function a(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function o(e,t){e.emit(`error`,t)}function s(e,t){var n=e._readableState,r=e._writableState;n&&n.autoDestroy||r&&r.autoDestroy?e.destroy(t):e.emit(`error`,t)}t.exports={destroy:n,undestroy:a,errorOrDestroy:s}})),Mh=o(((e,t)=>{let n={};function r(e,t,r){r||=Error;function i(e,n,r){return typeof t==`string`?t:t(e,n,r)}class a extends r{constructor(e,t,n){super(i(e,t,n))}}a.prototype.name=r.name,a.prototype.code=e,n[e]=a}function i(e,t){if(Array.isArray(e)){let n=e.length;return e=e.map(e=>String(e)),n>2?`one of ${t} ${e.slice(0,n-1).join(`, `)}, or `+e[n-1]:n===2?`one of ${t} ${e[0]} or ${e[1]}`:`of ${t} ${e[0]}`}else return`of ${t} ${String(e)}`}function a(e,t,n){return e.substr(!n||n<0?0:+n,t.length)===t}function o(e,t,n){return(n===void 0||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}function s(e,t,n){return typeof n!=`number`&&(n=0),n+t.length>e.length?!1:e.indexOf(t,n)!==-1}r(`ERR_INVALID_OPT_VALUE`,function(e,t){return`The value "`+t+`" is invalid for option "`+e+`"`},TypeError),r(`ERR_INVALID_ARG_TYPE`,function(e,t,n){let r;typeof t==`string`&&a(t,`not `)?(r=`must not be`,t=t.replace(/^not /,``)):r=`must be`;let c;return c=o(e,` argument`)?`The ${e} ${r} ${i(t,`type`)}`:`The "${e}" ${s(e,`.`)?`property`:`argument`} ${r} ${i(t,`type`)}`,c+=`. Received type ${typeof n}`,c},TypeError),r(`ERR_STREAM_PUSH_AFTER_EOF`,`stream.push() after EOF`),r(`ERR_METHOD_NOT_IMPLEMENTED`,function(e){return`The `+e+` method is not implemented`}),r(`ERR_STREAM_PREMATURE_CLOSE`,`Premature close`),r(`ERR_STREAM_DESTROYED`,function(e){return`Cannot call `+e+` after a stream was destroyed`}),r(`ERR_MULTIPLE_CALLBACK`,`Callback called multiple times`),r(`ERR_STREAM_CANNOT_PIPE`,`Cannot pipe, not readable`),r(`ERR_STREAM_WRITE_AFTER_END`,`write after end`),r(`ERR_STREAM_NULL_VALUES`,`May not write null values to stream`,TypeError),r(`ERR_UNKNOWN_ENCODING`,function(e){return`Unknown encoding: `+e},TypeError),r(`ERR_STREAM_UNSHIFT_AFTER_END_EVENT`,`stream.unshift() after end event`),t.exports.codes=n})),Nh=o(((e,t)=>{var n=Mh().codes.ERR_INVALID_OPT_VALUE;function r(e,t,n){return e.highWaterMark==null?t?e[n]:null:e.highWaterMark}function i(e,t,i,a){var o=r(t,a,i);if(o!=null){if(!(isFinite(o)&&Math.floor(o)===o)||o<0)throw new n(a?i:`highWaterMark`,o);return Math.floor(o)}return e.objectMode?16:16*1024}t.exports={getHighWaterMark:i}})),Ph=o(((e,t)=>{typeof Object.create==`function`?t.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:t.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}})),Fh=o(((e,t)=>{try{var n=require(`util`);if(typeof n.inherits!=`function`)throw``;t.exports=n.inherits}catch{t.exports=Ph()}})),Ih=o(((e,t)=>{t.exports=require(`util`).deprecate})),Lh=o(((e,t)=>{t.exports=T;function n(e){var t=this;this.next=null,this.entry=null,this.finish=function(){ie(t,e)}}var r;T.WritableState=C;var i={deprecate:Ih()},a=kh(),o=require(`buffer`).Buffer,s=(typeof global<`u`?global:typeof window<`u`?window:typeof self<`u`?self:{}).Uint8Array||function(){};function c(e){return o.from(e)}function l(e){return o.isBuffer(e)||e instanceof s}var u=jh(),d=Nh().getHighWaterMark,f=Mh().codes,p=f.ERR_INVALID_ARG_TYPE,m=f.ERR_METHOD_NOT_IMPLEMENTED,h=f.ERR_MULTIPLE_CALLBACK,g=f.ERR_STREAM_CANNOT_PIPE,_=f.ERR_STREAM_DESTROYED,v=f.ERR_STREAM_NULL_VALUES,y=f.ERR_STREAM_WRITE_AFTER_END,b=f.ERR_UNKNOWN_ENCODING,x=u.errorOrDestroy;Fh()(T,a);function S(){}function C(e,t,i){r||=Rh(),e||={},typeof i!=`boolean`&&(i=t instanceof r),this.objectMode=!!e.objectMode,i&&(this.objectMode=this.objectMode||!!e.writableObjectMode),this.highWaterMark=d(this,e,`writableHighWaterMark`,i),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1,this.decodeStrings=e.decodeStrings!==!1,this.defaultEncoding=e.defaultEncoding||`utf8`,this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){ee(t,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=e.emitClose!==!1,this.autoDestroy=!!e.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new n(this)}C.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},(function(){try{Object.defineProperty(C.prototype,`buffer`,{get:i.deprecate(function(){return this.getBuffer()},`_writableState.buffer is deprecated. Use _writableState.getBuffer instead.`,`DEP0003`)})}catch{}})();var w;typeof Symbol==`function`&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==`function`?(w=Function.prototype[Symbol.hasInstance],Object.defineProperty(T,Symbol.hasInstance,{value:function(e){return w.call(this,e)?!0:this===T?e&&e._writableState instanceof C:!1}})):w=function(e){return e instanceof this};function T(e){r||=Rh();var t=this instanceof r;if(!t&&!w.call(T,this))return new T(e);this._writableState=new C(e,this,t),this.writable=!0,e&&(typeof e.write==`function`&&(this._write=e.write),typeof e.writev==`function`&&(this._writev=e.writev),typeof e.destroy==`function`&&(this._destroy=e.destroy),typeof e.final==`function`&&(this._final=e.final)),a.call(this)}T.prototype.pipe=function(){x(this,new g)};function E(e,t){var n=new y;x(e,n),process.nextTick(t,n)}function D(e,t,n,r){var i;return n===null?i=new v:typeof n!=`string`&&!t.objectMode&&(i=new p(`chunk`,[`string`,`Buffer`],n)),i?(x(e,i),process.nextTick(r,i),!1):!0}T.prototype.write=function(e,t,n){var r=this._writableState,i=!1,a=!r.objectMode&&l(e);return a&&!o.isBuffer(e)&&(e=c(e)),typeof t==`function`&&(n=t,t=null),a?t=`buffer`:t||=r.defaultEncoding,typeof n!=`function`&&(n=S),r.ending?E(this,n):(a||D(this,r,e,n))&&(r.pendingcb++,i=k(this,r,a,e,t,n)),i},T.prototype.cork=function(){this._writableState.corked++},T.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest&&P(this,e))},T.prototype.setDefaultEncoding=function(e){if(typeof e==`string`&&(e=e.toLowerCase()),!([`hex`,`utf8`,`utf-8`,`ascii`,`binary`,`base64`,`ucs2`,`ucs-2`,`utf16le`,`utf-16le`,`raw`].indexOf((e+``).toLowerCase())>-1))throw new b(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(T.prototype,`writableBuffer`,{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function O(e,t,n){return!e.objectMode&&e.decodeStrings!==!1&&typeof t==`string`&&(t=o.from(t,n)),t}Object.defineProperty(T.prototype,`writableHighWaterMark`,{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function k(e,t,n,r,i,a){if(!n){var o=O(t,r,i);r!==o&&(n=!0,i=`buffer`,r=o)}var s=t.objectMode?1:r.length;t.length+=s;var c=t.length<t.highWaterMark;if(c||(t.needDrain=!0),t.writing||t.corked){var l=t.lastBufferedRequest;t.lastBufferedRequest={chunk:r,encoding:i,isBuf:n,callback:a,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else A(e,t,!1,s,r,i,a);return c}function A(e,t,n,r,i,a,o){t.writelen=r,t.writecb=o,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new _(`write`)):n?e._writev(i,t.onwrite):e._write(i,a,t.onwrite),t.sync=!1}function j(e,t,n,r,i){--t.pendingcb,n?(process.nextTick(i,r),process.nextTick(re,e,t),e._writableState.errorEmitted=!0,x(e,r)):(i(r),e._writableState.errorEmitted=!0,x(e,r),re(e,t))}function M(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function ee(e,t){var n=e._writableState,r=n.sync,i=n.writecb;if(typeof i!=`function`)throw new h;if(M(n),t)j(e,n,r,t,i);else{var a=ne(n)||e.destroyed;!a&&!n.corked&&!n.bufferProcessing&&n.bufferedRequest&&P(e,n),r?process.nextTick(N,e,n,a,i):N(e,n,a,i)}}function N(e,t,n,r){n||te(e,t),t.pendingcb--,r(),re(e,t)}function te(e,t){t.length===0&&t.needDrain&&(t.needDrain=!1,e.emit(`drain`))}function P(e,t){t.bufferProcessing=!0;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var i=t.bufferedRequestCount,a=Array(i),o=t.corkedRequestsFree;o.entry=r;for(var s=0,c=!0;r;)a[s]=r,r.isBuf||(c=!1),r=r.next,s+=1;a.allBuffers=c,A(e,t,!0,t.length,a,``,o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new n(t),t.bufferedRequestCount=0}else{for(;r;){var l=r.chunk,u=r.encoding,d=r.callback;if(A(e,t,!1,t.objectMode?1:l.length,l,u,d),r=r.next,t.bufferedRequestCount--,t.writing)break}r===null&&(t.lastBufferedRequest=null)}t.bufferedRequest=r,t.bufferProcessing=!1}T.prototype._write=function(e,t,n){n(new m(`_write()`))},T.prototype._writev=null,T.prototype.end=function(e,t,n){var r=this._writableState;return typeof e==`function`?(n=e,e=null,t=null):typeof t==`function`&&(n=t,t=null),e!=null&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||L(this,r,n),this},Object.defineProperty(T.prototype,`writableLength`,{enumerable:!1,get:function(){return this._writableState.length}});function ne(e){return e.ending&&e.length===0&&e.bufferedRequest===null&&!e.finished&&!e.writing}function F(e,t){e._final(function(n){t.pendingcb--,n&&x(e,n),t.prefinished=!0,e.emit(`prefinish`),re(e,t)})}function I(e,t){!t.prefinished&&!t.finalCalled&&(typeof e._final==`function`&&!t.destroyed?(t.pendingcb++,t.finalCalled=!0,process.nextTick(F,e,t)):(t.prefinished=!0,e.emit(`prefinish`)))}function re(e,t){var n=ne(t);if(n&&(I(e,t),t.pendingcb===0&&(t.finished=!0,e.emit(`finish`),t.autoDestroy))){var r=e._readableState;(!r||r.autoDestroy&&r.endEmitted)&&e.destroy()}return n}function L(e,t,n){t.ending=!0,re(e,t),n&&(t.finished?process.nextTick(n):e.once(`finish`,n)),t.ended=!0,e.writable=!1}function ie(e,t,n){var r=e.entry;for(e.entry=null;r;){var i=r.callback;t.pendingcb--,i(n),r=r.next}t.corkedRequestsFree.next=e}Object.defineProperty(T.prototype,`destroyed`,{enumerable:!1,get:function(){return this._writableState===void 0?!1:this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),T.prototype.destroy=u.destroy,T.prototype._undestroy=u.undestroy,T.prototype._destroy=function(e,t){t(e)}})),Rh=o(((e,t)=>{var n=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=c;var r=Wh(),i=Lh();Fh()(c,r);for(var a=n(i.prototype),o=0;o<a.length;o++){var s=a[o];c.prototype[s]||(c.prototype[s]=i.prototype[s])}function c(e){if(!(this instanceof c))return new c(e);r.call(this,e),i.call(this,e),this.allowHalfOpen=!0,e&&(e.readable===!1&&(this.readable=!1),e.writable===!1&&(this.writable=!1),e.allowHalfOpen===!1&&(this.allowHalfOpen=!1,this.once(`end`,l)))}Object.defineProperty(c.prototype,`writableHighWaterMark`,{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(c.prototype,`writableBuffer`,{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(c.prototype,`writableLength`,{enumerable:!1,get:function(){return this._writableState.length}});function l(){this._writableState.ended||process.nextTick(u,this)}function u(e){e.end()}Object.defineProperty(c.prototype,`destroyed`,{enumerable:!1,get:function(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set:function(e){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=e,this._writableState.destroyed=e)}})})),zh=o(((e,t)=>{
|
|
458
458
|
/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
|
|
459
|
-
var n=require(`buffer`),r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?t.exports=n:(i(n,e),e.Buffer=a);function a(e,t,n){return r(e,t,n)}a.prototype=Object.create(r.prototype),i(r,a),a.from=function(e,t,n){if(typeof e==`number`)throw TypeError(`Argument must not be a number`);return r(e,t,n)},a.alloc=function(e,t,n){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);var i=r(e);return t===void 0?i.fill(0):typeof n==`string`?i.fill(t,n):i.fill(t),i},a.allocUnsafe=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return r(e)},a.allocUnsafeSlow=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return n.SlowBuffer(e)}})),zh=o((e=>{var t=Rh().Buffer,n=t.isEncoding||function(e){switch(e=``+e,e&&e.toLowerCase()){case`hex`:case`utf8`:case`utf-8`:case`ascii`:case`binary`:case`base64`:case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:case`raw`:return!0;default:return!1}};function r(e){if(!e)return`utf8`;for(var t;;)switch(e){case`utf8`:case`utf-8`:return`utf8`;case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return`utf16le`;case`latin1`:case`binary`:return`latin1`;case`base64`:case`ascii`:case`hex`:return e;default:if(t)return;e=(``+e).toLowerCase(),t=!0}}function i(e){var i=r(e);if(typeof i!=`string`&&(t.isEncoding===n||!n(e)))throw Error(`Unknown encoding: `+e);return i||e}e.StringDecoder=a;function a(e){this.encoding=i(e);var n;switch(this.encoding){case`utf16le`:this.text=f,this.end=p,n=4;break;case`utf8`:this.fillLast=l,n=4;break;case`base64`:this.text=m,this.end=h,n=3;break;default:this.write=g,this.end=_;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=t.allocUnsafe(n)}a.prototype.write=function(e){if(e.length===0)return``;var t,n;if(this.lastNeed){if(t=this.fillLast(e),t===void 0)return``;n=this.lastNeed,this.lastNeed=0}else n=0;return n<e.length?t?t+this.text(e,n):this.text(e,n):t||``},a.prototype.end=d,a.prototype.text=u,a.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length};function o(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function s(e,t,n){var r=t.length-1;if(r<n)return 0;var i=o(t[r]);return i>=0?(i>0&&(e.lastNeed=i-1),i):--r<n||i===-2?0:(i=o(t[r]),i>=0?(i>0&&(e.lastNeed=i-2),i):--r<n||i===-2?0:(i=o(t[r]),i>=0?(i>0&&(i===2?i=0:e.lastNeed=i-3),i):0))}function c(e,t,n){if((t[0]&192)!=128)return e.lastNeed=0,`�`;if(e.lastNeed>1&&t.length>1){if((t[1]&192)!=128)return e.lastNeed=1,`�`;if(e.lastNeed>2&&t.length>2&&(t[2]&192)!=128)return e.lastNeed=2,`�`}}function l(e){var t=this.lastTotal-this.lastNeed,n=c(this,e,t);if(n!==void 0)return n;if(this.lastNeed<=e.length)return e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,t,0,e.length),this.lastNeed-=e.length}function u(e,t){var n=s(this,e,t);if(!this.lastNeed)return e.toString(`utf8`,t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString(`utf8`,t,r)}function d(e){var t=e&&e.length?this.write(e):``;return this.lastNeed?t+`�`:t}function f(e,t){if((e.length-t)%2==0){var n=e.toString(`utf16le`,t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString(`utf16le`,t,e.length-1)}function p(e){var t=e&&e.length?this.write(e):``;if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString(`utf16le`,0,n)}return t}function m(e,t){var n=(e.length-t)%3;return n===0?e.toString(`base64`,t):(this.lastNeed=3-n,this.lastTotal=3,n===1?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString(`base64`,t,e.length-n))}function h(e){var t=e&&e.length?this.write(e):``;return this.lastNeed?t+this.lastChar.toString(`base64`,0,3-this.lastNeed):t}function g(e){return e.toString(this.encoding)}function _(e){return e&&e.length?this.write(e):``}})),Bh=o(((e,t)=>{var n=jh().codes.ERR_STREAM_PREMATURE_CLOSE;function r(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,r=Array(n),i=0;i<n;i++)r[i]=arguments[i];e.apply(this,r)}}}function i(){}function a(e){return e.setHeader&&typeof e.abort==`function`}function o(e,t,s){if(typeof t==`function`)return o(e,null,t);t||={},s=r(s||i);var c=t.readable||t.readable!==!1&&e.readable,l=t.writable||t.writable!==!1&&e.writable,u=function(){e.writable||f()},d=e._writableState&&e._writableState.finished,f=function(){l=!1,d=!0,c||s.call(e)},p=e._readableState&&e._readableState.endEmitted,m=function(){c=!1,p=!0,l||s.call(e)},h=function(t){s.call(e,t)},g=function(){var t;if(c&&!p)return(!e._readableState||!e._readableState.ended)&&(t=new n),s.call(e,t);if(l&&!d)return(!e._writableState||!e._writableState.ended)&&(t=new n),s.call(e,t)},_=function(){e.req.on(`finish`,f)};return a(e)?(e.on(`complete`,f),e.on(`abort`,g),e.req?_():e.on(`request`,_)):l&&!e._writableState&&(e.on(`end`,u),e.on(`close`,u)),e.on(`end`,m),e.on(`finish`,f),t.error!==!1&&e.on(`error`,h),e.on(`close`,g),function(){e.removeListener(`complete`,f),e.removeListener(`abort`,g),e.removeListener(`request`,_),e.req&&e.req.removeListener(`finish`,f),e.removeListener(`end`,u),e.removeListener(`close`,u),e.removeListener(`finish`,f),e.removeListener(`end`,m),e.removeListener(`error`,h),e.removeListener(`close`,g)}}t.exports=o})),Vh=o(((e,t)=>{var n;function r(e,t,n){return t=i(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e){var t=a(e,`string`);return typeof t==`symbol`?t:String(t)}function a(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var o=Bh(),s=Symbol(`lastResolve`),c=Symbol(`lastReject`),l=Symbol(`error`),u=Symbol(`ended`),d=Symbol(`lastPromise`),f=Symbol(`handlePromise`),p=Symbol(`stream`);function m(e,t){return{value:e,done:t}}function h(e){var t=e[s];if(t!==null){var n=e[p].read();n!==null&&(e[d]=null,e[s]=null,e[c]=null,t(m(n,!1)))}}function g(e){process.nextTick(h,e)}function _(e,t){return function(n,r){e.then(function(){if(t[u]){n(m(void 0,!0));return}t[f](n,r)},r)}}var v=Object.getPrototypeOf(function(){}),y=Object.setPrototypeOf((n={get stream(){return this[p]},next:function(){var e=this,t=this[l];if(t!==null)return Promise.reject(t);if(this[u])return Promise.resolve(m(void 0,!0));if(this[p].destroyed)return new Promise(function(t,n){process.nextTick(function(){e[l]?n(e[l]):t(m(void 0,!0))})});var n=this[d],r;if(n)r=new Promise(_(n,this));else{var i=this[p].read();if(i!==null)return Promise.resolve(m(i,!1));r=new Promise(this[f])}return this[d]=r,r}},r(n,Symbol.asyncIterator,function(){return this}),r(n,`return`,function(){var e=this;return new Promise(function(t,n){e[p].destroy(null,function(e){if(e){n(e);return}t(m(void 0,!0))})})}),n),v);t.exports=function(e){var t,n=Object.create(y,(t={},r(t,p,{value:e,writable:!0}),r(t,s,{value:null,writable:!0}),r(t,c,{value:null,writable:!0}),r(t,l,{value:null,writable:!0}),r(t,u,{value:e._readableState.endEmitted,writable:!0}),r(t,f,{value:function(e,t){var r=n[p].read();r?(n[d]=null,n[s]=null,n[c]=null,e(m(r,!1))):(n[s]=e,n[c]=t)},writable:!0}),t));return n[d]=null,o(e,function(e){if(e&&e.code!==`ERR_STREAM_PREMATURE_CLOSE`){var t=n[c];t!==null&&(n[d]=null,n[s]=null,n[c]=null,t(e)),n[l]=e;return}var r=n[s];r!==null&&(n[d]=null,n[s]=null,n[c]=null,r(m(void 0,!0))),n[u]=!0}),e.on(`readable`,g.bind(null,n)),n}})),Hh=o(((e,t)=>{function n(e,t,n,r,i,a,o){try{var s=e[a](o),c=s.value}catch(e){n(e);return}s.done?t(c):Promise.resolve(c).then(r,i)}function r(e){return function(){var t=this,r=arguments;return new Promise(function(i,a){var o=e.apply(t,r);function s(e){n(o,i,a,s,c,`next`,e)}function c(e){n(o,i,a,s,c,`throw`,e)}s(void 0)})}}function i(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function a(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?i(Object(n),!0).forEach(function(t){o(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):i(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function o(e,t,n){return t=s(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(e){var t=c(e,`string`);return typeof t==`symbol`?t:String(t)}function c(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var l=jh().codes.ERR_INVALID_ARG_TYPE;function u(e,t,n){var i;if(t&&typeof t.next==`function`)i=t;else if(t&&t[Symbol.asyncIterator])i=t[Symbol.asyncIterator]();else if(t&&t[Symbol.iterator])i=t[Symbol.iterator]();else throw new l(`iterable`,[`Iterable`],t);var o=new e(a({objectMode:!0},n)),s=!1;o._read=function(){s||(s=!0,c())};function c(){return u.apply(this,arguments)}function u(){return u=r(function*(){try{var e=yield i.next(),t=e.value;e.done?o.push(null):o.push(yield t)?c():s=!1}catch(e){o.destroy(e)}}),u.apply(this,arguments)}return o}t.exports=u})),Uh=o(((e,t)=>{t.exports=E;var n;E.ReadableState=T,require(`events`).EventEmitter;var r=function(e,t){return e.listeners(t).length},i=Oh(),a=require(`buffer`).Buffer,o=(typeof global<`u`?global:typeof window<`u`?window:typeof self<`u`?self:{}).Uint8Array||function(){};function s(e){return a.from(e)}function c(e){return a.isBuffer(e)||e instanceof o}var l=require(`util`),u=l&&l.debuglog?l.debuglog(`stream`):function(){},d=kh(),f=Ah(),p=Mh().getHighWaterMark,m=jh().codes,h=m.ERR_INVALID_ARG_TYPE,g=m.ERR_STREAM_PUSH_AFTER_EOF,_=m.ERR_METHOD_NOT_IMPLEMENTED,v=m.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,y,b,x;Ph()(E,i);var S=f.errorOrDestroy,C=[`error`,`close`,`destroy`,`pause`,`resume`];function w(e,t,n){if(typeof e.prependListener==`function`)return e.prependListener(t,n);!e._events||!e._events[t]?e.on(t,n):Array.isArray(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]}function T(e,t,r){n||=Lh(),e||={},typeof r!=`boolean`&&(r=t instanceof n),this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.readableObjectMode),this.highWaterMark=p(this,e,`readableHighWaterMark`,r),this.buffer=new d,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=e.emitClose!==!1,this.autoDestroy=!!e.autoDestroy,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||`utf8`,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(y||=zh().StringDecoder,this.decoder=new y(e.encoding),this.encoding=e.encoding)}function E(e){if(n||=Lh(),!(this instanceof E))return new E(e);var t=this instanceof n;this._readableState=new T(e,this,t),this.readable=!0,e&&(typeof e.read==`function`&&(this._read=e.read),typeof e.destroy==`function`&&(this._destroy=e.destroy)),i.call(this)}Object.defineProperty(E.prototype,`destroyed`,{enumerable:!1,get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),E.prototype.destroy=f.destroy,E.prototype._undestroy=f.undestroy,E.prototype._destroy=function(e,t){t(e)},E.prototype.push=function(e,t){var n=this._readableState,r;return n.objectMode?r=!0:typeof e==`string`&&(t||=n.defaultEncoding,t!==n.encoding&&(e=a.from(e,t),t=``),r=!0),D(this,e,t,!1,r)},E.prototype.unshift=function(e){return D(this,e,null,!0,!1)};function D(e,t,n,r,i){u(`readableAddChunk`,t);var o=e._readableState;if(t===null)o.reading=!1,ee(e,o);else{var c;if(i||(c=k(o,t)),c)S(e,c);else if(o.objectMode||t&&t.length>0)if(typeof t!=`string`&&!o.objectMode&&Object.getPrototypeOf(t)!==a.prototype&&(t=s(t)),r)o.endEmitted?S(e,new v):O(e,o,t,!0);else if(o.ended)S(e,new g);else if(o.destroyed)return!1;else o.reading=!1,o.decoder&&!n?(t=o.decoder.write(t),o.objectMode||t.length!==0?O(e,o,t,!1):P(e,o)):O(e,o,t,!1);else r||(o.reading=!1,P(e,o))}return!o.ended&&(o.length<o.highWaterMark||o.length===0)}function O(e,t,n,r){t.flowing&&t.length===0&&!t.sync?(t.awaitDrain=0,e.emit(`data`,n)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&N(e)),P(e,t)}function k(e,t){var n;return!c(t)&&typeof t!=`string`&&t!==void 0&&!e.objectMode&&(n=new h(`chunk`,[`string`,`Buffer`,`Uint8Array`],t)),n}E.prototype.isPaused=function(){return this._readableState.flowing===!1},E.prototype.setEncoding=function(e){y||=zh().StringDecoder;var t=new y(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;for(var n=this._readableState.buffer.head,r=``;n!==null;)r+=t.write(n.data),n=n.next;return this._readableState.buffer.clear(),r!==``&&this._readableState.buffer.push(r),this._readableState.length=r.length,this};var A=1073741824;function j(e){return e>=A?e=A:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function M(e,t){return e<=0||t.length===0&&t.ended?0:t.objectMode?1:e===e?(e>t.highWaterMark&&(t.highWaterMark=j(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0)):t.flowing&&t.length?t.buffer.head.data.length:t.length}E.prototype.read=function(e){u(`read`,e),e=parseInt(e,10);var t=this._readableState,n=e;if(e!==0&&(t.emittedReadable=!1),e===0&&t.needReadable&&((t.highWaterMark===0?t.length>0:t.length>=t.highWaterMark)||t.ended))return u(`read: emitReadable`,t.length,t.ended),t.length===0&&t.ended?oe(this):N(this),null;if(e=M(e,t),e===0&&t.ended)return t.length===0&&oe(this),null;var r=t.needReadable;u(`need readable`,r),(t.length===0||t.length-e<t.highWaterMark)&&(r=!0,u(`length less than watermark`,r)),t.ended||t.reading?(r=!1,u(`reading or ended`,r)):r&&(u(`do read`),t.reading=!0,t.sync=!0,t.length===0&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=M(n,t)));var i=e>0?R(e,t):null;return i===null?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),t.length===0&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&oe(this)),i!==null&&this.emit(`data`,i),i};function ee(e,t){if(u(`onEofChunk`),!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?N(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,te(e)))}}function N(e){var t=e._readableState;u(`emitReadable`,t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(u(`emitReadable`,t.flowing),t.emittedReadable=!0,process.nextTick(te,e))}function te(e){var t=e._readableState;u(`emitReadable_`,t.destroyed,t.length,t.ended),!t.destroyed&&(t.length||t.ended)&&(e.emit(`readable`),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,ae(e)}function P(e,t){t.readingMore||(t.readingMore=!0,process.nextTick(ne,e,t))}function ne(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&t.length===0);){var n=t.length;if(u(`maybeReadMore read 0`),e.read(0),n===t.length)break}t.readingMore=!1}E.prototype._read=function(e){S(this,new _(`_read()`))},E.prototype.pipe=function(e,t){var n=this,i=this._readableState;switch(i.pipesCount){case 0:i.pipes=e;break;case 1:i.pipes=[i.pipes,e];break;default:i.pipes.push(e);break}i.pipesCount+=1,u(`pipe count=%d opts=%j`,i.pipesCount,t);var a=(!t||t.end!==!1)&&e!==process.stdout&&e!==process.stderr?s:g;i.endEmitted?process.nextTick(a):n.once(`end`,a),e.on(`unpipe`,o);function o(e,t){u(`onunpipe`),e===n&&t&&t.hasUnpiped===!1&&(t.hasUnpiped=!0,d())}function s(){u(`onend`),e.end()}var c=F(n);e.on(`drain`,c);var l=!1;function d(){u(`cleanup`),e.removeListener(`close`,m),e.removeListener(`finish`,h),e.removeListener(`drain`,c),e.removeListener(`error`,p),e.removeListener(`unpipe`,o),n.removeListener(`end`,s),n.removeListener(`end`,g),n.removeListener(`data`,f),l=!0,i.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&c()}n.on(`data`,f);function f(t){u(`ondata`);var r=e.write(t);u(`dest.write`,r),r===!1&&((i.pipesCount===1&&i.pipes===e||i.pipesCount>1&&ce(i.pipes,e)!==-1)&&!l&&(u(`false write response, pause`,i.awaitDrain),i.awaitDrain++),n.pause())}function p(t){u(`onerror`,t),g(),e.removeListener(`error`,p),r(e,`error`)===0&&S(e,t)}w(e,`error`,p);function m(){e.removeListener(`finish`,h),g()}e.once(`close`,m);function h(){u(`onfinish`),e.removeListener(`close`,m),g()}e.once(`finish`,h);function g(){u(`unpipe`),n.unpipe(e)}return e.emit(`pipe`,n),i.flowing||(u(`pipe resume`),n.resume()),e};function F(e){return function(){var t=e._readableState;u(`pipeOnDrain`,t.awaitDrain),t.awaitDrain&&t.awaitDrain--,t.awaitDrain===0&&r(e,`data`)&&(t.flowing=!0,ae(e))}}E.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(t.pipesCount===0)return this;if(t.pipesCount===1)return e&&e!==t.pipes?this:(e||=t.pipes,t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit(`unpipe`,this,n),this);if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var a=0;a<i;a++)r[a].emit(`unpipe`,this,{hasUnpiped:!1});return this}var o=ce(t.pipes,e);return o===-1?this:(t.pipes.splice(o,1),--t.pipesCount,t.pipesCount===1&&(t.pipes=t.pipes[0]),e.emit(`unpipe`,this,n),this)},E.prototype.on=function(e,t){var n=i.prototype.on.call(this,e,t),r=this._readableState;return e===`data`?(r.readableListening=this.listenerCount(`readable`)>0,r.flowing!==!1&&this.resume()):e===`readable`&&!r.endEmitted&&!r.readableListening&&(r.readableListening=r.needReadable=!0,r.flowing=!1,r.emittedReadable=!1,u(`on readable`,r.length,r.reading),r.length?N(this):r.reading||process.nextTick(re,this)),n},E.prototype.addListener=E.prototype.on,E.prototype.removeListener=function(e,t){var n=i.prototype.removeListener.call(this,e,t);return e===`readable`&&process.nextTick(I,this),n},E.prototype.removeAllListeners=function(e){var t=i.prototype.removeAllListeners.apply(this,arguments);return(e===`readable`||e===void 0)&&process.nextTick(I,this),t};function I(e){var t=e._readableState;t.readableListening=e.listenerCount(`readable`)>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount(`data`)>0&&e.resume()}function re(e){u(`readable nexttick read 0`),e.read(0)}E.prototype.resume=function(){var e=this._readableState;return e.flowing||(u(`resume`),e.flowing=!e.readableListening,L(this,e)),e.paused=!1,this};function L(e,t){t.resumeScheduled||(t.resumeScheduled=!0,process.nextTick(ie,e,t))}function ie(e,t){u(`resume`,t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit(`resume`),ae(e),t.flowing&&!t.reading&&e.read(0)}E.prototype.pause=function(){return u(`call pause flowing=%j`,this._readableState.flowing),this._readableState.flowing!==!1&&(u(`pause`),this._readableState.flowing=!1,this.emit(`pause`)),this._readableState.paused=!0,this};function ae(e){var t=e._readableState;for(u(`flow`,t.flowing);t.flowing&&e.read()!==null;);}E.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var i in e.on(`end`,function(){if(u(`wrapped end`),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)}),e.on(`data`,function(i){u(`wrapped data`),n.decoder&&(i=n.decoder.write(i)),!(n.objectMode&&i==null)&&(!n.objectMode&&(!i||!i.length)||t.push(i)||(r=!0,e.pause()))}),e)this[i]===void 0&&typeof e[i]==`function`&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));for(var a=0;a<C.length;a++)e.on(C[a],this.emit.bind(this,C[a]));return this._read=function(t){u(`wrapped _read`,t),r&&(r=!1,e.resume())},this},typeof Symbol==`function`&&(E.prototype[Symbol.asyncIterator]=function(){return b===void 0&&(b=Vh()),b(this)}),Object.defineProperty(E.prototype,`readableHighWaterMark`,{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(E.prototype,`readableBuffer`,{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(E.prototype,`readableFlowing`,{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),E._fromList=R,Object.defineProperty(E.prototype,`readableLength`,{enumerable:!1,get:function(){return this._readableState.length}});function R(e,t){if(t.length===0)return null;var n;return t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(``):t.buffer.length===1?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n}function oe(e){var t=e._readableState;u(`endReadable`,t.endEmitted),t.endEmitted||(t.ended=!0,process.nextTick(se,t,e))}function se(e,t){if(u(`endReadableNT`,e.endEmitted,e.length),!e.endEmitted&&e.length===0&&(e.endEmitted=!0,t.readable=!1,t.emit(`end`),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}typeof Symbol==`function`&&(E.from=function(e,t){return x===void 0&&(x=Hh()),x(E,e,t)});function ce(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}})),Wh=o(((e,t)=>{t.exports=l;var n=jh().codes,r=n.ERR_METHOD_NOT_IMPLEMENTED,i=n.ERR_MULTIPLE_CALLBACK,a=n.ERR_TRANSFORM_ALREADY_TRANSFORMING,o=n.ERR_TRANSFORM_WITH_LENGTH_0,s=Lh();Ph()(l,s);function c(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(r===null)return this.emit(`error`,new i);n.writechunk=null,n.writecb=null,t!=null&&this.push(t),r(e);var a=this._readableState;a.reading=!1,(a.needReadable||a.length<a.highWaterMark)&&this._read(a.highWaterMark)}function l(e){if(!(this instanceof l))return new l(e);s.call(this,e),this._transformState={afterTransform:c.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&(typeof e.transform==`function`&&(this._transform=e.transform),typeof e.flush==`function`&&(this._flush=e.flush)),this.on(`prefinish`,u)}function u(){var e=this;typeof this._flush==`function`&&!this._readableState.destroyed?this._flush(function(t,n){d(e,t,n)}):d(this,null,null)}l.prototype.push=function(e,t){return this._transformState.needTransform=!1,s.prototype.push.call(this,e,t)},l.prototype._transform=function(e,t,n){n(new r(`_transform()`))},l.prototype._write=function(e,t,n){var r=this._transformState;if(r.writecb=n,r.writechunk=e,r.writeencoding=t,!r.transforming){var i=this._readableState;(r.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}},l.prototype._read=function(e){var t=this._transformState;t.writechunk!==null&&!t.transforming?(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=!0},l.prototype._destroy=function(e,t){s.prototype._destroy.call(this,e,function(e){t(e)})};function d(e,t,n){if(t)return e.emit(`error`,t);if(n!=null&&e.push(n),e._writableState.length)throw new o;if(e._transformState.transforming)throw new a;return e.push(null)}})),Gh=o(((e,t)=>{t.exports=r;var n=Wh();Ph()(r,n);function r(e){if(!(this instanceof r))return new r(e);n.call(this,e)}r.prototype._transform=function(e,t,n){n(null,e)}})),Kh=o(((e,t)=>{var n;function r(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var i=jh().codes,a=i.ERR_MISSING_ARGS,o=i.ERR_STREAM_DESTROYED;function s(e){if(e)throw e}function c(e){return e.setHeader&&typeof e.abort==`function`}function l(e,t,i,a){a=r(a);var s=!1;e.on(`close`,function(){s=!0}),n===void 0&&(n=Bh()),n(e,{readable:t,writable:i},function(e){if(e)return a(e);s=!0,a()});var l=!1;return function(t){if(!s&&!l){if(l=!0,c(e))return e.abort();if(typeof e.destroy==`function`)return e.destroy();a(t||new o(`pipe`))}}}function u(e){e()}function d(e,t){return e.pipe(t)}function f(e){return!e.length||typeof e[e.length-1]!=`function`?s:e.pop()}function p(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var r=f(t);if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new a(`streams`);var i,o=t.map(function(e,n){var a=n<t.length-1;return l(e,a,n>0,function(e){i||=e,e&&o.forEach(u),!a&&(o.forEach(u),r(i))})});return t.reduce(d)}t.exports=p})),qh=o(((e,t)=>{var n=require(`stream`);process.env.READABLE_STREAM===`disable`&&n?(t.exports=n.Readable,Object.assign(t.exports,n),t.exports.Stream=n):(e=t.exports=Uh(),e.Stream=n||e,e.Readable=e,e.Writable=Ih(),e.Duplex=Lh(),e.Transform=Wh(),e.PassThrough=Gh(),e.finished=Bh(),e.pipeline=Kh())})),Jh=o(((e,t)=>{t.exports=n;function n(e,t){if(e&&t)return n(e)(t);if(typeof e!=`function`)throw TypeError(`need wrapper function`);return Object.keys(e).forEach(function(t){r[t]=e[t]}),r;function r(){for(var t=Array(arguments.length),n=0;n<t.length;n++)t[n]=arguments[n];var r=e.apply(this,t),i=t[t.length-1];return typeof r==`function`&&r!==i&&Object.keys(i).forEach(function(e){r[e]=i[e]}),r}}})),Yh=o(((e,t)=>{var n=Jh();t.exports=n(r),t.exports.strict=n(i),r.proto=r(function(){Object.defineProperty(Function.prototype,`once`,{value:function(){return r(this)},configurable:!0}),Object.defineProperty(Function.prototype,`onceStrict`,{value:function(){return i(this)},configurable:!0})});function r(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function i(e){var t=function(){if(t.called)throw Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)};return t.onceError=(e.name||"Function wrapped with `once`")+` shouldn't be called more than once`,t.called=!1,t}})),Xh=o(((e,t)=>{var n=Yh(),r=function(){},i=global.Bare?queueMicrotask:process.nextTick.bind(process),a=function(e){return e.setHeader&&typeof e.abort==`function`},o=function(e){return e.stdio&&Array.isArray(e.stdio)&&e.stdio.length===3},s=function(e,t,c){if(typeof t==`function`)return s(e,null,t);t||={},c=n(c||r);var l=e._writableState,u=e._readableState,d=t.readable||t.readable!==!1&&e.readable,f=t.writable||t.writable!==!1&&e.writable,p=!1,m=function(){e.writable||h()},h=function(){f=!1,d||c.call(e)},g=function(){d=!1,f||c.call(e)},_=function(t){c.call(e,t?Error(`exited with error code: `+t):null)},v=function(t){c.call(e,t)},y=function(){i(b)},b=function(){if(!p&&(d&&!(u&&u.ended&&!u.destroyed)||f&&!(l&&l.ended&&!l.destroyed)))return c.call(e,Error(`premature close`))},x=function(){e.req.on(`finish`,h)};return a(e)?(e.on(`complete`,h),e.on(`abort`,y),e.req?x():e.on(`request`,x)):f&&!l&&(e.on(`end`,m),e.on(`close`,m)),o(e)&&e.on(`exit`,_),e.on(`end`,g),e.on(`finish`,h),t.error!==!1&&e.on(`error`,v),e.on(`close`,y),function(){p=!0,e.removeListener(`complete`,h),e.removeListener(`abort`,y),e.removeListener(`request`,x),e.req&&e.req.removeListener(`finish`,h),e.removeListener(`end`,m),e.removeListener(`close`,m),e.removeListener(`finish`,h),e.removeListener(`exit`,_),e.removeListener(`end`,g),e.removeListener(`error`,v),e.removeListener(`close`,y)}};t.exports=s})),Zh=o(((e,t)=>{t.exports=n;function n(e){var t=e._readableState;return t?t.objectMode||typeof e._duplexState==`number`?e.read():e.read(r(t)):null}function r(e){if(e.buffer.length){var t=e.bufferIndex||0;if(e.buffer.head)return e.buffer.head.data.length;if(e.buffer.length-t>0&&e.buffer[t])return e.buffer[t].length}return e.length}})),Qh=o(((e,t)=>{var n=qh(),r=Xh(),i=Ph(),a=Zh(),o=Buffer.from&&Buffer.from!==Uint8Array.from?Buffer.from([0]):new Buffer([0]),s=function(e,t){e._corked?e.once(`uncork`,t):t()},c=function(e,t){e._autoDestroy&&e.destroy(t)},l=function(e,t){return function(n){n?c(e,n.message===`premature close`?null:n):t&&!e._ended&&e.end()}},u=function(e,t){if(!e||e._writableState&&e._writableState.finished)return t();if(e._writableState)return e.end(t);e.end(),t()},d=function(){},f=function(e){return new n.Readable({objectMode:!0,highWaterMark:16}).wrap(e)},p=function(e,t,r){if(!(this instanceof p))return new p(e,t,r);n.Duplex.call(this,r),this._writable=null,this._readable=null,this._readable2=null,this._autoDestroy=!r||r.autoDestroy!==!1,this._forwardDestroy=!r||r.destroy!==!1,this._forwardEnd=!r||r.end!==!1,this._corked=1,this._ondrain=null,this._drained=!1,this._forwarding=!1,this._unwrite=null,this._unread=null,this._ended=!1,this.destroyed=!1,e&&this.setWritable(e),t&&this.setReadable(t)};i(p,n.Duplex),p.obj=function(e,t,n){return n||={},n.objectMode=!0,n.highWaterMark=16,new p(e,t,n)},p.prototype.cork=function(){++this._corked===1&&this.emit(`cork`)},p.prototype.uncork=function(){this._corked&&--this._corked===0&&this.emit(`uncork`)},p.prototype.setWritable=function(e){if(this._unwrite&&this._unwrite(),this.destroyed){e&&e.destroy&&e.destroy();return}if(e===null||e===!1){this.end();return}var t=this,n=r(e,{writable:!0,readable:!1},l(this,this._forwardEnd)),i=function(){var e=t._ondrain;t._ondrain=null,e&&e()};this._unwrite&&process.nextTick(i),this._writable=e,this._writable.on(`drain`,i),this._unwrite=function(){t._writable.removeListener(`drain`,i),n()},this.uncork()},p.prototype.setReadable=function(e){if(this._unread&&this._unread(),this.destroyed){e&&e.destroy&&e.destroy();return}if(e===null||e===!1){this.push(null),this.resume();return}var t=this,n=r(e,{writable:!1,readable:!0},l(this)),i=function(){t._forward()},a=function(){t.push(null)};this._drained=!0,this._readable=e,this._readable2=e._readableState?e:f(e),this._readable2.on(`readable`,i),this._readable2.on(`end`,a),this._unread=function(){t._readable2.removeListener(`readable`,i),t._readable2.removeListener(`end`,a),n()},this._forward()},p.prototype._read=function(){this._drained=!0,this._forward()},p.prototype._forward=function(){if(!(this._forwarding||!this._readable2||!this._drained)){this._forwarding=!0;for(var e;this._drained&&(e=a(this._readable2))!==null;)this.destroyed||(this._drained=this.push(e));this._forwarding=!1}},p.prototype.destroy=function(e,t){if(t||=d,this.destroyed)return t(null);this.destroyed=!0;var n=this;process.nextTick(function(){n._destroy(e),t(null)})},p.prototype._destroy=function(e){if(e){var t=this._ondrain;this._ondrain=null,t?t(e):this.emit(`error`,e)}this._forwardDestroy&&(this._readable&&this._readable.destroy&&this._readable.destroy(),this._writable&&this._writable.destroy&&this._writable.destroy()),this.emit(`close`)},p.prototype._write=function(e,t,n){if(!this.destroyed){if(this._corked)return s(this,this._write.bind(this,e,t,n));if(e===o)return this._finish(n);if(!this._writable)return n();this._writable.write(e)===!1?this._ondrain=n:this.destroyed||n()}},p.prototype._finish=function(e){var t=this;this.emit(`preend`),s(this,function(){u(t._forwardEnd&&t._writable,function(){t._writableState.prefinished===!1&&(t._writableState.prefinished=!0),t.emit(`prefinish`),s(t,e)})})},p.prototype.end=function(e,t,r){return typeof e==`function`?this.end(null,null,e):typeof t==`function`?this.end(e,null,t):(this._ended=!0,e&&this.write(e),!this._writableState.ending&&!this._writableState.destroyed&&this.write(o),n.Writable.prototype.end.call(this,r))},t.exports=p})),$h=c(o(((e,t)=>{let{ServerResponse:n}=require(`node:http`),{PassThrough:r}=require(`node:stream`),{randomBytes:i}=require(`node:crypto`),a=ah(),o=Dh(),s=Qh(),c=Symbol(`ws-socket`),l=Symbol(`ws-head`),u=/HTTP\/1.1 (\d+)/u;function d(e,t,a){e.decorateRequest(`ws`,null);let d=x;if(t.errorHandler){if(typeof t.errorHandler!=`function`)return a(Error(`invalid errorHandler function`));d=t.errorHandler}let f=y;if(t?.preClose){if(typeof t.preClose!=`function`)return a(Error(`invalid preClose function`));f=t.preClose}if(t.options?.noServer)return a(Error(`fastify-websocket doesn't support the ws noServer option. If you want to create a websocket server detatched from fastify, use the ws library directly.`));let p=Object.assign({noServer:!0},t.options);p.path&&e.log.warn(`ws server path option shouldn't be provided, use a route instead`);let m=p.server||e.server;delete p.server;let h=new o.Server(p);e.decorate(`websocketServer`,h);async function g(e=`/`,t={},n={}){let a=new r,d=new r,f=new s(a,d),p=new s(d,a),h=new o(null,void 0,{isServer:!1}),g=Buffer.from([]),_,v,y=new Promise((e,t)=>{_=e,v=t});typeof n.onInit==`function`&&n.onInit(h),h.on(`open`,()=>{typeof n.onOpen==`function`&&n.onOpen(h),p.removeListener(`data`,b),_(h)});let b=e=>{if(e.toString().includes(`HTTP/1.1 101 Switching Protocols`))h._isServer=!1,h.setSocket(p,g,{maxPayload:0});else{p.removeListener(`data`,b);let t=Number(u.exec(e.toString())[1]);v(Error(`Unexpected server response: `+t))}};p.on(`data`,b);let x={...t,method:`GET`,headers:{...t.headers,connection:`upgrade`,upgrade:`websocket`,"sec-websocket-version":13,"sec-websocket-key":i(16).toString(`base64`)},httpVersion:`1.1`,url:e,[c]:f,[l]:g};return m.emit(`upgrade`,x,x[c],x[l]),y}e.decorate(`injectWS`,g);function _(t,r,i){t[c]=r,t[l]=i;let a=new n(t);try{a.assignSocket(r),e.routing(t,a)}catch(t){e.log.warn({err:t},`websocket upgrade failed`)}}m.on(`upgrade`,_);let v=(t,n)=>{h.handleUpgrade(t,t[c],t[l],r=>{h.emit(`connection`,r,t),r.on(`error`,t=>{e.log.error(t)}),n(r)})};e.addHook(`onRequest`,(e,t,n)=>{e.raw[c]?e.ws=!0:e.ws=!1,n()}),e.addHook(`onResponse`,(e,t,n)=>{e.ws&&e.raw[c].destroy(),n()}),e.addHook(`onRoute`,e=>{let t=!1,n=e.wsHandler,r=e.handler;if(e.websocket||e.wsHandler){if(e.method===`HEAD`)return;if(e.method!==`GET`)throw Error(`websocket handler can only be declared in GET method`);if(t=!0,e.websocket&&(e.schema||={},e.schema.hide=!0,n=e.handler,r=function(e,t){t.code(404).send()}),typeof n!=`function`)throw TypeError(`invalid wsHandler function`)}e.handler=function(e,i){if(e.raw[c])i.hijack(),v(e.raw,r=>{let a;try{a=t?n.call(this,r,e):b.call(this,r,e)}catch(t){return d.call(this,t,r,e,i)}a&&typeof a.catch==`function`&&a.catch(t=>d.call(this,t,r,e,i))});else return r.call(this,e,i)}}),e.addHook(`preClose`,f);function y(t){let n=this.websocketServer;if(n.clients)for(let e of n.clients)e.close();e.server.removeListener(`upgrade`,_),n.close(t),t()}function b(e,t){this.log.info({path:t.url},`closed incoming websocket connection for path with no websocket handler`),e.close()}function x(e,t,n){n.log.error(e),t.terminate()}a()}t.exports=a(d,{fastify:`5.x`,name:`@fastify/websocket`}),t.exports.default=d,t.exports.fastifyWebsocket=d}))(),1),eg=c(ph(),1),tg=c(nh(),1);let ng,rg;function ig(e){!ng||ng.length<e?(ng=Buffer.allocUnsafe(e*128),l.webcrypto.getRandomValues(ng),rg=0):rg+e>ng.length&&(l.webcrypto.getRandomValues(ng),rg=0),rg+=e}function ag(e=21){ig(e|=0);let t=``;for(let n=rg-e;n<rg;n++)t+=`useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict`[ng[n]&63];return t}var og=o(((e,t)=>{var n=Rh().Buffer,r=require(`stream`),i=require(`util`);function a(e){if(this.buffer=null,this.writable=!0,this.readable=!0,!e)return this.buffer=n.alloc(0),this;if(typeof e.pipe==`function`)return this.buffer=n.alloc(0),e.pipe(this),this;if(e.length||typeof e==`object`)return this.buffer=e,this.writable=!1,process.nextTick(function(){this.emit(`end`,e),this.readable=!1,this.emit(`close`)}.bind(this)),this;throw TypeError(`Unexpected data type (`+typeof e+`)`)}i.inherits(a,r),a.prototype.write=function(e){this.buffer=n.concat([this.buffer,n.from(e)]),this.emit(`data`,e)},a.prototype.end=function(e){e&&this.write(e),this.emit(`end`,e),this.emit(`close`),this.writable=!1,this.readable=!1},t.exports=a})),sg=o(((e,t)=>{function n(e){return(e/8|0)+(e%8==0?0:1)}var r={ES256:n(256),ES384:n(384),ES512:n(521)};function i(e){var t=r[e];if(t)return t;throw Error(`Unknown algorithm "`+e+`"`)}t.exports=i})),cg=o(((e,t)=>{var n=Rh().Buffer,r=sg(),i=128,a=0,o=32,s=16,c=2,l=s|o|a<<6,u=c|a<<6;function d(e){return e.replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function f(e){if(n.isBuffer(e))return e;if(typeof e==`string`)return n.from(e,`base64`);throw TypeError(`ECDSA signature must be a Base64 string or a Buffer`)}function p(e,t){e=f(e);var a=r(t),o=a+1,s=e.length,c=0;if(e[c++]!==l)throw Error(`Could not find expected "seq"`);var p=e[c++];if(p===(i|1)&&(p=e[c++]),s-c<p)throw Error(`"seq" specified length of "`+p+`", only "`+(s-c)+`" remaining`);if(e[c++]!==u)throw Error(`Could not find expected "int" for "r"`);var m=e[c++];if(s-c-2<m)throw Error(`"r" specified length of "`+m+`", only "`+(s-c-2)+`" available`);if(o<m)throw Error(`"r" specified length of "`+m+`", max of "`+o+`" is acceptable`);var h=c;if(c+=m,e[c++]!==u)throw Error(`Could not find expected "int" for "s"`);var g=e[c++];if(s-c!==g)throw Error(`"s" specified length of "`+g+`", expected "`+(s-c)+`"`);if(o<g)throw Error(`"s" specified length of "`+g+`", max of "`+o+`" is acceptable`);var _=c;if(c+=g,c!==s)throw Error(`Expected to consume entire buffer, but "`+(s-c)+`" bytes remain`);var v=a-m,y=a-g,b=n.allocUnsafe(v+m+y+g);for(c=0;c<v;++c)b[c]=0;e.copy(b,c,h+Math.max(-v,0),h+m),c=a;for(var x=c;c<x+y;++c)b[c]=0;return e.copy(b,c,_+Math.max(-y,0),_+g),b=b.toString(`base64`),b=d(b),b}function m(e,t,n){for(var r=0;t+r<n&&e[t+r]===0;)++r;return e[t+r]>=i&&--r,r}function h(e,t){e=f(e);var a=r(t),o=e.length;if(o!==a*2)throw TypeError(`"`+t+`" signatures must be "`+a*2+`" bytes, saw "`+o+`"`);var s=m(e,0,a),c=m(e,a,e.length),d=a-s,p=a-c,h=2+d+1+1+p,g=h<i,_=n.allocUnsafe((g?2:3)+h),v=0;return _[v++]=l,g?_[v++]=h:(_[v++]=i|1,_[v++]=h&255),_[v++]=u,_[v++]=d,s<0?(_[v++]=0,v+=e.copy(_,v,0,a)):v+=e.copy(_,v,s,a),_[v++]=u,_[v++]=p,c<0?(_[v++]=0,e.copy(_,v,a)):e.copy(_,v,a+c),_}t.exports={derToJose:p,joseToDer:h}})),lg=o(((e,t)=>{var n=require(`buffer`).Buffer,r=require(`buffer`).SlowBuffer;t.exports=i;function i(e,t){if(!n.isBuffer(e)||!n.isBuffer(t)||e.length!==t.length)return!1;for(var r=0,i=0;i<e.length;i++)r|=e[i]^t[i];return r===0}i.install=function(){n.prototype.equal=r.prototype.equal=function(e){return i(this,e)}};var a=n.prototype.equal,o=r.prototype.equal;i.restore=function(){n.prototype.equal=a,r.prototype.equal=o}})),ug=o(((e,t)=>{var n=Rh().Buffer,r=require(`crypto`),i=cg(),a=require(`util`),o=`"%s" is not a valid algorithm.
|
|
459
|
+
var n=require(`buffer`),r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?t.exports=n:(i(n,e),e.Buffer=a);function a(e,t,n){return r(e,t,n)}a.prototype=Object.create(r.prototype),i(r,a),a.from=function(e,t,n){if(typeof e==`number`)throw TypeError(`Argument must not be a number`);return r(e,t,n)},a.alloc=function(e,t,n){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);var i=r(e);return t===void 0?i.fill(0):typeof n==`string`?i.fill(t,n):i.fill(t),i},a.allocUnsafe=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return r(e)},a.allocUnsafeSlow=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return n.SlowBuffer(e)}})),Bh=o((e=>{var t=zh().Buffer,n=t.isEncoding||function(e){switch(e=``+e,e&&e.toLowerCase()){case`hex`:case`utf8`:case`utf-8`:case`ascii`:case`binary`:case`base64`:case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:case`raw`:return!0;default:return!1}};function r(e){if(!e)return`utf8`;for(var t;;)switch(e){case`utf8`:case`utf-8`:return`utf8`;case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return`utf16le`;case`latin1`:case`binary`:return`latin1`;case`base64`:case`ascii`:case`hex`:return e;default:if(t)return;e=(``+e).toLowerCase(),t=!0}}function i(e){var i=r(e);if(typeof i!=`string`&&(t.isEncoding===n||!n(e)))throw Error(`Unknown encoding: `+e);return i||e}e.StringDecoder=a;function a(e){this.encoding=i(e);var n;switch(this.encoding){case`utf16le`:this.text=f,this.end=p,n=4;break;case`utf8`:this.fillLast=l,n=4;break;case`base64`:this.text=m,this.end=h,n=3;break;default:this.write=g,this.end=_;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=t.allocUnsafe(n)}a.prototype.write=function(e){if(e.length===0)return``;var t,n;if(this.lastNeed){if(t=this.fillLast(e),t===void 0)return``;n=this.lastNeed,this.lastNeed=0}else n=0;return n<e.length?t?t+this.text(e,n):this.text(e,n):t||``},a.prototype.end=d,a.prototype.text=u,a.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length};function o(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function s(e,t,n){var r=t.length-1;if(r<n)return 0;var i=o(t[r]);return i>=0?(i>0&&(e.lastNeed=i-1),i):--r<n||i===-2?0:(i=o(t[r]),i>=0?(i>0&&(e.lastNeed=i-2),i):--r<n||i===-2?0:(i=o(t[r]),i>=0?(i>0&&(i===2?i=0:e.lastNeed=i-3),i):0))}function c(e,t,n){if((t[0]&192)!=128)return e.lastNeed=0,`�`;if(e.lastNeed>1&&t.length>1){if((t[1]&192)!=128)return e.lastNeed=1,`�`;if(e.lastNeed>2&&t.length>2&&(t[2]&192)!=128)return e.lastNeed=2,`�`}}function l(e){var t=this.lastTotal-this.lastNeed,n=c(this,e,t);if(n!==void 0)return n;if(this.lastNeed<=e.length)return e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,t,0,e.length),this.lastNeed-=e.length}function u(e,t){var n=s(this,e,t);if(!this.lastNeed)return e.toString(`utf8`,t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString(`utf8`,t,r)}function d(e){var t=e&&e.length?this.write(e):``;return this.lastNeed?t+`�`:t}function f(e,t){if((e.length-t)%2==0){var n=e.toString(`utf16le`,t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString(`utf16le`,t,e.length-1)}function p(e){var t=e&&e.length?this.write(e):``;if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString(`utf16le`,0,n)}return t}function m(e,t){var n=(e.length-t)%3;return n===0?e.toString(`base64`,t):(this.lastNeed=3-n,this.lastTotal=3,n===1?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString(`base64`,t,e.length-n))}function h(e){var t=e&&e.length?this.write(e):``;return this.lastNeed?t+this.lastChar.toString(`base64`,0,3-this.lastNeed):t}function g(e){return e.toString(this.encoding)}function _(e){return e&&e.length?this.write(e):``}})),Vh=o(((e,t)=>{var n=Mh().codes.ERR_STREAM_PREMATURE_CLOSE;function r(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,r=Array(n),i=0;i<n;i++)r[i]=arguments[i];e.apply(this,r)}}}function i(){}function a(e){return e.setHeader&&typeof e.abort==`function`}function o(e,t,s){if(typeof t==`function`)return o(e,null,t);t||={},s=r(s||i);var c=t.readable||t.readable!==!1&&e.readable,l=t.writable||t.writable!==!1&&e.writable,u=function(){e.writable||f()},d=e._writableState&&e._writableState.finished,f=function(){l=!1,d=!0,c||s.call(e)},p=e._readableState&&e._readableState.endEmitted,m=function(){c=!1,p=!0,l||s.call(e)},h=function(t){s.call(e,t)},g=function(){var t;if(c&&!p)return(!e._readableState||!e._readableState.ended)&&(t=new n),s.call(e,t);if(l&&!d)return(!e._writableState||!e._writableState.ended)&&(t=new n),s.call(e,t)},_=function(){e.req.on(`finish`,f)};return a(e)?(e.on(`complete`,f),e.on(`abort`,g),e.req?_():e.on(`request`,_)):l&&!e._writableState&&(e.on(`end`,u),e.on(`close`,u)),e.on(`end`,m),e.on(`finish`,f),t.error!==!1&&e.on(`error`,h),e.on(`close`,g),function(){e.removeListener(`complete`,f),e.removeListener(`abort`,g),e.removeListener(`request`,_),e.req&&e.req.removeListener(`finish`,f),e.removeListener(`end`,u),e.removeListener(`close`,u),e.removeListener(`finish`,f),e.removeListener(`end`,m),e.removeListener(`error`,h),e.removeListener(`close`,g)}}t.exports=o})),Hh=o(((e,t)=>{var n;function r(e,t,n){return t=i(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e){var t=a(e,`string`);return typeof t==`symbol`?t:String(t)}function a(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var o=Vh(),s=Symbol(`lastResolve`),c=Symbol(`lastReject`),l=Symbol(`error`),u=Symbol(`ended`),d=Symbol(`lastPromise`),f=Symbol(`handlePromise`),p=Symbol(`stream`);function m(e,t){return{value:e,done:t}}function h(e){var t=e[s];if(t!==null){var n=e[p].read();n!==null&&(e[d]=null,e[s]=null,e[c]=null,t(m(n,!1)))}}function g(e){process.nextTick(h,e)}function _(e,t){return function(n,r){e.then(function(){if(t[u]){n(m(void 0,!0));return}t[f](n,r)},r)}}var v=Object.getPrototypeOf(function(){}),y=Object.setPrototypeOf((n={get stream(){return this[p]},next:function(){var e=this,t=this[l];if(t!==null)return Promise.reject(t);if(this[u])return Promise.resolve(m(void 0,!0));if(this[p].destroyed)return new Promise(function(t,n){process.nextTick(function(){e[l]?n(e[l]):t(m(void 0,!0))})});var n=this[d],r;if(n)r=new Promise(_(n,this));else{var i=this[p].read();if(i!==null)return Promise.resolve(m(i,!1));r=new Promise(this[f])}return this[d]=r,r}},r(n,Symbol.asyncIterator,function(){return this}),r(n,`return`,function(){var e=this;return new Promise(function(t,n){e[p].destroy(null,function(e){if(e){n(e);return}t(m(void 0,!0))})})}),n),v);t.exports=function(e){var t,n=Object.create(y,(t={},r(t,p,{value:e,writable:!0}),r(t,s,{value:null,writable:!0}),r(t,c,{value:null,writable:!0}),r(t,l,{value:null,writable:!0}),r(t,u,{value:e._readableState.endEmitted,writable:!0}),r(t,f,{value:function(e,t){var r=n[p].read();r?(n[d]=null,n[s]=null,n[c]=null,e(m(r,!1))):(n[s]=e,n[c]=t)},writable:!0}),t));return n[d]=null,o(e,function(e){if(e&&e.code!==`ERR_STREAM_PREMATURE_CLOSE`){var t=n[c];t!==null&&(n[d]=null,n[s]=null,n[c]=null,t(e)),n[l]=e;return}var r=n[s];r!==null&&(n[d]=null,n[s]=null,n[c]=null,r(m(void 0,!0))),n[u]=!0}),e.on(`readable`,g.bind(null,n)),n}})),Uh=o(((e,t)=>{function n(e,t,n,r,i,a,o){try{var s=e[a](o),c=s.value}catch(e){n(e);return}s.done?t(c):Promise.resolve(c).then(r,i)}function r(e){return function(){var t=this,r=arguments;return new Promise(function(i,a){var o=e.apply(t,r);function s(e){n(o,i,a,s,c,`next`,e)}function c(e){n(o,i,a,s,c,`throw`,e)}s(void 0)})}}function i(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function a(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?i(Object(n),!0).forEach(function(t){o(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):i(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function o(e,t,n){return t=s(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(e){var t=c(e,`string`);return typeof t==`symbol`?t:String(t)}function c(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var l=Mh().codes.ERR_INVALID_ARG_TYPE;function u(e,t,n){var i;if(t&&typeof t.next==`function`)i=t;else if(t&&t[Symbol.asyncIterator])i=t[Symbol.asyncIterator]();else if(t&&t[Symbol.iterator])i=t[Symbol.iterator]();else throw new l(`iterable`,[`Iterable`],t);var o=new e(a({objectMode:!0},n)),s=!1;o._read=function(){s||(s=!0,c())};function c(){return u.apply(this,arguments)}function u(){return u=r(function*(){try{var e=yield i.next(),t=e.value;e.done?o.push(null):o.push(yield t)?c():s=!1}catch(e){o.destroy(e)}}),u.apply(this,arguments)}return o}t.exports=u})),Wh=o(((e,t)=>{t.exports=E;var n;E.ReadableState=T,require(`events`).EventEmitter;var r=function(e,t){return e.listeners(t).length},i=kh(),a=require(`buffer`).Buffer,o=(typeof global<`u`?global:typeof window<`u`?window:typeof self<`u`?self:{}).Uint8Array||function(){};function s(e){return a.from(e)}function c(e){return a.isBuffer(e)||e instanceof o}var l=require(`util`),u=l&&l.debuglog?l.debuglog(`stream`):function(){},d=Ah(),f=jh(),p=Nh().getHighWaterMark,m=Mh().codes,h=m.ERR_INVALID_ARG_TYPE,g=m.ERR_STREAM_PUSH_AFTER_EOF,_=m.ERR_METHOD_NOT_IMPLEMENTED,v=m.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,y,b,x;Fh()(E,i);var S=f.errorOrDestroy,C=[`error`,`close`,`destroy`,`pause`,`resume`];function w(e,t,n){if(typeof e.prependListener==`function`)return e.prependListener(t,n);!e._events||!e._events[t]?e.on(t,n):Array.isArray(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]}function T(e,t,r){n||=Rh(),e||={},typeof r!=`boolean`&&(r=t instanceof n),this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.readableObjectMode),this.highWaterMark=p(this,e,`readableHighWaterMark`,r),this.buffer=new d,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=e.emitClose!==!1,this.autoDestroy=!!e.autoDestroy,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||`utf8`,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(y||=Bh().StringDecoder,this.decoder=new y(e.encoding),this.encoding=e.encoding)}function E(e){if(n||=Rh(),!(this instanceof E))return new E(e);var t=this instanceof n;this._readableState=new T(e,this,t),this.readable=!0,e&&(typeof e.read==`function`&&(this._read=e.read),typeof e.destroy==`function`&&(this._destroy=e.destroy)),i.call(this)}Object.defineProperty(E.prototype,`destroyed`,{enumerable:!1,get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),E.prototype.destroy=f.destroy,E.prototype._undestroy=f.undestroy,E.prototype._destroy=function(e,t){t(e)},E.prototype.push=function(e,t){var n=this._readableState,r;return n.objectMode?r=!0:typeof e==`string`&&(t||=n.defaultEncoding,t!==n.encoding&&(e=a.from(e,t),t=``),r=!0),D(this,e,t,!1,r)},E.prototype.unshift=function(e){return D(this,e,null,!0,!1)};function D(e,t,n,r,i){u(`readableAddChunk`,t);var o=e._readableState;if(t===null)o.reading=!1,ee(e,o);else{var c;if(i||(c=k(o,t)),c)S(e,c);else if(o.objectMode||t&&t.length>0)if(typeof t!=`string`&&!o.objectMode&&Object.getPrototypeOf(t)!==a.prototype&&(t=s(t)),r)o.endEmitted?S(e,new v):O(e,o,t,!0);else if(o.ended)S(e,new g);else if(o.destroyed)return!1;else o.reading=!1,o.decoder&&!n?(t=o.decoder.write(t),o.objectMode||t.length!==0?O(e,o,t,!1):P(e,o)):O(e,o,t,!1);else r||(o.reading=!1,P(e,o))}return!o.ended&&(o.length<o.highWaterMark||o.length===0)}function O(e,t,n,r){t.flowing&&t.length===0&&!t.sync?(t.awaitDrain=0,e.emit(`data`,n)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&N(e)),P(e,t)}function k(e,t){var n;return!c(t)&&typeof t!=`string`&&t!==void 0&&!e.objectMode&&(n=new h(`chunk`,[`string`,`Buffer`,`Uint8Array`],t)),n}E.prototype.isPaused=function(){return this._readableState.flowing===!1},E.prototype.setEncoding=function(e){y||=Bh().StringDecoder;var t=new y(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;for(var n=this._readableState.buffer.head,r=``;n!==null;)r+=t.write(n.data),n=n.next;return this._readableState.buffer.clear(),r!==``&&this._readableState.buffer.push(r),this._readableState.length=r.length,this};var A=1073741824;function j(e){return e>=A?e=A:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function M(e,t){return e<=0||t.length===0&&t.ended?0:t.objectMode?1:e===e?(e>t.highWaterMark&&(t.highWaterMark=j(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0)):t.flowing&&t.length?t.buffer.head.data.length:t.length}E.prototype.read=function(e){u(`read`,e),e=parseInt(e,10);var t=this._readableState,n=e;if(e!==0&&(t.emittedReadable=!1),e===0&&t.needReadable&&((t.highWaterMark===0?t.length>0:t.length>=t.highWaterMark)||t.ended))return u(`read: emitReadable`,t.length,t.ended),t.length===0&&t.ended?oe(this):N(this),null;if(e=M(e,t),e===0&&t.ended)return t.length===0&&oe(this),null;var r=t.needReadable;u(`need readable`,r),(t.length===0||t.length-e<t.highWaterMark)&&(r=!0,u(`length less than watermark`,r)),t.ended||t.reading?(r=!1,u(`reading or ended`,r)):r&&(u(`do read`),t.reading=!0,t.sync=!0,t.length===0&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=M(n,t)));var i=e>0?R(e,t):null;return i===null?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),t.length===0&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&oe(this)),i!==null&&this.emit(`data`,i),i};function ee(e,t){if(u(`onEofChunk`),!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?N(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,te(e)))}}function N(e){var t=e._readableState;u(`emitReadable`,t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(u(`emitReadable`,t.flowing),t.emittedReadable=!0,process.nextTick(te,e))}function te(e){var t=e._readableState;u(`emitReadable_`,t.destroyed,t.length,t.ended),!t.destroyed&&(t.length||t.ended)&&(e.emit(`readable`),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,ae(e)}function P(e,t){t.readingMore||(t.readingMore=!0,process.nextTick(ne,e,t))}function ne(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&t.length===0);){var n=t.length;if(u(`maybeReadMore read 0`),e.read(0),n===t.length)break}t.readingMore=!1}E.prototype._read=function(e){S(this,new _(`_read()`))},E.prototype.pipe=function(e,t){var n=this,i=this._readableState;switch(i.pipesCount){case 0:i.pipes=e;break;case 1:i.pipes=[i.pipes,e];break;default:i.pipes.push(e);break}i.pipesCount+=1,u(`pipe count=%d opts=%j`,i.pipesCount,t);var a=(!t||t.end!==!1)&&e!==process.stdout&&e!==process.stderr?s:g;i.endEmitted?process.nextTick(a):n.once(`end`,a),e.on(`unpipe`,o);function o(e,t){u(`onunpipe`),e===n&&t&&t.hasUnpiped===!1&&(t.hasUnpiped=!0,d())}function s(){u(`onend`),e.end()}var c=F(n);e.on(`drain`,c);var l=!1;function d(){u(`cleanup`),e.removeListener(`close`,m),e.removeListener(`finish`,h),e.removeListener(`drain`,c),e.removeListener(`error`,p),e.removeListener(`unpipe`,o),n.removeListener(`end`,s),n.removeListener(`end`,g),n.removeListener(`data`,f),l=!0,i.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&c()}n.on(`data`,f);function f(t){u(`ondata`);var r=e.write(t);u(`dest.write`,r),r===!1&&((i.pipesCount===1&&i.pipes===e||i.pipesCount>1&&ce(i.pipes,e)!==-1)&&!l&&(u(`false write response, pause`,i.awaitDrain),i.awaitDrain++),n.pause())}function p(t){u(`onerror`,t),g(),e.removeListener(`error`,p),r(e,`error`)===0&&S(e,t)}w(e,`error`,p);function m(){e.removeListener(`finish`,h),g()}e.once(`close`,m);function h(){u(`onfinish`),e.removeListener(`close`,m),g()}e.once(`finish`,h);function g(){u(`unpipe`),n.unpipe(e)}return e.emit(`pipe`,n),i.flowing||(u(`pipe resume`),n.resume()),e};function F(e){return function(){var t=e._readableState;u(`pipeOnDrain`,t.awaitDrain),t.awaitDrain&&t.awaitDrain--,t.awaitDrain===0&&r(e,`data`)&&(t.flowing=!0,ae(e))}}E.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(t.pipesCount===0)return this;if(t.pipesCount===1)return e&&e!==t.pipes?this:(e||=t.pipes,t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit(`unpipe`,this,n),this);if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var a=0;a<i;a++)r[a].emit(`unpipe`,this,{hasUnpiped:!1});return this}var o=ce(t.pipes,e);return o===-1?this:(t.pipes.splice(o,1),--t.pipesCount,t.pipesCount===1&&(t.pipes=t.pipes[0]),e.emit(`unpipe`,this,n),this)},E.prototype.on=function(e,t){var n=i.prototype.on.call(this,e,t),r=this._readableState;return e===`data`?(r.readableListening=this.listenerCount(`readable`)>0,r.flowing!==!1&&this.resume()):e===`readable`&&!r.endEmitted&&!r.readableListening&&(r.readableListening=r.needReadable=!0,r.flowing=!1,r.emittedReadable=!1,u(`on readable`,r.length,r.reading),r.length?N(this):r.reading||process.nextTick(re,this)),n},E.prototype.addListener=E.prototype.on,E.prototype.removeListener=function(e,t){var n=i.prototype.removeListener.call(this,e,t);return e===`readable`&&process.nextTick(I,this),n},E.prototype.removeAllListeners=function(e){var t=i.prototype.removeAllListeners.apply(this,arguments);return(e===`readable`||e===void 0)&&process.nextTick(I,this),t};function I(e){var t=e._readableState;t.readableListening=e.listenerCount(`readable`)>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount(`data`)>0&&e.resume()}function re(e){u(`readable nexttick read 0`),e.read(0)}E.prototype.resume=function(){var e=this._readableState;return e.flowing||(u(`resume`),e.flowing=!e.readableListening,L(this,e)),e.paused=!1,this};function L(e,t){t.resumeScheduled||(t.resumeScheduled=!0,process.nextTick(ie,e,t))}function ie(e,t){u(`resume`,t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit(`resume`),ae(e),t.flowing&&!t.reading&&e.read(0)}E.prototype.pause=function(){return u(`call pause flowing=%j`,this._readableState.flowing),this._readableState.flowing!==!1&&(u(`pause`),this._readableState.flowing=!1,this.emit(`pause`)),this._readableState.paused=!0,this};function ae(e){var t=e._readableState;for(u(`flow`,t.flowing);t.flowing&&e.read()!==null;);}E.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var i in e.on(`end`,function(){if(u(`wrapped end`),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)}),e.on(`data`,function(i){u(`wrapped data`),n.decoder&&(i=n.decoder.write(i)),!(n.objectMode&&i==null)&&(!n.objectMode&&(!i||!i.length)||t.push(i)||(r=!0,e.pause()))}),e)this[i]===void 0&&typeof e[i]==`function`&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));for(var a=0;a<C.length;a++)e.on(C[a],this.emit.bind(this,C[a]));return this._read=function(t){u(`wrapped _read`,t),r&&(r=!1,e.resume())},this},typeof Symbol==`function`&&(E.prototype[Symbol.asyncIterator]=function(){return b===void 0&&(b=Hh()),b(this)}),Object.defineProperty(E.prototype,`readableHighWaterMark`,{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(E.prototype,`readableBuffer`,{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(E.prototype,`readableFlowing`,{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),E._fromList=R,Object.defineProperty(E.prototype,`readableLength`,{enumerable:!1,get:function(){return this._readableState.length}});function R(e,t){if(t.length===0)return null;var n;return t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(``):t.buffer.length===1?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n}function oe(e){var t=e._readableState;u(`endReadable`,t.endEmitted),t.endEmitted||(t.ended=!0,process.nextTick(se,t,e))}function se(e,t){if(u(`endReadableNT`,e.endEmitted,e.length),!e.endEmitted&&e.length===0&&(e.endEmitted=!0,t.readable=!1,t.emit(`end`),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}typeof Symbol==`function`&&(E.from=function(e,t){return x===void 0&&(x=Uh()),x(E,e,t)});function ce(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}})),Gh=o(((e,t)=>{t.exports=l;var n=Mh().codes,r=n.ERR_METHOD_NOT_IMPLEMENTED,i=n.ERR_MULTIPLE_CALLBACK,a=n.ERR_TRANSFORM_ALREADY_TRANSFORMING,o=n.ERR_TRANSFORM_WITH_LENGTH_0,s=Rh();Fh()(l,s);function c(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(r===null)return this.emit(`error`,new i);n.writechunk=null,n.writecb=null,t!=null&&this.push(t),r(e);var a=this._readableState;a.reading=!1,(a.needReadable||a.length<a.highWaterMark)&&this._read(a.highWaterMark)}function l(e){if(!(this instanceof l))return new l(e);s.call(this,e),this._transformState={afterTransform:c.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&(typeof e.transform==`function`&&(this._transform=e.transform),typeof e.flush==`function`&&(this._flush=e.flush)),this.on(`prefinish`,u)}function u(){var e=this;typeof this._flush==`function`&&!this._readableState.destroyed?this._flush(function(t,n){d(e,t,n)}):d(this,null,null)}l.prototype.push=function(e,t){return this._transformState.needTransform=!1,s.prototype.push.call(this,e,t)},l.prototype._transform=function(e,t,n){n(new r(`_transform()`))},l.prototype._write=function(e,t,n){var r=this._transformState;if(r.writecb=n,r.writechunk=e,r.writeencoding=t,!r.transforming){var i=this._readableState;(r.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}},l.prototype._read=function(e){var t=this._transformState;t.writechunk!==null&&!t.transforming?(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=!0},l.prototype._destroy=function(e,t){s.prototype._destroy.call(this,e,function(e){t(e)})};function d(e,t,n){if(t)return e.emit(`error`,t);if(n!=null&&e.push(n),e._writableState.length)throw new o;if(e._transformState.transforming)throw new a;return e.push(null)}})),Kh=o(((e,t)=>{t.exports=r;var n=Gh();Fh()(r,n);function r(e){if(!(this instanceof r))return new r(e);n.call(this,e)}r.prototype._transform=function(e,t,n){n(null,e)}})),qh=o(((e,t)=>{var n;function r(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var i=Mh().codes,a=i.ERR_MISSING_ARGS,o=i.ERR_STREAM_DESTROYED;function s(e){if(e)throw e}function c(e){return e.setHeader&&typeof e.abort==`function`}function l(e,t,i,a){a=r(a);var s=!1;e.on(`close`,function(){s=!0}),n===void 0&&(n=Vh()),n(e,{readable:t,writable:i},function(e){if(e)return a(e);s=!0,a()});var l=!1;return function(t){if(!s&&!l){if(l=!0,c(e))return e.abort();if(typeof e.destroy==`function`)return e.destroy();a(t||new o(`pipe`))}}}function u(e){e()}function d(e,t){return e.pipe(t)}function f(e){return!e.length||typeof e[e.length-1]!=`function`?s:e.pop()}function p(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var r=f(t);if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new a(`streams`);var i,o=t.map(function(e,n){var a=n<t.length-1;return l(e,a,n>0,function(e){i||=e,e&&o.forEach(u),!a&&(o.forEach(u),r(i))})});return t.reduce(d)}t.exports=p})),Jh=o(((e,t)=>{var n=require(`stream`);process.env.READABLE_STREAM===`disable`&&n?(t.exports=n.Readable,Object.assign(t.exports,n),t.exports.Stream=n):(e=t.exports=Wh(),e.Stream=n||e,e.Readable=e,e.Writable=Lh(),e.Duplex=Rh(),e.Transform=Gh(),e.PassThrough=Kh(),e.finished=Vh(),e.pipeline=qh())})),Yh=o(((e,t)=>{t.exports=n;function n(e,t){if(e&&t)return n(e)(t);if(typeof e!=`function`)throw TypeError(`need wrapper function`);return Object.keys(e).forEach(function(t){r[t]=e[t]}),r;function r(){for(var t=Array(arguments.length),n=0;n<t.length;n++)t[n]=arguments[n];var r=e.apply(this,t),i=t[t.length-1];return typeof r==`function`&&r!==i&&Object.keys(i).forEach(function(e){r[e]=i[e]}),r}}})),Xh=o(((e,t)=>{var n=Yh();t.exports=n(r),t.exports.strict=n(i),r.proto=r(function(){Object.defineProperty(Function.prototype,`once`,{value:function(){return r(this)},configurable:!0}),Object.defineProperty(Function.prototype,`onceStrict`,{value:function(){return i(this)},configurable:!0})});function r(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function i(e){var t=function(){if(t.called)throw Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)};return t.onceError=(e.name||"Function wrapped with `once`")+` shouldn't be called more than once`,t.called=!1,t}})),Zh=o(((e,t)=>{var n=Xh(),r=function(){},i=global.Bare?queueMicrotask:process.nextTick.bind(process),a=function(e){return e.setHeader&&typeof e.abort==`function`},o=function(e){return e.stdio&&Array.isArray(e.stdio)&&e.stdio.length===3},s=function(e,t,c){if(typeof t==`function`)return s(e,null,t);t||={},c=n(c||r);var l=e._writableState,u=e._readableState,d=t.readable||t.readable!==!1&&e.readable,f=t.writable||t.writable!==!1&&e.writable,p=!1,m=function(){e.writable||h()},h=function(){f=!1,d||c.call(e)},g=function(){d=!1,f||c.call(e)},_=function(t){c.call(e,t?Error(`exited with error code: `+t):null)},v=function(t){c.call(e,t)},y=function(){i(b)},b=function(){if(!p&&(d&&!(u&&u.ended&&!u.destroyed)||f&&!(l&&l.ended&&!l.destroyed)))return c.call(e,Error(`premature close`))},x=function(){e.req.on(`finish`,h)};return a(e)?(e.on(`complete`,h),e.on(`abort`,y),e.req?x():e.on(`request`,x)):f&&!l&&(e.on(`end`,m),e.on(`close`,m)),o(e)&&e.on(`exit`,_),e.on(`end`,g),e.on(`finish`,h),t.error!==!1&&e.on(`error`,v),e.on(`close`,y),function(){p=!0,e.removeListener(`complete`,h),e.removeListener(`abort`,y),e.removeListener(`request`,x),e.req&&e.req.removeListener(`finish`,h),e.removeListener(`end`,m),e.removeListener(`close`,m),e.removeListener(`finish`,h),e.removeListener(`exit`,_),e.removeListener(`end`,g),e.removeListener(`error`,v),e.removeListener(`close`,y)}};t.exports=s})),Qh=o(((e,t)=>{t.exports=n;function n(e){var t=e._readableState;return t?t.objectMode||typeof e._duplexState==`number`?e.read():e.read(r(t)):null}function r(e){if(e.buffer.length){var t=e.bufferIndex||0;if(e.buffer.head)return e.buffer.head.data.length;if(e.buffer.length-t>0&&e.buffer[t])return e.buffer[t].length}return e.length}})),$h=o(((e,t)=>{var n=Jh(),r=Zh(),i=Fh(),a=Qh(),o=Buffer.from&&Buffer.from!==Uint8Array.from?Buffer.from([0]):new Buffer([0]),s=function(e,t){e._corked?e.once(`uncork`,t):t()},c=function(e,t){e._autoDestroy&&e.destroy(t)},l=function(e,t){return function(n){n?c(e,n.message===`premature close`?null:n):t&&!e._ended&&e.end()}},u=function(e,t){if(!e||e._writableState&&e._writableState.finished)return t();if(e._writableState)return e.end(t);e.end(),t()},d=function(){},f=function(e){return new n.Readable({objectMode:!0,highWaterMark:16}).wrap(e)},p=function(e,t,r){if(!(this instanceof p))return new p(e,t,r);n.Duplex.call(this,r),this._writable=null,this._readable=null,this._readable2=null,this._autoDestroy=!r||r.autoDestroy!==!1,this._forwardDestroy=!r||r.destroy!==!1,this._forwardEnd=!r||r.end!==!1,this._corked=1,this._ondrain=null,this._drained=!1,this._forwarding=!1,this._unwrite=null,this._unread=null,this._ended=!1,this.destroyed=!1,e&&this.setWritable(e),t&&this.setReadable(t)};i(p,n.Duplex),p.obj=function(e,t,n){return n||={},n.objectMode=!0,n.highWaterMark=16,new p(e,t,n)},p.prototype.cork=function(){++this._corked===1&&this.emit(`cork`)},p.prototype.uncork=function(){this._corked&&--this._corked===0&&this.emit(`uncork`)},p.prototype.setWritable=function(e){if(this._unwrite&&this._unwrite(),this.destroyed){e&&e.destroy&&e.destroy();return}if(e===null||e===!1){this.end();return}var t=this,n=r(e,{writable:!0,readable:!1},l(this,this._forwardEnd)),i=function(){var e=t._ondrain;t._ondrain=null,e&&e()};this._unwrite&&process.nextTick(i),this._writable=e,this._writable.on(`drain`,i),this._unwrite=function(){t._writable.removeListener(`drain`,i),n()},this.uncork()},p.prototype.setReadable=function(e){if(this._unread&&this._unread(),this.destroyed){e&&e.destroy&&e.destroy();return}if(e===null||e===!1){this.push(null),this.resume();return}var t=this,n=r(e,{writable:!1,readable:!0},l(this)),i=function(){t._forward()},a=function(){t.push(null)};this._drained=!0,this._readable=e,this._readable2=e._readableState?e:f(e),this._readable2.on(`readable`,i),this._readable2.on(`end`,a),this._unread=function(){t._readable2.removeListener(`readable`,i),t._readable2.removeListener(`end`,a),n()},this._forward()},p.prototype._read=function(){this._drained=!0,this._forward()},p.prototype._forward=function(){if(!(this._forwarding||!this._readable2||!this._drained)){this._forwarding=!0;for(var e;this._drained&&(e=a(this._readable2))!==null;)this.destroyed||(this._drained=this.push(e));this._forwarding=!1}},p.prototype.destroy=function(e,t){if(t||=d,this.destroyed)return t(null);this.destroyed=!0;var n=this;process.nextTick(function(){n._destroy(e),t(null)})},p.prototype._destroy=function(e){if(e){var t=this._ondrain;this._ondrain=null,t?t(e):this.emit(`error`,e)}this._forwardDestroy&&(this._readable&&this._readable.destroy&&this._readable.destroy(),this._writable&&this._writable.destroy&&this._writable.destroy()),this.emit(`close`)},p.prototype._write=function(e,t,n){if(!this.destroyed){if(this._corked)return s(this,this._write.bind(this,e,t,n));if(e===o)return this._finish(n);if(!this._writable)return n();this._writable.write(e)===!1?this._ondrain=n:this.destroyed||n()}},p.prototype._finish=function(e){var t=this;this.emit(`preend`),s(this,function(){u(t._forwardEnd&&t._writable,function(){t._writableState.prefinished===!1&&(t._writableState.prefinished=!0),t.emit(`prefinish`),s(t,e)})})},p.prototype.end=function(e,t,r){return typeof e==`function`?this.end(null,null,e):typeof t==`function`?this.end(e,null,t):(this._ended=!0,e&&this.write(e),!this._writableState.ending&&!this._writableState.destroyed&&this.write(o),n.Writable.prototype.end.call(this,r))},t.exports=p})),eg=c(o(((e,t)=>{let{ServerResponse:n}=require(`node:http`),{PassThrough:r}=require(`node:stream`),{randomBytes:i}=require(`node:crypto`),a=oh(),o=Oh(),s=$h(),c=Symbol(`ws-socket`),l=Symbol(`ws-head`),u=/HTTP\/1.1 (\d+)/u;function d(e,t,a){e.decorateRequest(`ws`,null);let d=x;if(t.errorHandler){if(typeof t.errorHandler!=`function`)return a(Error(`invalid errorHandler function`));d=t.errorHandler}let f=y;if(t?.preClose){if(typeof t.preClose!=`function`)return a(Error(`invalid preClose function`));f=t.preClose}if(t.options?.noServer)return a(Error(`fastify-websocket doesn't support the ws noServer option. If you want to create a websocket server detatched from fastify, use the ws library directly.`));let p=Object.assign({noServer:!0},t.options);p.path&&e.log.warn(`ws server path option shouldn't be provided, use a route instead`);let m=p.server||e.server;delete p.server;let h=new o.Server(p);e.decorate(`websocketServer`,h);async function g(e=`/`,t={},n={}){let a=new r,d=new r,f=new s(a,d),p=new s(d,a),h=new o(null,void 0,{isServer:!1}),g=Buffer.from([]),_,v,y=new Promise((e,t)=>{_=e,v=t});typeof n.onInit==`function`&&n.onInit(h),h.on(`open`,()=>{typeof n.onOpen==`function`&&n.onOpen(h),p.removeListener(`data`,b),_(h)});let b=e=>{if(e.toString().includes(`HTTP/1.1 101 Switching Protocols`))h._isServer=!1,h.setSocket(p,g,{maxPayload:0});else{p.removeListener(`data`,b);let t=Number(u.exec(e.toString())[1]);v(Error(`Unexpected server response: `+t))}};p.on(`data`,b);let x={...t,method:`GET`,headers:{...t.headers,connection:`upgrade`,upgrade:`websocket`,"sec-websocket-version":13,"sec-websocket-key":i(16).toString(`base64`)},httpVersion:`1.1`,url:e,[c]:f,[l]:g};return m.emit(`upgrade`,x,x[c],x[l]),y}e.decorate(`injectWS`,g);function _(t,r,i){t[c]=r,t[l]=i;let a=new n(t);try{a.assignSocket(r),e.routing(t,a)}catch(t){e.log.warn({err:t},`websocket upgrade failed`)}}m.on(`upgrade`,_);let v=(t,n)=>{h.handleUpgrade(t,t[c],t[l],r=>{h.emit(`connection`,r,t),r.on(`error`,t=>{e.log.error(t)}),n(r)})};e.addHook(`onRequest`,(e,t,n)=>{e.raw[c]?e.ws=!0:e.ws=!1,n()}),e.addHook(`onResponse`,(e,t,n)=>{e.ws&&e.raw[c].destroy(),n()}),e.addHook(`onRoute`,e=>{let t=!1,n=e.wsHandler,r=e.handler;if(e.websocket||e.wsHandler){if(e.method===`HEAD`)return;if(e.method!==`GET`)throw Error(`websocket handler can only be declared in GET method`);if(t=!0,e.websocket&&(e.schema||={},e.schema.hide=!0,n=e.handler,r=function(e,t){t.code(404).send()}),typeof n!=`function`)throw TypeError(`invalid wsHandler function`)}e.handler=function(e,i){if(e.raw[c])i.hijack(),v(e.raw,r=>{let a;try{a=t?n.call(this,r,e):b.call(this,r,e)}catch(t){return d.call(this,t,r,e,i)}a&&typeof a.catch==`function`&&a.catch(t=>d.call(this,t,r,e,i))});else return r.call(this,e,i)}}),e.addHook(`preClose`,f);function y(t){let n=this.websocketServer;if(n.clients)for(let e of n.clients)e.close();e.server.removeListener(`upgrade`,_),n.close(t),t()}function b(e,t){this.log.info({path:t.url},`closed incoming websocket connection for path with no websocket handler`),e.close()}function x(e,t,n){n.log.error(e),t.terminate()}a()}t.exports=a(d,{fastify:`5.x`,name:`@fastify/websocket`}),t.exports.default=d,t.exports.fastifyWebsocket=d}))(),1),tg=c(mh(),1),ng=c(rh(),1);let rg,ig;function ag(e){!rg||rg.length<e?(rg=Buffer.allocUnsafe(e*128),l.webcrypto.getRandomValues(rg),ig=0):ig+e>rg.length&&(l.webcrypto.getRandomValues(rg),ig=0),ig+=e}function og(e=21){ag(e|=0);let t=``;for(let n=ig-e;n<ig;n++)t+=`useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict`[rg[n]&63];return t}var sg=o(((e,t)=>{var n=zh().Buffer,r=require(`stream`),i=require(`util`);function a(e){if(this.buffer=null,this.writable=!0,this.readable=!0,!e)return this.buffer=n.alloc(0),this;if(typeof e.pipe==`function`)return this.buffer=n.alloc(0),e.pipe(this),this;if(e.length||typeof e==`object`)return this.buffer=e,this.writable=!1,process.nextTick(function(){this.emit(`end`,e),this.readable=!1,this.emit(`close`)}.bind(this)),this;throw TypeError(`Unexpected data type (`+typeof e+`)`)}i.inherits(a,r),a.prototype.write=function(e){this.buffer=n.concat([this.buffer,n.from(e)]),this.emit(`data`,e)},a.prototype.end=function(e){e&&this.write(e),this.emit(`end`,e),this.emit(`close`),this.writable=!1,this.readable=!1},t.exports=a})),cg=o(((e,t)=>{function n(e){return(e/8|0)+(e%8==0?0:1)}var r={ES256:n(256),ES384:n(384),ES512:n(521)};function i(e){var t=r[e];if(t)return t;throw Error(`Unknown algorithm "`+e+`"`)}t.exports=i})),lg=o(((e,t)=>{var n=zh().Buffer,r=cg(),i=128,a=0,o=32,s=16,c=2,l=s|o|a<<6,u=c|a<<6;function d(e){return e.replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function f(e){if(n.isBuffer(e))return e;if(typeof e==`string`)return n.from(e,`base64`);throw TypeError(`ECDSA signature must be a Base64 string or a Buffer`)}function p(e,t){e=f(e);var a=r(t),o=a+1,s=e.length,c=0;if(e[c++]!==l)throw Error(`Could not find expected "seq"`);var p=e[c++];if(p===(i|1)&&(p=e[c++]),s-c<p)throw Error(`"seq" specified length of "`+p+`", only "`+(s-c)+`" remaining`);if(e[c++]!==u)throw Error(`Could not find expected "int" for "r"`);var m=e[c++];if(s-c-2<m)throw Error(`"r" specified length of "`+m+`", only "`+(s-c-2)+`" available`);if(o<m)throw Error(`"r" specified length of "`+m+`", max of "`+o+`" is acceptable`);var h=c;if(c+=m,e[c++]!==u)throw Error(`Could not find expected "int" for "s"`);var g=e[c++];if(s-c!==g)throw Error(`"s" specified length of "`+g+`", expected "`+(s-c)+`"`);if(o<g)throw Error(`"s" specified length of "`+g+`", max of "`+o+`" is acceptable`);var _=c;if(c+=g,c!==s)throw Error(`Expected to consume entire buffer, but "`+(s-c)+`" bytes remain`);var v=a-m,y=a-g,b=n.allocUnsafe(v+m+y+g);for(c=0;c<v;++c)b[c]=0;e.copy(b,c,h+Math.max(-v,0),h+m),c=a;for(var x=c;c<x+y;++c)b[c]=0;return e.copy(b,c,_+Math.max(-y,0),_+g),b=b.toString(`base64`),b=d(b),b}function m(e,t,n){for(var r=0;t+r<n&&e[t+r]===0;)++r;return e[t+r]>=i&&--r,r}function h(e,t){e=f(e);var a=r(t),o=e.length;if(o!==a*2)throw TypeError(`"`+t+`" signatures must be "`+a*2+`" bytes, saw "`+o+`"`);var s=m(e,0,a),c=m(e,a,e.length),d=a-s,p=a-c,h=2+d+1+1+p,g=h<i,_=n.allocUnsafe((g?2:3)+h),v=0;return _[v++]=l,g?_[v++]=h:(_[v++]=i|1,_[v++]=h&255),_[v++]=u,_[v++]=d,s<0?(_[v++]=0,v+=e.copy(_,v,0,a)):v+=e.copy(_,v,s,a),_[v++]=u,_[v++]=p,c<0?(_[v++]=0,e.copy(_,v,a)):e.copy(_,v,a+c),_}t.exports={derToJose:p,joseToDer:h}})),ug=o(((e,t)=>{var n=require(`buffer`).Buffer,r=require(`buffer`).SlowBuffer;t.exports=i;function i(e,t){if(!n.isBuffer(e)||!n.isBuffer(t)||e.length!==t.length)return!1;for(var r=0,i=0;i<e.length;i++)r|=e[i]^t[i];return r===0}i.install=function(){n.prototype.equal=r.prototype.equal=function(e){return i(this,e)}};var a=n.prototype.equal,o=r.prototype.equal;i.restore=function(){n.prototype.equal=a,r.prototype.equal=o}})),dg=o(((e,t)=>{var n=zh().Buffer,r=require(`crypto`),i=lg(),a=require(`util`),o=`"%s" is not a valid algorithm.
|
|
460
460
|
Supported algorithms are:
|
|
461
|
-
"HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,s=`secret must be a string or buffer`,c=`key must be a string or a buffer`,l=`key must be a string, a buffer or an object`,u=typeof r.createPublicKey==`function`;u&&(c+=` or a KeyObject`,s+=`or a KeyObject`);function d(e){if(!n.isBuffer(e)&&typeof e!=`string`&&(!u||typeof e!=`object`||typeof e.type!=`string`||typeof e.asymmetricKeyType!=`string`||typeof e.export!=`function`))throw g(c)}function f(e){if(!n.isBuffer(e)&&typeof e!=`string`&&typeof e!=`object`)throw g(l)}function p(e){if(!n.isBuffer(e)){if(typeof e==`string`)return e;if(!u||typeof e!=`object`||e.type!==`secret`||typeof e.export!=`function`)throw g(s)}}function m(e){return e.replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function h(e){e=e.toString();var t=4-e.length%4;if(t!==4)for(var n=0;n<t;++n)e+=`=`;return e.replace(/\-/g,`+`).replace(/_/g,`/`)}function g(e){var t=[].slice.call(arguments,1),n=a.format.bind(a,e).apply(null,t);return TypeError(n)}function _(e){return n.isBuffer(e)||typeof e==`string`}function v(e){return _(e)||(e=JSON.stringify(e)),e}function y(e){return function(t,n){p(n),t=v(t);var i=r.createHmac(`sha`+e,n);return m((i.update(t),i.digest(`base64`)))}}var b,x=`timingSafeEqual`in r?function(e,t){return e.byteLength===t.byteLength?r.timingSafeEqual(e,t):!1}:function(e,t){return b||=lg(),b(e,t)};function S(e){return function(t,r,i){var a=y(e)(t,i);return x(n.from(r),n.from(a))}}function C(e){return function(t,n){f(n),t=v(t);var i=r.createSign(`RSA-SHA`+e);return m((i.update(t),i.sign(n,`base64`)))}}function w(e){return function(t,n,i){d(i),t=v(t),n=h(n);var a=r.createVerify(`RSA-SHA`+e);return a.update(t),a.verify(i,n,`base64`)}}function T(e){return function(t,n){f(n),t=v(t);var i=r.createSign(`RSA-SHA`+e);return m((i.update(t),i.sign({key:n,padding:r.constants.RSA_PKCS1_PSS_PADDING,saltLength:r.constants.RSA_PSS_SALTLEN_DIGEST},`base64`)))}}function E(e){return function(t,n,i){d(i),t=v(t),n=h(n);var a=r.createVerify(`RSA-SHA`+e);return a.update(t),a.verify({key:i,padding:r.constants.RSA_PKCS1_PSS_PADDING,saltLength:r.constants.RSA_PSS_SALTLEN_DIGEST},n,`base64`)}}function D(e){var t=C(e);return function(){var n=t.apply(null,arguments);return n=i.derToJose(n,`ES`+e),n}}function O(e){var t=w(e);return function(n,r,a){return r=i.joseToDer(r,`ES`+e).toString(`base64`),t(n,r,a)}}function k(){return function(){return``}}function A(){return function(e,t){return t===``}}t.exports=function(e){var t={hs:y,rs:C,ps:T,es:D,none:k},n={hs:S,rs:w,ps:E,es:O,none:A},r=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!r)throw g(o,e);var i=(r[1]||r[3]).toLowerCase(),a=r[2];return{sign:t[i](a),verify:n[i](a)}}})),dg=o(((e,t)=>{var n=require(`buffer`).Buffer;t.exports=function(e){return typeof e==`string`?e:typeof e==`number`||n.isBuffer(e)?e.toString():JSON.stringify(e)}})),fg=o(((e,t)=>{var n=Rh().Buffer,r=og(),i=ug(),a=require(`stream`),o=dg(),s=require(`util`);function c(e,t){return n.from(e,t).toString(`base64`).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function l(e,t,n){n||=`utf8`;var r=c(o(e),`binary`),i=c(o(t),n);return s.format(`%s.%s`,r,i)}function u(e){var t=e.header,n=e.payload,r=e.secret||e.privateKey,a=e.encoding,o=i(t.alg),c=l(t,n,a),u=o.sign(c,r);return s.format(`%s.%s`,c,u)}function d(e){var t=e.secret;if(t??=e.privateKey,t??=e.key,/^hs/i.test(e.header.alg)===!0&&t==null)throw TypeError(`secret must be a string or buffer or a KeyObject`);var n=new r(t);this.readable=!0,this.header=e.header,this.encoding=e.encoding,this.secret=this.privateKey=this.key=n,this.payload=new r(e.payload),this.secret.once(`close`,function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once(`close`,function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}s.inherits(d,a),d.prototype.sign=function(){try{var e=u({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit(`done`,e),this.emit(`data`,e),this.emit(`end`),this.readable=!1,e}catch(e){this.readable=!1,this.emit(`error`,e),this.emit(`close`)}},d.sign=u,t.exports=d})),pg=o(((e,t)=>{var n=Rh().Buffer,r=og(),i=ug(),a=require(`stream`),o=dg(),s=require(`util`),c=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function l(e){return Object.prototype.toString.call(e)===`[object Object]`}function u(e){if(l(e))return e;try{return JSON.parse(e)}catch{return}}function d(e){var t=e.split(`.`,1)[0];return u(n.from(t,`base64`).toString(`binary`))}function f(e){return e.split(`.`,2).join(`.`)}function p(e){return e.split(`.`)[2]}function m(e,t){t||=`utf8`;var r=e.split(`.`)[1];return n.from(r,`base64`).toString(t)}function h(e){return c.test(e)&&!!d(e)}function g(e,t,n){if(!t){var r=Error(`Missing algorithm parameter for jws.verify`);throw r.code=`MISSING_ALGORITHM`,r}e=o(e);var a=p(e),s=f(e);return i(t).verify(s,a,n)}function _(e,t){if(t||={},e=o(e),!h(e))return null;var n=d(e);if(!n)return null;var r=m(e);return(n.typ===`JWT`||t.json)&&(r=JSON.parse(r,t.encoding)),{header:n,payload:r,signature:p(e)}}function v(e){e||={};var t=e.secret;if(t??=e.publicKey,t??=e.key,/^hs/i.test(e.algorithm)===!0&&t==null)throw TypeError(`secret must be a string or buffer or a KeyObject`);var n=new r(t);this.readable=!0,this.algorithm=e.algorithm,this.encoding=e.encoding,this.secret=this.publicKey=this.key=n,this.signature=new r(e.signature),this.secret.once(`close`,function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once(`close`,function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}s.inherits(v,a),v.prototype.verify=function(){try{var e=g(this.signature.buffer,this.algorithm,this.key.buffer),t=_(this.signature.buffer,this.encoding);return this.emit(`done`,e,t),this.emit(`data`,e),this.emit(`end`),this.readable=!1,e}catch(e){this.readable=!1,this.emit(`error`,e),this.emit(`close`)}},v.decode=_,v.isValid=h,v.verify=g,t.exports=v})),mg=o((e=>{var t=fg(),n=pg();e.ALGORITHMS=[`HS256`,`HS384`,`HS512`,`RS256`,`RS384`,`RS512`,`PS256`,`PS384`,`PS512`,`ES256`,`ES384`,`ES512`],e.sign=t.sign,e.verify=n.verify,e.decode=n.decode,e.isValid=n.isValid,e.createSign=function(e){return new t(e)},e.createVerify=function(e){return new n(e)}})),hg=o(((e,t)=>{var n=mg();t.exports=function(e,t){t||={};var r=n.decode(e,t);if(!r)return null;var i=r.payload;if(typeof i==`string`)try{var a=JSON.parse(i);typeof a==`object`&&a&&(i=a)}catch{}return t.complete===!0?{header:r.header,payload:i,signature:r.signature}:i}})),gg=o(((e,t)=>{var n=function(e,t){Error.call(this,e),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name=`JsonWebTokenError`,this.message=e,t&&(this.inner=t)};n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,t.exports=n})),_g=o(((e,t)=>{var n=gg(),r=function(e,t){n.call(this,e),this.name=`NotBeforeError`,this.date=t};r.prototype=Object.create(n.prototype),r.prototype.constructor=r,t.exports=r})),vg=o(((e,t)=>{var n=gg(),r=function(e,t){n.call(this,e),this.name=`TokenExpiredError`,this.expiredAt=t};r.prototype=Object.create(n.prototype),r.prototype.constructor=r,t.exports=r})),yg=o(((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})),bg=o(((e,t)=>{var n=yg();t.exports=function(e,t){var r=t||Math.floor(Date.now()/1e3);if(typeof e==`string`){var i=n(e);return i===void 0?void 0:Math.floor(r+i/1e3)}else if(typeof e==`number`)return r+e;else return}})),xg=o(((e,t)=>{t.exports=um().satisfies(process.version,`>=15.7.0`)})),Sg=o(((e,t)=>{t.exports=um().satisfies(process.version,`>=16.9.0`)})),Cg=o(((e,t)=>{let n=xg(),r=Sg(),i={ec:[`ES256`,`ES384`,`ES512`],rsa:[`RS256`,`PS256`,`RS384`,`PS384`,`RS512`,`PS512`],"rsa-pss":[`PS256`,`PS384`,`PS512`]},a={ES256:`prime256v1`,ES384:`secp384r1`,ES512:`secp521r1`};t.exports=function(e,t){if(!e||!t)return;let o=t.asymmetricKeyType;if(!o)return;let s=i[o];if(!s)throw Error(`Unknown key type "${o}".`);if(!s.includes(e))throw Error(`"alg" parameter for "${o}" key type must be one of: ${s.join(`, `)}.`);if(n)switch(o){case`ec`:let n=t.asymmetricKeyDetails.namedCurve,i=a[e];if(n!==i)throw Error(`"alg" parameter "${e}" requires curve "${i}".`);break;case`rsa-pss`:if(r){let n=parseInt(e.slice(-3),10),{hashAlgorithm:r,mgf1HashAlgorithm:i,saltLength:a}=t.asymmetricKeyDetails;if(r!==`sha${n}`||i!==r)throw Error(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}.`);if(a!==void 0&&a>n>>3)throw Error(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}.`)}break}}})),wg=o(((e,t)=>{t.exports=um().satisfies(process.version,`^6.12.0 || >=8.0.0`)})),Tg=o(((e,t)=>{let n=gg(),r=_g(),i=vg(),a=hg(),o=bg(),s=Cg(),c=wg(),l=mg(),{KeyObject:u,createSecretKey:d,createPublicKey:f}=require(`crypto`),p=[`RS256`,`RS384`,`RS512`],m=[`ES256`,`ES384`,`ES512`],h=[`RS256`,`RS384`,`RS512`],g=[`HS256`,`HS384`,`HS512`];c&&(p.splice(p.length,0,`PS256`,`PS384`,`PS512`),h.splice(h.length,0,`PS256`,`PS384`,`PS512`)),t.exports=function(e,t,c,_){typeof c==`function`&&!_&&(_=c,c={}),c||={},c=Object.assign({},c);let v;if(v=_||function(e,t){if(e)throw e;return t},c.clockTimestamp&&typeof c.clockTimestamp!=`number`)return v(new n(`clockTimestamp must be a number`));if(c.nonce!==void 0&&(typeof c.nonce!=`string`||c.nonce.trim()===``))return v(new n(`nonce must be a non-empty string`));if(c.allowInvalidAsymmetricKeyTypes!==void 0&&typeof c.allowInvalidAsymmetricKeyTypes!=`boolean`)return v(new n(`allowInvalidAsymmetricKeyTypes must be a boolean`));let y=c.clockTimestamp||Math.floor(Date.now()/1e3);if(!e)return v(new n(`jwt must be provided`));if(typeof e!=`string`)return v(new n(`jwt must be a string`));let b=e.split(`.`);if(b.length!==3)return v(new n(`jwt malformed`));let x;try{x=a(e,{complete:!0})}catch(e){return v(e)}if(!x)return v(new n(`invalid token`));let S=x.header,C;if(typeof t==`function`){if(!_)return v(new n(`verify must be called asynchronous if secret or public key is provided as a callback`));C=t}else C=function(e,n){return n(null,t)};return C(S,function(t,a){if(t)return v(new n(`error in secret or public key callback: `+t.message));let _=b[2].trim()!==``;if(!_&&a)return v(new n(`jwt signature is required`));if(_&&!a)return v(new n(`secret or public key must be provided`));if(!_&&!c.algorithms)return v(new n(`please specify "none" in "algorithms" to verify unsigned tokens`));if(a!=null&&!(a instanceof u))try{a=f(a)}catch{try{a=d(typeof a==`string`?Buffer.from(a):a)}catch{return v(new n(`secretOrPublicKey is not valid key material`))}}if(c.algorithms||(a.type===`secret`?c.algorithms=g:[`rsa`,`rsa-pss`].includes(a.asymmetricKeyType)?c.algorithms=h:a.asymmetricKeyType===`ec`?c.algorithms=m:c.algorithms=p),c.algorithms.indexOf(x.header.alg)===-1)return v(new n(`invalid algorithm`));if(S.alg.startsWith(`HS`)&&a.type!==`secret`)return v(new n(`secretOrPublicKey must be a symmetric key when using ${S.alg}`));if(/^(?:RS|PS|ES)/.test(S.alg)&&a.type!==`public`)return v(new n(`secretOrPublicKey must be an asymmetric key when using ${S.alg}`));if(!c.allowInvalidAsymmetricKeyTypes)try{s(S.alg,a)}catch(e){return v(e)}let C;try{C=l.verify(e,x.header.alg,a)}catch(e){return v(e)}if(!C)return v(new n(`invalid signature`));let w=x.payload;if(w.nbf!==void 0&&!c.ignoreNotBefore){if(typeof w.nbf!=`number`)return v(new n(`invalid nbf value`));if(w.nbf>y+(c.clockTolerance||0))return v(new r(`jwt not active`,new Date(w.nbf*1e3)))}if(w.exp!==void 0&&!c.ignoreExpiration){if(typeof w.exp!=`number`)return v(new n(`invalid exp value`));if(y>=w.exp+(c.clockTolerance||0))return v(new i(`jwt expired`,new Date(w.exp*1e3)))}if(c.audience){let e=Array.isArray(c.audience)?c.audience:[c.audience];if(!(Array.isArray(w.aud)?w.aud:[w.aud]).some(function(t){return e.some(function(e){return e instanceof RegExp?e.test(t):e===t})}))return v(new n(`jwt audience invalid. expected: `+e.join(` or `)))}if(c.issuer&&(typeof c.issuer==`string`&&w.iss!==c.issuer||Array.isArray(c.issuer)&&c.issuer.indexOf(w.iss)===-1))return v(new n(`jwt issuer invalid. expected: `+c.issuer));if(c.subject&&w.sub!==c.subject)return v(new n(`jwt subject invalid. expected: `+c.subject));if(c.jwtid&&w.jti!==c.jwtid)return v(new n(`jwt jwtid invalid. expected: `+c.jwtid));if(c.nonce&&w.nonce!==c.nonce)return v(new n(`jwt nonce invalid. expected: `+c.nonce));if(c.maxAge){if(typeof w.iat!=`number`)return v(new n(`iat required when maxAge is specified`));let e=o(c.maxAge,w.iat);if(e===void 0)return v(new n(`"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60`));if(y>=e+(c.clockTolerance||0))return v(new i(`maxAge exceeded`,new Date(e*1e3)))}if(c.complete===!0){let e=x.signature;return v(null,{header:S,payload:w,signature:e})}return v(null,w)})}})),Eg=o(((e,t)=>{var n=1/0,r=9007199254740991,i=17976931348623157e292,a=NaN,o=`[object Arguments]`,s=`[object Function]`,c=`[object GeneratorFunction]`,l=`[object String]`,u=`[object Symbol]`,d=/^\s+|\s+$/g,f=/^[-+]0x[0-9a-f]+$/i,p=/^0b[01]+$/i,m=/^0o[0-7]+$/i,h=/^(?:0|[1-9]\d*)$/,g=parseInt;function _(e,t){for(var n=-1,r=e?e.length:0,i=Array(r);++n<r;)i[n]=t(e[n],n,e);return i}function v(e,t,n,r){for(var i=e.length,a=n+(r?1:-1);r?a--:++a<i;)if(t(e[a],a,e))return a;return-1}function y(e,t,n){if(t!==t)return v(e,b,n);for(var r=n-1,i=e.length;++r<i;)if(e[r]===t)return r;return-1}function b(e){return e!==e}function x(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}function S(e,t){return _(t,function(t){return e[t]})}function C(e,t){return function(n){return e(t(n))}}var w=Object.prototype,T=w.hasOwnProperty,E=w.toString,D=w.propertyIsEnumerable,O=C(Object.keys,Object),k=Math.max;function A(e,t){var n=P(e)||te(e)?x(e.length,String):[],r=n.length,i=!!r;for(var a in e)(t||T.call(e,a))&&!(i&&(a==`length`||M(a,r)))&&n.push(a);return n}function j(e){if(!ee(e))return O(e);var t=[];for(var n in Object(e))T.call(e,n)&&n!=`constructor`&&t.push(n);return t}function M(e,t){return t??=r,!!t&&(typeof e==`number`||h.test(e))&&e>-1&&e%1==0&&e<t}function ee(e){var t=e&&e.constructor;return e===(typeof t==`function`&&t.prototype||w)}function N(e,t,n,r){e=ne(e)?e:ue(e),n=n&&!r?se(n):0;var i=e.length;return n<0&&(n=k(i+n,0)),ae(e)?n<=i&&e.indexOf(t,n)>-1:!!i&&y(e,t,n)>-1}function te(e){return F(e)&&T.call(e,`callee`)&&(!D.call(e,`callee`)||E.call(e)==o)}var P=Array.isArray;function ne(e){return e!=null&&re(e.length)&&!I(e)}function F(e){return ie(e)&&ne(e)}function I(e){var t=L(e)?E.call(e):``;return t==s||t==c}function re(e){return typeof e==`number`&&e>-1&&e%1==0&&e<=r}function L(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function ie(e){return!!e&&typeof e==`object`}function ae(e){return typeof e==`string`||!P(e)&&ie(e)&&E.call(e)==l}function R(e){return typeof e==`symbol`||ie(e)&&E.call(e)==u}function oe(e){return e?(e=ce(e),e===n||e===-n?(e<0?-1:1)*i:e===e?e:0):e===0?e:0}function se(e){var t=oe(e),n=t%1;return t===t?n?t-n:t:0}function ce(e){if(typeof e==`number`)return e;if(R(e))return a;if(L(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=L(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=e.replace(d,``);var n=p.test(e);return n||m.test(e)?g(e.slice(2),n?2:8):f.test(e)?a:+e}function le(e){return ne(e)?A(e):j(e)}function ue(e){return e?S(e,le(e)):[]}t.exports=N})),Dg=o(((e,t)=>{var n=`[object Boolean]`,r=Object.prototype.toString;function i(e){return e===!0||e===!1||a(e)&&r.call(e)==n}function a(e){return!!e&&typeof e==`object`}t.exports=i})),Og=o(((e,t)=>{var n=1/0,r=17976931348623157e292,i=NaN,a=`[object Symbol]`,o=/^\s+|\s+$/g,s=/^[-+]0x[0-9a-f]+$/i,c=/^0b[01]+$/i,l=/^0o[0-7]+$/i,u=parseInt,d=Object.prototype.toString;function f(e){return typeof e==`number`&&e==_(e)}function p(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function m(e){return!!e&&typeof e==`object`}function h(e){return typeof e==`symbol`||m(e)&&d.call(e)==a}function g(e){return e?(e=v(e),e===n||e===-n?(e<0?-1:1)*r:e===e?e:0):e===0?e:0}function _(e){var t=g(e),n=t%1;return t===t?n?t-n:t:0}function v(e){if(typeof e==`number`)return e;if(h(e))return i;if(p(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=p(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=e.replace(o,``);var n=c.test(e);return n||l.test(e)?u(e.slice(2),n?2:8):s.test(e)?i:+e}t.exports=f})),kg=o(((e,t)=>{var n=`[object Number]`,r=Object.prototype.toString;function i(e){return!!e&&typeof e==`object`}function a(e){return typeof e==`number`||i(e)&&r.call(e)==n}t.exports=a})),Ag=o(((e,t)=>{var n=`[object Object]`;function r(e){var t=!1;if(e!=null&&typeof e.toString!=`function`)try{t=!!(e+``)}catch{}return t}function i(e,t){return function(n){return e(t(n))}}var a=Function.prototype,o=Object.prototype,s=a.toString,c=o.hasOwnProperty,l=s.call(Object),u=o.toString,d=i(Object.getPrototypeOf,Object);function f(e){return!!e&&typeof e==`object`}function p(e){if(!f(e)||u.call(e)!=n||r(e))return!1;var t=d(e);if(t===null)return!0;var i=c.call(t,`constructor`)&&t.constructor;return typeof i==`function`&&i instanceof i&&s.call(i)==l}t.exports=p})),jg=o(((e,t)=>{var n=`[object String]`,r=Object.prototype.toString,i=Array.isArray;function a(e){return!!e&&typeof e==`object`}function o(e){return typeof e==`string`||!i(e)&&a(e)&&r.call(e)==n}t.exports=o})),Mg=o(((e,t)=>{var n=`Expected a function`,r=1/0,i=17976931348623157e292,a=NaN,o=`[object Symbol]`,s=/^\s+|\s+$/g,c=/^[-+]0x[0-9a-f]+$/i,l=/^0b[01]+$/i,u=/^0o[0-7]+$/i,d=parseInt,f=Object.prototype.toString;function p(e,t){var r;if(typeof t!=`function`)throw TypeError(n);return e=y(e),function(){return--e>0&&(r=t.apply(this,arguments)),e<=1&&(t=void 0),r}}function m(e){return p(2,e)}function h(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function g(e){return!!e&&typeof e==`object`}function _(e){return typeof e==`symbol`||g(e)&&f.call(e)==o}function v(e){return e?(e=b(e),e===r||e===-r?(e<0?-1:1)*i:e===e?e:0):e===0?e:0}function y(e){var t=v(e),n=t%1;return t===t?n?t-n:t:0}function b(e){if(typeof e==`number`)return e;if(_(e))return a;if(h(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=h(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=e.replace(s,``);var n=l.test(e);return n||u.test(e)?d(e.slice(2),n?2:8):c.test(e)?a:+e}t.exports=m})),Ng=o(((e,t)=>{let n=bg(),r=wg(),i=Cg(),a=mg(),o=Eg(),s=Dg(),c=Og(),l=kg(),u=Ag(),d=jg(),f=Mg(),{KeyObject:p,createSecretKey:m,createPrivateKey:h}=require(`crypto`),g=[`RS256`,`RS384`,`RS512`,`ES256`,`ES384`,`ES512`,`HS256`,`HS384`,`HS512`,`none`];r&&g.splice(3,0,`PS256`,`PS384`,`PS512`);let _={expiresIn:{isValid:function(e){return c(e)||d(e)&&e},message:`"expiresIn" should be a number of seconds or string representing a timespan`},notBefore:{isValid:function(e){return c(e)||d(e)&&e},message:`"notBefore" should be a number of seconds or string representing a timespan`},audience:{isValid:function(e){return d(e)||Array.isArray(e)},message:`"audience" must be a string or array`},algorithm:{isValid:o.bind(null,g),message:`"algorithm" must be a valid string enum value`},header:{isValid:u,message:`"header" must be an object`},encoding:{isValid:d,message:`"encoding" must be a string`},issuer:{isValid:d,message:`"issuer" must be a string`},subject:{isValid:d,message:`"subject" must be a string`},jwtid:{isValid:d,message:`"jwtid" must be a string`},noTimestamp:{isValid:s,message:`"noTimestamp" must be a boolean`},keyid:{isValid:d,message:`"keyid" must be a string`},mutatePayload:{isValid:s,message:`"mutatePayload" must be a boolean`},allowInsecureKeySizes:{isValid:s,message:`"allowInsecureKeySizes" must be a boolean`},allowInvalidAsymmetricKeyTypes:{isValid:s,message:`"allowInvalidAsymmetricKeyTypes" must be a boolean`}},v={iat:{isValid:l,message:`"iat" should be a number of seconds`},exp:{isValid:l,message:`"exp" should be a number of seconds`},nbf:{isValid:l,message:`"nbf" should be a number of seconds`}};function y(e,t,n,r){if(!u(n))throw Error(`Expected "`+r+`" to be a plain object.`);Object.keys(n).forEach(function(i){let a=e[i];if(!a){if(!t)throw Error(`"`+i+`" is not allowed in "`+r+`"`);return}if(!a.isValid(n[i]))throw Error(a.message)})}function b(e){return y(_,!1,e,`options`)}function x(e){return y(v,!0,e,`payload`)}let S={audience:`aud`,issuer:`iss`,subject:`sub`,jwtid:`jti`},C=[`expiresIn`,`notBefore`,`noTimestamp`,`audience`,`issuer`,`subject`,`jwtid`];t.exports=function(e,t,r,o){typeof r==`function`?(o=r,r={}):r||={};let s=typeof e==`object`&&!Buffer.isBuffer(e),c=Object.assign({alg:r.algorithm||`HS256`,typ:s?`JWT`:void 0,kid:r.keyid},r.header);function l(e){if(o)return o(e);throw e}if(!t&&r.algorithm!==`none`)return l(Error(`secretOrPrivateKey must have a value`));if(t!=null&&!(t instanceof p))try{t=h(t)}catch{try{t=m(typeof t==`string`?Buffer.from(t):t)}catch{return l(Error(`secretOrPrivateKey is not valid key material`))}}if(c.alg.startsWith(`HS`)&&t.type!==`secret`)return l(Error(`secretOrPrivateKey must be a symmetric key when using ${c.alg}`));if(/^(?:RS|PS|ES)/.test(c.alg)){if(t.type!==`private`)return l(Error(`secretOrPrivateKey must be an asymmetric key when using ${c.alg}`));if(!r.allowInsecureKeySizes&&!c.alg.startsWith(`ES`)&&t.asymmetricKeyDetails!==void 0&&t.asymmetricKeyDetails.modulusLength<2048)return l(Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${c.alg}`))}if(e===void 0)return l(Error(`payload is required`));if(s){try{x(e)}catch(e){return l(e)}r.mutatePayload||(e=Object.assign({},e))}else{let t=C.filter(function(e){return r[e]!==void 0});if(t.length>0)return l(Error(`invalid `+t.join(`,`)+` option for `+typeof e+` payload`))}if(e.exp!==void 0&&r.expiresIn!==void 0)return l(Error(`Bad "options.expiresIn" option the payload already has an "exp" property.`));if(e.nbf!==void 0&&r.notBefore!==void 0)return l(Error(`Bad "options.notBefore" option the payload already has an "nbf" property.`));try{b(r)}catch(e){return l(e)}if(!r.allowInvalidAsymmetricKeyTypes)try{i(c.alg,t)}catch(e){return l(e)}let u=e.iat||Math.floor(Date.now()/1e3);if(r.noTimestamp?delete e.iat:s&&(e.iat=u),r.notBefore!==void 0){try{e.nbf=n(r.notBefore,u)}catch(e){return l(e)}if(e.nbf===void 0)return l(Error(`"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60`))}if(r.expiresIn!==void 0&&typeof e==`object`){try{e.exp=n(r.expiresIn,u)}catch(e){return l(e)}if(e.exp===void 0)return l(Error(`"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60`))}Object.keys(S).forEach(function(t){let n=S[t];if(r[t]!==void 0){if(e[n]!==void 0)return l(Error(`Bad "options.`+t+`" option. The payload already has an "`+n+`" property.`));e[n]=r[t]}});let d=r.encoding||`utf8`;if(typeof o==`function`)o&&=f(o),a.createSign({header:c,privateKey:t,payload:e,encoding:d}).once(`error`,o).once(`done`,function(e){if(!r.allowInsecureKeySizes&&/^(?:RS|PS)/.test(c.alg)&&e.length<256)return o(Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${c.alg}`));o(null,e)});else{let n=a.sign({header:c,payload:e,secret:t,encoding:d});if(!r.allowInsecureKeySizes&&/^(?:RS|PS)/.test(c.alg)&&n.length<256)throw Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${c.alg}`);return n}}})),Pg=c(o(((e,t)=>{t.exports={decode:hg(),verify:Tg(),sign:Ng(),JsonWebTokenError:gg(),NotBeforeError:_g(),TokenExpiredError:vg()}}))(),1),Fg=c($u(),1),Ig=class extends Error{code;status;details;constructor(e){super(e.message),this.name=`Error`,this.code=e.code,this.status=e.status,this.details=e.details}};function Lg(e){return e instanceof Ig}function Rg(){return new Ig({code:`PAIRING_CODE_INVALID`,status:400,message:`Invalid pairing code`})}function zg(){return new Ig({code:`PAIRING_CODE_EXPIRED`,status:400,message:`Pairing code expired`})}function Bg(){return new Ig({code:`REFRESH_TOKEN_REVOKED`,status:401,message:`Refresh token revoked`})}function Vg(e=`Device revoked`){return new Ig({code:`DEVICE_REVOKED`,status:401,message:e})}function Hg(){return new Ig({code:`REFRESH_TOKEN_DEVICE_MISMATCH`,status:401,message:`Refresh token device mismatch`})}function Ug(e){return new Ig({code:`PROJECT_NOT_FOUND`,status:404,message:`Project not found: ${e}`})}function Wg(e,t){return new Ig({code:`PROJECT_SESSION_NOT_FOUND`,status:404,message:`Session ${t} not found in project ${e}`})}function Gg(e){return new Ig({code:`SESSION_NOT_FOUND`,status:404,message:`Session not found: ${e}`})}function Kg(e){return new Ig({code:`PROJECT_DELETE_CONFLICT`,status:409,message:`Cannot delete project ${e} while sessions are running`})}function qg(e){return new Ig({code:`DISCOVERED_PROJECT_NOT_FOUND`,status:404,message:`Discovered project not found: ${e}`})}function Jg(){return new Ig({code:`DEVICE_IDENTITY_NOT_REGISTERED`,status:400,message:`Device identity not registered`})}function Yg(){return new Ig({code:`DEVICE_IDENTITY_MISMATCH`,status:400,message:`Device identity mismatch`})}function Xg(e){return new Ig({code:`DEVICE_IDENTITY_NOT_ACTIVE`,status:400,message:`Device identity not active: ${e}`})}function Zg(e){return e instanceof Error&&(e.name===`TokenExpiredError`||e.name===`JsonWebTokenError`||e.name===`NotBeforeError`)}var Qg=class{indexPath;pairingCodes=new Map;devices=new Map;refreshTokens=new Map;ready;mutationQueue=Promise.resolve();constructor(e){this.config=e,this.indexPath=p.default.join(e.authStoreDir,`auth-state.json`),this.ready=this.loadFromDisk()}async init(){await this.ready}async createPairingCode(e=300){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let t=$g(),n=Date.now()+e*1e3;return this.pairingCodes.set(t,{code:t,expiresAtMs:n}),await this.persistState(),{code:t,expiresAt:new Date(n).toISOString()}})}async claimPairingCode(e,t,n){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let r=this.pairingCodes.get(e);if(!r)throw Rg();if(r.expiresAtMs<Date.now())throw this.pairingCodes.delete(e),await this.persistState(),zg();this.pairingCodes.delete(e);let i=`dev_${ag(12)}`,a=new Date().toISOString();this.devices.set(i,{id:i,name:t,createdAt:a,identityAlgorithm:n?.algorithm,publicKey:n?.publicKey,publicKeyFingerprint:n?.publicKeyFingerprint,identityStatus:n?`active`:void 0,lastVerifiedAt:n?a:void 0});let o=this.issueTokenPair(i);return await this.persistState(),{...o,gatewayId:this.config.gatewayId,deviceId:i,deviceIdentityFingerprint:n?.publicKeyFingerprint,deviceIdentityStatus:n?`active`:void 0}})}async refreshAccessToken(e){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let t=Pg.default.verify(e,this.config.refreshSecret);if(t.type!==`refresh`)throw Error(`Invalid token type`);let n=this.refreshTokens.get(t.jti);if(!n||n.revoked)throw Bg();let r=this.devices.get(t.sub);if(!r||r.revokedAt)throw Vg();let i=new Date().toISOString();n.revoked=!0,n.revokedAt=i,this.refreshTokens.set(t.jti,n);let a=this.issueTokenPair(t.sub);return await this.persistState(),{...a,deviceId:t.sub,deviceIdentityFingerprint:r.publicKeyFingerprint,deviceIdentityStatus:r.identityStatus}})}verifyAccessToken(e){let t=Pg.default.verify(e,this.config.accessSecret);if(t.type!==`access`)throw Error(`Invalid token type`);let n=this.devices.get(t.sub);if(!n||n.revokedAt)throw Vg(`Device revoked or not found`);return t}async revokeDevice(e){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let t=this.devices.get(e);if(!t)return!1;let n=new Date().toISOString();t.revokedAt=n,t.identityStatus=`revoked`,this.devices.set(e,t);for(let t of this.refreshTokens.values())t.deviceId===e&&(t.revoked=!0,t.revokedAt=n);return await this.persistState(),!0})}async verifyDeviceIdentityBinding(e,t){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let n=this.devices.get(e);if(!n||n.revokedAt)throw Vg(`Device revoked or not found`);if(!n.publicKey||!n.publicKeyFingerprint)throw Jg();if(!t_(n.publicKey,t.publicKey)||n.publicKeyFingerprint!==t.publicKeyFingerprint)throw Yg();if(n.identityStatus!==`active`)throw Xg(n.identityStatus??`unknown`);n.lastVerifiedAt=new Date().toISOString(),this.devices.set(e,n),await this.persistState();let{publicKey:r,...i}=n;return i})}listDevices(){return[...this.devices.values()].map(({publicKey:e,...t})=>t)}inspectRefreshToken(e){let t=Pg.default.decode(e),n=t&&typeof t==`object`?t:null,r=typeof n?.jti==`string`?n.jti:void 0,i=typeof n?.sub==`string`?n.sub:void 0,a=r?this.refreshTokens.get(r):void 0,o=i||a?.deviceId?[...this.refreshTokens.values()].filter(e=>e.deviceId===(i??a?.deviceId)&&!e.revoked).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))[0]:void 0;return{claimDeviceId:i,claimExpAt:typeof n?.exp==`number`?new Date(n.exp*1e3).toISOString():void 0,claimIssuedAt:typeof n?.iat==`number`?new Date(n.iat*1e3).toISOString():void 0,claimJti:r,claimType:typeof n?.type==`string`?n.type:void 0,latestActiveTokenCreatedAt:o?.createdAt,latestActiveTokenJti:o?.jti,tokenRecordCreatedAt:a?.createdAt,tokenRecordDeviceId:a?.deviceId,tokenRecordRevokedAt:a?.revokedAt,tokenRecordState:a?a.revoked?`revoked`:`active`:`missing`}}issueTokenPair(e){let t=Pg.default.sign({sub:e,type:`access`},this.config.accessSecret,{expiresIn:this.config.accessTtl}),n=`rt_${ag(14)}`,r=Pg.default.sign({sub:e,type:`refresh`,jti:n},this.config.refreshSecret,{expiresIn:this.config.refreshTtl}),i=Pg.default.decode(r);this.refreshTokens.set(n,{jti:n,deviceId:e,revoked:!1,createdAt:new Date().toISOString(),expiresAtMs:typeof i.exp==`number`?i.exp*1e3:void 0});let a=Pg.default.decode(t);return{accessToken:t,refreshToken:r,expiresInSeconds:a.exp-a.iat}}async loadFromDisk(){await this.readStateFromDisk()&&await this.persistState()}async reloadStateFromDisk(){await this.readStateFromDisk()&&await this.persistState()}async readStateFromDisk(){await d.default.mkdir(this.config.authStoreDir,{recursive:!0});let e=new Map,t=new Map,n=new Map,r=!1;try{let i=await d.default.readFile(this.indexPath,`utf8`);if(!i.trim())await r_(this.indexPath),r=!0;else{let a=null;try{a=JSON.parse(i)}catch{await r_(this.indexPath),r=!0}if(a)if(a.v!==1||!Array.isArray(a.pairingCodes)||!Array.isArray(a.devices)||!Array.isArray(a.refreshTokens))await r_(this.indexPath),r=!0;else{for(let t of a.pairingCodes){if(typeof t?.code!=`string`||typeof t?.expiresAtMs!=`number`){r=!0;continue}e.set(t.code,{code:t.code,expiresAtMs:t.expiresAtMs})}for(let e of a.devices){if(typeof e?.id!=`string`||typeof e?.name!=`string`||typeof e?.createdAt!=`string`){r=!0;continue}t.set(e.id,{id:e.id,name:e.name,createdAt:e.createdAt,revokedAt:typeof e.revokedAt==`string`?e.revokedAt:void 0,identityAlgorithm:e.identityAlgorithm===`ed25519`?`ed25519`:void 0,publicKey:typeof e.publicKey==`string`?e.publicKey:void 0,publicKeyFingerprint:typeof e.publicKeyFingerprint==`string`?e.publicKeyFingerprint:void 0,identityStatus:e_(e.identityStatus)?e.identityStatus:void 0,lastVerifiedAt:typeof e.lastVerifiedAt==`string`?e.lastVerifiedAt:void 0})}for(let e of a.refreshTokens){if(typeof e?.jti!=`string`||typeof e?.deviceId!=`string`||typeof e?.revoked!=`boolean`||typeof e?.createdAt!=`string`){r=!0;continue}n.set(e.jti,{jti:e.jti,deviceId:e.deviceId,revoked:e.revoked,createdAt:e.createdAt,revokedAt:typeof e.revokedAt==`string`?e.revokedAt:void 0,expiresAtMs:typeof e.expiresAtMs==`number`?e.expiresAtMs:void 0})}}}}catch(e){if(e.code!==`ENOENT`)throw e}return n_(this.pairingCodes,e),n_(this.devices,t),n_(this.refreshTokens,n),r=this.pruneExpiredPairingCodes()||r,r=this.pruneRefreshTokens()||r,r}pruneExpiredPairingCodes(e=Date.now()){let t=!1;for(let[n,r]of this.pairingCodes.entries())r.expiresAtMs<=e&&(this.pairingCodes.delete(n),t=!0);return t}pruneRefreshTokens(e=Date.now()){let t=!1;for(let[n,r]of this.refreshTokens.entries()){if(!this.devices.has(r.deviceId)){this.refreshTokens.delete(n),t=!0;continue}typeof r.expiresAtMs==`number`&&r.expiresAtMs<=e&&(this.refreshTokens.delete(n),t=!0)}return t}async persistState(){await d.default.mkdir(this.config.authStoreDir,{recursive:!0});let e={v:1,pairingCodes:[...this.pairingCodes.values()].sort((e,t)=>e.code.localeCompare(t.code)),devices:[...this.devices.values()].sort((e,t)=>t.createdAt.localeCompare(e.createdAt)),refreshTokens:[...this.refreshTokens.values()].sort((e,t)=>t.createdAt.localeCompare(e.createdAt))},t=`${this.indexPath}.${process.pid}.${Date.now()}.tmp`,n=!1;try{await d.default.writeFile(t,`${JSON.stringify(e,null,2)}\n`,`utf8`),await d.default.rename(t,this.indexPath),n=!0}finally{n||await d.default.rm(t,{force:!0})}}enqueueMutation(e){let t=this.mutationQueue.then(e,e);return this.mutationQueue=t.then(()=>void 0,()=>void 0),t}};function $g(){let e=``;for(let t=0;t<6;t+=1)e+=`ABCDEFGHJKLMNPQRSTUVWXYZ23456789`[Math.floor(Math.random()*32)];return e}function e_(e){return e===`active`||e===`revoked`||e===`rotating`||e===`unknown`}function t_(e,t){let n=Buffer.from(e,`base64`),r=Buffer.from(t,`base64`);return n.length===r.length&&n.equals(r)}function n_(e,t){e.clear();for(let[n,r]of t.entries())e.set(n,r)}async function r_(e){let t=`${e}.corrupt-${Date.now()}`;try{await d.default.rename(e,t)}catch(e){if(e.code!==`ENOENT`)throw e}}var i_=class{constructor(e){this.logPath=e}async record(e){let t=p.default.dirname(this.logPath);await d.default.mkdir(t,{recursive:!0}),await d.default.appendFile(this.logPath,`${JSON.stringify(e)}\n`,`utf8`)}};function a_(){}a_.prototype={diff:function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=n.callback;typeof n==`function`&&(r=n,n={});var i=this;function a(e){return e=i.postProcess(e,n),r?(setTimeout(function(){r(e)},0),!0):e}e=this.castInput(e,n),t=this.castInput(t,n),e=this.removeEmpty(this.tokenize(e,n)),t=this.removeEmpty(this.tokenize(t,n));var o=t.length,s=e.length,c=1,l=o+s;n.maxEditLength!=null&&(l=Math.min(l,n.maxEditLength));var u=n.timeout??1/0,d=Date.now()+u,f=[{oldPos:-1,lastComponent:void 0}],p=this.extractCommon(f[0],t,e,0,n);if(f[0].oldPos+1>=s&&p+1>=o)return a(o_(i,f[0].lastComponent,t,e,i.useLongestToken));var m=-1/0,h=1/0;function g(){for(var r=Math.max(m,-c);r<=Math.min(h,c);r+=2){var l=void 0,u=f[r-1],d=f[r+1];u&&(f[r-1]=void 0);var g=!1;if(d){var _=d.oldPos-r;g=d&&0<=_&&_<o}var v=u&&u.oldPos+1<s;if(!g&&!v){f[r]=void 0;continue}if(l=!v||g&&u.oldPos<d.oldPos?i.addToPath(d,!0,!1,0,n):i.addToPath(u,!1,!0,1,n),p=i.extractCommon(l,t,e,r,n),l.oldPos+1>=s&&p+1>=o)return a(o_(i,l.lastComponent,t,e,i.useLongestToken));f[r]=l,l.oldPos+1>=s&&(h=Math.min(h,r-1)),p+1>=o&&(m=Math.max(m,r+1))}c++}if(r)(function e(){setTimeout(function(){if(c>l||Date.now()>d)return r();g()||e()},0)})();else for(;c<=l&&Date.now()<=d;){var _=g();if(_)return _}},addToPath:function(e,t,n,r,i){var a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}},extractCommon:function(e,t,n,r,i){for(var a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c},equals:function(e,t,n){return n.comparator?n.comparator(e,t):e===t||n.ignoreCase&&e.toLowerCase()===t.toLowerCase()},removeEmpty:function(e){for(var t=[],n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t},castInput:function(e){return e},tokenize:function(e){return Array.from(e)},join:function(e){return e.join(``)},postProcess:function(e){return e}};function o_(e,t,n,r,i){for(var a=[],o;t;)a.push(t),o=t.previousComponent,delete t.previousComponent,t=o;a.reverse();for(var s=0,c=a.length,l=0,u=0;s<c;s++){var d=a[s];if(d.removed)d.value=e.join(r.slice(u,u+d.count)),u+=d.count;else{if(!d.added&&i){var f=n.slice(l,l+d.count);f=f.map(function(e,t){var n=r[u+t];return n.length>e.length?n:e}),d.value=e.join(f)}else d.value=e.join(n.slice(l,l+d.count));l+=d.count,d.added||(u+=d.count)}}return a}new a_;function s_(e,t){var n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function c_(e,t){var n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function l_(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function u_(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function d_(e,t){return l_(e,t,``)}function f_(e,t){return u_(e,t,``)}function p_(e,t){return t.slice(0,m_(e,t))}function m_(e,t){var n=0;e.length>t.length&&(n=e.length-t.length);var r=t.length;e.length<t.length&&(r=e.length);var i=Array(r),a=0;i[0]=0;for(var o=1;o<r;o++){for(t[o]==t[a]?i[o]=i[a]:i[o]=a;a>0&&t[o]!=t[a];)a=i[a];t[o]==t[a]&&a++}a=0;for(var s=n;s<e.length;s++){for(;a>0&&e[s]!=t[a];)a=i[a];e[s]==t[a]&&a++}return a}var h_=`a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,g_=RegExp(`[${h_}]+|\\s+|[^${h_}]`,`ug`),__=new a_;__.equals=function(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()},__.tokenize=function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n;if(t.intlSegmenter){if(t.intlSegmenter.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=Array.from(t.intlSegmenter.segment(e),function(e){return e.segment})}else n=e.match(g_)||[];var r=[],i=null;return n.forEach(function(e){/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r},__.join=function(e){return e.map(function(e,t){return t==0?e:e.replace(/^\s+/,``)}).join(``)},__.postProcess=function(e,t){if(!e||t.oneChangePerToken)return e;var n=null,r=null,i=null;return e.forEach(function(e){e.added?r=e:e.removed?i=e:((r||i)&&v_(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&v_(n,i,r,null),e};function v_(e,t,n,r){if(t&&n){var i=t.value.match(/^\s*/)[0],a=t.value.match(/\s*$/)[0],o=n.value.match(/^\s*/)[0],s=n.value.match(/\s*$/)[0];if(e){var c=s_(i,o);e.value=u_(e.value,o,c),t.value=d_(t.value,c),n.value=d_(n.value,c)}if(r){var l=c_(a,s);r.value=l_(r.value,s,l),t.value=f_(t.value,l),n.value=f_(n.value,l)}}else if(n)e&&(n.value=n.value.replace(/^\s*/,``)),r&&(r.value=r.value.replace(/^\s*/,``));else if(e&&r){var u=r.value.match(/^\s*/)[0],d=t.value.match(/^\s*/)[0],f=t.value.match(/\s*$/)[0],p=s_(u,d);t.value=d_(t.value,p);var m=c_(d_(u,p),f);t.value=f_(t.value,m),r.value=l_(r.value,u,m),e.value=u_(e.value,u,u.slice(0,u.length-m.length))}else if(r){var h=r.value.match(/^\s*/)[0],g=t.value.match(/\s*$/)[0],_=p_(g,h);t.value=f_(t.value,_)}else if(e){var v=e.value.match(/\s*$/)[0],y=t.value.match(/^\s*/)[0],b=p_(v,y);t.value=d_(t.value,b)}}var y_=new a_;y_.tokenize=function(e){var t=RegExp(`(\\r?\\n)|[${h_}]+|[^\\S\\n\\r]+|[^${h_}]`,`ug`);return e.match(t)||[]};var b_=new a_;b_.tokenize=function(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
|
|
462
|
-
`));var n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(var i=0;i<r.length;i++){var a=r[i];i%2&&!t.newlineIsToken?n[n.length-1]+=a:n.push(a)}return n},
|
|
461
|
+
"HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,s=`secret must be a string or buffer`,c=`key must be a string or a buffer`,l=`key must be a string, a buffer or an object`,u=typeof r.createPublicKey==`function`;u&&(c+=` or a KeyObject`,s+=`or a KeyObject`);function d(e){if(!n.isBuffer(e)&&typeof e!=`string`&&(!u||typeof e!=`object`||typeof e.type!=`string`||typeof e.asymmetricKeyType!=`string`||typeof e.export!=`function`))throw g(c)}function f(e){if(!n.isBuffer(e)&&typeof e!=`string`&&typeof e!=`object`)throw g(l)}function p(e){if(!n.isBuffer(e)){if(typeof e==`string`)return e;if(!u||typeof e!=`object`||e.type!==`secret`||typeof e.export!=`function`)throw g(s)}}function m(e){return e.replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function h(e){e=e.toString();var t=4-e.length%4;if(t!==4)for(var n=0;n<t;++n)e+=`=`;return e.replace(/\-/g,`+`).replace(/_/g,`/`)}function g(e){var t=[].slice.call(arguments,1),n=a.format.bind(a,e).apply(null,t);return TypeError(n)}function _(e){return n.isBuffer(e)||typeof e==`string`}function v(e){return _(e)||(e=JSON.stringify(e)),e}function y(e){return function(t,n){p(n),t=v(t);var i=r.createHmac(`sha`+e,n);return m((i.update(t),i.digest(`base64`)))}}var b,x=`timingSafeEqual`in r?function(e,t){return e.byteLength===t.byteLength?r.timingSafeEqual(e,t):!1}:function(e,t){return b||=ug(),b(e,t)};function S(e){return function(t,r,i){var a=y(e)(t,i);return x(n.from(r),n.from(a))}}function C(e){return function(t,n){f(n),t=v(t);var i=r.createSign(`RSA-SHA`+e);return m((i.update(t),i.sign(n,`base64`)))}}function w(e){return function(t,n,i){d(i),t=v(t),n=h(n);var a=r.createVerify(`RSA-SHA`+e);return a.update(t),a.verify(i,n,`base64`)}}function T(e){return function(t,n){f(n),t=v(t);var i=r.createSign(`RSA-SHA`+e);return m((i.update(t),i.sign({key:n,padding:r.constants.RSA_PKCS1_PSS_PADDING,saltLength:r.constants.RSA_PSS_SALTLEN_DIGEST},`base64`)))}}function E(e){return function(t,n,i){d(i),t=v(t),n=h(n);var a=r.createVerify(`RSA-SHA`+e);return a.update(t),a.verify({key:i,padding:r.constants.RSA_PKCS1_PSS_PADDING,saltLength:r.constants.RSA_PSS_SALTLEN_DIGEST},n,`base64`)}}function D(e){var t=C(e);return function(){var n=t.apply(null,arguments);return n=i.derToJose(n,`ES`+e),n}}function O(e){var t=w(e);return function(n,r,a){return r=i.joseToDer(r,`ES`+e).toString(`base64`),t(n,r,a)}}function k(){return function(){return``}}function A(){return function(e,t){return t===``}}t.exports=function(e){var t={hs:y,rs:C,ps:T,es:D,none:k},n={hs:S,rs:w,ps:E,es:O,none:A},r=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!r)throw g(o,e);var i=(r[1]||r[3]).toLowerCase(),a=r[2];return{sign:t[i](a),verify:n[i](a)}}})),fg=o(((e,t)=>{var n=require(`buffer`).Buffer;t.exports=function(e){return typeof e==`string`?e:typeof e==`number`||n.isBuffer(e)?e.toString():JSON.stringify(e)}})),pg=o(((e,t)=>{var n=zh().Buffer,r=sg(),i=dg(),a=require(`stream`),o=fg(),s=require(`util`);function c(e,t){return n.from(e,t).toString(`base64`).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function l(e,t,n){n||=`utf8`;var r=c(o(e),`binary`),i=c(o(t),n);return s.format(`%s.%s`,r,i)}function u(e){var t=e.header,n=e.payload,r=e.secret||e.privateKey,a=e.encoding,o=i(t.alg),c=l(t,n,a),u=o.sign(c,r);return s.format(`%s.%s`,c,u)}function d(e){var t=e.secret;if(t??=e.privateKey,t??=e.key,/^hs/i.test(e.header.alg)===!0&&t==null)throw TypeError(`secret must be a string or buffer or a KeyObject`);var n=new r(t);this.readable=!0,this.header=e.header,this.encoding=e.encoding,this.secret=this.privateKey=this.key=n,this.payload=new r(e.payload),this.secret.once(`close`,function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once(`close`,function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}s.inherits(d,a),d.prototype.sign=function(){try{var e=u({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit(`done`,e),this.emit(`data`,e),this.emit(`end`),this.readable=!1,e}catch(e){this.readable=!1,this.emit(`error`,e),this.emit(`close`)}},d.sign=u,t.exports=d})),mg=o(((e,t)=>{var n=zh().Buffer,r=sg(),i=dg(),a=require(`stream`),o=fg(),s=require(`util`),c=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function l(e){return Object.prototype.toString.call(e)===`[object Object]`}function u(e){if(l(e))return e;try{return JSON.parse(e)}catch{return}}function d(e){var t=e.split(`.`,1)[0];return u(n.from(t,`base64`).toString(`binary`))}function f(e){return e.split(`.`,2).join(`.`)}function p(e){return e.split(`.`)[2]}function m(e,t){t||=`utf8`;var r=e.split(`.`)[1];return n.from(r,`base64`).toString(t)}function h(e){return c.test(e)&&!!d(e)}function g(e,t,n){if(!t){var r=Error(`Missing algorithm parameter for jws.verify`);throw r.code=`MISSING_ALGORITHM`,r}e=o(e);var a=p(e),s=f(e);return i(t).verify(s,a,n)}function _(e,t){if(t||={},e=o(e),!h(e))return null;var n=d(e);if(!n)return null;var r=m(e);return(n.typ===`JWT`||t.json)&&(r=JSON.parse(r,t.encoding)),{header:n,payload:r,signature:p(e)}}function v(e){e||={};var t=e.secret;if(t??=e.publicKey,t??=e.key,/^hs/i.test(e.algorithm)===!0&&t==null)throw TypeError(`secret must be a string or buffer or a KeyObject`);var n=new r(t);this.readable=!0,this.algorithm=e.algorithm,this.encoding=e.encoding,this.secret=this.publicKey=this.key=n,this.signature=new r(e.signature),this.secret.once(`close`,function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once(`close`,function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}s.inherits(v,a),v.prototype.verify=function(){try{var e=g(this.signature.buffer,this.algorithm,this.key.buffer),t=_(this.signature.buffer,this.encoding);return this.emit(`done`,e,t),this.emit(`data`,e),this.emit(`end`),this.readable=!1,e}catch(e){this.readable=!1,this.emit(`error`,e),this.emit(`close`)}},v.decode=_,v.isValid=h,v.verify=g,t.exports=v})),hg=o((e=>{var t=pg(),n=mg();e.ALGORITHMS=[`HS256`,`HS384`,`HS512`,`RS256`,`RS384`,`RS512`,`PS256`,`PS384`,`PS512`,`ES256`,`ES384`,`ES512`],e.sign=t.sign,e.verify=n.verify,e.decode=n.decode,e.isValid=n.isValid,e.createSign=function(e){return new t(e)},e.createVerify=function(e){return new n(e)}})),gg=o(((e,t)=>{var n=hg();t.exports=function(e,t){t||={};var r=n.decode(e,t);if(!r)return null;var i=r.payload;if(typeof i==`string`)try{var a=JSON.parse(i);typeof a==`object`&&a&&(i=a)}catch{}return t.complete===!0?{header:r.header,payload:i,signature:r.signature}:i}})),_g=o(((e,t)=>{var n=function(e,t){Error.call(this,e),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name=`JsonWebTokenError`,this.message=e,t&&(this.inner=t)};n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,t.exports=n})),vg=o(((e,t)=>{var n=_g(),r=function(e,t){n.call(this,e),this.name=`NotBeforeError`,this.date=t};r.prototype=Object.create(n.prototype),r.prototype.constructor=r,t.exports=r})),yg=o(((e,t)=>{var n=_g(),r=function(e,t){n.call(this,e),this.name=`TokenExpiredError`,this.expiredAt=t};r.prototype=Object.create(n.prototype),r.prototype.constructor=r,t.exports=r})),bg=o(((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})),xg=o(((e,t)=>{var n=bg();t.exports=function(e,t){var r=t||Math.floor(Date.now()/1e3);if(typeof e==`string`){var i=n(e);return i===void 0?void 0:Math.floor(r+i/1e3)}else if(typeof e==`number`)return r+e;else return}})),Sg=o(((e,t)=>{t.exports=dm().satisfies(process.version,`>=15.7.0`)})),Cg=o(((e,t)=>{t.exports=dm().satisfies(process.version,`>=16.9.0`)})),wg=o(((e,t)=>{let n=Sg(),r=Cg(),i={ec:[`ES256`,`ES384`,`ES512`],rsa:[`RS256`,`PS256`,`RS384`,`PS384`,`RS512`,`PS512`],"rsa-pss":[`PS256`,`PS384`,`PS512`]},a={ES256:`prime256v1`,ES384:`secp384r1`,ES512:`secp521r1`};t.exports=function(e,t){if(!e||!t)return;let o=t.asymmetricKeyType;if(!o)return;let s=i[o];if(!s)throw Error(`Unknown key type "${o}".`);if(!s.includes(e))throw Error(`"alg" parameter for "${o}" key type must be one of: ${s.join(`, `)}.`);if(n)switch(o){case`ec`:let n=t.asymmetricKeyDetails.namedCurve,i=a[e];if(n!==i)throw Error(`"alg" parameter "${e}" requires curve "${i}".`);break;case`rsa-pss`:if(r){let n=parseInt(e.slice(-3),10),{hashAlgorithm:r,mgf1HashAlgorithm:i,saltLength:a}=t.asymmetricKeyDetails;if(r!==`sha${n}`||i!==r)throw Error(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}.`);if(a!==void 0&&a>n>>3)throw Error(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}.`)}break}}})),Tg=o(((e,t)=>{t.exports=dm().satisfies(process.version,`^6.12.0 || >=8.0.0`)})),Eg=o(((e,t)=>{let n=_g(),r=vg(),i=yg(),a=gg(),o=xg(),s=wg(),c=Tg(),l=hg(),{KeyObject:u,createSecretKey:d,createPublicKey:f}=require(`crypto`),p=[`RS256`,`RS384`,`RS512`],m=[`ES256`,`ES384`,`ES512`],h=[`RS256`,`RS384`,`RS512`],g=[`HS256`,`HS384`,`HS512`];c&&(p.splice(p.length,0,`PS256`,`PS384`,`PS512`),h.splice(h.length,0,`PS256`,`PS384`,`PS512`)),t.exports=function(e,t,c,_){typeof c==`function`&&!_&&(_=c,c={}),c||={},c=Object.assign({},c);let v;if(v=_||function(e,t){if(e)throw e;return t},c.clockTimestamp&&typeof c.clockTimestamp!=`number`)return v(new n(`clockTimestamp must be a number`));if(c.nonce!==void 0&&(typeof c.nonce!=`string`||c.nonce.trim()===``))return v(new n(`nonce must be a non-empty string`));if(c.allowInvalidAsymmetricKeyTypes!==void 0&&typeof c.allowInvalidAsymmetricKeyTypes!=`boolean`)return v(new n(`allowInvalidAsymmetricKeyTypes must be a boolean`));let y=c.clockTimestamp||Math.floor(Date.now()/1e3);if(!e)return v(new n(`jwt must be provided`));if(typeof e!=`string`)return v(new n(`jwt must be a string`));let b=e.split(`.`);if(b.length!==3)return v(new n(`jwt malformed`));let x;try{x=a(e,{complete:!0})}catch(e){return v(e)}if(!x)return v(new n(`invalid token`));let S=x.header,C;if(typeof t==`function`){if(!_)return v(new n(`verify must be called asynchronous if secret or public key is provided as a callback`));C=t}else C=function(e,n){return n(null,t)};return C(S,function(t,a){if(t)return v(new n(`error in secret or public key callback: `+t.message));let _=b[2].trim()!==``;if(!_&&a)return v(new n(`jwt signature is required`));if(_&&!a)return v(new n(`secret or public key must be provided`));if(!_&&!c.algorithms)return v(new n(`please specify "none" in "algorithms" to verify unsigned tokens`));if(a!=null&&!(a instanceof u))try{a=f(a)}catch{try{a=d(typeof a==`string`?Buffer.from(a):a)}catch{return v(new n(`secretOrPublicKey is not valid key material`))}}if(c.algorithms||(a.type===`secret`?c.algorithms=g:[`rsa`,`rsa-pss`].includes(a.asymmetricKeyType)?c.algorithms=h:a.asymmetricKeyType===`ec`?c.algorithms=m:c.algorithms=p),c.algorithms.indexOf(x.header.alg)===-1)return v(new n(`invalid algorithm`));if(S.alg.startsWith(`HS`)&&a.type!==`secret`)return v(new n(`secretOrPublicKey must be a symmetric key when using ${S.alg}`));if(/^(?:RS|PS|ES)/.test(S.alg)&&a.type!==`public`)return v(new n(`secretOrPublicKey must be an asymmetric key when using ${S.alg}`));if(!c.allowInvalidAsymmetricKeyTypes)try{s(S.alg,a)}catch(e){return v(e)}let C;try{C=l.verify(e,x.header.alg,a)}catch(e){return v(e)}if(!C)return v(new n(`invalid signature`));let w=x.payload;if(w.nbf!==void 0&&!c.ignoreNotBefore){if(typeof w.nbf!=`number`)return v(new n(`invalid nbf value`));if(w.nbf>y+(c.clockTolerance||0))return v(new r(`jwt not active`,new Date(w.nbf*1e3)))}if(w.exp!==void 0&&!c.ignoreExpiration){if(typeof w.exp!=`number`)return v(new n(`invalid exp value`));if(y>=w.exp+(c.clockTolerance||0))return v(new i(`jwt expired`,new Date(w.exp*1e3)))}if(c.audience){let e=Array.isArray(c.audience)?c.audience:[c.audience];if(!(Array.isArray(w.aud)?w.aud:[w.aud]).some(function(t){return e.some(function(e){return e instanceof RegExp?e.test(t):e===t})}))return v(new n(`jwt audience invalid. expected: `+e.join(` or `)))}if(c.issuer&&(typeof c.issuer==`string`&&w.iss!==c.issuer||Array.isArray(c.issuer)&&c.issuer.indexOf(w.iss)===-1))return v(new n(`jwt issuer invalid. expected: `+c.issuer));if(c.subject&&w.sub!==c.subject)return v(new n(`jwt subject invalid. expected: `+c.subject));if(c.jwtid&&w.jti!==c.jwtid)return v(new n(`jwt jwtid invalid. expected: `+c.jwtid));if(c.nonce&&w.nonce!==c.nonce)return v(new n(`jwt nonce invalid. expected: `+c.nonce));if(c.maxAge){if(typeof w.iat!=`number`)return v(new n(`iat required when maxAge is specified`));let e=o(c.maxAge,w.iat);if(e===void 0)return v(new n(`"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60`));if(y>=e+(c.clockTolerance||0))return v(new i(`maxAge exceeded`,new Date(e*1e3)))}if(c.complete===!0){let e=x.signature;return v(null,{header:S,payload:w,signature:e})}return v(null,w)})}})),Dg=o(((e,t)=>{var n=1/0,r=9007199254740991,i=17976931348623157e292,a=NaN,o=`[object Arguments]`,s=`[object Function]`,c=`[object GeneratorFunction]`,l=`[object String]`,u=`[object Symbol]`,d=/^\s+|\s+$/g,f=/^[-+]0x[0-9a-f]+$/i,p=/^0b[01]+$/i,m=/^0o[0-7]+$/i,h=/^(?:0|[1-9]\d*)$/,g=parseInt;function _(e,t){for(var n=-1,r=e?e.length:0,i=Array(r);++n<r;)i[n]=t(e[n],n,e);return i}function v(e,t,n,r){for(var i=e.length,a=n+(r?1:-1);r?a--:++a<i;)if(t(e[a],a,e))return a;return-1}function y(e,t,n){if(t!==t)return v(e,b,n);for(var r=n-1,i=e.length;++r<i;)if(e[r]===t)return r;return-1}function b(e){return e!==e}function x(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}function S(e,t){return _(t,function(t){return e[t]})}function C(e,t){return function(n){return e(t(n))}}var w=Object.prototype,T=w.hasOwnProperty,E=w.toString,D=w.propertyIsEnumerable,O=C(Object.keys,Object),k=Math.max;function A(e,t){var n=P(e)||te(e)?x(e.length,String):[],r=n.length,i=!!r;for(var a in e)(t||T.call(e,a))&&!(i&&(a==`length`||M(a,r)))&&n.push(a);return n}function j(e){if(!ee(e))return O(e);var t=[];for(var n in Object(e))T.call(e,n)&&n!=`constructor`&&t.push(n);return t}function M(e,t){return t??=r,!!t&&(typeof e==`number`||h.test(e))&&e>-1&&e%1==0&&e<t}function ee(e){var t=e&&e.constructor;return e===(typeof t==`function`&&t.prototype||w)}function N(e,t,n,r){e=ne(e)?e:ue(e),n=n&&!r?se(n):0;var i=e.length;return n<0&&(n=k(i+n,0)),ae(e)?n<=i&&e.indexOf(t,n)>-1:!!i&&y(e,t,n)>-1}function te(e){return F(e)&&T.call(e,`callee`)&&(!D.call(e,`callee`)||E.call(e)==o)}var P=Array.isArray;function ne(e){return e!=null&&re(e.length)&&!I(e)}function F(e){return ie(e)&&ne(e)}function I(e){var t=L(e)?E.call(e):``;return t==s||t==c}function re(e){return typeof e==`number`&&e>-1&&e%1==0&&e<=r}function L(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function ie(e){return!!e&&typeof e==`object`}function ae(e){return typeof e==`string`||!P(e)&&ie(e)&&E.call(e)==l}function R(e){return typeof e==`symbol`||ie(e)&&E.call(e)==u}function oe(e){return e?(e=ce(e),e===n||e===-n?(e<0?-1:1)*i:e===e?e:0):e===0?e:0}function se(e){var t=oe(e),n=t%1;return t===t?n?t-n:t:0}function ce(e){if(typeof e==`number`)return e;if(R(e))return a;if(L(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=L(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=e.replace(d,``);var n=p.test(e);return n||m.test(e)?g(e.slice(2),n?2:8):f.test(e)?a:+e}function le(e){return ne(e)?A(e):j(e)}function ue(e){return e?S(e,le(e)):[]}t.exports=N})),Og=o(((e,t)=>{var n=`[object Boolean]`,r=Object.prototype.toString;function i(e){return e===!0||e===!1||a(e)&&r.call(e)==n}function a(e){return!!e&&typeof e==`object`}t.exports=i})),kg=o(((e,t)=>{var n=1/0,r=17976931348623157e292,i=NaN,a=`[object Symbol]`,o=/^\s+|\s+$/g,s=/^[-+]0x[0-9a-f]+$/i,c=/^0b[01]+$/i,l=/^0o[0-7]+$/i,u=parseInt,d=Object.prototype.toString;function f(e){return typeof e==`number`&&e==_(e)}function p(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function m(e){return!!e&&typeof e==`object`}function h(e){return typeof e==`symbol`||m(e)&&d.call(e)==a}function g(e){return e?(e=v(e),e===n||e===-n?(e<0?-1:1)*r:e===e?e:0):e===0?e:0}function _(e){var t=g(e),n=t%1;return t===t?n?t-n:t:0}function v(e){if(typeof e==`number`)return e;if(h(e))return i;if(p(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=p(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=e.replace(o,``);var n=c.test(e);return n||l.test(e)?u(e.slice(2),n?2:8):s.test(e)?i:+e}t.exports=f})),Ag=o(((e,t)=>{var n=`[object Number]`,r=Object.prototype.toString;function i(e){return!!e&&typeof e==`object`}function a(e){return typeof e==`number`||i(e)&&r.call(e)==n}t.exports=a})),jg=o(((e,t)=>{var n=`[object Object]`;function r(e){var t=!1;if(e!=null&&typeof e.toString!=`function`)try{t=!!(e+``)}catch{}return t}function i(e,t){return function(n){return e(t(n))}}var a=Function.prototype,o=Object.prototype,s=a.toString,c=o.hasOwnProperty,l=s.call(Object),u=o.toString,d=i(Object.getPrototypeOf,Object);function f(e){return!!e&&typeof e==`object`}function p(e){if(!f(e)||u.call(e)!=n||r(e))return!1;var t=d(e);if(t===null)return!0;var i=c.call(t,`constructor`)&&t.constructor;return typeof i==`function`&&i instanceof i&&s.call(i)==l}t.exports=p})),Mg=o(((e,t)=>{var n=`[object String]`,r=Object.prototype.toString,i=Array.isArray;function a(e){return!!e&&typeof e==`object`}function o(e){return typeof e==`string`||!i(e)&&a(e)&&r.call(e)==n}t.exports=o})),Ng=o(((e,t)=>{var n=`Expected a function`,r=1/0,i=17976931348623157e292,a=NaN,o=`[object Symbol]`,s=/^\s+|\s+$/g,c=/^[-+]0x[0-9a-f]+$/i,l=/^0b[01]+$/i,u=/^0o[0-7]+$/i,d=parseInt,f=Object.prototype.toString;function p(e,t){var r;if(typeof t!=`function`)throw TypeError(n);return e=y(e),function(){return--e>0&&(r=t.apply(this,arguments)),e<=1&&(t=void 0),r}}function m(e){return p(2,e)}function h(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function g(e){return!!e&&typeof e==`object`}function _(e){return typeof e==`symbol`||g(e)&&f.call(e)==o}function v(e){return e?(e=b(e),e===r||e===-r?(e<0?-1:1)*i:e===e?e:0):e===0?e:0}function y(e){var t=v(e),n=t%1;return t===t?n?t-n:t:0}function b(e){if(typeof e==`number`)return e;if(_(e))return a;if(h(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=h(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=e.replace(s,``);var n=l.test(e);return n||u.test(e)?d(e.slice(2),n?2:8):c.test(e)?a:+e}t.exports=m})),Pg=o(((e,t)=>{let n=xg(),r=Tg(),i=wg(),a=hg(),o=Dg(),s=Og(),c=kg(),l=Ag(),u=jg(),d=Mg(),f=Ng(),{KeyObject:p,createSecretKey:m,createPrivateKey:h}=require(`crypto`),g=[`RS256`,`RS384`,`RS512`,`ES256`,`ES384`,`ES512`,`HS256`,`HS384`,`HS512`,`none`];r&&g.splice(3,0,`PS256`,`PS384`,`PS512`);let _={expiresIn:{isValid:function(e){return c(e)||d(e)&&e},message:`"expiresIn" should be a number of seconds or string representing a timespan`},notBefore:{isValid:function(e){return c(e)||d(e)&&e},message:`"notBefore" should be a number of seconds or string representing a timespan`},audience:{isValid:function(e){return d(e)||Array.isArray(e)},message:`"audience" must be a string or array`},algorithm:{isValid:o.bind(null,g),message:`"algorithm" must be a valid string enum value`},header:{isValid:u,message:`"header" must be an object`},encoding:{isValid:d,message:`"encoding" must be a string`},issuer:{isValid:d,message:`"issuer" must be a string`},subject:{isValid:d,message:`"subject" must be a string`},jwtid:{isValid:d,message:`"jwtid" must be a string`},noTimestamp:{isValid:s,message:`"noTimestamp" must be a boolean`},keyid:{isValid:d,message:`"keyid" must be a string`},mutatePayload:{isValid:s,message:`"mutatePayload" must be a boolean`},allowInsecureKeySizes:{isValid:s,message:`"allowInsecureKeySizes" must be a boolean`},allowInvalidAsymmetricKeyTypes:{isValid:s,message:`"allowInvalidAsymmetricKeyTypes" must be a boolean`}},v={iat:{isValid:l,message:`"iat" should be a number of seconds`},exp:{isValid:l,message:`"exp" should be a number of seconds`},nbf:{isValid:l,message:`"nbf" should be a number of seconds`}};function y(e,t,n,r){if(!u(n))throw Error(`Expected "`+r+`" to be a plain object.`);Object.keys(n).forEach(function(i){let a=e[i];if(!a){if(!t)throw Error(`"`+i+`" is not allowed in "`+r+`"`);return}if(!a.isValid(n[i]))throw Error(a.message)})}function b(e){return y(_,!1,e,`options`)}function x(e){return y(v,!0,e,`payload`)}let S={audience:`aud`,issuer:`iss`,subject:`sub`,jwtid:`jti`},C=[`expiresIn`,`notBefore`,`noTimestamp`,`audience`,`issuer`,`subject`,`jwtid`];t.exports=function(e,t,r,o){typeof r==`function`?(o=r,r={}):r||={};let s=typeof e==`object`&&!Buffer.isBuffer(e),c=Object.assign({alg:r.algorithm||`HS256`,typ:s?`JWT`:void 0,kid:r.keyid},r.header);function l(e){if(o)return o(e);throw e}if(!t&&r.algorithm!==`none`)return l(Error(`secretOrPrivateKey must have a value`));if(t!=null&&!(t instanceof p))try{t=h(t)}catch{try{t=m(typeof t==`string`?Buffer.from(t):t)}catch{return l(Error(`secretOrPrivateKey is not valid key material`))}}if(c.alg.startsWith(`HS`)&&t.type!==`secret`)return l(Error(`secretOrPrivateKey must be a symmetric key when using ${c.alg}`));if(/^(?:RS|PS|ES)/.test(c.alg)){if(t.type!==`private`)return l(Error(`secretOrPrivateKey must be an asymmetric key when using ${c.alg}`));if(!r.allowInsecureKeySizes&&!c.alg.startsWith(`ES`)&&t.asymmetricKeyDetails!==void 0&&t.asymmetricKeyDetails.modulusLength<2048)return l(Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${c.alg}`))}if(e===void 0)return l(Error(`payload is required`));if(s){try{x(e)}catch(e){return l(e)}r.mutatePayload||(e=Object.assign({},e))}else{let t=C.filter(function(e){return r[e]!==void 0});if(t.length>0)return l(Error(`invalid `+t.join(`,`)+` option for `+typeof e+` payload`))}if(e.exp!==void 0&&r.expiresIn!==void 0)return l(Error(`Bad "options.expiresIn" option the payload already has an "exp" property.`));if(e.nbf!==void 0&&r.notBefore!==void 0)return l(Error(`Bad "options.notBefore" option the payload already has an "nbf" property.`));try{b(r)}catch(e){return l(e)}if(!r.allowInvalidAsymmetricKeyTypes)try{i(c.alg,t)}catch(e){return l(e)}let u=e.iat||Math.floor(Date.now()/1e3);if(r.noTimestamp?delete e.iat:s&&(e.iat=u),r.notBefore!==void 0){try{e.nbf=n(r.notBefore,u)}catch(e){return l(e)}if(e.nbf===void 0)return l(Error(`"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60`))}if(r.expiresIn!==void 0&&typeof e==`object`){try{e.exp=n(r.expiresIn,u)}catch(e){return l(e)}if(e.exp===void 0)return l(Error(`"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60`))}Object.keys(S).forEach(function(t){let n=S[t];if(r[t]!==void 0){if(e[n]!==void 0)return l(Error(`Bad "options.`+t+`" option. The payload already has an "`+n+`" property.`));e[n]=r[t]}});let d=r.encoding||`utf8`;if(typeof o==`function`)o&&=f(o),a.createSign({header:c,privateKey:t,payload:e,encoding:d}).once(`error`,o).once(`done`,function(e){if(!r.allowInsecureKeySizes&&/^(?:RS|PS)/.test(c.alg)&&e.length<256)return o(Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${c.alg}`));o(null,e)});else{let n=a.sign({header:c,payload:e,secret:t,encoding:d});if(!r.allowInsecureKeySizes&&/^(?:RS|PS)/.test(c.alg)&&n.length<256)throw Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${c.alg}`);return n}}})),Fg=c(o(((e,t)=>{t.exports={decode:gg(),verify:Eg(),sign:Pg(),JsonWebTokenError:_g(),NotBeforeError:vg(),TokenExpiredError:yg()}}))(),1),Ig=c($u(),1),Lg=class extends Error{code;status;details;constructor(e){super(e.message),this.name=`Error`,this.code=e.code,this.status=e.status,this.details=e.details}};function Rg(e){return e instanceof Lg}function zg(){return new Lg({code:`PAIRING_CODE_INVALID`,status:400,message:`Invalid pairing code`})}function Bg(){return new Lg({code:`PAIRING_CODE_EXPIRED`,status:400,message:`Pairing code expired`})}function Vg(){return new Lg({code:`REFRESH_TOKEN_REVOKED`,status:401,message:`Refresh token revoked`})}function Hg(e=`Device revoked`){return new Lg({code:`DEVICE_REVOKED`,status:401,message:e})}function Ug(){return new Lg({code:`REFRESH_TOKEN_DEVICE_MISMATCH`,status:401,message:`Refresh token device mismatch`})}function Wg(e){return new Lg({code:`PROJECT_NOT_FOUND`,status:404,message:`Project not found: ${e}`})}function Gg(e,t){return new Lg({code:`PROJECT_SESSION_NOT_FOUND`,status:404,message:`Session ${t} not found in project ${e}`})}function Kg(e){return new Lg({code:`SESSION_NOT_FOUND`,status:404,message:`Session not found: ${e}`})}function qg(e){return new Lg({code:`PROJECT_DELETE_CONFLICT`,status:409,message:`Cannot delete project ${e} while sessions are running`})}function Jg(e){return new Lg({code:`DISCOVERED_PROJECT_NOT_FOUND`,status:404,message:`Discovered project not found: ${e}`})}function Yg(){return new Lg({code:`DEVICE_IDENTITY_NOT_REGISTERED`,status:400,message:`Device identity not registered`})}function Xg(){return new Lg({code:`DEVICE_IDENTITY_MISMATCH`,status:400,message:`Device identity mismatch`})}function Zg(e){return new Lg({code:`DEVICE_IDENTITY_NOT_ACTIVE`,status:400,message:`Device identity not active: ${e}`})}function Qg(e){return e instanceof Error&&(e.name===`TokenExpiredError`||e.name===`JsonWebTokenError`||e.name===`NotBeforeError`)}var $g=class{indexPath;pairingCodes=new Map;devices=new Map;refreshTokens=new Map;ready;mutationQueue=Promise.resolve();constructor(e){this.config=e,this.indexPath=p.default.join(e.authStoreDir,`auth-state.json`),this.ready=this.loadFromDisk()}async init(){await this.ready}async createPairingCode(e=300){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let t=e_(),n=Date.now()+e*1e3;return this.pairingCodes.set(t,{code:t,expiresAtMs:n}),await this.persistState(),{code:t,expiresAt:new Date(n).toISOString()}})}async claimPairingCode(e,t,n){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let r=this.pairingCodes.get(e);if(!r)throw zg();if(r.expiresAtMs<Date.now())throw this.pairingCodes.delete(e),await this.persistState(),Bg();this.pairingCodes.delete(e);let i=`dev_${og(12)}`,a=new Date().toISOString();this.devices.set(i,{id:i,name:t,createdAt:a,identityAlgorithm:n?.algorithm,publicKey:n?.publicKey,publicKeyFingerprint:n?.publicKeyFingerprint,identityStatus:n?`active`:void 0,lastVerifiedAt:n?a:void 0});let o=this.issueTokenPair(i);return await this.persistState(),{...o,gatewayId:this.config.gatewayId,deviceId:i,deviceIdentityFingerprint:n?.publicKeyFingerprint,deviceIdentityStatus:n?`active`:void 0}})}async refreshAccessToken(e){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let t=Fg.default.verify(e,this.config.refreshSecret);if(t.type!==`refresh`)throw Error(`Invalid token type`);let n=this.refreshTokens.get(t.jti);if(!n||n.revoked)throw Vg();let r=this.devices.get(t.sub);if(!r||r.revokedAt)throw Hg();let i=new Date().toISOString();n.revoked=!0,n.revokedAt=i,this.refreshTokens.set(t.jti,n);let a=this.issueTokenPair(t.sub);return await this.persistState(),{...a,deviceId:t.sub,deviceIdentityFingerprint:r.publicKeyFingerprint,deviceIdentityStatus:r.identityStatus}})}verifyAccessToken(e){let t=Fg.default.verify(e,this.config.accessSecret);if(t.type!==`access`)throw Error(`Invalid token type`);let n=this.devices.get(t.sub);if(!n||n.revokedAt)throw Hg(`Device revoked or not found`);return t}async revokeDevice(e){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let t=this.devices.get(e);if(!t)return!1;let n=new Date().toISOString();t.revokedAt=n,t.identityStatus=`revoked`,this.devices.set(e,t);for(let t of this.refreshTokens.values())t.deviceId===e&&(t.revoked=!0,t.revokedAt=n);return await this.persistState(),!0})}async verifyDeviceIdentityBinding(e,t){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let n=this.devices.get(e);if(!n||n.revokedAt)throw Hg(`Device revoked or not found`);if(!n.publicKey||!n.publicKeyFingerprint)throw Yg();if(!n_(n.publicKey,t.publicKey)||n.publicKeyFingerprint!==t.publicKeyFingerprint)throw Xg();if(n.identityStatus!==`active`)throw Zg(n.identityStatus??`unknown`);n.lastVerifiedAt=new Date().toISOString(),this.devices.set(e,n),await this.persistState();let{publicKey:r,...i}=n;return i})}listDevices(){return[...this.devices.values()].map(({publicKey:e,...t})=>t)}inspectRefreshToken(e){let t=Fg.default.decode(e),n=t&&typeof t==`object`?t:null,r=typeof n?.jti==`string`?n.jti:void 0,i=typeof n?.sub==`string`?n.sub:void 0,a=r?this.refreshTokens.get(r):void 0,o=i||a?.deviceId?[...this.refreshTokens.values()].filter(e=>e.deviceId===(i??a?.deviceId)&&!e.revoked).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))[0]:void 0;return{claimDeviceId:i,claimExpAt:typeof n?.exp==`number`?new Date(n.exp*1e3).toISOString():void 0,claimIssuedAt:typeof n?.iat==`number`?new Date(n.iat*1e3).toISOString():void 0,claimJti:r,claimType:typeof n?.type==`string`?n.type:void 0,latestActiveTokenCreatedAt:o?.createdAt,latestActiveTokenJti:o?.jti,tokenRecordCreatedAt:a?.createdAt,tokenRecordDeviceId:a?.deviceId,tokenRecordRevokedAt:a?.revokedAt,tokenRecordState:a?a.revoked?`revoked`:`active`:`missing`}}issueTokenPair(e){let t=Fg.default.sign({sub:e,type:`access`},this.config.accessSecret,{expiresIn:this.config.accessTtl}),n=`rt_${og(14)}`,r=Fg.default.sign({sub:e,type:`refresh`,jti:n},this.config.refreshSecret,{expiresIn:this.config.refreshTtl}),i=Fg.default.decode(r);this.refreshTokens.set(n,{jti:n,deviceId:e,revoked:!1,createdAt:new Date().toISOString(),expiresAtMs:typeof i.exp==`number`?i.exp*1e3:void 0});let a=Fg.default.decode(t);return{accessToken:t,refreshToken:r,expiresInSeconds:a.exp-a.iat}}async loadFromDisk(){await this.readStateFromDisk()&&await this.persistState()}async reloadStateFromDisk(){await this.readStateFromDisk()&&await this.persistState()}async readStateFromDisk(){await d.default.mkdir(this.config.authStoreDir,{recursive:!0});let e=new Map,t=new Map,n=new Map,r=!1;try{let i=await d.default.readFile(this.indexPath,`utf8`);if(!i.trim())await i_(this.indexPath),r=!0;else{let a=null;try{a=JSON.parse(i)}catch{await i_(this.indexPath),r=!0}if(a)if(a.v!==1||!Array.isArray(a.pairingCodes)||!Array.isArray(a.devices)||!Array.isArray(a.refreshTokens))await i_(this.indexPath),r=!0;else{for(let t of a.pairingCodes){if(typeof t?.code!=`string`||typeof t?.expiresAtMs!=`number`){r=!0;continue}e.set(t.code,{code:t.code,expiresAtMs:t.expiresAtMs})}for(let e of a.devices){if(typeof e?.id!=`string`||typeof e?.name!=`string`||typeof e?.createdAt!=`string`){r=!0;continue}t.set(e.id,{id:e.id,name:e.name,createdAt:e.createdAt,revokedAt:typeof e.revokedAt==`string`?e.revokedAt:void 0,identityAlgorithm:e.identityAlgorithm===`ed25519`?`ed25519`:void 0,publicKey:typeof e.publicKey==`string`?e.publicKey:void 0,publicKeyFingerprint:typeof e.publicKeyFingerprint==`string`?e.publicKeyFingerprint:void 0,identityStatus:t_(e.identityStatus)?e.identityStatus:void 0,lastVerifiedAt:typeof e.lastVerifiedAt==`string`?e.lastVerifiedAt:void 0})}for(let e of a.refreshTokens){if(typeof e?.jti!=`string`||typeof e?.deviceId!=`string`||typeof e?.revoked!=`boolean`||typeof e?.createdAt!=`string`){r=!0;continue}n.set(e.jti,{jti:e.jti,deviceId:e.deviceId,revoked:e.revoked,createdAt:e.createdAt,revokedAt:typeof e.revokedAt==`string`?e.revokedAt:void 0,expiresAtMs:typeof e.expiresAtMs==`number`?e.expiresAtMs:void 0})}}}}catch(e){if(e.code!==`ENOENT`)throw e}return r_(this.pairingCodes,e),r_(this.devices,t),r_(this.refreshTokens,n),r=this.pruneExpiredPairingCodes()||r,r=this.pruneRefreshTokens()||r,r}pruneExpiredPairingCodes(e=Date.now()){let t=!1;for(let[n,r]of this.pairingCodes.entries())r.expiresAtMs<=e&&(this.pairingCodes.delete(n),t=!0);return t}pruneRefreshTokens(e=Date.now()){let t=!1;for(let[n,r]of this.refreshTokens.entries()){if(!this.devices.has(r.deviceId)){this.refreshTokens.delete(n),t=!0;continue}typeof r.expiresAtMs==`number`&&r.expiresAtMs<=e&&(this.refreshTokens.delete(n),t=!0)}return t}async persistState(){await d.default.mkdir(this.config.authStoreDir,{recursive:!0});let e={v:1,pairingCodes:[...this.pairingCodes.values()].sort((e,t)=>e.code.localeCompare(t.code)),devices:[...this.devices.values()].sort((e,t)=>t.createdAt.localeCompare(e.createdAt)),refreshTokens:[...this.refreshTokens.values()].sort((e,t)=>t.createdAt.localeCompare(e.createdAt))},t=`${this.indexPath}.${process.pid}.${Date.now()}.tmp`,n=!1;try{await d.default.writeFile(t,`${JSON.stringify(e,null,2)}\n`,`utf8`),await d.default.rename(t,this.indexPath),n=!0}finally{n||await d.default.rm(t,{force:!0})}}enqueueMutation(e){let t=this.mutationQueue.then(e,e);return this.mutationQueue=t.then(()=>void 0,()=>void 0),t}};function e_(){let e=``;for(let t=0;t<6;t+=1)e+=`ABCDEFGHJKLMNPQRSTUVWXYZ23456789`[Math.floor(Math.random()*32)];return e}function t_(e){return e===`active`||e===`revoked`||e===`rotating`||e===`unknown`}function n_(e,t){let n=Buffer.from(e,`base64`),r=Buffer.from(t,`base64`);return n.length===r.length&&n.equals(r)}function r_(e,t){e.clear();for(let[n,r]of t.entries())e.set(n,r)}async function i_(e){let t=`${e}.corrupt-${Date.now()}`;try{await d.default.rename(e,t)}catch(e){if(e.code!==`ENOENT`)throw e}}var a_=class{constructor(e){this.logPath=e}async record(e){let t=p.default.dirname(this.logPath);await d.default.mkdir(t,{recursive:!0}),await d.default.appendFile(this.logPath,`${JSON.stringify(e)}\n`,`utf8`)}};function o_(){}o_.prototype={diff:function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=n.callback;typeof n==`function`&&(r=n,n={});var i=this;function a(e){return e=i.postProcess(e,n),r?(setTimeout(function(){r(e)},0),!0):e}e=this.castInput(e,n),t=this.castInput(t,n),e=this.removeEmpty(this.tokenize(e,n)),t=this.removeEmpty(this.tokenize(t,n));var o=t.length,s=e.length,c=1,l=o+s;n.maxEditLength!=null&&(l=Math.min(l,n.maxEditLength));var u=n.timeout??1/0,d=Date.now()+u,f=[{oldPos:-1,lastComponent:void 0}],p=this.extractCommon(f[0],t,e,0,n);if(f[0].oldPos+1>=s&&p+1>=o)return a(s_(i,f[0].lastComponent,t,e,i.useLongestToken));var m=-1/0,h=1/0;function g(){for(var r=Math.max(m,-c);r<=Math.min(h,c);r+=2){var l=void 0,u=f[r-1],d=f[r+1];u&&(f[r-1]=void 0);var g=!1;if(d){var _=d.oldPos-r;g=d&&0<=_&&_<o}var v=u&&u.oldPos+1<s;if(!g&&!v){f[r]=void 0;continue}if(l=!v||g&&u.oldPos<d.oldPos?i.addToPath(d,!0,!1,0,n):i.addToPath(u,!1,!0,1,n),p=i.extractCommon(l,t,e,r,n),l.oldPos+1>=s&&p+1>=o)return a(s_(i,l.lastComponent,t,e,i.useLongestToken));f[r]=l,l.oldPos+1>=s&&(h=Math.min(h,r-1)),p+1>=o&&(m=Math.max(m,r+1))}c++}if(r)(function e(){setTimeout(function(){if(c>l||Date.now()>d)return r();g()||e()},0)})();else for(;c<=l&&Date.now()<=d;){var _=g();if(_)return _}},addToPath:function(e,t,n,r,i){var a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}},extractCommon:function(e,t,n,r,i){for(var a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c},equals:function(e,t,n){return n.comparator?n.comparator(e,t):e===t||n.ignoreCase&&e.toLowerCase()===t.toLowerCase()},removeEmpty:function(e){for(var t=[],n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t},castInput:function(e){return e},tokenize:function(e){return Array.from(e)},join:function(e){return e.join(``)},postProcess:function(e){return e}};function s_(e,t,n,r,i){for(var a=[],o;t;)a.push(t),o=t.previousComponent,delete t.previousComponent,t=o;a.reverse();for(var s=0,c=a.length,l=0,u=0;s<c;s++){var d=a[s];if(d.removed)d.value=e.join(r.slice(u,u+d.count)),u+=d.count;else{if(!d.added&&i){var f=n.slice(l,l+d.count);f=f.map(function(e,t){var n=r[u+t];return n.length>e.length?n:e}),d.value=e.join(f)}else d.value=e.join(n.slice(l,l+d.count));l+=d.count,d.added||(u+=d.count)}}return a}new o_;function c_(e,t){var n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function l_(e,t){var n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function u_(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function d_(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function f_(e,t){return u_(e,t,``)}function p_(e,t){return d_(e,t,``)}function m_(e,t){return t.slice(0,h_(e,t))}function h_(e,t){var n=0;e.length>t.length&&(n=e.length-t.length);var r=t.length;e.length<t.length&&(r=e.length);var i=Array(r),a=0;i[0]=0;for(var o=1;o<r;o++){for(t[o]==t[a]?i[o]=i[a]:i[o]=a;a>0&&t[o]!=t[a];)a=i[a];t[o]==t[a]&&a++}a=0;for(var s=n;s<e.length;s++){for(;a>0&&e[s]!=t[a];)a=i[a];e[s]==t[a]&&a++}return a}var g_=`a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,__=RegExp(`[${g_}]+|\\s+|[^${g_}]`,`ug`),v_=new o_;v_.equals=function(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()},v_.tokenize=function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n;if(t.intlSegmenter){if(t.intlSegmenter.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=Array.from(t.intlSegmenter.segment(e),function(e){return e.segment})}else n=e.match(__)||[];var r=[],i=null;return n.forEach(function(e){/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r},v_.join=function(e){return e.map(function(e,t){return t==0?e:e.replace(/^\s+/,``)}).join(``)},v_.postProcess=function(e,t){if(!e||t.oneChangePerToken)return e;var n=null,r=null,i=null;return e.forEach(function(e){e.added?r=e:e.removed?i=e:((r||i)&&y_(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&y_(n,i,r,null),e};function y_(e,t,n,r){if(t&&n){var i=t.value.match(/^\s*/)[0],a=t.value.match(/\s*$/)[0],o=n.value.match(/^\s*/)[0],s=n.value.match(/\s*$/)[0];if(e){var c=c_(i,o);e.value=d_(e.value,o,c),t.value=f_(t.value,c),n.value=f_(n.value,c)}if(r){var l=l_(a,s);r.value=u_(r.value,s,l),t.value=p_(t.value,l),n.value=p_(n.value,l)}}else if(n)e&&(n.value=n.value.replace(/^\s*/,``)),r&&(r.value=r.value.replace(/^\s*/,``));else if(e&&r){var u=r.value.match(/^\s*/)[0],d=t.value.match(/^\s*/)[0],f=t.value.match(/\s*$/)[0],p=c_(u,d);t.value=f_(t.value,p);var m=l_(f_(u,p),f);t.value=p_(t.value,m),r.value=u_(r.value,u,m),e.value=d_(e.value,u,u.slice(0,u.length-m.length))}else if(r){var h=r.value.match(/^\s*/)[0],g=t.value.match(/\s*$/)[0],_=m_(g,h);t.value=p_(t.value,_)}else if(e){var v=e.value.match(/\s*$/)[0],y=t.value.match(/^\s*/)[0],b=m_(v,y);t.value=f_(t.value,b)}}var b_=new o_;b_.tokenize=function(e){var t=RegExp(`(\\r?\\n)|[${g_}]+|[^\\S\\n\\r]+|[^${g_}]`,`ug`);return e.match(t)||[]};var x_=new o_;x_.tokenize=function(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
|
|
462
|
+
`));var n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(var i=0;i<r.length;i++){var a=r[i];i%2&&!t.newlineIsToken?n[n.length-1]+=a:n.push(a)}return n},x_.equals=function(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
|
|
463
463
|
`))&&(e=e.trim()),(!n.newlineIsToken||!t.includes(`
|
|
464
464
|
`))&&(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
|
|
465
465
|
`)&&(e=e.slice(0,-1)),t.endsWith(`
|
|
466
|
-
`)&&(t=t.slice(0,-1))),
|
|
467
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var
|
|
468
|
-
`)?_.lines[v]=_.lines[v].slice(0,-1):(_.lines.splice(v+1,0,`\`),v++);return{oldFileName:e,newFileName:t,oldHeader:i,newHeader:a,hunks:s}}}function
|
|
466
|
+
`)&&(t=t.slice(0,-1))),o_.prototype.equals.call(this,e,t,n)};function S_(e,t,n){return x_.diff(e,t,n)}var C_=new o_;C_.tokenize=function(e){return e.split(/(\S.+?[.!?])(?=\s+|$)/)};var w_=new o_;w_.tokenize=function(e){return e.split(/([{}:;,]|\s+)/)};function T_(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function E_(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?T_(Object(n),!0).forEach(function(t){A_(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):T_(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function D_(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function O_(e){var t=D_(e,`string`);return typeof t==`symbol`?t:t+``}function k_(e){"@babel/helpers - typeof";return k_=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},k_(e)}function A_(e,t,n){return t=O_(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function j_(e){return M_(e)||N_(e)||P_(e)||I_()}function M_(e){if(Array.isArray(e))return F_(e)}function N_(e){if(typeof Symbol<`u`&&e[Symbol.iterator]!=null||e[`@@iterator`]!=null)return Array.from(e)}function P_(e,t){if(e){if(typeof e==`string`)return F_(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`)return Array.from(e);if(n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return F_(e,t)}}function F_(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function I_(){throw TypeError(`Invalid attempt to spread non-iterable instance.
|
|
467
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var L_=new o_;L_.useLongestToken=!0,L_.tokenize=x_.tokenize,L_.castInput=function(e,t){var n=t.undefinedReplacement,r=t.stringifyReplacer,i=r===void 0?function(e,t){return t===void 0?n:t}:r;return typeof e==`string`?e:JSON.stringify(R_(e,null,null,i),i,` `)},L_.equals=function(e,t,n){return o_.prototype.equals.call(L_,e.replace(/,([\r\n])/g,`$1`),t.replace(/,([\r\n])/g,`$1`),n)};function R_(e,t,n,r,i){t||=[],n||=[],r&&(e=r(i,e));var a;for(a=0;a<t.length;a+=1)if(t[a]===e)return n[a];var o;if(Object.prototype.toString.call(e)===`[object Array]`){for(t.push(e),o=Array(e.length),n.push(o),a=0;a<e.length;a+=1)o[a]=R_(e[a],t,n,r,i);return t.pop(),n.pop(),o}if(e&&e.toJSON&&(e=e.toJSON()),k_(e)===`object`&&e!==null){t.push(e),o={},n.push(o);var s=[],c;for(c in e)Object.prototype.hasOwnProperty.call(e,c)&&s.push(c);for(s.sort(),a=0;a<s.length;a+=1)c=s[a],o[c]=R_(e[c],t,n,r,c);t.pop(),n.pop()}else o=e;return o}var z_=new o_;z_.tokenize=function(e){return e.slice()},z_.join=z_.removeEmpty=function(e){return e};function B_(e,t,n,r,i,a,o){if(o||={},typeof o==`function`&&(o={callback:o}),o.context===void 0&&(o.context=4),o.newlineIsToken)throw Error(`newlineIsToken may not be used with patch-generation functions, only with diffing functions`);if(o.callback){var s=o.callback;S_(n,r,E_(E_({},o),{},{callback:function(e){s(c(e))}}))}else return c(S_(n,r,o));function c(n){if(!n)return;n.push({value:``,lines:[]});function r(e){return e.map(function(e){return` `+e})}for(var s=[],c=0,l=0,u=[],d=1,f=1,p=function(){var e=n[m],t=e.lines||U_(e.value);if(e.lines=t,e.added||e.removed){var i;if(!c){var a=n[m-1];c=d,l=f,a&&(u=o.context>0?r(a.lines.slice(-o.context)):[],c-=u.length,l-=u.length)}(i=u).push.apply(i,j_(t.map(function(t){return(e.added?`+`:`-`)+t}))),e.added?f+=t.length:d+=t.length}else{if(c)if(t.length<=o.context*2&&m<n.length-2){var p;(p=u).push.apply(p,j_(r(t)))}else{var h,g=Math.min(t.length,o.context);(h=u).push.apply(h,j_(r(t.slice(0,g))));var _={oldStart:c,oldLines:d-c+g,newStart:l,newLines:f-l+g,lines:u};s.push(_),c=0,l=0,u=[]}d+=t.length,f+=t.length}},m=0;m<n.length;m++)p();for(var h=0,g=s;h<g.length;h++)for(var _=g[h],v=0;v<_.lines.length;v++)_.lines[v].endsWith(`
|
|
468
|
+
`)?_.lines[v]=_.lines[v].slice(0,-1):(_.lines.splice(v+1,0,`\`),v++);return{oldFileName:e,newFileName:t,oldHeader:i,newHeader:a,hunks:s}}}function V_(e){if(Array.isArray(e))return e.map(V_).join(`
|
|
469
469
|
`);var t=[];e.oldFileName==e.newFileName&&t.push(`Index: `+e.oldFileName),t.push(`===================================================================`),t.push(`--- `+e.oldFileName+(e.oldHeader===void 0?``:` `+e.oldHeader)),t.push(`+++ `+e.newFileName+(e.newHeader===void 0?``:` `+e.newHeader));for(var n=0;n<e.hunks.length;n++){var r=e.hunks[n];r.oldLines===0&&--r.oldStart,r.newLines===0&&--r.newStart,t.push(`@@ -`+r.oldStart+`,`+r.oldLines+` +`+r.newStart+`,`+r.newLines+` @@`),t.push.apply(t,r.lines)}return t.join(`
|
|
470
470
|
`)+`
|
|
471
|
-
`}function
|
|
471
|
+
`}function H_(e,t,n,r,i,a,o){var s;if(typeof o==`function`&&(o={callback:o}),(s=o)!=null&&s.callback){var c=o.callback;B_(e,t,n,r,i,a,E_(E_({},o),{},{callback:function(e){e?c(V_(e)):c()}}))}else{var l=B_(e,t,n,r,i,a,o);return l?V_(l):void 0}}function U_(e){var t=e.endsWith(`
|
|
472
472
|
`),n=e.split(`
|
|
473
473
|
`).map(function(e){return e+`
|
|
474
|
-
`});return t?n.pop():n.push(n.pop().slice(0,-1)),n}var U_=class{async listDirectories(e,t,n=200){let r=await d.default.realpath(p.default.resolve(e));return Z_(r,await Y_(r,t),n)}async listDirectoriesUnrestricted(e,t=200,n=f.default.homedir()){let r=await X_(e,n),i=p.default.parse(r).root;return Z_(i,r,t)}async readFile(e,t){let{absolutePath:n,normalizedPath:r}=await W_(e,t);return{path:r,absolutePath:n,content:await d.default.readFile(n,`utf8`)}}async diffFile(e,t,n=``){let{absolutePath:r,normalizedPath:i}=await W_(e,t),a=await d.default.readFile(r,`utf8`);return{path:i,absolutePath:r,diff:V_(i,i,n,a,`base`,`current`),currentContent:a}}async listTree(e,t=`.`,n=500){let r=await d.default.realpath(p.default.resolve(e)),i=G_(t),a=await K_(r,i),o=[];async function s(e,t){let r=await d.default.readdir(e,{withFileTypes:!0});for(let i of r){if(o.length>=n)return;let r=p.default.join(e,i.name),a=t?p.default.join(t,i.name):i.name;i.isSymbolicLink()||(i.isDirectory()?(o.push({path:a,kind:`dir`}),await s(r,a)):o.push({path:a,kind:`file`}))}}return await s(a,``),{root:i,entries:o}}};async function W_(e,t){let n=await d.default.realpath(p.default.resolve(e)),r=G_(t),i=await K_(n,r),a=await d.default.realpath(i);return q_(n,a,r),{absolutePath:a,normalizedPath:r}}function G_(e){let t=e.trim();if(!t)throw Error(`Path is required`);return t}async function K_(e,t){if(p.default.isAbsolute(t))throw Error(`Path must be relative to project root: ${t}`);let n=p.default.resolve(e,t);return q_(e,n,t),n}function q_(e,t,n){let r=J_(e),i=J_(t);if(t!==e&&!i.startsWith(r))throw Error(`Path outside project root is not allowed: ${n}`)}function J_(e){return e.endsWith(p.default.sep)?e:`${e}${p.default.sep}`}async function Y_(e,t){let n=t?.trim(),r=n?p.default.isAbsolute(n)?p.default.resolve(n):p.default.resolve(e,n):e;q_(e,r,n??`.`);let i=await d.default.realpath(r);if(q_(e,i,n??`.`),!(await d.default.stat(i)).isDirectory())throw Error(`Path is not a directory: ${i}`);return i}async function X_(e,t=f.default.homedir()){let n=e?.trim(),r=p.default.resolve(t),i=n?p.default.isAbsolute(n)?p.default.resolve(n):p.default.resolve(r,n):r,a=await d.default.realpath(i);if(!(await d.default.stat(a)).isDirectory())throw Error(`Path is not a directory: ${a}`);return a}async function Z_(e,t,n){let r=(await d.default.readdir(t,{withFileTypes:!0})).filter(e=>e.isDirectory()&&!e.isSymbolicLink()).sort((e,t)=>e.name.localeCompare(t.name)).slice(0,Math.max(1,n)).map(e=>({name:e.name,path:p.default.join(t,e.name)}));return{rootPath:e,currentPath:t,parentPath:t===e?null:p.default.dirname(t),directories:r}}var Q_=class{indexPath;projects=new Map;projectByPath=new Map;ready;writeQueue=Promise.resolve();constructor(e){this.baseDir=e,this.indexPath=p.default.join(e,`project-index.json`),this.ready=this.loadFromDisk()}async upsertByPath(e,t){await this.ready;let n=await ev(e),r=this.projectByPath.get(n),i=new Date().toISOString(),a=$_(t)??(p.default.basename(n)||n),o=r?{...r,title:$_(t)??r.title,updatedAt:i}:{id:`proj_${ag(12)}`,title:a,path:n,createdAt:i,updatedAt:i};return this.projects.set(o.id,o),this.projectByPath.set(n,o),await this.enqueueWrite(async()=>{await this.persistIndex()}),o}async list(){return await this.ready,[...this.projects.values()].sort((e,t)=>e.title.localeCompare(t.title))}async getById(e){return await this.ready,this.projects.get(e)}async getByPath(e){await this.ready;let t=await ev(e);return this.projectByPath.get(t)}async remove(e){await this.ready;let t=this.projects.get(e);return t?(this.projects.delete(e),this.projectByPath.delete(t.path),await this.enqueueWrite(async()=>{await this.persistIndex()}),!0):!1}async loadFromDisk(){await d.default.mkdir(this.baseDir,{recursive:!0});try{let e=await d.default.readFile(this.indexPath,`utf8`),t=JSON.parse(e);if(t.v!==1||!Array.isArray(t.projects))return;for(let e of t.projects)typeof e?.id!=`string`||typeof e?.title!=`string`||typeof e?.path!=`string`||typeof e?.createdAt!=`string`||typeof e?.updatedAt!=`string`||(this.projects.set(e.id,e),this.projectByPath.set(e.path,e))}catch(e){if(e.code!==`ENOENT`)throw e}}async persistIndex(){await d.default.mkdir(this.baseDir,{recursive:!0});let e={v:1,projects:[...this.projects.values()].sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))};await d.default.writeFile(this.indexPath,`${JSON.stringify(e,null,2)}\n`,`utf8`)}enqueueWrite(e){return this.writeQueue=this.writeQueue.then(e,e),this.writeQueue}};function $_(e){if(typeof e==`string`)return e.replace(/\s+/g,` `).trim()||void 0}async function ev(e){if(!p.default.isAbsolute(e))throw Error(`Project path must be absolute: ${e}`);let t=p.default.resolve(e),n;try{n=await d.default.stat(t)}catch(e){throw Error(`Project path does not exist: ${t}; ${String(e)}`)}if(!n.isDirectory())throw Error(`Project path is not a directory: ${t}`);return d.default.realpath(t)}wh(),yh(),bh();var tv=c(Ch(),1);Eh();var nv=tv.default,rv=120,iv=class{id;provider;providerMode=`mock`;model;listeners=new Set;pendingApprovals=new Map;closed=!1;constructor(e,t){this.id=t.sessionId,this.provider=e,this.model=t.model}onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async sendInput(e,t){if(this.ensureOpen(),this.emit({type:`turn.started`,text:e}),this.emit({type:`item.started`,itemType:`assistant.message`,text:``}),this.requiresApproval(e)){let t=`req_${ag(8)}`;this.pendingApprovals.set(t,{input:e}),this.emit({type:`tool.permission.requested`,requestId:t,toolName:`fs.read`,args:{path:`README.md`},reason:`Mock adapter requires approval for tool-like prompts.`}),this.emit({type:`status.progress`,message:`Waiting for tool approval`});return}await this.streamAssistantText(`(${this.provider}) response: ${e}`)}async interrupt(){this.ensureOpen(),this.emit({type:`turn.failed`,reason:`Interrupted by user`})}async close(){this.closed||=!0}async respondToolPermission(e,t,n){this.ensureOpen();let r=this.pendingApprovals.get(e);if(!r)throw Error(`Unknown tool approval request: ${e}`);if(this.pendingApprovals.delete(e),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n}),t===`deny`){this.emit({type:`turn.failed`,reason:n??`Tool request denied`});return}await this.streamAssistantText(`Tool approved. Proceeded with request derived from: ${r.input}`)}requiresApproval(e){return/tool|approve|permission|read file|diff/i.test(e)}async streamAssistantText(e){let t=e.split(/\s+/).filter(Boolean),n=``;for(let e of t)n=`${n} ${e}`.trim(),this.emit({type:`item.updated`,text:n}),await av(rv);this.emit({type:`item.completed`,text:n}),this.emit({type:`turn.completed`,text:n})}emit(e){for(let t of this.listeners)t(e)}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}};function av(e){return new Promise(t=>setTimeout(t,e))}var ov=class{provider;constructor(e){this.provider=e}async isNativeAvailable(){return!1}async createSession(e){return new iv(this.provider,e)}};function sv(e){let t=dv(lv(e)),n=$(t.type);return n&&(t.type=cv(n)),t}function cv(e){switch(e){case`userMessage`:return`user_message`;case`agentMessage`:return`agent_message`;case`commandExecution`:return`command_execution`;case`fileChange`:return`file_change`;case`mcpToolCall`:return`mcp_tool_call`;case`collabAgentToolCall`:return`collab_tool_call`;case`webSearch`:return`web_search`;case`enteredReviewMode`:return`entered_review_mode`;case`exitedReviewMode`:return`exited_review_mode`;case`contextCompaction`:return`context_compaction`;default:return uv(e)}}function lv(e){if(Array.isArray(e))return e.map(e=>lv(e));if(typeof e==`object`&&e){let t={};for(let[n,r]of Object.entries(e))t[uv(n)]=lv(r);return t}return e}function uv(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1_$2`).replace(/[\-\s/]+/g,`_`).toLowerCase()}function dv(e){return typeof e==`object`&&e?e:{}}function $(e){if(typeof e==`string`)return e}function fv(e){return typeof e==`string`||typeof e==`number`?String(e):``}var pv=[...`agent_message.agent_message_content_delta.agent_message_delta.agent_reasoning.agent_reasoning_delta.agent_reasoning_raw_content.agent_reasoning_raw_content_delta.agent_reasoning_section_break.apply_patch_approval_request.background_event.collab_agent_interaction_begin.collab_agent_interaction_end.collab_agent_spawn_begin.collab_agent_spawn_end.collab_close_begin.collab_close_end.collab_resume_begin.collab_resume_end.collab_waiting_begin.collab_waiting_end.context_compacted.deprecation_notice.dynamic_tool_call_request.dynamic_tool_call_response.elicitation_request.entered_review_mode.error.exec_approval_request.exec_command_begin.exec_command_end.exec_command_output_delta.exited_review_mode.get_history_entry_response.item_completed.item_started.list_custom_prompts_response.list_remote_skills_response.list_skills_response.mcp_list_tools_response.mcp_startup_complete.mcp_startup_update.mcp_tool_call_begin.mcp_tool_call_end.model_reroute.patch_apply_begin.patch_apply_end.plan_delta.plan_update.raw_response_item.realtime_conversation_closed.realtime_conversation_realtime.realtime_conversation_started.reasoning_content_delta.reasoning_raw_content_delta.remote_skill_downloaded.request_user_input.session_configured.shutdown_complete.skills_update_available.stream_error.task_complete.task_started.terminal_interaction.thread_name_updated.thread_rolled_back.token_count.turn_aborted.turn_diff.undo_completed.undo_started.user_message.view_image_tool_call.warning.web_search_begin.web_search_end`.split(`.`).map(e=>`codex/event/${e}`)],mv=[b.default.join(b.default.dirname(process.execPath),`__remote_agent_runtime__.cjs`),b.default.join(process.cwd(),`__remote_agent_runtime__.cjs`)];function hv(e,t){let n=gv(e);if(!n)return null;let r=JSON.parse(y.default.readFileSync(n,`utf8`)),i=typeof r.bin==`string`?r.bin:r.bin?.[t];return typeof i!=`string`||!i.trim()?null:b.default.resolve(b.default.dirname(n),i)}function gv(e){for(let t of mv)try{return(0,x.createRequire)(t).resolve(`${e}/package.json`)}catch{continue}return null}function _v(e,t){return t?{reasoningEffort:t.reasoningEffort??e.reasoningEffort,approvalPolicy:t.approvalPolicy??e.approvalPolicy,sandboxMode:t.sandboxMode??e.sandboxMode,permissionMode:t.permissionMode??e.permissionMode}:{...e}}function vv(e){let t=0;for(let n of Object.values(e))n.some(e=>e.trim().length>0)&&(t+=1);return t}var yv=5e3;async function bv(e=yv){let t=xv();return new Promise(n=>{let r=!1,i=(0,C.spawn)(t.command,[...t.args,`app-server`,`--help`],{stdio:[`ignore`,`ignore`,`ignore`],windowsHide:!0}),a=e=>{r||(r=!0,clearTimeout(o),n(e))},o=setTimeout(()=>{!i.killed&&i.exitCode===null&&i.kill(),a(!1)},e);i.on(`error`,()=>{a(!1)}),i.on(`exit`,e=>{a(e===0)})})}function xv(){let e=process.env.REMOTE_AGENT_CODEX_BIN?.trim();if(e)return{command:process.execPath,args:[b.default.resolve(e)]};try{let e=hv(`@openai/codex`,`codex`);if(e)return{command:process.execPath,args:[e]}}catch{}return{command:`codex`,args:[]}}var Sv=1e4,Cv=100,wv=2e3,Tv=new Map;async function Ev(e){return kv(e).createConnection()}async function Dv(){let e=[...Tv.values()];await Promise.allSettled(e.map(e=>e.shutdown())),Tv.clear()}function Ov(e){let t=e?.trim()||process.env.REMOTE_AGENT_CODEX_BIN?.trim();if(t)return{command:process.execPath,args:[b.default.resolve(t)]};try{let e=hv(`@openai/codex`,`codex`);if(e)return{command:process.execPath,args:[e]}}catch{}return{command:`codex`,args:[]}}function kv(e){let t=e?.trim()||process.env.REMOTE_AGENT_CODEX_BIN?.trim()||`__default__`,n=Tv.get(t);if(n)return n;let r=new Av(e);return Tv.set(t,r),r}var Av=class{constructor(e){this.codexBinOverride=e}running=null;startupPromise=null;shutdownPromise=null;async createConnection(){let e=await this.ensureRunning(),t=await Mv(e.url,()=>this.buildStartupError(e.stderrTail));return e.connections.add(t),t.onClosed(()=>{e.connections.delete(t)}),t}async shutdown(){if(this.shutdownPromise)return this.shutdownPromise;this.shutdownPromise=this.shutdownInternal(),await this.shutdownPromise}async shutdownInternal(){let e=this.running;if(this.running=null,this.startupPromise=null,!e)return;e.shuttingDown=!0;let t=[...e.connections];await Promise.allSettled(t.map(e=>e.close())),e.child.exitCode===null&&(e.child.kill(`SIGTERM`),await Iv(e.child,wv)||(e.child.kill(`SIGKILL`),await Iv(e.child,wv)))}async ensureRunning(){if(this.running&&this.running.child.exitCode===null)return this.running;if(this.startupPromise)return this.startupPromise;this.startupPromise=this.startServer();try{let e=await this.startupPromise;return this.running=e,e}finally{this.startupPromise=null}}async startServer(){let e=`ws://127.0.0.1:${await Fv()}`,t=Ov(this.codexBinOverride),n=(0,C.spawn)(t.command,[...t.args,`app-server`,`--listen`,e],{stdio:[`ignore`,`ignore`,`pipe`],windowsHide:!0}),r={child:n,url:e,stderrTail:``,connections:new Set,shuttingDown:!1};if(n.stderr.setEncoding(`utf8`),n.stderr.on(`data`,e=>{r.stderrTail=`${r.stderrTail}${e}`,r.stderrTail.length>4e3&&(r.stderrTail=r.stderrTail.slice(r.stderrTail.length-4e3))}),n.on(`exit`,(e,t)=>{if(this.running!==r)return;this.running=null;let n=r.stderrTail.trim(),i=`Codex app-server exited unexpectedly (${t?`signal=${t}`:`code=${String(e)}`})${n?`; stderr: ${n}`:``}`;if(!r.shuttingDown)for(let e of r.connections)e.fail(i);r.connections.clear()}),n.on(`error`,e=>{if(this.running!==r)return;this.running=null;let t=`Codex app-server process error: ${String(e)}`;for(let e of r.connections)e.fail(t);r.connections.clear()}),!await Pv(e,n,()=>this.buildStartupError(r.stderrTail))){let e=this.buildStartupError(r.stderrTail);throw n.exitCode===null&&(n.kill(`SIGTERM`),await Iv(n,wv)),Error(e)}return r}buildStartupError(e){let t=e.trim();return t?`Failed to start shared Codex app-server; stderr: ${t}`:`Failed to start shared Codex app-server`}},jv=class{constructor(e){this.socket=e,this.socket.on(`message`,this.handleMessage),this.socket.on(`error`,this.handleError),this.socket.on(`close`,this.handleClose)}messageListeners=new Set;failureListeners=new Set;closeListeners=new Set;closed=!1;send(e){if(this.closed)throw Error(`Codex app-server connection is closed`);this.socket.send(e)}onMessage(e){return this.messageListeners.add(e),()=>{this.messageListeners.delete(e)}}onFailure(e){return this.failureListeners.add(e),()=>{this.failureListeners.delete(e)}}onClosed(e){this.closeListeners.add(e)}fail(e){if(!this.closed){this.closed=!0;for(let t of this.failureListeners)t(e);this.dispose()}}async close(){this.closed||(this.closed=!0,this.socket.readyState<=1&&this.socket.close(1e3,`Client closing`),this.dispose())}handleMessage=e=>{if(this.closed)return;let t=Lv(e);if(t!==null)for(let e of this.messageListeners)e(t)};handleError=e=>{this.closed||this.fail(`Codex app-server WebSocket error: ${String(e)}`)};handleClose=(e,t)=>{if(this.closed){this.dispose();return}let n=typeof e==`number`?e:`unknown`,r=t.length>0?`: ${t.toString(`utf8`)}`:``;this.fail(`Codex app-server WebSocket closed (${String(n)})${r}`)};dispose(){this.socket.off(`message`,this.handleMessage),this.socket.off(`error`,this.handleError),this.socket.off(`close`,this.handleClose);for(let e of this.closeListeners)e();this.closeListeners.clear()}};async function Mv(e,t){let n=Date.now()+Sv,r=null;for(;Date.now()<n;)try{return await Nv(e,Math.max(250,n-Date.now()))}catch(e){r=e instanceof Error?e:Error(String(e)),await Rv(Cv)}throw r??Error(t())}async function Nv(e,t){let n=new nv(e);return new Promise((r,i)=>{let a=!1,o=setTimeout(()=>{s(),n.close(1e3,`Connect timeout`),i(Error(`Timed out connecting to Codex app-server at ${e}`))},t),s=()=>{o&&=(clearTimeout(o),null),n.off(`open`,c),n.off(`error`,l),n.off(`close`,u)},c=()=>{a||(a=!0,s(),r(new jv(n)))},l=e=>{a||(a=!0,s(),i(Error(String(e))))},u=(e,t)=>{if(a)return;a=!0,s();let n=typeof e==`number`?e:`unknown`,r=t.length>0?`: ${t.toString(`utf8`)}`:``;i(Error(`Connection closed before open (${String(n)})${r}`))};n.on(`open`,c),n.on(`error`,l),n.on(`close`,u)})}async function Pv(e,t,n){let r=Date.now()+Sv;for(;Date.now()<r;){if(t.exitCode!==null)throw Error(n());try{return await(await Nv(e,500)).close(),!0}catch{await Rv(Cv)}}return!1}async function Fv(){let e=(0,S.createServer)();try{await new Promise((t,n)=>{e.once(`error`,n),e.listen(0,`127.0.0.1`,()=>{t()})});let t=e.address();if(!t||typeof t==`string`)throw Error(`Failed to reserve a local port for Codex app-server`);return t.port}finally{await new Promise(t=>{e.close(()=>t())})}}async function Iv(e,t){return e.exitCode===null?new Promise(n=>{let r=!1,i=setTimeout(()=>{r||(r=!0,n(e.exitCode!==null))},t);e.once(`exit`,()=>{r||(r=!0,clearTimeout(i),n(!0))})}):!0}function Lv(e){return typeof e==`string`?e:Array.isArray(e)&&e.every(e=>ArrayBuffer.isView(e))?Buffer.concat(e.map(e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength))).toString(`utf8`):e instanceof ArrayBuffer?Buffer.from(e).toString(`utf8`):ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`utf8`):null}function Rv(e){return new Promise(t=>{setTimeout(t,e)})}var zv=3e4,Bv=8,Vv=160,Hv={name:`remote-agent-desktop-gateway`,title:`Remote Agent Desktop Gateway`,version:`0.1.0`},Uv=class e{id;provider=`codex`;providerMode=`native`;model;cwd;resumeSessionId;activeModel;activeSessionConfig;listeners=new Set;deferredEventsUntilListener=[];pendingRequests=new Map;pendingApprovals=new Map;pendingUserInputs=new Map;bufferedThreadScopedMessages=[];recentAppServerActivity=[];requestTimeoutMs;connection;logger;nextRequestId=1;closed=!1;threadId;threadTitle;activeTurnId;turnInProgress=!1;titleReadInFlight=!1;closePromise=null;unsubscribeMessage=null;unsubscribeFailure=null;static async create(t,n={}){let r=new e(t,n.createConnection?await n.createConnection():await Ev(),n.requestTimeoutMs??zv);try{return await r.bootstrap(),r}catch(e){throw await r.close(),e}}constructor(e,t,n){this.id=e.sessionId,this.model=e.model,this.activeModel=e.model,this.cwd=e.cwd,this.activeSessionConfig={...e.sessionConfig??{}},this.resumeSessionId=e.resumeSessionId,this.requestTimeoutMs=n,this.connection=t,this.logger=e.logger,this.bindConnection()}onEvent(e){let t=this.listeners.size===0&&this.deferredEventsUntilListener.length>0;if(this.listeners.add(e),t){let t=this.deferredEventsUntilListener.splice(0);for(let n of t)e(n)}return()=>{this.listeners.delete(e)}}getNativeSessionId(){return this.threadId}async sendInput(e,t){if(this.ensureOpen(),!this.threadId)throw Error(`Codex app-server thread is not initialized`);if(this.turnInProgress)throw Error(`A turn is already in progress`);this.turnInProgress=!0;try{let n=t?.model??this.activeModel,r=_v(this.activeSessionConfig,t?.sessionConfig);if(this.hasThreadOverrideChanges(n,r)){let e=await this.resumeThread(this.threadId,{model:n,sessionConfig:r});e&&(this.threadId=e)}this.activeModel=n,this.activeSessionConfig=r;let i=[{type:`text`,text:e,text_elements:[]}],a=Qv(this.activeSessionConfig.reasoningEffort),o,s=$v(t?.mode,n,a);try{o=await this.sendRequest(`turn/start`,{threadId:this.threadId,input:i,effort:a,collaborationMode:s})}catch(e){if(!(a===`minimal`&&ey(e)))throw e;this.emit({type:`status.progress`,message:`Retrying turn/start with reasoning effort 'low' because 'minimal' is incompatible with web_search.`,originalMethod:`turn/start`,params:{requested_effort:a,retry_effort:`low`}}),o=await this.sendRequest(`turn/start`,{threadId:this.threadId,input:i,effort:`low`,collaborationMode:$v(t?.mode,n,`low`)})}let c=$(o.turn?.id);c&&(this.activeTurnId=c)}catch(e){throw this.turnInProgress=!1,e}}async interrupt(){if(this.ensureOpen(),!this.threadId||!this.activeTurnId)return;let e={threadId:this.threadId,turnId:this.activeTurnId};await this.sendRequest(`turn/interrupt`,e)}async close(){if(this.closePromise)return this.closePromise;this.closePromise=this.closeInternal(),await this.closePromise}async respondToolPermission(e,t,n){this.ensureOpen();let r=this.pendingApprovals.get(e);if(!r)throw Error(`Unknown approval request: ${e}`);let i=t===`allow`?`accept`:`decline`;switch(r.method){case`item/commandExecution/requestApproval`:case`execCommandApproval`:{let e={decision:i};this.sendResponse(r.rpcId,e);break}case`item/fileChange/requestApproval`:case`applyPatchApproval`:{let e={decision:i};this.sendResponse(r.rpcId,e);break}default:this.sendErrorResponse(r.rpcId,-32601,`Unsupported approval method: ${r.method}`)}this.pendingApprovals.delete(e),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n,nativeDecision:i,approvalMethod:r.method,approvalKind:r.kind})}async respondUserInput(e,t){this.ensureOpen();let n=this.pendingUserInputs.get(e);if(!n)throw Error(`Unknown user input request: ${e}`);let r=ny(t),i={answers:Object.fromEntries(Object.entries(r).map(([e,t])=>[e,{answers:t}]))};this.sendResponse(n.rpcId,i),this.pendingUserInputs.delete(e),this.emit({type:`user.input.resolved`,requestId:e,status:`submitted`,answeredCount:vv(r),inputMethod:n.method})}bindConnection(){this.unsubscribeMessage=this.connection.onMessage(e=>{this.handleIncomingMessage(e)}),this.unsubscribeFailure=this.connection.onFailure(e=>{this.handleConnectionFailure(e)})}async bootstrap(){let e={clientInfo:Hv,capabilities:{experimentalApi:!0,optOutNotificationMethods:pv}};await this.sendRequest(`initialize`,e),this.sendNotification(`initialized`);let t=await this.sendRequest(`account/read`,{refreshToken:!1});if(t.requiresOpenaiAuth&&t.account===null)throw Error("Codex app-server requires OpenAI authentication. Please sign in with `codex` on this machine first.");let n=this.resumeSessionId?await this.resumeThread(this.resumeSessionId):await this.startThread();if(!n)throw Error(`Codex app-server did not return a thread id`);this.threadId=n}async startThread(){let e={model:this.activeModel??null,cwd:this.cwd??null,approvalPolicy:this.activeSessionConfig.approvalPolicy??null,sandbox:this.activeSessionConfig.sandboxMode??null,experimentalRawEvents:!1,persistExtendedHistory:!1};return $((await this.sendRequest(`thread/start`,e)).thread?.id)}async resumeThread(e,t){let n=t?.model??this.activeModel,r=t?.sessionConfig??this.activeSessionConfig,i={threadId:e,model:n??null,cwd:this.cwd??null,approvalPolicy:r.approvalPolicy??null,sandbox:r.sandboxMode??null,persistExtendedHistory:!1};return $((await this.sendRequest(`thread/resume`,i)).thread?.id)}hasThreadOverrideChanges(e,t){return this.activeModel!==e||this.activeSessionConfig.approvalPolicy!==t.approvalPolicy||this.activeSessionConfig.sandboxMode!==t.sandboxMode}async closeInternal(){if(!this.closed)try{await this.interrupt()}catch{}this.closed=!0,this.turnInProgress=!1,this.activeTurnId=void 0;for(let[e,t]of this.pendingApprovals.entries())this.emit({type:`tool.permission.resolved`,requestId:e,decision:`deny`,reason:`Session closed before approval response`,nativeDecision:`decline`,approvalMethod:t.method,approvalKind:t.kind});this.pendingApprovals.clear();for(let[e,t]of this.pendingUserInputs.entries())this.emit({type:`user.input.resolved`,requestId:e,status:`expired`,answeredCount:0,reason:`Session closed before user input response`,inputMethod:t.method});this.pendingUserInputs.clear(),this.rejectPendingRequests(Error(`Session ${this.id} is closed`)),this.unsubscribeMessage?.(),this.unsubscribeFailure?.(),this.unsubscribeMessage=null,this.unsubscribeFailure=null,await this.connection.close()}handleIncomingMessage(e){let t;try{t=JSON.parse(e)}catch{this.recordAppServerActivity({at:new Date().toISOString(),direction:`incoming`,messageKind:`parse_error`,payloadLength:e.length,preview:Yv(e)}),this.emitNativeRaw({parse_error:!0,line:e}),this.emit({type:`status.progress`,message:`Received non-JSON message from codex app-server`,line:e});return}let n=$(t.method),r=Object.prototype.hasOwnProperty.call(t,`id`);if(n&&r){let r={method:n,id:t.id,params:t.params};this.recordIncomingAppServerActivity(t,e.length);let i=this.extractThreadIdFromServerRequest(r),a=this.classifyThreadScopedMessage(i);if(a===`buffer`&&i){this.bufferedThreadScopedMessages.push({kind:`serverRequest`,threadId:i,message:t,payload:r});return}if(a===`ignore`)return;this.emitNativeRaw({message:t}),this.handleServerRequest(r);return}if(n){let r={method:n,params:t.params};this.recordIncomingAppServerActivity(t,e.length);let i=this.extractThreadIdFromNotification(r),a=this.classifyThreadScopedMessage(i);if(a===`buffer`&&i){this.bufferedThreadScopedMessages.push({kind:`notification`,threadId:i,message:t,payload:r});return}if(a===`ignore`)return;this.emitNativeRaw({message:t}),this.handleNotification(r);return}if(r){let n=this.getPendingRequest(t.id);if(!n)return;this.recordIncomingAppServerActivity(t,e.length,n.method);let r=this.extractThreadIdFromResponse(n.method,t.result);r&&this.setThreadIdAndFlushBuffered(r),this.emitNativeRaw({message:t}),this.handleResponse(t),!r&&this.isThreadBindingMethod(n.method)&&!this.hasPendingThreadBindingRequest()&&(this.bufferedThreadScopedMessages.length=0)}}handleResponse(e){let t=fv(e.id),n=this.pendingRequests.get(t);if(n){if(this.pendingRequests.delete(t),clearTimeout(n.timeoutId),e.error!==void 0){let t=dv(e.error),r=$(t.message)??JSON.stringify(t);n.reject(Error(`Codex app-server request failed (${n.method}): ${r}`));return}n.resolve(e.result)}}handleServerRequest(e){switch(e.method){case`item/commandExecution/requestApproval`:this.registerApprovalRequest(e.id,e.method,`command`,e.params);return;case`item/fileChange/requestApproval`:this.registerApprovalRequest(e.id,e.method,`file`,e.params);return;case`execCommandApproval`:this.registerApprovalRequest(e.id,e.method,`command`,e.params);return;case`applyPatchApproval`:this.registerApprovalRequest(e.id,e.method,`file`,e.params);return;case`item/tool/requestUserInput`:this.registerUserInputRequest(e.id,e.method,e.params);return;default:this.sendErrorResponse(e.id,-32601,`Unsupported server request: ${e.method}`)}}registerApprovalRequest(e,t,n,r){let i=dv(r),a=$(i.threadId);if(!this.shouldHandleThreadScopedMessage(a))return;let o=`req_${ag(8)}`;this.pendingApprovals.set(o,{rpcId:e,method:t,kind:n}),this.emit({type:`tool.permission.requested`,requestId:o,toolName:n===`command`?`command_execution`:`file_change`,reason:$(i.reason),threadId:a,turnId:$(i.turnId),itemId:$(i.itemId),approvalMethod:t,rawParams:lv(i)})}registerUserInputRequest(e,t,n){let r=$(n.threadId);if(!this.shouldHandleThreadScopedMessage(r))return;let i=`req_${ag(8)}`;this.pendingUserInputs.set(i,{rpcId:e,method:t});let a=Array.isArray(n.questions)?n.questions.map(ty).filter(e=>e!==null):[];this.emit({type:`user.input.requested`,requestId:i,threadId:n.threadId,turnId:n.turnId,itemId:n.itemId,questions:a,inputMethod:t,rawParams:lv(n)})}handleNotification(e){switch(e.method){case`thread/started`:{let t=e.params,n=$(t.thread?.id);if(!this.shouldHandleThreadScopedMessage(n))return;this.emitThreadTitleUpdated($(t.thread?.preview),`codex.thread_preview`,{thread_id:n??this.threadId}),this.emit({type:`thread.started`,thread_id:n,thread:lv(t.thread)});return}case`thread/name/updated`:{let t=e.params,n=$(t.threadId);if(!this.shouldHandleThreadScopedMessage(n))return;this.emitThreadTitleUpdated($(t.threadName),`codex.thread_name_updated`,{thread_id:n??this.threadId});return}case`turn/started`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage($(t.threadId)))return;let n=$(t.turn?.id);n&&(this.activeTurnId=n),this.turnInProgress=!0,this.emit({type:`turn.started`,turn:lv(t.turn)});return}case`turn/completed`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage($(t.threadId)))return;let n=$(t.turn?.status);if(this.turnInProgress=!1,this.activeTurnId=void 0,n===`failed`){this.emit({type:`turn.failed`,status:n,turn:lv(t.turn),error:lv(t.turn?.error??{})});return}this.emit({type:`turn.completed`,status:n,turn:lv(t.turn)}),this.tryEmitTitleFromThreadRead();return}case`item/started`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage($(t.threadId)))return;this.emit({type:`item.started`,item:sv(t.item)});return}case`item/completed`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage($(t.threadId)))return;this.emit({type:`item.completed`,item:sv(t.item)});return}case`item/agentMessage/delta`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage($(t.threadId)))return;this.emit({type:`item.updated`,item:{id:t.itemId,type:`agent_message`,text:t.delta,original_method:e.method,payload:{delta:t.delta}}});return}case`item/commandExecution/outputDelta`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage($(t.threadId)))return;this.emit({type:`item.updated`,item:{id:t.itemId,type:`command_execution`,aggregated_output:t.delta,output_delta:t.delta}});return}case`item/fileChange/outputDelta`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage($(t.threadId)))return;this.emit({type:`item.updated`,item:{id:t.itemId,type:`file_change`,output_delta:t.delta}});return}case`item/plan/delta`:case`item/reasoning/summaryTextDelta`:case`item/reasoning/summaryPartAdded`:case`item/reasoning/textDelta`:{let t=dv(e.params);if(!this.shouldHandleThreadScopedMessage($(t.threadId)))return;this.emit({type:`item.updated`,item:{id:$(t.itemId),type:e.method.startsWith(`item/plan`)?`plan`:`reasoning`,text:$(t.delta)??$(t.text)??``,original_method:e.method,payload:lv(t)}});return}case`error`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage($(t.threadId)))return;this.emit({type:`error`,message:$(t.error?.message)??`Codex app-server error`,error:lv(t.error),will_retry:t.willRetry===!0,thread_id:$(t.threadId),turn_id:$(t.turnId)});return}default:return}}async sendRequest(e,t){this.ensureOpen();let n=this.nextRequestId;this.nextRequestId+=1;let r={method:e,id:n,params:t},i=fv(n),a=new Promise((t,n)=>{let r=setTimeout(()=>{this.pendingRequests.delete(i),n(Error(`Codex app-server request timed out: ${e}`))},this.requestTimeoutMs);this.pendingRequests.set(i,{method:e,timeoutId:r,resolve:t,reject:n})});return this.writeMessage(r),await a}sendNotification(e){let t={method:e};this.writeMessage(t)}sendResponse(e,t){this.writeMessage({id:e,result:t})}sendErrorResponse(e,t,n){this.writeMessage({id:e,error:{code:t,message:n}})}writeMessage(e){this.ensureOpen();let t=JSON.stringify(e);this.recordOutgoingAppServerActivity(e,t.length),this.connection.send(t)}emit(e){if(this.listeners.size===0&&e.type!==`native.raw`){this.deferredEventsUntilListener.push(e);return}for(let t of this.listeners)t(e)}emitThreadTitleUpdated(e,t,n={}){let r=Wv(e);!r||r===this.threadTitle||(this.threadTitle=r,this.emit({type:`thread.title.updated`,title:r,source:t,...n}))}async tryEmitTitleFromThreadRead(){if(!(!this.threadId||this.threadTitle||this.closed||this.titleReadInFlight)){this.titleReadInFlight=!0;try{let e=await this.sendRequest(`thread/read`,{threadId:this.threadId,includeTurns:!1});this.emitThreadTitleUpdated($(e.thread?.preview),`codex.thread_read_preview`,{thread_id:this.threadId})}catch{}finally{this.titleReadInFlight=!1}}}handleConnectionFailure(e){if(this.closed)return;let t=Xv(e),n=Zv(e),r=this.recentAppServerActivity[this.recentAppServerActivity.length-1],i=this.threadId,a=this.activeTurnId;this.log(`error`,`codex app-server websocket session failed`,{failureMessage:e,failureCloseCode:t,failureCloseReason:n,pendingRequestCount:this.pendingRequests.size,pendingRequestMethods:[...new Set([...this.pendingRequests.values()].map(e=>e.method))],pendingApprovalCount:this.pendingApprovals.size,pendingUserInputCount:this.pendingUserInputs.size,bufferedThreadScopedMessageCount:this.bufferedThreadScopedMessages.length,lastAppServerActivity:r,lastAppServerActivityMethod:r?.method,lastAppServerActivityThreadId:r?.threadId,lastAppServerActivityTurnId:r?.turnId,lastAppServerActivityItemId:r?.itemId,lastAppServerActivityDeltaLength:r?.deltaLength,lastAppServerActivityPreview:r?.preview,recentAppServerActivity:[...this.recentAppServerActivity]}),this.closed=!0,this.turnInProgress=!1,this.activeTurnId=void 0,this.rejectPendingRequests(Error(e));for(let[e,t]of this.pendingApprovals.entries())this.emit({type:`tool.permission.resolved`,requestId:e,decision:`deny`,reason:`Session terminated before approval response`,nativeDecision:`decline`,approvalMethod:t.method,approvalKind:t.kind});this.pendingApprovals.clear();for(let e of this.pendingUserInputs.keys())this.emit({type:`user.input.resolved`,requestId:e,status:`expired`,answeredCount:0,reason:`Session terminated before user input response`});this.pendingUserInputs.clear(),this.emit({type:`error.runtime`,message:e,source:`codex.app_server.websocket`,...t===void 0?{}:{close_code:t},...n?{close_reason:n}:{},...i?{thread_id:i}:{},...a?{turn_id:a}:{}})}rejectPendingRequests(e){for(let t of this.pendingRequests.values())clearTimeout(t.timeoutId),t.reject(e);this.pendingRequests.clear()}emitNativeRaw(e){this.emit({type:`native.raw`,source:`codex.app_server`,...e})}getPendingRequest(e){return this.pendingRequests.get(fv(e))}classifyThreadScopedMessage(e){return!e||this.threadId&&e===this.threadId?`handle`:this.hasPendingThreadBindingRequest()?`buffer`:`ignore`}extractThreadIdFromServerRequest(e){return $(dv(e.params).threadId)}extractThreadIdFromNotification(e){let t=dv(e.params);return $(t.threadId)||$(dv(t.thread).id)}extractThreadIdFromResponse(e,t){if(this.isThreadBindingMethod(e))return $(dv(dv(t).thread).id)}hasPendingThreadBindingRequest(){for(let e of this.pendingRequests.values())if(this.isThreadBindingMethod(e.method))return!0;return!1}isThreadBindingMethod(e){return e===`thread/start`||e===`thread/resume`}setThreadIdAndFlushBuffered(e){if(this.threadId=e,this.bufferedThreadScopedMessages.length===0)return;let t=this.bufferedThreadScopedMessages.splice(0);for(let n of t)n.threadId===e&&(this.emitNativeRaw({message:n.message}),n.kind===`serverRequest`?this.handleServerRequest(n.payload):this.handleNotification(n.payload))}shouldHandleThreadScopedMessage(e){return!!e&&e===this.threadId}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}log(e,t,n={}){if(!this.logger)return;let r={provider:this.provider,providerMode:this.providerMode,sessionId:this.id,threadId:this.threadId,activeTurnId:this.activeTurnId,model:this.activeModel??this.model,cwd:this.cwd,...n};if(e===`info`){this.logger.info?.(r,t);return}if(e===`warn`){this.logger.warn?.(r,t);return}this.logger.error?.(r,t)}recordIncomingAppServerActivity(e,t,n){this.recordAppServerActivity(Gv({direction:`incoming`,message:e,payloadLength:t,responseMethod:n}))}recordOutgoingAppServerActivity(e,t){this.recordAppServerActivity(Gv({direction:`outgoing`,message:e,payloadLength:t}))}recordAppServerActivity(e){this.recentAppServerActivity.push(e),this.recentAppServerActivity.length>Bv&&this.recentAppServerActivity.splice(0,this.recentAppServerActivity.length-Bv)}};function Wv(e){if(typeof e!=`string`)return;let t=e.replace(/\s+/g,` `).trim();if(t)return t}function Gv(e){let t=$(e.message.method),n=Object.prototype.hasOwnProperty.call(e.message,`id`),r=dv(e.message.error),i=qv(t,t?e.message.params:e.message.error??e.message.result);return{at:new Date().toISOString(),direction:e.direction,messageKind:Kv(t,n,e.direction),method:t,requestId:n?fv(e.message.id):void 0,requestMethod:e.responseMethod,threadId:i.threadId,turnId:i.turnId,itemId:i.itemId,payloadLength:e.payloadLength,deltaLength:i.deltaLength,preview:i.preview??Yv($(r.message))}}function Kv(e,t,n){return e&&t?n===`incoming`?`server_request`:`request`:e?`notification`:`response`}function qv(e,t){let n=dv(t),r=dv(n.thread),i=dv(n.turn),a=dv(n.item),o=$(n.delta)??$(n.text),s=Jv(e,n,o);return{threadId:$(n.threadId)??$(r.id),turnId:$(n.turnId)??$(i.id),itemId:$(n.itemId)??$(a.id),deltaLength:typeof o==`string`?o.length:void 0,preview:Yv(s)}}function Jv(e,t,n){if(e===`item/commandExecution/outputDelta`||e===`item/fileChange/outputDelta`||e===`item/agentMessage/delta`||e===`item/plan/delta`||e===`item/reasoning/summaryTextDelta`||e===`item/reasoning/textDelta`)return n;if(e===`error`)return $(dv(t.error).message)??$(t.message)}function Yv(e){if(typeof e!=`string`)return;let t=e.replace(/\s+/g,` `).trim();if(t)return t.length<=Vv?t:`${t.slice(0,Vv)}...`}function Xv(e){let t=/WebSocket closed \((\d+)\)/.exec(e);if(!t)return;let n=Number.parseInt(t[1]??``,10);return Number.isFinite(n)?n:void 0}function Zv(e){return/WebSocket closed \(\d+\): (.+)$/.exec(e)?.[1]}function Qv(e){return e?e===`max`?`xhigh`:e:null}function $v(e,t,n){if(e===`plan`){if(!t)throw Error(`Codex plan mode requires a resolved model.`);return{mode:`plan`,settings:{model:t,reasoning_effort:n,developer_instructions:null}}}}function ey(e){return e instanceof Error?/reasoning\.effort ['"]minimal['"]/i.test(e.message)&&/web_search/i.test(e.message):!1}function ty(e){let t=dv(e),n=$(t.id),r=$(t.header),i=$(t.question),a=t.options;if(!n||!r||!i)return null;let o=Array.isArray(a)?a.map(e=>{let t=dv(e),n=$(t.label),r=$(t.description)??n,i=$(t.markdown);return n?{label:n,description:r,...i?{markdown:i}:{}}:null}).filter(e=>e!==null):null;return{id:n,header:r,question:i,multiSelect:t.multiSelect===!0,isOther:!!t.isOther,isSecret:!!t.isSecret,options:o}}function ny(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Array.from(new Set(t.map(e=>e.trim()).filter(Boolean)))]))}var ry=class{constructor(e,t,n={}){this.preferNative=e,this.requireNative=t,this.runtime=n}provider=`codex`;mockAdapter=new ov(`codex`);async isNativeAvailable(){try{return this.runtime.probeAvailability?await this.runtime.probeAvailability():await bv()}catch{return!1}}async createSession(e){if(this.requireNative&&!this.preferNative)throw Error(`Native Codex provider is required but ENABLE_NATIVE_PROVIDERS is disabled`);if(!this.preferNative)return this.mockAdapter.createSession(e);let t=this.runtime.createNativeSession??Uv.create;try{return await t(e)}catch(t){if(this.requireNative)throw t;return console.warn(`[provider-adapters] codex native fallback to mock: ${String(t)}`),this.mockAdapter.createSession(e)}}},iy=15e3,ay={name:`remote-agent-desktop-gateway`,title:`Remote Agent Desktop Gateway`,version:`0.1.0`},oy=class{constructor(e,t={}){this.transport=e,this.requestTimeoutMs=t.requestTimeoutMs??iy,this.bindTransport()}pendingRequests=new Map;requestTimeoutMs;nextRequestId=1;closed=!1;unsubscribeMessage=null;unsubscribeFailure=null;async bootstrap(){let e={clientInfo:ay,capabilities:{experimentalApi:!1,optOutNotificationMethods:pv}};await this.sendRequest(`initialize`,e),this.sendNotification(`initialized`);let t=await this.sendRequest(`account/read`,{refreshToken:!1});if(t.requiresOpenaiAuth&&t.account===null)throw Error("Codex app-server requires OpenAI authentication. Please sign in with `codex` on this machine first.")}async close(){this.closed||(this.closed=!0,this.rejectPendingRequests(Error(`Codex RPC client closed`)),this.unsubscribeMessage?.(),this.unsubscribeFailure?.(),this.unsubscribeMessage=null,this.unsubscribeFailure=null,await this.transport.close())}async sendRequest(e,t){this.ensureOpen();let n=this.nextRequestId;this.nextRequestId+=1;let r=fv(n),i=new Promise((t,n)=>{let i=setTimeout(()=>{this.pendingRequests.delete(r),n(Error(`Codex app-server request timed out: ${e}`))},this.requestTimeoutMs);this.pendingRequests.set(r,{timeoutId:i,resolve:t,reject:n})});return this.writeMessage({method:e,id:n,params:t}),await i}bindTransport(){this.unsubscribeMessage=this.transport.onMessage(e=>{this.handleIncomingMessage(e)}),this.unsubscribeFailure=this.transport.onFailure(e=>{this.handleTransportFailure(e)})}sendNotification(e){this.writeMessage({method:e})}writeMessage(e){this.ensureOpen(),this.transport.send(JSON.stringify(e))}ensureOpen(){if(this.closed)throw Error(`Codex RPC client is closed`)}handleIncomingMessage(e){let t;try{t=JSON.parse(e)}catch{return}let n=Object.prototype.hasOwnProperty.call(t,`id`),r=$(t.method);if(n&&r){let e=t.id;this.writeMessage({id:e,error:{code:-32601,message:`Unsupported server request: ${r}`}});return}n&&this.handleResponse(t)}handleResponse(e){let t=fv(e.id),n=this.pendingRequests.get(t);if(n){if(this.pendingRequests.delete(t),clearTimeout(n.timeoutId),e.error!==void 0){let t=dv(e.error),r=$(t.message)??JSON.stringify(t);n.reject(Error(`Codex app-server request failed: ${r}`));return}n.resolve(e.result)}}handleTransportFailure(e){this.closed||(this.closed=!0,this.rejectPendingRequests(Error(e)))}rejectPendingRequests(e){for(let[t,n]of this.pendingRequests.entries())clearTimeout(n.timeoutId),n.reject(e),this.pendingRequests.delete(t)}};async function sy(e,t={}){let n=new oy(await cy(t),t);try{return await n.bootstrap(),await e(n)}finally{await n.close()}}async function cy(e){return e.spawnProcess?new uy(e.spawnProcess()):new ly(await Ev(e.codexBinOverride))}var ly=class{constructor(e){this.connection=e}send(e){this.connection.send(e)}onMessage(e){return this.connection.onMessage(e)}onFailure(e){return this.connection.onFailure(e)}async close(){await this.connection.close()}},uy=class{constructor(e){this.process=e,this.bindProcess()}messageListeners=new Set;failureListeners=new Set;stdoutBuffer=``;stderrTail=``;closed=!1;send(e){if(this.closed)throw Error(`Codex app-server process transport is closed`);this.process.stdin.write(`${e}
|
|
474
|
+
`});return t?n.pop():n.push(n.pop().slice(0,-1)),n}var W_=class{async listDirectories(e,t,n=200){let r=await d.default.realpath(p.default.resolve(e));return Q_(r,await X_(r,t),n)}async listDirectoriesUnrestricted(e,t=200,n=f.default.homedir()){let r=await Z_(e,n),i=p.default.parse(r).root;return Q_(i,r,t)}async readFile(e,t){let{absolutePath:n,normalizedPath:r}=await G_(e,t);return{path:r,absolutePath:n,content:await d.default.readFile(n,`utf8`)}}async diffFile(e,t,n=``){let{absolutePath:r,normalizedPath:i}=await G_(e,t),a=await d.default.readFile(r,`utf8`);return{path:i,absolutePath:r,diff:H_(i,i,n,a,`base`,`current`),currentContent:a}}async listTree(e,t=`.`,n=500){let r=await d.default.realpath(p.default.resolve(e)),i=K_(t),a=await q_(r,i),o=[];async function s(e,t){let r=await d.default.readdir(e,{withFileTypes:!0});for(let i of r){if(o.length>=n)return;let r=p.default.join(e,i.name),a=t?p.default.join(t,i.name):i.name;i.isSymbolicLink()||(i.isDirectory()?(o.push({path:a,kind:`dir`}),await s(r,a)):o.push({path:a,kind:`file`}))}}return await s(a,``),{root:i,entries:o}}};async function G_(e,t){let n=await d.default.realpath(p.default.resolve(e)),r=K_(t),i=await q_(n,r),a=await d.default.realpath(i);return J_(n,a,r),{absolutePath:a,normalizedPath:r}}function K_(e){let t=e.trim();if(!t)throw Error(`Path is required`);return t}async function q_(e,t){if(p.default.isAbsolute(t))throw Error(`Path must be relative to project root: ${t}`);let n=p.default.resolve(e,t);return J_(e,n,t),n}function J_(e,t,n){let r=Y_(e),i=Y_(t);if(t!==e&&!i.startsWith(r))throw Error(`Path outside project root is not allowed: ${n}`)}function Y_(e){return e.endsWith(p.default.sep)?e:`${e}${p.default.sep}`}async function X_(e,t){let n=t?.trim(),r=n?p.default.isAbsolute(n)?p.default.resolve(n):p.default.resolve(e,n):e;J_(e,r,n??`.`);let i=await d.default.realpath(r);if(J_(e,i,n??`.`),!(await d.default.stat(i)).isDirectory())throw Error(`Path is not a directory: ${i}`);return i}async function Z_(e,t=f.default.homedir()){let n=e?.trim(),r=p.default.resolve(t),i=n?p.default.isAbsolute(n)?p.default.resolve(n):p.default.resolve(r,n):r,a=await d.default.realpath(i);if(!(await d.default.stat(a)).isDirectory())throw Error(`Path is not a directory: ${a}`);return a}async function Q_(e,t,n){let r=(await d.default.readdir(t,{withFileTypes:!0})).filter(e=>e.isDirectory()&&!e.isSymbolicLink()).sort((e,t)=>e.name.localeCompare(t.name)).slice(0,Math.max(1,n)).map(e=>({name:e.name,path:p.default.join(t,e.name)}));return{rootPath:e,currentPath:t,parentPath:t===e?null:p.default.dirname(t),directories:r}}var $_=class{indexPath;projects=new Map;projectByPath=new Map;ready;writeQueue=Promise.resolve();constructor(e){this.baseDir=e,this.indexPath=p.default.join(e,`project-index.json`),this.ready=this.loadFromDisk()}async upsertByPath(e,t){await this.ready;let n=await tv(e),r=this.projectByPath.get(n),i=new Date().toISOString(),a=ev(t)??(p.default.basename(n)||n),o=r?{...r,title:ev(t)??r.title,updatedAt:i}:{id:`proj_${og(12)}`,title:a,path:n,createdAt:i,updatedAt:i};return this.projects.set(o.id,o),this.projectByPath.set(n,o),await this.enqueueWrite(async()=>{await this.persistIndex()}),o}async list(){return await this.ready,[...this.projects.values()].sort((e,t)=>e.title.localeCompare(t.title))}async getById(e){return await this.ready,this.projects.get(e)}async getByPath(e){await this.ready;let t=await tv(e);return this.projectByPath.get(t)}async remove(e){await this.ready;let t=this.projects.get(e);return t?(this.projects.delete(e),this.projectByPath.delete(t.path),await this.enqueueWrite(async()=>{await this.persistIndex()}),!0):!1}async loadFromDisk(){await d.default.mkdir(this.baseDir,{recursive:!0});try{let e=await d.default.readFile(this.indexPath,`utf8`),t=JSON.parse(e);if(t.v!==1||!Array.isArray(t.projects))return;for(let e of t.projects)typeof e?.id!=`string`||typeof e?.title!=`string`||typeof e?.path!=`string`||typeof e?.createdAt!=`string`||typeof e?.updatedAt!=`string`||(this.projects.set(e.id,e),this.projectByPath.set(e.path,e))}catch(e){if(e.code!==`ENOENT`)throw e}}async persistIndex(){await d.default.mkdir(this.baseDir,{recursive:!0});let e={v:1,projects:[...this.projects.values()].sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))};await d.default.writeFile(this.indexPath,`${JSON.stringify(e,null,2)}\n`,`utf8`)}enqueueWrite(e){return this.writeQueue=this.writeQueue.then(e,e),this.writeQueue}};function ev(e){if(typeof e==`string`)return e.replace(/\s+/g,` `).trim()||void 0}async function tv(e){if(!p.default.isAbsolute(e))throw Error(`Project path must be absolute: ${e}`);let t=p.default.resolve(e),n;try{n=await d.default.stat(t)}catch(e){throw Error(`Project path does not exist: ${t}; ${String(e)}`)}if(!n.isDirectory())throw Error(`Project path is not a directory: ${t}`);return d.default.realpath(t)}Th(),bh(),xh();var nv=c(wh(),1);Dh();var rv=nv.default,iv=120,av=class{id;provider;providerMode=`mock`;model;listeners=new Set;pendingApprovals=new Map;closed=!1;constructor(e,t){this.id=t.sessionId,this.provider=e,this.model=t.model}onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async sendInput(e,t){if(this.ensureOpen(),this.emit({type:`turn.started`,text:e}),this.emit({type:`item.started`,itemType:`assistant.message`,text:``}),this.requiresApproval(e)){let t=`req_${og(8)}`;this.pendingApprovals.set(t,{input:e}),this.emit({type:`tool.permission.requested`,requestId:t,toolName:`fs.read`,args:{path:`README.md`},reason:`Mock adapter requires approval for tool-like prompts.`}),this.emit({type:`status.progress`,message:`Waiting for tool approval`});return}await this.streamAssistantText(`(${this.provider}) response: ${e}`)}async interrupt(){this.ensureOpen(),this.emit({type:`turn.failed`,reason:`Interrupted by user`})}async close(){this.closed||=!0}async respondToolPermission(e,t,n){this.ensureOpen();let r=this.pendingApprovals.get(e);if(!r)throw Error(`Unknown tool approval request: ${e}`);if(this.pendingApprovals.delete(e),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n}),t===`deny`){this.emit({type:`turn.failed`,reason:n??`Tool request denied`});return}await this.streamAssistantText(`Tool approved. Proceeded with request derived from: ${r.input}`)}requiresApproval(e){return/tool|approve|permission|read file|diff/i.test(e)}async streamAssistantText(e){let t=e.split(/\s+/).filter(Boolean),n=``;for(let e of t)n=`${n} ${e}`.trim(),this.emit({type:`item.updated`,text:n}),await ov(iv);this.emit({type:`item.completed`,text:n}),this.emit({type:`turn.completed`,text:n})}emit(e){for(let t of this.listeners)t(e)}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}};function ov(e){return new Promise(t=>setTimeout(t,e))}var sv=class{provider;constructor(e){this.provider=e}async isNativeAvailable(){return!1}async createSession(e){return new av(this.provider,e)}};function cv(e){let t=fv(uv(e)),n=Q(t.type);return n&&(t.type=lv(n)),t}function lv(e){switch(e){case`userMessage`:return`user_message`;case`agentMessage`:return`agent_message`;case`commandExecution`:return`command_execution`;case`fileChange`:return`file_change`;case`mcpToolCall`:return`mcp_tool_call`;case`collabAgentToolCall`:return`collab_tool_call`;case`webSearch`:return`web_search`;case`enteredReviewMode`:return`entered_review_mode`;case`exitedReviewMode`:return`exited_review_mode`;case`contextCompaction`:return`context_compaction`;default:return dv(e)}}function uv(e){if(Array.isArray(e))return e.map(e=>uv(e));if(typeof e==`object`&&e){let t={};for(let[n,r]of Object.entries(e))t[dv(n)]=uv(r);return t}return e}function dv(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1_$2`).replace(/[\-\s/]+/g,`_`).toLowerCase()}function fv(e){return typeof e==`object`&&e?e:{}}function Q(e){if(typeof e==`string`)return e}function pv(e){return typeof e==`string`||typeof e==`number`?String(e):``}var mv=[...`agent_message.agent_message_content_delta.agent_message_delta.agent_reasoning.agent_reasoning_delta.agent_reasoning_raw_content.agent_reasoning_raw_content_delta.agent_reasoning_section_break.apply_patch_approval_request.background_event.collab_agent_interaction_begin.collab_agent_interaction_end.collab_agent_spawn_begin.collab_agent_spawn_end.collab_close_begin.collab_close_end.collab_resume_begin.collab_resume_end.collab_waiting_begin.collab_waiting_end.context_compacted.deprecation_notice.dynamic_tool_call_request.dynamic_tool_call_response.elicitation_request.entered_review_mode.error.exec_approval_request.exec_command_begin.exec_command_end.exec_command_output_delta.exited_review_mode.get_history_entry_response.item_completed.item_started.list_custom_prompts_response.list_remote_skills_response.list_skills_response.mcp_list_tools_response.mcp_startup_complete.mcp_startup_update.mcp_tool_call_begin.mcp_tool_call_end.model_reroute.patch_apply_begin.patch_apply_end.plan_delta.plan_update.raw_response_item.realtime_conversation_closed.realtime_conversation_realtime.realtime_conversation_started.reasoning_content_delta.reasoning_raw_content_delta.remote_skill_downloaded.request_user_input.session_configured.shutdown_complete.skills_update_available.stream_error.task_complete.task_started.terminal_interaction.thread_name_updated.thread_rolled_back.token_count.turn_aborted.turn_diff.undo_completed.undo_started.user_message.view_image_tool_call.warning.web_search_begin.web_search_end`.split(`.`).map(e=>`codex/event/${e}`)],hv=[b.default.join(b.default.dirname(process.execPath),`__remote_agent_runtime__.cjs`),b.default.join(process.cwd(),`__remote_agent_runtime__.cjs`)];function gv(e,t){let n=_v(e);if(!n)return null;let r=JSON.parse(y.default.readFileSync(n,`utf8`)),i=typeof r.bin==`string`?r.bin:r.bin?.[t];return typeof i!=`string`||!i.trim()?null:b.default.resolve(b.default.dirname(n),i)}function _v(e){for(let t of hv)try{return(0,x.createRequire)(t).resolve(`${e}/package.json`)}catch{continue}return null}function vv(e,t){return t?{reasoningEffort:t.reasoningEffort??e.reasoningEffort,approvalPolicy:t.approvalPolicy??e.approvalPolicy,sandboxMode:t.sandboxMode??e.sandboxMode,permissionMode:t.permissionMode??e.permissionMode}:{...e}}function yv(e){let t=0;for(let n of Object.values(e))n.some(e=>e.trim().length>0)&&(t+=1);return t}var bv=5e3;async function xv(e=bv){let t=Sv();return new Promise(n=>{let r=!1,i=(0,C.spawn)(t.command,[...t.args,`app-server`,`--help`],{stdio:[`ignore`,`ignore`,`ignore`],windowsHide:!0}),a=e=>{r||(r=!0,clearTimeout(o),n(e))},o=setTimeout(()=>{!i.killed&&i.exitCode===null&&i.kill(),a(!1)},e);i.on(`error`,()=>{a(!1)}),i.on(`exit`,e=>{a(e===0)})})}function Sv(){let e=process.env.REMOTE_AGENT_CODEX_BIN?.trim();if(e)return{command:process.execPath,args:[b.default.resolve(e)]};try{let e=gv(`@openai/codex`,`codex`);if(e)return{command:process.execPath,args:[e]}}catch{}return{command:`codex`,args:[]}}var Cv=1e4,wv=100,Tv=2e3,Ev=new Map;async function Dv(e){return Av(e).createConnection()}async function Ov(){let e=[...Ev.values()];await Promise.allSettled(e.map(e=>e.shutdown())),Ev.clear()}function kv(e){let t=e?.trim()||process.env.REMOTE_AGENT_CODEX_BIN?.trim();if(t)return{command:process.execPath,args:[b.default.resolve(t)]};try{let e=gv(`@openai/codex`,`codex`);if(e)return{command:process.execPath,args:[e]}}catch{}return{command:`codex`,args:[]}}function Av(e){let t=e?.trim()||process.env.REMOTE_AGENT_CODEX_BIN?.trim()||`__default__`,n=Ev.get(t);if(n)return n;let r=new jv(e);return Ev.set(t,r),r}var jv=class{constructor(e){this.codexBinOverride=e}running=null;startupPromise=null;shutdownPromise=null;async createConnection(){let e=await this.ensureRunning(),t=await Nv(e.url,()=>this.buildStartupError(e.stderrTail));return e.connections.add(t),t.onClosed(()=>{e.connections.delete(t)}),t}async shutdown(){if(this.shutdownPromise)return this.shutdownPromise;this.shutdownPromise=this.shutdownInternal(),await this.shutdownPromise}async shutdownInternal(){let e=this.running;if(this.running=null,this.startupPromise=null,!e)return;e.shuttingDown=!0;let t=[...e.connections];await Promise.allSettled(t.map(e=>e.close())),e.child.exitCode===null&&(e.child.kill(`SIGTERM`),await Lv(e.child,Tv)||(e.child.kill(`SIGKILL`),await Lv(e.child,Tv)))}async ensureRunning(){if(this.running&&this.running.child.exitCode===null)return this.running;if(this.startupPromise)return this.startupPromise;this.startupPromise=this.startServer();try{let e=await this.startupPromise;return this.running=e,e}finally{this.startupPromise=null}}async startServer(){let e=`ws://127.0.0.1:${await Iv()}`,t=kv(this.codexBinOverride),n=(0,C.spawn)(t.command,[...t.args,`app-server`,`--listen`,e],{stdio:[`ignore`,`ignore`,`pipe`],windowsHide:!0}),r={child:n,url:e,stderrTail:``,connections:new Set,shuttingDown:!1};if(n.stderr.setEncoding(`utf8`),n.stderr.on(`data`,e=>{r.stderrTail=`${r.stderrTail}${e}`,r.stderrTail.length>4e3&&(r.stderrTail=r.stderrTail.slice(r.stderrTail.length-4e3))}),n.on(`exit`,(e,t)=>{if(this.running!==r)return;this.running=null;let n=r.stderrTail.trim(),i=`Codex app-server exited unexpectedly (${t?`signal=${t}`:`code=${String(e)}`})${n?`; stderr: ${n}`:``}`;if(!r.shuttingDown)for(let e of r.connections)e.fail(i);r.connections.clear()}),n.on(`error`,e=>{if(this.running!==r)return;this.running=null;let t=`Codex app-server process error: ${String(e)}`;for(let e of r.connections)e.fail(t);r.connections.clear()}),!await Fv(e,n,()=>this.buildStartupError(r.stderrTail))){let e=this.buildStartupError(r.stderrTail);throw n.exitCode===null&&(n.kill(`SIGTERM`),await Lv(n,Tv)),Error(e)}return r}buildStartupError(e){let t=e.trim();return t?`Failed to start shared Codex app-server; stderr: ${t}`:`Failed to start shared Codex app-server`}},Mv=class{constructor(e){this.socket=e,this.socket.on(`message`,this.handleMessage),this.socket.on(`error`,this.handleError),this.socket.on(`close`,this.handleClose)}messageListeners=new Set;failureListeners=new Set;closeListeners=new Set;closed=!1;send(e){if(this.closed)throw Error(`Codex app-server connection is closed`);this.socket.send(e)}onMessage(e){return this.messageListeners.add(e),()=>{this.messageListeners.delete(e)}}onFailure(e){return this.failureListeners.add(e),()=>{this.failureListeners.delete(e)}}onClosed(e){this.closeListeners.add(e)}fail(e){if(!this.closed){this.closed=!0;for(let t of this.failureListeners)t(e);this.dispose()}}async close(){this.closed||(this.closed=!0,this.socket.readyState<=1&&this.socket.close(1e3,`Client closing`),this.dispose())}handleMessage=e=>{if(this.closed)return;let t=Rv(e);if(t!==null)for(let e of this.messageListeners)e(t)};handleError=e=>{this.closed||this.fail(`Codex app-server WebSocket error: ${String(e)}`)};handleClose=(e,t)=>{if(this.closed){this.dispose();return}let n=typeof e==`number`?e:`unknown`,r=t.length>0?`: ${t.toString(`utf8`)}`:``;this.fail(`Codex app-server WebSocket closed (${String(n)})${r}`)};dispose(){this.socket.off(`message`,this.handleMessage),this.socket.off(`error`,this.handleError),this.socket.off(`close`,this.handleClose);for(let e of this.closeListeners)e();this.closeListeners.clear()}};async function Nv(e,t){let n=Date.now()+Cv,r=null;for(;Date.now()<n;)try{return await Pv(e,Math.max(250,n-Date.now()))}catch(e){r=e instanceof Error?e:Error(String(e)),await zv(wv)}throw r??Error(t())}async function Pv(e,t){let n=new rv(e);return new Promise((r,i)=>{let a=!1,o=setTimeout(()=>{s(),n.close(1e3,`Connect timeout`),i(Error(`Timed out connecting to Codex app-server at ${e}`))},t),s=()=>{o&&=(clearTimeout(o),null),n.off(`open`,c),n.off(`error`,l),n.off(`close`,u)},c=()=>{a||(a=!0,s(),r(new Mv(n)))},l=e=>{a||(a=!0,s(),i(Error(String(e))))},u=(e,t)=>{if(a)return;a=!0,s();let n=typeof e==`number`?e:`unknown`,r=t.length>0?`: ${t.toString(`utf8`)}`:``;i(Error(`Connection closed before open (${String(n)})${r}`))};n.on(`open`,c),n.on(`error`,l),n.on(`close`,u)})}async function Fv(e,t,n){let r=Date.now()+Cv;for(;Date.now()<r;){if(t.exitCode!==null)throw Error(n());try{return await(await Pv(e,500)).close(),!0}catch{await zv(wv)}}return!1}async function Iv(){let e=(0,S.createServer)();try{await new Promise((t,n)=>{e.once(`error`,n),e.listen(0,`127.0.0.1`,()=>{t()})});let t=e.address();if(!t||typeof t==`string`)throw Error(`Failed to reserve a local port for Codex app-server`);return t.port}finally{await new Promise(t=>{e.close(()=>t())})}}async function Lv(e,t){return e.exitCode===null?new Promise(n=>{let r=!1,i=setTimeout(()=>{r||(r=!0,n(e.exitCode!==null))},t);e.once(`exit`,()=>{r||(r=!0,clearTimeout(i),n(!0))})}):!0}function Rv(e){return typeof e==`string`?e:Array.isArray(e)&&e.every(e=>ArrayBuffer.isView(e))?Buffer.concat(e.map(e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength))).toString(`utf8`):e instanceof ArrayBuffer?Buffer.from(e).toString(`utf8`):ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`utf8`):null}function zv(e){return new Promise(t=>{setTimeout(t,e)})}var Bv=3e4,Vv=8,Hv=160,Uv={name:`remote-agent-desktop-gateway`,title:`Remote Agent Desktop Gateway`,version:`0.1.0`},Wv=class e{id;provider=`codex`;providerMode=`native`;model;cwd;resumeSessionId;activeModel;activeSessionConfig;listeners=new Set;deferredEventsUntilListener=[];pendingRequests=new Map;pendingApprovals=new Map;pendingUserInputs=new Map;bufferedThreadScopedMessages=[];recentAppServerActivity=[];requestTimeoutMs;connection;logger;nextRequestId=1;closed=!1;threadId;threadTitle;activeTurnId;turnInProgress=!1;titleReadInFlight=!1;closePromise=null;unsubscribeMessage=null;unsubscribeFailure=null;static async create(t,n={}){let r=new e(t,n.createConnection?await n.createConnection():await Dv(),n.requestTimeoutMs??Bv);try{return await r.bootstrap(),r}catch(e){throw await r.close(),e}}constructor(e,t,n){this.id=e.sessionId,this.model=e.model,this.activeModel=e.model,this.cwd=e.cwd,this.activeSessionConfig={...e.sessionConfig??{}},this.resumeSessionId=e.resumeSessionId,this.requestTimeoutMs=n,this.connection=t,this.logger=e.logger,this.bindConnection()}onEvent(e){let t=this.listeners.size===0&&this.deferredEventsUntilListener.length>0;if(this.listeners.add(e),t){let t=this.deferredEventsUntilListener.splice(0);for(let n of t)e(n)}return()=>{this.listeners.delete(e)}}getNativeSessionId(){return this.threadId}async sendInput(e,t){if(this.ensureOpen(),!this.threadId)throw Error(`Codex app-server thread is not initialized`);if(this.turnInProgress)throw Error(`A turn is already in progress`);this.turnInProgress=!0;try{let n=t?.model??this.activeModel,r=vv(this.activeSessionConfig,t?.sessionConfig);if(this.hasThreadOverrideChanges(n,r)){let e=await this.resumeThread(this.threadId,{model:n,sessionConfig:r});e&&(this.threadId=e)}this.activeModel=n,this.activeSessionConfig=r;let i=[{type:`text`,text:e,text_elements:[]}],a=$v(this.activeSessionConfig.reasoningEffort),o,s=ey(t?.mode,n,a);try{o=await this.sendRequest(`turn/start`,{threadId:this.threadId,input:i,effort:a,collaborationMode:s})}catch(e){if(!(a===`minimal`&&ty(e)))throw e;this.emit({type:`status.progress`,message:`Retrying turn/start with reasoning effort 'low' because 'minimal' is incompatible with web_search.`,originalMethod:`turn/start`,params:{requested_effort:a,retry_effort:`low`}}),o=await this.sendRequest(`turn/start`,{threadId:this.threadId,input:i,effort:`low`,collaborationMode:ey(t?.mode,n,`low`)})}let c=Q(o.turn?.id);c&&(this.activeTurnId=c)}catch(e){throw this.turnInProgress=!1,e}}async interrupt(){if(this.ensureOpen(),!this.threadId||!this.activeTurnId)return;let e={threadId:this.threadId,turnId:this.activeTurnId};await this.sendRequest(`turn/interrupt`,e)}async close(){if(this.closePromise)return this.closePromise;this.closePromise=this.closeInternal(),await this.closePromise}async respondToolPermission(e,t,n){this.ensureOpen();let r=this.pendingApprovals.get(e);if(!r)throw Error(`Unknown approval request: ${e}`);let i=t===`allow`?`accept`:`decline`;switch(r.method){case`item/commandExecution/requestApproval`:case`execCommandApproval`:{let e={decision:i};this.sendResponse(r.rpcId,e);break}case`item/fileChange/requestApproval`:case`applyPatchApproval`:{let e={decision:i};this.sendResponse(r.rpcId,e);break}default:this.sendErrorResponse(r.rpcId,-32601,`Unsupported approval method: ${r.method}`)}this.pendingApprovals.delete(e),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n,nativeDecision:i,approvalMethod:r.method,approvalKind:r.kind})}async respondUserInput(e,t){this.ensureOpen();let n=this.pendingUserInputs.get(e);if(!n)throw Error(`Unknown user input request: ${e}`);let r=ry(t),i={answers:Object.fromEntries(Object.entries(r).map(([e,t])=>[e,{answers:t}]))};this.sendResponse(n.rpcId,i),this.pendingUserInputs.delete(e),this.emit({type:`user.input.resolved`,requestId:e,status:`submitted`,answeredCount:yv(r),inputMethod:n.method})}bindConnection(){this.unsubscribeMessage=this.connection.onMessage(e=>{this.handleIncomingMessage(e)}),this.unsubscribeFailure=this.connection.onFailure(e=>{this.handleConnectionFailure(e)})}async bootstrap(){let e={clientInfo:Uv,capabilities:{experimentalApi:!0,optOutNotificationMethods:mv}};await this.sendRequest(`initialize`,e),this.sendNotification(`initialized`);let t=await this.sendRequest(`account/read`,{refreshToken:!1});if(t.requiresOpenaiAuth&&t.account===null)throw Error("Codex app-server requires OpenAI authentication. Please sign in with `codex` on this machine first.");let n=this.resumeSessionId?await this.resumeThread(this.resumeSessionId):await this.startThread();if(!n)throw Error(`Codex app-server did not return a thread id`);this.threadId=n}async startThread(){let e={model:this.activeModel??null,cwd:this.cwd??null,approvalPolicy:this.activeSessionConfig.approvalPolicy??null,sandbox:this.activeSessionConfig.sandboxMode??null,experimentalRawEvents:!1,persistExtendedHistory:!1};return Q((await this.sendRequest(`thread/start`,e)).thread?.id)}async resumeThread(e,t){let n=t?.model??this.activeModel,r=t?.sessionConfig??this.activeSessionConfig,i={threadId:e,model:n??null,cwd:this.cwd??null,approvalPolicy:r.approvalPolicy??null,sandbox:r.sandboxMode??null,persistExtendedHistory:!1};return Q((await this.sendRequest(`thread/resume`,i)).thread?.id)}hasThreadOverrideChanges(e,t){return this.activeModel!==e||this.activeSessionConfig.approvalPolicy!==t.approvalPolicy||this.activeSessionConfig.sandboxMode!==t.sandboxMode}async closeInternal(){if(!this.closed)try{await this.interrupt()}catch{}this.closed=!0,this.turnInProgress=!1,this.activeTurnId=void 0;for(let[e,t]of this.pendingApprovals.entries())this.emit({type:`tool.permission.resolved`,requestId:e,decision:`deny`,reason:`Session closed before approval response`,nativeDecision:`decline`,approvalMethod:t.method,approvalKind:t.kind});this.pendingApprovals.clear();for(let[e,t]of this.pendingUserInputs.entries())this.emit({type:`user.input.resolved`,requestId:e,status:`expired`,answeredCount:0,reason:`Session closed before user input response`,inputMethod:t.method});this.pendingUserInputs.clear(),this.rejectPendingRequests(Error(`Session ${this.id} is closed`)),this.unsubscribeMessage?.(),this.unsubscribeFailure?.(),this.unsubscribeMessage=null,this.unsubscribeFailure=null,await this.connection.close()}handleIncomingMessage(e){let t;try{t=JSON.parse(e)}catch{this.recordAppServerActivity({at:new Date().toISOString(),direction:`incoming`,messageKind:`parse_error`,payloadLength:e.length,preview:Xv(e)}),this.emitNativeRaw({parse_error:!0,line:e}),this.emit({type:`status.progress`,message:`Received non-JSON message from codex app-server`,line:e});return}let n=Q(t.method),r=Object.prototype.hasOwnProperty.call(t,`id`);if(n&&r){let r={method:n,id:t.id,params:t.params};this.recordIncomingAppServerActivity(t,e.length);let i=this.extractThreadIdFromServerRequest(r),a=this.classifyThreadScopedMessage(i);if(a===`buffer`&&i){this.bufferedThreadScopedMessages.push({kind:`serverRequest`,threadId:i,message:t,payload:r});return}if(a===`ignore`)return;this.emitNativeRaw({message:t}),this.handleServerRequest(r);return}if(n){let r={method:n,params:t.params};this.recordIncomingAppServerActivity(t,e.length);let i=this.extractThreadIdFromNotification(r),a=this.classifyThreadScopedMessage(i);if(a===`buffer`&&i){this.bufferedThreadScopedMessages.push({kind:`notification`,threadId:i,message:t,payload:r});return}if(a===`ignore`)return;this.emitNativeRaw({message:t}),this.handleNotification(r);return}if(r){let n=this.getPendingRequest(t.id);if(!n)return;this.recordIncomingAppServerActivity(t,e.length,n.method);let r=this.extractThreadIdFromResponse(n.method,t.result);r&&this.setThreadIdAndFlushBuffered(r),this.emitNativeRaw({message:t}),this.handleResponse(t),!r&&this.isThreadBindingMethod(n.method)&&!this.hasPendingThreadBindingRequest()&&(this.bufferedThreadScopedMessages.length=0)}}handleResponse(e){let t=pv(e.id),n=this.pendingRequests.get(t);if(n){if(this.pendingRequests.delete(t),clearTimeout(n.timeoutId),e.error!==void 0){let t=fv(e.error),r=Q(t.message)??JSON.stringify(t);n.reject(Error(`Codex app-server request failed (${n.method}): ${r}`));return}n.resolve(e.result)}}handleServerRequest(e){switch(e.method){case`item/commandExecution/requestApproval`:this.registerApprovalRequest(e.id,e.method,`command`,e.params);return;case`item/fileChange/requestApproval`:this.registerApprovalRequest(e.id,e.method,`file`,e.params);return;case`execCommandApproval`:this.registerApprovalRequest(e.id,e.method,`command`,e.params);return;case`applyPatchApproval`:this.registerApprovalRequest(e.id,e.method,`file`,e.params);return;case`item/tool/requestUserInput`:this.registerUserInputRequest(e.id,e.method,e.params);return;default:this.sendErrorResponse(e.id,-32601,`Unsupported server request: ${e.method}`)}}registerApprovalRequest(e,t,n,r){let i=fv(r),a=Q(i.threadId);if(!this.shouldHandleThreadScopedMessage(a))return;let o=`req_${og(8)}`;this.pendingApprovals.set(o,{rpcId:e,method:t,kind:n}),this.emit({type:`tool.permission.requested`,requestId:o,toolName:n===`command`?`command_execution`:`file_change`,reason:Q(i.reason),threadId:a,turnId:Q(i.turnId),itemId:Q(i.itemId),approvalMethod:t,rawParams:uv(i)})}registerUserInputRequest(e,t,n){let r=Q(n.threadId);if(!this.shouldHandleThreadScopedMessage(r))return;let i=`req_${og(8)}`;this.pendingUserInputs.set(i,{rpcId:e,method:t});let a=Array.isArray(n.questions)?n.questions.map(ny).filter(e=>e!==null):[];this.emit({type:`user.input.requested`,requestId:i,threadId:n.threadId,turnId:n.turnId,itemId:n.itemId,questions:a,inputMethod:t,rawParams:uv(n)})}handleNotification(e){switch(e.method){case`thread/started`:{let t=e.params,n=Q(t.thread?.id);if(!this.shouldHandleThreadScopedMessage(n))return;this.emitThreadTitleUpdated(Q(t.thread?.preview),`codex.thread_preview`,{thread_id:n??this.threadId}),this.emit({type:`thread.started`,thread_id:n,thread:uv(t.thread)});return}case`thread/name/updated`:{let t=e.params,n=Q(t.threadId);if(!this.shouldHandleThreadScopedMessage(n))return;this.emitThreadTitleUpdated(Q(t.threadName),`codex.thread_name_updated`,{thread_id:n??this.threadId});return}case`turn/started`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;let n=Q(t.turn?.id);n&&(this.activeTurnId=n),this.turnInProgress=!0,this.emit({type:`turn.started`,turn:uv(t.turn)});return}case`turn/completed`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;let n=Q(t.turn?.status);if(this.turnInProgress=!1,this.activeTurnId=void 0,n===`failed`){this.emit({type:`turn.failed`,status:n,turn:uv(t.turn),error:uv(t.turn?.error??{})});return}this.emit({type:`turn.completed`,status:n,turn:uv(t.turn)}),this.tryEmitTitleFromThreadRead();return}case`item/started`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`item.started`,item:cv(t.item)});return}case`item/completed`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`item.completed`,item:cv(t.item)});return}case`item/agentMessage/delta`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`item.updated`,item:{id:t.itemId,type:`agent_message`,text:t.delta,original_method:e.method,payload:{delta:t.delta}}});return}case`item/commandExecution/outputDelta`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`item.updated`,item:{id:t.itemId,type:`command_execution`,aggregated_output:t.delta,output_delta:t.delta}});return}case`item/fileChange/outputDelta`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`item.updated`,item:{id:t.itemId,type:`file_change`,output_delta:t.delta}});return}case`item/plan/delta`:case`item/reasoning/summaryTextDelta`:case`item/reasoning/summaryPartAdded`:case`item/reasoning/textDelta`:{let t=fv(e.params);if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`item.updated`,item:{id:Q(t.itemId),type:e.method.startsWith(`item/plan`)?`plan`:`reasoning`,text:Q(t.delta)??Q(t.text)??``,original_method:e.method,payload:uv(t)}});return}case`error`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`error`,message:Q(t.error?.message)??`Codex app-server error`,error:uv(t.error),will_retry:t.willRetry===!0,thread_id:Q(t.threadId),turn_id:Q(t.turnId)});return}default:return}}async sendRequest(e,t){this.ensureOpen();let n=this.nextRequestId;this.nextRequestId+=1;let r={method:e,id:n,params:t},i=pv(n),a=new Promise((t,n)=>{let r=setTimeout(()=>{this.pendingRequests.delete(i),n(Error(`Codex app-server request timed out: ${e}`))},this.requestTimeoutMs);this.pendingRequests.set(i,{method:e,timeoutId:r,resolve:t,reject:n})});return this.writeMessage(r),await a}sendNotification(e){let t={method:e};this.writeMessage(t)}sendResponse(e,t){this.writeMessage({id:e,result:t})}sendErrorResponse(e,t,n){this.writeMessage({id:e,error:{code:t,message:n}})}writeMessage(e){this.ensureOpen();let t=JSON.stringify(e);this.recordOutgoingAppServerActivity(e,t.length),this.connection.send(t)}emit(e){if(this.listeners.size===0&&e.type!==`native.raw`){this.deferredEventsUntilListener.push(e);return}for(let t of this.listeners)t(e)}emitThreadTitleUpdated(e,t,n={}){let r=Gv(e);!r||r===this.threadTitle||(this.threadTitle=r,this.emit({type:`thread.title.updated`,title:r,source:t,...n}))}async tryEmitTitleFromThreadRead(){if(!(!this.threadId||this.threadTitle||this.closed||this.titleReadInFlight)){this.titleReadInFlight=!0;try{let e=await this.sendRequest(`thread/read`,{threadId:this.threadId,includeTurns:!1});this.emitThreadTitleUpdated(Q(e.thread?.name)??Q(e.thread?.preview),Q(e.thread?.name)?`codex.thread_read_name`:`codex.thread_read_preview`,{thread_id:this.threadId})}catch{}finally{this.titleReadInFlight=!1}}}handleConnectionFailure(e){if(this.closed)return;let t=Zv(e),n=Qv(e),r=this.recentAppServerActivity[this.recentAppServerActivity.length-1],i=this.threadId,a=this.activeTurnId;this.log(`error`,`codex app-server websocket session failed`,{failureMessage:e,failureCloseCode:t,failureCloseReason:n,pendingRequestCount:this.pendingRequests.size,pendingRequestMethods:[...new Set([...this.pendingRequests.values()].map(e=>e.method))],pendingApprovalCount:this.pendingApprovals.size,pendingUserInputCount:this.pendingUserInputs.size,bufferedThreadScopedMessageCount:this.bufferedThreadScopedMessages.length,lastAppServerActivity:r,lastAppServerActivityMethod:r?.method,lastAppServerActivityThreadId:r?.threadId,lastAppServerActivityTurnId:r?.turnId,lastAppServerActivityItemId:r?.itemId,lastAppServerActivityDeltaLength:r?.deltaLength,lastAppServerActivityPreview:r?.preview,recentAppServerActivity:[...this.recentAppServerActivity]}),this.closed=!0,this.turnInProgress=!1,this.activeTurnId=void 0,this.rejectPendingRequests(Error(e));for(let[e,t]of this.pendingApprovals.entries())this.emit({type:`tool.permission.resolved`,requestId:e,decision:`deny`,reason:`Session terminated before approval response`,nativeDecision:`decline`,approvalMethod:t.method,approvalKind:t.kind});this.pendingApprovals.clear();for(let e of this.pendingUserInputs.keys())this.emit({type:`user.input.resolved`,requestId:e,status:`expired`,answeredCount:0,reason:`Session terminated before user input response`});this.pendingUserInputs.clear(),this.emit({type:`error.runtime`,message:e,source:`codex.app_server.websocket`,...t===void 0?{}:{close_code:t},...n?{close_reason:n}:{},...i?{thread_id:i}:{},...a?{turn_id:a}:{}})}rejectPendingRequests(e){for(let t of this.pendingRequests.values())clearTimeout(t.timeoutId),t.reject(e);this.pendingRequests.clear()}emitNativeRaw(e){this.emit({type:`native.raw`,source:`codex.app_server`,...e})}getPendingRequest(e){return this.pendingRequests.get(pv(e))}classifyThreadScopedMessage(e){return!e||this.threadId&&e===this.threadId?`handle`:this.hasPendingThreadBindingRequest()?`buffer`:`ignore`}extractThreadIdFromServerRequest(e){return Q(fv(e.params).threadId)}extractThreadIdFromNotification(e){let t=fv(e.params);return Q(t.threadId)||Q(fv(t.thread).id)}extractThreadIdFromResponse(e,t){if(this.isThreadBindingMethod(e))return Q(fv(fv(t).thread).id)}hasPendingThreadBindingRequest(){for(let e of this.pendingRequests.values())if(this.isThreadBindingMethod(e.method))return!0;return!1}isThreadBindingMethod(e){return e===`thread/start`||e===`thread/resume`}setThreadIdAndFlushBuffered(e){if(this.threadId=e,this.bufferedThreadScopedMessages.length===0)return;let t=this.bufferedThreadScopedMessages.splice(0);for(let n of t)n.threadId===e&&(this.emitNativeRaw({message:n.message}),n.kind===`serverRequest`?this.handleServerRequest(n.payload):this.handleNotification(n.payload))}shouldHandleThreadScopedMessage(e){return!!e&&e===this.threadId}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}log(e,t,n={}){if(!this.logger)return;let r={provider:this.provider,providerMode:this.providerMode,sessionId:this.id,threadId:this.threadId,activeTurnId:this.activeTurnId,model:this.activeModel??this.model,cwd:this.cwd,...n};if(e===`info`){this.logger.info?.(r,t);return}if(e===`warn`){this.logger.warn?.(r,t);return}this.logger.error?.(r,t)}recordIncomingAppServerActivity(e,t,n){this.recordAppServerActivity(Kv({direction:`incoming`,message:e,payloadLength:t,responseMethod:n}))}recordOutgoingAppServerActivity(e,t){this.recordAppServerActivity(Kv({direction:`outgoing`,message:e,payloadLength:t}))}recordAppServerActivity(e){this.recentAppServerActivity.push(e),this.recentAppServerActivity.length>Vv&&this.recentAppServerActivity.splice(0,this.recentAppServerActivity.length-Vv)}};function Gv(e){if(typeof e!=`string`)return;let t=e.replace(/\s+/g,` `).trim();if(t)return t}function Kv(e){let t=Q(e.message.method),n=Object.prototype.hasOwnProperty.call(e.message,`id`),r=fv(e.message.error),i=Jv(t,t?e.message.params:e.message.error??e.message.result);return{at:new Date().toISOString(),direction:e.direction,messageKind:qv(t,n,e.direction),method:t,requestId:n?pv(e.message.id):void 0,requestMethod:e.responseMethod,threadId:i.threadId,turnId:i.turnId,itemId:i.itemId,payloadLength:e.payloadLength,deltaLength:i.deltaLength,preview:i.preview??Xv(Q(r.message))}}function qv(e,t,n){return e&&t?n===`incoming`?`server_request`:`request`:e?`notification`:`response`}function Jv(e,t){let n=fv(t),r=fv(n.thread),i=fv(n.turn),a=fv(n.item),o=Q(n.delta)??Q(n.text),s=Yv(e,n,o);return{threadId:Q(n.threadId)??Q(r.id),turnId:Q(n.turnId)??Q(i.id),itemId:Q(n.itemId)??Q(a.id),deltaLength:typeof o==`string`?o.length:void 0,preview:Xv(s)}}function Yv(e,t,n){if(e===`item/commandExecution/outputDelta`||e===`item/fileChange/outputDelta`||e===`item/agentMessage/delta`||e===`item/plan/delta`||e===`item/reasoning/summaryTextDelta`||e===`item/reasoning/textDelta`)return n;if(e===`error`)return Q(fv(t.error).message)??Q(t.message)}function Xv(e){if(typeof e!=`string`)return;let t=e.replace(/\s+/g,` `).trim();if(t)return t.length<=Hv?t:`${t.slice(0,Hv)}...`}function Zv(e){let t=/WebSocket closed \((\d+)\)/.exec(e);if(!t)return;let n=Number.parseInt(t[1]??``,10);return Number.isFinite(n)?n:void 0}function Qv(e){return/WebSocket closed \(\d+\): (.+)$/.exec(e)?.[1]}function $v(e){return e?e===`max`?`xhigh`:e:null}function ey(e,t,n){if(e===`plan`){if(!t)throw Error(`Codex plan mode requires a resolved model.`);return{mode:`plan`,settings:{model:t,reasoning_effort:n,developer_instructions:null}}}}function ty(e){return e instanceof Error?/reasoning\.effort ['"]minimal['"]/i.test(e.message)&&/web_search/i.test(e.message):!1}function ny(e){let t=fv(e),n=Q(t.id),r=Q(t.header),i=Q(t.question),a=t.options;if(!n||!r||!i)return null;let o=Array.isArray(a)?a.map(e=>{let t=fv(e),n=Q(t.label),r=Q(t.description)??n,i=Q(t.markdown);return n?{label:n,description:r,...i?{markdown:i}:{}}:null}).filter(e=>e!==null):null;return{id:n,header:r,question:i,multiSelect:t.multiSelect===!0,isOther:!!t.isOther,isSecret:!!t.isSecret,options:o}}function ry(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Array.from(new Set(t.map(e=>e.trim()).filter(Boolean)))]))}var iy=class{constructor(e,t,n={}){this.preferNative=e,this.requireNative=t,this.runtime=n}provider=`codex`;mockAdapter=new sv(`codex`);async isNativeAvailable(){try{return this.runtime.probeAvailability?await this.runtime.probeAvailability():await xv()}catch{return!1}}async createSession(e){if(this.requireNative&&!this.preferNative)throw Error(`Native Codex provider is required but ENABLE_NATIVE_PROVIDERS is disabled`);if(!this.preferNative)return this.mockAdapter.createSession(e);let t=this.runtime.createNativeSession??Wv.create;try{return await t(e)}catch(t){if(this.requireNative)throw t;return console.warn(`[provider-adapters] codex native fallback to mock: ${String(t)}`),this.mockAdapter.createSession(e)}}},ay=15e3,oy={name:`remote-agent-desktop-gateway`,title:`Remote Agent Desktop Gateway`,version:`0.1.0`},sy=class{constructor(e,t={}){this.transport=e,this.requestTimeoutMs=t.requestTimeoutMs??ay,this.bindTransport()}pendingRequests=new Map;requestTimeoutMs;nextRequestId=1;closed=!1;unsubscribeMessage=null;unsubscribeFailure=null;async bootstrap(){let e={clientInfo:oy,capabilities:{experimentalApi:!1,optOutNotificationMethods:mv}};await this.sendRequest(`initialize`,e),this.sendNotification(`initialized`);let t=await this.sendRequest(`account/read`,{refreshToken:!1});if(t.requiresOpenaiAuth&&t.account===null)throw Error("Codex app-server requires OpenAI authentication. Please sign in with `codex` on this machine first.")}async close(){this.closed||(this.closed=!0,this.rejectPendingRequests(Error(`Codex RPC client closed`)),this.unsubscribeMessage?.(),this.unsubscribeFailure?.(),this.unsubscribeMessage=null,this.unsubscribeFailure=null,await this.transport.close())}async sendRequest(e,t){this.ensureOpen();let n=this.nextRequestId;this.nextRequestId+=1;let r=pv(n),i=new Promise((t,n)=>{let i=setTimeout(()=>{this.pendingRequests.delete(r),n(Error(`Codex app-server request timed out: ${e}`))},this.requestTimeoutMs);this.pendingRequests.set(r,{timeoutId:i,resolve:t,reject:n})});return this.writeMessage({method:e,id:n,params:t}),await i}bindTransport(){this.unsubscribeMessage=this.transport.onMessage(e=>{this.handleIncomingMessage(e)}),this.unsubscribeFailure=this.transport.onFailure(e=>{this.handleTransportFailure(e)})}sendNotification(e){this.writeMessage({method:e})}writeMessage(e){this.ensureOpen(),this.transport.send(JSON.stringify(e))}ensureOpen(){if(this.closed)throw Error(`Codex RPC client is closed`)}handleIncomingMessage(e){let t;try{t=JSON.parse(e)}catch{return}let n=Object.prototype.hasOwnProperty.call(t,`id`),r=Q(t.method);if(n&&r){let e=t.id;this.writeMessage({id:e,error:{code:-32601,message:`Unsupported server request: ${r}`}});return}n&&this.handleResponse(t)}handleResponse(e){let t=pv(e.id),n=this.pendingRequests.get(t);if(n){if(this.pendingRequests.delete(t),clearTimeout(n.timeoutId),e.error!==void 0){let t=fv(e.error),r=Q(t.message)??JSON.stringify(t);n.reject(Error(`Codex app-server request failed: ${r}`));return}n.resolve(e.result)}}handleTransportFailure(e){this.closed||(this.closed=!0,this.rejectPendingRequests(Error(e)))}rejectPendingRequests(e){for(let[t,n]of this.pendingRequests.entries())clearTimeout(n.timeoutId),n.reject(e),this.pendingRequests.delete(t)}};async function cy(e,t={}){let n=new sy(await ly(t),t);try{return await n.bootstrap(),await e(n)}finally{await n.close()}}async function ly(e){return e.spawnProcess?new dy(e.spawnProcess()):new uy(await Dv(e.codexBinOverride))}var uy=class{constructor(e){this.connection=e}send(e){this.connection.send(e)}onMessage(e){return this.connection.onMessage(e)}onFailure(e){return this.connection.onFailure(e)}async close(){await this.connection.close()}},dy=class{constructor(e){this.process=e,this.bindProcess()}messageListeners=new Set;failureListeners=new Set;stdoutBuffer=``;stderrTail=``;closed=!1;send(e){if(this.closed)throw Error(`Codex app-server process transport is closed`);this.process.stdin.write(`${e}
|
|
475
475
|
`)}onMessage(e){return this.messageListeners.add(e),()=>{this.messageListeners.delete(e)}}onFailure(e){return this.failureListeners.add(e),()=>{this.failureListeners.delete(e)}}async close(){this.closed||(this.closed=!0,this.process.stdin.destroyed||this.process.stdin.end(),!this.process.killed&&this.process.exitCode===null&&this.process.kill())}bindProcess(){this.process.stdout.setEncoding(`utf8`),this.process.stderr.setEncoding(`utf8`),this.process.stdout.on(`data`,e=>{this.consumeStdoutChunk(String(e))}),this.process.stderr.on(`data`,e=>{this.stderrTail=`${this.stderrTail}${e}`,this.stderrTail.length>2e3&&(this.stderrTail=this.stderrTail.slice(this.stderrTail.length-2e3))}),this.process.on(`error`,e=>{this.fail(`Codex app-server process error: ${String(e)}`)}),this.process.on(`exit`,(e,t)=>{if(this.closed)return;let n=this.stderrTail.trim(),r=n?`; stderr: ${n}`:``,i=t?`signal=${t}`:`code=${String(e)}`;this.fail(`Codex app-server exited unexpectedly (${i})${r}`)})}consumeStdoutChunk(e){for(this.stdoutBuffer+=e;;){let e=this.stdoutBuffer.indexOf(`
|
|
476
|
-
`);if(e<0)break;let t=this.stdoutBuffer.slice(0,e).trim();if(this.stdoutBuffer=this.stdoutBuffer.slice(e+1),t)for(let e of this.messageListeners)e(t)}}fail(e){if(!this.closed){this.closed=!0;for(let t of this.failureListeners)t(e)}}};async function dy(e){let t=[],n=null;do{let r=await fy({cwd:e,archived:!1,cursor:n,limit:100});t.push(...r.threads),n=r.nextCursor}while(n);return t}async function fy(e){return sy(async t=>{let n=await t.sendRequest(`thread/list`,e);return{threads:n.data.map(e=>hy(e)),nextCursor:n.nextCursor}})}async function py(e,t=!0){return sy(async n=>hy((await n.sendRequest(`thread/read`,{threadId:e,includeTurns:t})).thread))}async function my(){let e=[],t=null;do{let n=await sy(async e=>e.sendRequest(`model/list`,{cursor:t,limit:100}));e.push(...n.data.map(e=>gy(e))),t=n.nextCursor}while(t);return e}function hy(e){let t=$(dv(e).model)?.trim()||void 0;return{id:e.id,name:e.name??void 0,preview:e.preview,model:t,modelProvider:e.modelProvider,createdAt:e.createdAt,updatedAt:e.updatedAt,path:e.path,cwd:e.cwd,cliVersion:e.cliVersion,source:vy(e.source),gitInfo:e.gitInfo?dv(lv(e.gitInfo)):null,turns:e.turns.map(e=>_y(e))}}function gy(e){return{id:e.id,model:e.model,displayName:e.displayName,description:e.description,isDefault:e.isDefault,defaultReasoningEffort:e.defaultReasoningEffort??void 0,supportedReasoningEfforts:(e.supportedReasoningEfforts??[]).map(e=>e.reasoningEffort)}}function _y(e){return{id:e.id,status:e.status,error:e.error?dv(lv(e.error)):null,items:e.items.map(e=>sv(e))}}function vy(e){if(typeof e==`string`)return e;if(typeof e==`object`&&e){let[t,n]=Object.entries(e)[0]??[];return t?typeof n==`string`&&n?`${t}:${n}`:t:`unknown`}return`unknown`}var yy=class{constructor(e,t,n,r,i){this.createQuery=n,this.id=e,this.model=t,this.activeModel=t,this.activeSessionConfig={},this.resumeSessionId=r,this.cwd=i?.cwd}id;provider=`claude`;providerMode=`native`;model;listeners=new Set;cwd;closed=!1;turnInProgress=!1;turnSequence=0;activeTurnId=null;activeAssistantItemId=null;assistantStarted=!1;assistantCompleted=!1;activeToolItemId=null;toolStarted=!1;activeQuery=null;activeAbortController=null;resumeSessionId;threadStartedEmitted=!1;activeModel;activeSessionConfig;interruptRequested=!1;pendingToolPermissionRequests=new Map;pendingUserInputRequests=new Map;pendingClaudeToolUses=new Map;activeTurnStarted=!1;closePromise=null;onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getNativeSessionId(){return this.resumeSessionId}async sendInput(e,t){if(this.ensureOpen(),this.turnInProgress)throw Error(`A turn is already in progress`);this.turnInProgress=!0,this.turnSequence+=1,this.activeTurnId=`claude_turn_${this.turnSequence}`,this.activeAssistantItemId=null,this.assistantStarted=!1,this.assistantCompleted=!1,this.activeToolItemId=null,this.toolStarted=!1,this.pendingClaudeToolUses.clear(),this.interruptRequested=!1,this.activeTurnStarted=!1,this.activeModel=t?.model??this.activeModel,this.activeSessionConfig=_v(this.activeSessionConfig,t?.sessionConfig),t?.mode===`plan`&&(this.activeSessionConfig.permissionMode=`plan`);let n=new AbortController,r=this.createQuery({prompt:e,model:this.activeModel,sessionConfig:this.activeSessionConfig,resume:this.resumeSessionId,abortController:n,canUseTool:this.handleCanUseTool});this.activeAbortController=n,this.activeQuery=r,this.emitSyntheticUserInputEvents(e),this.startQueryLoop(r)}async interrupt(){if(!this.turnInProgress||this.closed)return;this.interruptRequested=!0,this.activeAbortController&&this.activeAbortController.abort();let e=this.activeQuery;if(e){if(typeof e.interrupt==`function`)try{await e.interrupt()}catch{}typeof e.close==`function`&&e.close()}}async close(){if(this.closePromise)return this.closePromise;this.closePromise=this.closeInternal(),await this.closePromise}async respondToolPermission(e,t,n){let r=this.pendingToolPermissionRequests.get(e);if(!r)throw Error(`Unknown tool approval request: ${e}`);this.pendingToolPermissionRequests.delete(e),t===`allow`?r.resolve({behavior:`allow`,updatedInput:r.input}):r.resolve({behavior:`deny`,message:n?.trim()||`Permission denied`}),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n,toolName:r.toolName,itemId:r.toolUseID,turn_id:this.activeTurnId,source_event_type:`can_use_tool`})}async respondUserInput(e,t){let n=this.pendingUserInputRequests.get(e);if(!n)throw Error(`Unknown user input request: ${e}`);this.pendingUserInputRequests.delete(e);let r=wy(t),i={...n.input,answers:r};n.resolve({behavior:`allow`,updatedInput:i}),this.emit({type:`user.input.resolved`,requestId:e,status:`submitted`,answeredCount:vv(r),questions:Sy(n.input),answers:r,source_event_type:`can_use_tool`})}startQueryLoop(e){(async()=>{try{for await(let t of e){if(this.closed||this.activeQuery!==e)return;let n=Uy(t);this.captureResumeSessionId(t),this.emit({type:`native.raw`,source:`claude.query`,native_type:Wy(n.type),message:t});let r=this.mapClaudeMessage(t);for(let e of r)this.emit(e)}}catch(t){if(this.closed||this.activeQuery!==e)return;let n=t instanceof Error?t.message:String(t);this.interruptRequested||this.emit({type:`error`,message:n})}finally{if(this.closed||this.activeQuery!==e)return;this.turnInProgress=!1,this.interruptRequested=!1,this.activeQuery=null,this.activeAbortController=null,this.expirePendingToolPermissionRequests(`Turn finished`),this.expirePendingUserInputRequests(`Turn finished`),this.clearTurnState()}})()}async closeInternal(){if(this.closed)return;this.closed=!0,this.interruptRequested=!0,this.activeAbortController&&=(this.activeAbortController.abort(),null);let e=this.activeQuery;if(this.activeQuery=null,typeof e?.interrupt==`function`)try{await e.interrupt()}catch{}typeof e?.close==`function`&&e.close(),this.turnInProgress=!1,this.clearTurnState(),this.expirePendingToolPermissionRequests(`Session closed`),this.expirePendingUserInputRequests(`Session closed`)}handleCanUseTool=async(e,t,n)=>xy(e,t)?this.requestUserInput(e,t,n):by(n)?this.requestToolPermission(e,t,n):{behavior:`allow`};requestToolPermission(e,t,n){let r=`req_${ag(8)}`;return this.emit({type:`tool.permission.requested`,requestId:r,toolName:e,reason:n.decisionReason,blockedPath:n.blockedPath,suggestions:n.suggestions,agentId:n.agentID,itemId:n.toolUseID,turn_id:this.activeTurnId,source_event_type:`can_use_tool`}),new Promise((i,a)=>{if(n.signal.aborted){i({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:r,decision:`deny`,reason:`Operation aborted`,toolName:e,itemId:n.toolUseID,source_event_type:`abort`});return}let o=()=>{n.signal.removeEventListener(`abort`,o);let e=this.pendingToolPermissionRequests.get(r);e&&(this.pendingToolPermissionRequests.delete(r),i({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:r,decision:`deny`,reason:`Operation aborted`,toolName:e.toolName,itemId:e.toolUseID,source_event_type:`abort`}))};n.signal.addEventListener(`abort`,o,{once:!0}),this.pendingToolPermissionRequests.set(r,{toolName:e,toolUseID:n.toolUseID,input:t,resolve:e=>{n.signal.removeEventListener(`abort`,o),i(e)},reject:e=>{n.signal.removeEventListener(`abort`,o),a(e)}})})}requestUserInput(e,t,n){let r=Sy(t),i=`req_${ag(8)}`;return this.emit({type:`user.input.requested`,requestId:i,tool_name:e,turn_id:this.activeTurnId,questions:r,source_event_type:`can_use_tool`}),new Promise((e,r)=>{if(n.signal.aborted){e({behavior:`deny`,message:`Operation aborted`,interrupt:!0});return}let a=()=>{n.signal.removeEventListener(`abort`,a),this.pendingUserInputRequests.has(i)&&(this.pendingUserInputRequests.delete(i),e({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emit({type:`user.input.resolved`,requestId:i,status:`expired`,answeredCount:0,source_event_type:`abort`}))};n.signal.addEventListener(`abort`,a,{once:!0}),this.pendingUserInputRequests.set(i,{input:t,resolve:t=>{n.signal.removeEventListener(`abort`,a),e(t)},reject:e=>{n.signal.removeEventListener(`abort`,a),r(e)}})})}expirePendingToolPermissionRequests(e){for(let[t,n]of this.pendingToolPermissionRequests.entries())n.resolve({behavior:`deny`,message:e,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:t,decision:`deny`,reason:e,toolName:n.toolName,itemId:n.toolUseID,source_event_type:`session_end`});this.pendingToolPermissionRequests.clear()}expirePendingUserInputRequests(e){for(let[t,n]of this.pendingUserInputRequests.entries())n.resolve({behavior:`deny`,message:e,interrupt:!0}),this.emit({type:`user.input.resolved`,requestId:t,status:`expired`,answeredCount:0,source_event_type:`session_end`});this.pendingUserInputRequests.clear()}emit(e){for(let t of this.listeners)t(e)}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}clearTurnState(){this.activeTurnId=null,this.activeAssistantItemId=null,this.assistantStarted=!1,this.assistantCompleted=!1,this.activeToolItemId=null,this.toolStarted=!1,this.activeTurnStarted=!1}captureResumeSessionId(e){let t=Uy(e),n=Wy(t.session_id)??Wy(t.sessionId);n&&(this.resumeSessionId=n)}emitSyntheticUserInputEvents(e){if(!e.trim())return;let t=new Date().toISOString(),n=this.resumeSessionId??this.id,r=`claude_user_${ag(10)}`,i={parentUuid:null,isSidechain:!1,userType:`external`,cwd:this.cwd,sessionId:n,session_id:n,version:`synthetic`,type:`user`,message:{role:`user`,content:[{type:`text`,text:e}]},uuid:r,timestamp:t,permissionMode:this.activeSessionConfig.permissionMode??`default`,source_event_type:`claude.synthetic.user_input`};this.emit({type:`native.raw`,source:`claude.synthetic.user_input`,native_type:`user`,message:i});let a=this.mapClaudeMessage(i);for(let e of a)this.emit(e)}ensureAssistantItemId(e){let t=Jy(e);if(t)return this.activeAssistantItemId=t,t;if(this.activeAssistantItemId)return this.activeAssistantItemId;let n=this.activeTurnId?`claude_assistant_${this.activeTurnId}`:`claude_assistant_${Date.now()}`;return this.activeAssistantItemId=n,n}ensureToolItemId(e){let t=Wy(e.tool_id)??Wy(e.tool_use_id)??Ky(e.preceding_tool_use_ids);if(t)return this.activeToolItemId=t,t;let n=Wy(e.uuid);if(n)return this.activeToolItemId=n,n;let r=Yy(Wy(e.tool_name)??`tool`),i=this.activeTurnId?`claude_tool_${this.activeTurnId}_${r}`:`claude_tool_${r}_${Date.now()}`;return this.activeToolItemId=i,i}buildAssistantCompletionTailEvent(){if(!this.assistantStarted||this.assistantCompleted)return[];let e=this.activeAssistantItemId;return e?(this.assistantCompleted=!0,[{type:`item.completed`,item:{id:e,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`stream_end`}}]):[]}mapClaudeMessage(e){let t=Uy(e),n=Wy(t.type);if(n===`user`){let e=this.mapStructuredClaudeToolResult(t);if(e.length>0)return e;if(!Ry(t))return[];let n=zy(Uy(t.message));return n?[{type:`item.completed`,item:{id:Wy(t.uuid)??`claude_user_${Date.now()}`,type:`user_message`,text:n,turn_id:this.activeTurnId,source_event_type:Wy(t.source_event_type)??`user`}}]:[]}if(n===`assistant`){let e=this.mapStructuredClaudeToolUse(t);if(e.length>0)return e;let n=this.activeAssistantItemId,r=this.ensureAssistantItemId(t);n&&n!==r&&(this.assistantStarted=!1,this.assistantCompleted=!1);let i=Ly(t),a=[...this.maybeEmitTurnStarted(`assistant`)];return this.assistantStarted||=(a.push({type:`item.started`,item:{id:r,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`assistant`}}),!0),a.push({type:`item.completed`,item:{id:r,type:`agent_message`,text:i,turn_id:this.activeTurnId,source_event_type:`assistant`}}),this.assistantCompleted=!0,a}if(n===`stream_event`){let e=Uy(t.event);if(Wy(e.type)===`message_start`){let t=Jy(e);return t&&(this.activeAssistantItemId=t,this.assistantStarted=!1,this.assistantCompleted=!1),[]}let n=By(t);if(!n)return[];let r=this.activeAssistantItemId,i=this.ensureAssistantItemId(t);r&&r!==i&&(this.assistantStarted=!1,this.assistantCompleted=!1);let a=[];return a.push(...this.maybeEmitTurnStarted(`stream_event`)),this.assistantStarted||=(a.push({type:`item.started`,item:{id:i,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`stream_event`}}),!0),a.push({type:`item.updated`,item:{id:i,type:`agent_message`,text:n,turn_id:this.activeTurnId,source_event_type:`stream_event`}}),a}if(n===`result`){let e=this.maybeEmitTurnStarted(`result`);if(t.is_error===!0||Wy(t.subtype)?.startsWith(`error_`)===!0){let n=Vy(t);return[...e,{type:`turn.failed`,error:{message:n},usage:Hy(t.usage),turn_id:this.activeTurnId,source_event_type:`result`}]}return[...e,...this.buildAssistantCompletionTailEvent(),{type:`turn.completed`,usage:Hy(t.usage),turn_id:this.activeTurnId,source_event_type:`result`}]}if(n===`tool_use_summary`){let e=this.activeToolItemId,n=this.ensureToolItemId(t);e&&e!==n&&(this.toolStarted=!1);let r=Wy(t.summary)??`tool summary`,i=Wy(t.tool_name)??`tool`,a=[];return a.push(...this.maybeEmitTurnStarted(`tool_use_summary`)),this.toolStarted||=(a.push({type:`item.started`,item:{id:n,type:`tool_status`,tool_name:i,turn_id:this.activeTurnId,source_event_type:`tool_use_summary`}}),!0),a.push({type:`item.updated`,item:{id:n,type:`tool_status`,text:r,status:`running`,tool_name:i,turn_id:this.activeTurnId,source_event_type:`tool_use_summary`}}),a.push({type:`item.completed`,item:{id:n,type:`tool_status`,text:r,status:`completed`,tool_name:i,turn_id:this.activeTurnId,source_event_type:`tool_use_summary`}}),this.activeToolItemId=null,this.toolStarted=!1,a}if(n===`tool_progress`){let e=this.activeToolItemId,n=this.ensureToolItemId(t);e&&e!==n&&(this.toolStarted=!1);let r=Wy(t.tool_name)??`tool`,i=Wy(t.message)??`${r} running`,a=[];return a.push(...this.maybeEmitTurnStarted(`tool_progress`)),this.toolStarted||=(a.push({type:`item.started`,item:{id:n,type:`tool_status`,tool_name:r,status:`running`,turn_id:this.activeTurnId,source_event_type:`tool_progress`}}),!0),a.push({type:`item.updated`,item:{id:n,type:`tool_status`,text:i,status:`running`,tool_name:r,turn_id:this.activeTurnId,source_event_type:`tool_progress`}}),a}if(n===`system`){let e=Wy(t.subtype);if(e===`init`){let e=this.maybeCreateThreadStartedEvent(Wy(t.session_id)??Wy(t.sessionId),`claude.system.init`);return e?[e]:[]}return e===`status`?[{type:`status.progress`,message:Wy(t.status)??`status update`}]:[{type:`status.progress`,message:e?`system.${e}`:`system event`}]}if(n===`auth_status`){let e=Wy(t.error);return e?[{type:`error`,message:e}]:[{type:`status.progress`,message:`auth status update`}]}return[]}mapStructuredClaudeToolUse(e){let t=Ty(e);if(t.length===0)return[];let n=[];n.push(...this.maybeEmitTurnStarted(`assistant.tool_use`));for(let e of t)this.pendingClaudeToolUses.set(e.id,e),n.push({type:`item.started`,item:{id:e.id,type:`tool_status`,turn_id:this.activeTurnId,tool_name:e.toolName,title:e.title,text:e.title,status:`running`,status_label:e.pendingStatusLabel,display_as:`tool_card`,response_label:e.responseLabel,prompt:e.prompt,subagent_type:e.subagentType,description:e.description,file_path:e.filePath,source_event_type:`assistant.tool_use`}});return n}mapStructuredClaudeToolResult(e){let t=Ey(e);if(!t)return[];let n=this.pendingClaudeToolUses.get(t.toolUseId);if(!n)return[];this.pendingClaudeToolUses.delete(t.toolUseId);let r=Dy({toolUse:n,toolUseId:t.toolUseId,raw:e,turnId:this.activeTurnId});return r?[...this.maybeEmitTurnStarted(`user.tool_use_result`),{type:`item.completed`,item:r}]:[]}maybeCreateThreadStartedEvent(e,t){return this.threadStartedEmitted?null:(this.threadStartedEmitted=!0,{type:`thread.started`,thread_id:e??this.resumeSessionId??this.id,source:t})}maybeEmitTurnStarted(e){return this.activeTurnStarted||!this.activeTurnId?[]:(this.activeTurnStarted=!0,[{type:`turn.started`,turn_id:this.activeTurnId,source_event_type:e}])}};function by(e){return typeof e.decisionReason==`string`&&e.decisionReason.trim().length>0||typeof e.blockedPath==`string`&&e.blockedPath.trim().length>0?!0:Array.isArray(e.suggestions)&&e.suggestions.length>0}function xy(e,t){let n=e.toLowerCase();return n.includes(`askuserquestion`)||n.includes(`request_user_input`)?!0:Array.isArray(t.questions)}function Sy(e){return(Array.isArray(e.questions)?e.questions:[{id:`question_1`,header:`Question`,question:typeof e.question==`string`?e.question:`Please provide input`,multiSelect:!1,isOther:e.isOther===!0,isSecret:e.isSecret===!0,options:e.options}]).map((e,t)=>{if(typeof e!=`object`||!e)return null;let n=e,r=typeof n.id==`string`&&n.id?n.id:`question_${t+1}`,i=typeof n.header==`string`&&n.header?n.header:`Question`,a=typeof n.question==`string`&&n.question?n.question:`Please provide input`,o=Cy(n.options);return{id:r,header:i,question:a,multiSelect:n.multiSelect===!0,isOther:n.isOther===!0,isSecret:n.isSecret===!0,options:o}}).filter(e=>e!==null)}function Cy(e){if(!Array.isArray(e))return null;let t=e.map(e=>{if(typeof e==`string`)return{label:e,description:e};if(typeof e!=`object`||!e)return null;let t=e,n=typeof t.label==`string`?t.label:``,r=typeof t.description==`string`?t.description:n,i=typeof t.markdown==`string`&&t.markdown.length>0?t.markdown:void 0;return n?{label:n,description:r,markdown:i}:null}).filter(e=>e!==null);return t.length>0?t:null}function wy(e){let t={};for(let[n,r]of Object.entries(e??{}))t[n]=Array.isArray(r)?r.map(e=>String(e)):[];return t}function Ty(e){let t=Uy(e.message),n=Array.isArray(t.content)?t.content:[],r=[];for(let e of n){let t=Uy(e);if(t.type!==`tool_use`)continue;let n=Wy(t.id),i=Wy(t.name),a=Uy(t.input);if(!(!n||!i)){if(i===`Task`){let e=Wy(a.subagent_type),t=Wy(a.description)??e??`任务`;r.push({id:n,toolName:`Task`,title:`${e??`Task`}(${t})`,pendingStatusLabel:`运行中`,prompt:Wy(a.prompt),responseLabel:`Response`,subagentType:e,description:t});continue}if(i===`Read`){let e=Wy(a.file_path);r.push({id:n,toolName:`Read`,title:`Read 1 file`,pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:e});continue}if(i===`Write`){let e=Wy(a.file_path);r.push({id:n,toolName:`Write`,title:My(e),pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:e})}}}return r}function Ey(e){let t=Uy(e.message),n=Array.isArray(t.content)?t.content:[];for(let e of n){let t=Uy(e);if(t.type!==`tool_result`)continue;let n=Wy(t.tool_use_id);if(n)return{toolUseId:n}}return null}function Dy(e){let t=Uy(e.raw.tool_use_result),n=Oy(t.content)??zy(Uy(e.raw.message)),r=Uy(t.usage),i=qy(t.totalTokens)??qy(r.total_tokens)??qy(r.output_tokens),a=qy(t.totalToolUseCount),o=qy(t.totalDurationMs),s=Wy(t.agentId),c=Wy(t.filePath)??e.toolUse.filePath;if(e.toolUse.toolName===`Task`){let t=Ay(a,i,o);return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:t,status:`completed`,status_label:t,display_as:`tool_card`,prompt:e.toolUse.prompt,response:n,response_label:e.toolUse.responseLabel,subagent_type:e.toolUse.subagentType,description:e.toolUse.description,agent_id:s,total_tokens:i,total_tool_uses:a,duration_ms:o,source_event_type:`user.tool_use_result`}}if(e.toolUse.toolName===`Read`){let r=ky(t)??n;return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:`Done`,status:`completed`,status_label:`Done`,display_as:`tool_card`,response:r,response_label:e.toolUse.responseLabel,file_path:c,total_tokens:i,duration_ms:o,source_event_type:`user.tool_use_result`}}if(e.toolUse.toolName===`Write`){let n=Gy(t.content),r=jy(Py(n),c);return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:r,status:`completed`,status_label:r,display_as:`tool_card`,response:n,response_label:e.toolUse.responseLabel,file_path:c,total_tokens:i,duration_ms:o,source_event_type:`user.tool_use_result`}}return null}function Oy(e){if(typeof e==`string`&&e.length>0)return e;if(!Array.isArray(e))return;let t=[];for(let n of e){let e=Uy(n);e.type===`text`&&typeof e.text==`string`&&e.text.length>0&&t.push(e.text)}return t.length>0?t.join(`
|
|
477
|
-
`):void 0}function
|
|
478
|
-
`).length}function
|
|
479
|
-
`)}function By(e){let t=Uy(Uy(e.event).delta);if(typeof t.text==`string`&&t.text.length>0)return t.text}function Vy(e){let t=Array.isArray(e.errors)?e.errors.filter(e=>typeof e==`string`):[];return t.length>0?t.join(`; `):Wy(e.subtype)||`Claude turn failed`}function Hy(e){let t=Uy(e);return{input_tokens:qy(t.input_tokens)??qy(t.inputTokens)??0,cached_input_tokens:qy(t.cached_input_tokens)??qy(t.cache_read_input_tokens)??qy(t.cacheReadInputTokens)??0,output_tokens:qy(t.output_tokens)??qy(t.outputTokens)??0}}function Uy(e){return typeof e==`object`&&e?e:{}}function Wy(e){if(typeof e==`string`&&e.trim())return e}function Gy(e){if(typeof e==`string`&&e.length>0)return e}function Ky(e){if(Array.isArray(e)){for(let t of e)if(typeof t==`string`&&t.trim())return t}}function qy(e){if(typeof e==`number`&&Number.isFinite(e))return e}function Jy(e){let t=Wy(Uy(e.message).id);if(t)return t;let n=Wy(Uy(Uy(e.event).message).id);if(n)return n}function Yy(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`_`);return t?t.replace(/^_+|_+$/g,``):`tool`}var Xy=class{constructor(e,t,n,r){this.nativeSession=r,this.provider=e,this.id=t,this.model=n,this.bindNativeEvents(r)}id;provider;providerMode=`native`;model;listeners=new Set;unsubscribe;onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async sendInput(e,t){if(typeof this.nativeSession?.sendInput==`function`){await this.nativeSession.sendInput(e);return}if(typeof this.nativeSession?.input==`function`){await this.nativeSession.input(e);return}if(typeof this.nativeSession?.turn==`function`){await this.nativeSession.turn({input:e});return}throw Error(`Native session does not expose a known input method`)}async interrupt(){if(typeof this.nativeSession?.interrupt==`function`){await this.nativeSession.interrupt();return}if(typeof this.nativeSession?.cancel==`function`){await this.nativeSession.cancel();return}throw Error(`Native session does not expose interrupt/cancel`)}async close(){if(typeof this.unsubscribe==`function`&&(this.unsubscribe(),this.unsubscribe=void 0),typeof this.nativeSession?.close==`function`){await this.nativeSession.close();return}if(typeof this.nativeSession?.dispose==`function`){await this.nativeSession.dispose();return}}async respondToolPermission(e,t,n){if(typeof this.nativeSession?.respondToolPermission==`function`){await this.nativeSession.respondToolPermission({requestId:e,decision:t,reason:n});return}if(typeof this.nativeSession?.approveToolCall==`function`){await this.nativeSession.approveToolCall({requestId:e,approved:t===`allow`,reason:n});return}throw Error(`Native session does not expose tool approval response method`)}bindNativeEvents(e){let t=e=>{let t=Zy(e);for(let e of this.listeners)e(t)};if(typeof e?.subscribe==`function`){let n=e.subscribe(e=>t(e));typeof n==`function`&&(this.unsubscribe=n);return}if(typeof e?.on==`function`){let n=e=>t(e);e.on(`event`,n),this.unsubscribe=()=>{typeof e?.off==`function`&&e.off(`event`,n)};return}throw Error(`Native session does not expose a known event subscription API`)}};function Zy(e){return typeof e==`object`&&e&&`type`in e?e:{type:`status.progress`,nativeEvent:e}}var Qy=`@anthropic-ai/claude-agent-sdk`,$y=`claude-sonnet-4-6`,eb=1e4,tb=class{constructor(e,t){this.preferNative=e,this.requireNative=t}provider=`claude`;async isNativeAvailable(){try{return await import(Qy),!0}catch{return!1}}async createSession(e){if(!this.preferNative)throw Error(`Claude native provider is disabled. Set ENABLE_NATIVE_PROVIDERS=true to use Claude sessions.`);try{let t=await import(Qy),n=await nb(rb(t,e),eb,`Claude native query session creation timed out`);if(n)return n;let r=await nb(ib(t,e),eb,`Claude legacy native session creation timed out`);if(r)return r;throw this.requireNative,Error(`Claude SDK loaded but no supported stable session API was found`)}catch(e){throw Error(`Claude native session creation failed: ${String(e)}`)}}};async function nb(e,t,n){if(!Number.isFinite(t)||t<=0)return e;let r,i=new Promise((e,i)=>{r=setTimeout(()=>{i(Error(n))},t)});try{return await Promise.race([e,i])}finally{r&&clearTimeout(r)}}async function rb(e,t){let n=ab(e);if(!n)return null;let r=t.model??$y;return new yy(t.sessionId,r,({prompt:e,model:i,sessionConfig:a,resume:o,abortController:s,canUseTool:c})=>{let l=a?.permissionMode??t.sessionConfig?.permissionMode??`default`,u={model:i??r,includePartialMessages:!0,abortController:s,canUseTool:c,permissionMode:l},d=ob(a?.reasoningEffort??t.sessionConfig?.reasoningEffort);return d&&(u.effort=d),l===`bypassPermissions`&&(u.allowDangerouslySkipPermissions=!0),t.cwd&&(u.cwd=t.cwd),o&&(u.resume=o,u.forkSession=!1),n({prompt:e,options:u})},t.resumeSessionId,{cwd:t.cwd})}async function ib(e,t){if(typeof e?.createSession==`function`){let n=await e.createSession({model:t.model,cwd:t.cwd,metadata:t.metadata,sessionId:t.sessionId});return new Xy(`claude`,t.sessionId,t.model,n)}if(typeof e?.ClaudeAgentClient==`function`){let n=new e.ClaudeAgentClient;if(typeof n?.createSession==`function`){let e=await n.createSession({model:t.model,cwd:t.cwd,metadata:t.metadata,sessionId:t.sessionId});return new Xy(`claude`,t.sessionId,t.model,e)}}if(typeof e?.default?.createSession==`function`){let n=await e.default.createSession({model:t.model,cwd:t.cwd,metadata:t.metadata,sessionId:t.sessionId});return new Xy(`claude`,t.sessionId,t.model,n)}return null}function ab(e){if(typeof e?.query==`function`)return e.query;if(typeof e?.default?.query==`function`)return e.default.query}function ob(e){if(e){if(e===`max`)return`max`;if(e===`high`||e===`medium`||e===`low`)return e;if(e===`xhigh`)return`max`;if(e===`minimal`||e===`none`)return`low`}}function sb(e,t={}){let n=t.preferNative??!1,r=t.requireNative??!1;return e===`codex`?new ry(n,r):new tb(n,r)}const cb=p.default.join(`.claude`,`projects`);async function lb(e){return(await(0,w.listSessions)(typeof e==`number`?{limit:e}:void 0)).map(e=>gb(e)).filter(e=>typeof e.cwd==`string`).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}async function ub(e,t){let n=mb(e,t?.homeDir),r;try{r=await d.default.readdir(n,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}let i=[];for(let e of r){if(!e.isFile()||!e.name.endsWith(`.jsonl`))continue;let t=p.default.join(n,e.name),r=e.name.slice(0,-6),a=await Cb(t);if(!bb(a))continue;let o=await d.default.stat(t),s=yb(a,{createdAtFallbackMs:o.birthtimeMs,updatedAtFallbackMs:o.mtimeMs});i.push({nativeSessionId:r,model:s.model,title:s.title,createdAt:s.createdAt,updatedAt:s.updatedAt})}return i.sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}async function db(e){let t=await wb(e.nativeSessionId,e.projectPath),n=await Tb(e.projectPath,e.nativeSessionId,e.homeDir);return _b({rows:t,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,nativeSessionId:e.nativeSessionId,createdAtFallbackMs:n.birthtimeMs,updatedAtFallbackMs:n.mtimeMs})}async function fb(e){let t=await wb(e.nativeSessionId,e.projectPath),n=await Tb(e.projectPath,e.nativeSessionId,e.homeDir);return vb({rows:t,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,nativeSessionId:e.nativeSessionId,createdAtFallbackMs:n.birthtimeMs,updatedAtFallbackMs:n.mtimeMs})}function pb(e,t,n){return p.default.join(mb(e,n),`${t}.jsonl`)}function mb(e,t){let n=t??f.default.homedir();return p.default.join(n,cb,hb(e))}function hb(e){let t=p.default.resolve(e).replace(/\\/g,`/`).replace(/:/g,`-`).replace(/\//g,`-`);return t.startsWith(`-`)?t:`-${t}`}function gb(e){let t=xb(e.customTitle)??xb(e.summary)??xb(e.firstPrompt),n=Sb(e.lastModified);return{nativeSessionId:e.sessionId,cwd:xb(e.cwd),title:t,createdAt:n,updatedAt:n}}function _b(e){let t=[],n=yb(e.rows,{createdAtFallbackMs:e.createdAtFallbackMs,updatedAtFallbackMs:e.updatedAtFallbackMs}),r=Date.parse(n.createdAt),i=0,a=Number.isFinite(r)?r:0,o=0,s,c=e=>{if(e){let t=Date.parse(e);if(Number.isFinite(t))return a=Math.max(a+1,t),new Date(t).toISOString()}return a+=1,new Date(a).toISOString()},l=(n,r,a)=>{i+=1,t.push({v:`1.0`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`hist_claude_${e.sessionId}_${i.toString().padStart(6,`0`)}_${n.replace(/\./g,`_`)}`,ts:c(a),type:n,payload:{raw:r}})},u=(e,t)=>s||(o+=1,s={id:`claude_hist_turn_${o}`,terminal:!1,failed:!1},l(`turn.started`,{turn_id:s.id,source_event_type:`claude.history`,source_line:t},e),s),d=(e,t)=>{if(!s||s.terminal){s=void 0;return}s.terminal=!0,l(`turn.completed`,{turn_id:s.id,source_event_type:`claude.history`,source_line:t},e),s=void 0},f=(e,t,n)=>{let r=u(t,n);r.terminal||(r.terminal=!0,r.failed=!0,l(`turn.failed`,{turn_id:r.id,source_event_type:`claude.history`,source_line:n,error:{message:e}},t),s=void 0)};l(`thread.started`,{thread_id:e.nativeSessionId,source:`claude.history.getSessionMessages`},n.createdAt),n.title&&l(`thread.title.updated`,{title:n.title,source:`claude.history.first_user_message`,thread_id:e.nativeSessionId},n.createdAt);for(let t of e.rows){let e=t.type;if(!e||e===`queue-operation`)continue;if(e===`user`){let e=Mb(t.raw.message),n=kb(e),r=Ob(e);if(n){d(t.timestamp,t.line);let e=u(t.timestamp,t.line);l(`item.completed`,{item:{id:Nb(t.raw.uuid)??`claude_user_${t.line}`,type:`user_message`,text:n,turn_id:e.id,source_event_type:`claude.user`},source_line:t.line},t.timestamp)}for(let e=0;e<r.length;e+=1){let n=r[e],i=u(t.timestamp,t.line);l(`item.completed`,{item:{id:n.toolUseId??`claude_tool_result_${t.line}_${e+1}`,type:`tool_status`,status:n.isError?`failed`:`completed`,tool_name:n.toolName??`tool`,text:n.text,turn_id:i.id,source_event_type:`claude.tool_result`},source_line:t.line},t.timestamp)}continue}if(e!==`assistant`)continue;let n=Mb(t.raw.message),r=u(t.timestamp,t.line),i=Db(n);for(let e=0;e<i.length;e+=1){let n=i[e];l(`item.started`,{item:{id:n.id??`claude_tool_use_${t.line}_${e+1}`,type:`tool_status`,status:`running`,tool_name:n.name,text:n.summary,command:n.command,turn_id:r.id,source_event_type:`claude.tool_use`},source_line:t.line},t.timestamp)}let a=kb(n);a&&l(`item.completed`,{item:{id:Nb(n.id)??Nb(t.raw.uuid)??`claude_assistant_${t.line}`,type:`agent_message`,text:a,turn_id:r.id,source_event_type:`claude.assistant`},source_line:t.line},t.timestamp);let o=Nb(t.raw.error);o&&f(o,t.timestamp,t.line)}return d(n.updatedAt),t}function vb(e){let t=[],n=yb(e.rows,{createdAtFallbackMs:e.createdAtFallbackMs,updatedAtFallbackMs:e.updatedAtFallbackMs}),r=Date.parse(n.createdAt),i=0,a=Number.isFinite(r)?r:0,o=e=>{if(e){let t=Date.parse(e);if(Number.isFinite(t))return a=Math.max(a+1,t),new Date(t).toISOString()}return a+=1,new Date(a).toISOString()};for(let n of e.rows)i+=1,t.push({v:`1.0`,kind:`provider.raw`,rawSeq:i,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`raw_hist_claude_${e.sessionId}_${i.toString().padStart(6,`0`)}`,ts:o(n.timestamp),type:`native.raw`,payload:{raw:{source:`claude.history.getSessionMessages`,native_type:n.type??`unknown`,message:n.raw,historyReplay:!0,replaySynthetic:!1,source_line:n.line,native_session_id:e.nativeSessionId}}});return t}function yb(e,t){let n,r,i,a;for(let t of e)t.timestampMs!==void 0&&(i=i===void 0?t.timestampMs:Math.min(i,t.timestampMs),a=a===void 0?t.timestampMs:Math.max(a,t.timestampMs)),!r&&t.type===`user`&&(r=jb(kb(Mb(t.raw.message)))),!n&&t.type===`assistant`&&(n=Nb(Mb(t.raw.message).model));let o=i??Fb(t.createdAtFallbackMs)??0,s=a??Fb(t.updatedAtFallbackMs)??o;return{model:n,title:r,createdAt:new Date(o).toISOString(),updatedAt:new Date(s).toISOString()}}function bb(e){for(let t of e){if(t.type===`user`){let e=Mb(t.raw.message);if(kb(e)||Ob(e).length>0)return!0;continue}if(t.type!==`assistant`)continue;let e=Mb(t.raw.message);if(kb(e)||Db(e).length>0||Nb(t.raw.error))return!0}return!1}function xb(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Sb(e){return Number.isFinite(e)?new Date(e).toISOString():new Date(0).toISOString()}async function Cb(e){let t=(await d.default.readFile(e,`utf8`)).split(`
|
|
480
|
-
`),n=[];for(let e=0;e<t.length;e+=1){let r=t[e]?.trim();if(!r)continue;let i;try{i=JSON.parse(r)}catch{continue}let a=
|
|
481
|
-
`)}function Ab(e){let t=Array.isArray(e.text_elements)?e.text_elements:Array.isArray(e.textElements)?e.textElements:[];if(t.length===0)return;let n=[];for(let e of t){let t=Mb(e),r=Nb(t.text)??Nb(t.value);r&&n.push(r)}return n.length>0?n.join(``):void 0}function jb(e,t=60){if(!e)return;let n=e.replace(/\s+/g,` `).trim();if(!n)return;let r=Array.from(n);return r.length<=t?n:r.slice(0,t).join(``).trimEnd()}function Mb(e){return typeof e==`object`&&e?e:{}}function Nb(e){return typeof e==`string`&&e.trim()||void 0}function Pb(e){let t=Date.parse(e);if(Number.isFinite(t))return t}function Fb(e){if(!(!Number.isFinite(e)||e<=0))return Math.round(e)}var Ib=class{constructor(e){this.options=e}async init(){await this.options.store.init()}async getProjects(){await this.init();let e=await this.options.store.getIndex();return e?{generatedAt:e.generatedAt,source:`cache`,providers:e.providers,projects:e.projects}:this.refreshProjects()}async refreshProjects(){await this.init();let e=new Map,[t,n]=await Promise.all([this.scanCodexSessions(e),this.scanClaudeSessions(e)]),r=new Date().toISOString(),i={codex:t.status,claude:n.status},{projects:a,projectSessions:o}=Rb(r,[t,n]);if(zb(i)){let e=await this.options.store.getSnapshot();if(e)return await this.options.store.writeSnapshot({...e,providers:i}),{generatedAt:e.generatedAt,source:`cache`,providers:i,projects:e.projects}}return await this.options.store.writeSnapshot({generatedAt:r,providers:i,projects:a,projectSessions:o}),{generatedAt:r,source:`fresh_scan`,providers:i,projects:a}}async listProjectSessions(e){await this.init();let t=e.trim(),n=await this.options.store.getIndex(),r=!1;n||(n=Vb(await this.refreshProjects()),r=!0);let i=await Bb(n.projects,t);if(!i)throw qg(t);let a=await this.options.store.getProject(i.key);if(!a&&!r){if(n=Vb(await this.refreshProjects()),i=await Bb(n.projects,t),!i)throw qg(t);if(a=await this.options.store.getProject(i.key),!a)throw Error(`Discovery cache missing project sessions: ${i.path}`)}if(!a)throw Error(`Discovery cache missing project sessions: ${i.path}`);return{canonicalProjectPath:i.path,project:a.project,providers:a.providers,sessions:a.sessions}}async scanCodexSessions(e){let t=new Date().toISOString();try{let n=new Map;for(let e of[!1,!0]){let t=null;do{let r=await fy({archived:e,cursor:t,limit:100});for(let e of r.threads)n.set(e.id,e);t=r.nextCursor}while(t)}let r=await Lb({sessions:[...n.values()],canonicalPathCache:e,getRawPath:e=>Wb(e.cwd),mapSession:e=>{let t=Gb(e.createdAt),n=Gb(e.updatedAt,t);return{provider:`codex`,nativeSessionId:e.id,title:Wb(e.name)??Wb(e.preview),model:Wb(e.model),createdAt:t,updatedAt:n}}});return{records:r.records,status:{scannedAt:t,sessionCount:r.records.length,status:r.skippedCount>0?`partial`:`ready`,...r.skippedCount>0?{error:`Skipped ${r.skippedCount} Codex session(s) with missing or invalid cwd`}:{}}}}catch(e){return{records:[],status:{scannedAt:t,sessionCount:0,status:`failed`,error:String(e)}}}}async scanClaudeSessions(e){let t=new Date().toISOString();try{let n=await Lb({sessions:await lb(),canonicalPathCache:e,getRawPath:e=>Wb(e.cwd),mapSession:e=>({provider:`claude`,nativeSessionId:e.nativeSessionId,title:Wb(e.title),model:Wb(e.model),createdAt:Wb(e.createdAt),updatedAt:e.updatedAt})});return{records:n.records,status:{scannedAt:t,sessionCount:n.records.length,status:n.skippedCount>0?`partial`:`ready`,...n.skippedCount>0?{error:`Skipped ${n.skippedCount} Claude session(s) with missing or invalid cwd`}:{}}}}catch(e){return{records:[],status:{scannedAt:t,sessionCount:0,status:`failed`,error:String(e)}}}}};async function Lb(e){let t=[],n=0;for(let r of e.sessions){let i=e.getRawPath(r);if(!i){n+=1;continue}try{let n=await Hb(i,e.canonicalPathCache);t.push({canonicalProjectPath:n,session:e.mapSession(r)})}catch{n+=1}}return{records:t,skippedCount:n}}function Rb(e,t){let n=new Map;for(let e of t)for(let t of e.records){let e=n.get(t.canonicalProjectPath);e||(e={path:t.canonicalProjectPath,key:Ub(t.canonicalProjectPath),title:p.default.basename(t.canonicalProjectPath)||t.canonicalProjectPath,providerCounts:{codex:0,claude:0},sessionsByKey:new Map},n.set(t.canonicalProjectPath,e));let r=`${t.session.provider}:${t.session.nativeSessionId}`,i=e.sessionsByKey.get(r);i||(e.providerCounts[t.session.provider]+=1);let a=Kb(i,t.session);e.sessionsByKey.set(r,a),(!e.lastSessionAt||t.session.updatedAt>e.lastSessionAt)&&(e.lastSessionAt=t.session.updatedAt)}let r=[...n.values()].map(t=>({project:{key:t.key,path:t.path,title:t.title,lastSessionAt:t.lastSessionAt,sessionCount:t.sessionsByKey.size,providerCounts:t.providerCounts,lastDiscoveryAt:e},sessions:[...t.sessionsByKey.values()].sort(Jb)})).sort((e,t)=>qb(e.project,t.project));return{projects:r.map(e=>e.project),projectSessions:r}}function zb(e){return Object.values(e).some(e=>e?.status===`failed`)}async function Bb(e,t){let n=e.find(e=>e.path===t);if(n)return n;let r=await ev(t);return e.find(e=>e.path===r)}function Vb(e){return{v:1,generatedAt:e.generatedAt,providers:e.providers,projects:e.projects}}async function Hb(e,t){let n=t.get(e);return n||(n=ev(e),t.set(e,n)),n}function Ub(e){return(0,l.createHash)(`sha256`).update(e).digest(`hex`).slice(0,16)}function Wb(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Gb(e,t){return!Number.isFinite(e)||e<=0?t??new Date(0).toISOString():new Date(e*1e3).toISOString()}function Kb(e,t){return e&&e.updatedAt>=t.updatedAt?e:t}function qb(e,t){let n=e.lastSessionAt??e.lastDiscoveryAt,r=t.lastSessionAt??t.lastDiscoveryAt;return n===r?e.path.localeCompare(t.path):r.localeCompare(n)}function Jb(e,t){return e.updatedAt===t.updatedAt?`${e.provider}:${e.nativeSessionId}`.localeCompare(`${t.provider}:${t.nativeSessionId}`):t.updatedAt.localeCompare(e.updatedAt)}var Yb=class{indexPath;projectsDir;ready;writeQueue=Promise.resolve();indexCache=null;projectCache=new Map;constructor(e){this.baseDir=e,this.indexPath=p.default.join(e,`discovery-index.json`),this.projectsDir=p.default.join(e,`discovery-projects`),this.ready=this.loadFromDisk()}async init(){await this.ready}async getIndex(){return await this.ready,this.indexCache?structuredClone(this.indexCache):null}async getProject(e){await this.ready;let t=this.projectCache.get(e);if(t)return structuredClone(t);let n=await Xb(this.getProjectPath(e),$b);return n?(this.projectCache.set(e,n),structuredClone(n)):null}async getSnapshot(){if(await this.ready,!this.indexCache)return null;let e=[];for(let t of this.indexCache.projects){let n=await this.getProject(t.key);if(!n)return null;e.push({project:n.project,sessions:n.sessions})}return{generatedAt:this.indexCache.generatedAt,providers:structuredClone(this.indexCache.providers),projects:structuredClone(this.indexCache.projects),projectSessions:e}}async writeSnapshot(e){await this.ready;let t={v:1,generatedAt:e.generatedAt,providers:e.providers,projects:e.projects},n=e.projectSessions.map(t=>({v:1,projectKey:t.project.key,canonicalProjectPath:t.project.path,project:t.project,providers:e.providers,sessions:t.sessions}));await this.enqueueWrite(async()=>{await d.default.mkdir(this.projectsDir,{recursive:!0});let e=new Set(n.map(e=>e.projectKey)),r=[];try{r=await d.default.readdir(this.projectsDir,{withFileTypes:!0})}catch(e){if(e.code!==`ENOENT`)throw e}await Promise.all(n.map(async e=>{await Zb(this.getProjectPath(e.projectKey),e)})),await Promise.all(r.map(async t=>{if(!t.isFile()||!t.name.endsWith(`.json`))return;let n=t.name.slice(0,-5);e.has(n)||(await d.default.rm(p.default.join(this.projectsDir,t.name),{force:!0}),this.projectCache.delete(n))})),await Zb(this.indexPath,t),this.indexCache=t,this.projectCache.clear();for(let e of n)this.projectCache.set(e.projectKey,e)})}async loadFromDisk(){await d.default.mkdir(this.baseDir,{recursive:!0}),await d.default.mkdir(this.projectsDir,{recursive:!0}),this.indexCache=await Xb(this.indexPath,Qb)}getProjectPath(e){return p.default.join(this.projectsDir,`${e}.json`)}enqueueWrite(e){return this.writeQueue=this.writeQueue.then(e,e),this.writeQueue}};async function Xb(e,t){try{let n=await d.default.readFile(e,`utf8`),r=JSON.parse(n);return t(r)?r:null}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Zb(e,t){let n=`${JSON.stringify(t,null,2)}\n`;try{if(await d.default.readFile(e,`utf8`)===n)return}catch(e){if(e.code!==`ENOENT`)throw e}await d.default.mkdir(p.default.dirname(e),{recursive:!0});let r=`${e}.${process.pid}.${Date.now()}.tmp`;await d.default.writeFile(r,n,`utf8`),await d.default.rename(r,e)}function Qb(e){return!ex(e)||e.v!==1||typeof e.generatedAt!=`string`||!Wa.safeParse(e.providers).success||!Array.isArray(e.projects)?!1:e.projects.every(e=>Ga.safeParse(e).success)}function $b(e){return!ex(e)||e.v!==1||typeof e.projectKey!=`string`||e.projectKey.length===0||typeof e.canonicalProjectPath!=`string`||e.canonicalProjectPath.length===0||!Ga.safeParse(e.project).success||!Wa.safeParse(e.providers).success||!Array.isArray(e.sessions)?!1:e.sessions.every(e=>Ka.safeParse(e).success)}function ex(e){return typeof e==`object`&&!!e}const tx=Buffer.from([48,42,48,5,6,3,43,101,112,3,33,0]);function nx(e){let t=vo.parse(e.clientHello),n=(0,l.randomBytes)(32).toString(`base64`),{privateKey:r,publicKey:i}=(0,l.generateKeyPairSync)(`x25519`),a=is(ss(ox(i.export({format:`jwk`})))),o=Jo({gatewayId:e.gatewayId,clientHello:t,gatewayHello:{gatewayNonce:n,gatewayPublicKeyFingerprint:e.gatewayIdentity.publicKeyFingerprint,gatewayEphemeralPublicKey:a}}),s=(0,l.sign)(null,Buffer.from(o,`utf8`),(0,l.createPrivateKey)(e.privateKeyPem)).toString(`base64`);return{gatewayHello:yo.parse({version:t.version,securityLevel:t.securityLevel,cipherSuite:t.cipherSuite,gatewayId:e.gatewayId,deviceId:t.deviceId,clientNonce:t.clientNonce,gatewayNonce:n,gatewayPublicKeyFingerprint:e.gatewayIdentity.publicKeyFingerprint,gatewayEphemeralPublicKey:a,signatureAlgorithm:`ed25519`,signature:s}),gatewayEphemeralPrivateKey:r}}function rx(e){let t=vo.parse(e.clientHello),n=yo.parse(e.gatewayHello),r=bo.parse(e.clientAuth);if(t.version!==n.version||r.version!==t.version||!so.safeParse(t.cipherSuite).success||n.cipherSuite!==t.cipherSuite||t.cipherSuite!==`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`)throw Error(`unsupported_version`);if(r.gatewayId!==e.gatewayId||n.gatewayId!==e.gatewayId)throw Error(`transcript_invalid`);if(r.deviceId!==t.deviceId||n.deviceId!==t.deviceId||r.deviceIdentityFingerprint!==t.deviceIdentity.publicKeyFingerprint)throw Error(`identity_mismatch`);let i=(0,l.createPublicKey)({format:`der`,type:`spki`,key:Buffer.concat([tx,as(t.deviceIdentity.publicKey)])});if(!(0,l.verify)(null,Buffer.from(Yo({gatewayId:e.gatewayId,clientHello:t,gatewayHello:{gatewayNonce:n.gatewayNonce,gatewayPublicKeyFingerprint:n.gatewayPublicKeyFingerprint,gatewayEphemeralPublicKey:n.gatewayEphemeralPublicKey},clientAuth:{clientEphemeralPublicKey:r.clientEphemeralPublicKey}}),`utf8`),i,as(r.signature)))throw Error(`transcript_invalid`)}function ix(e){let t=yo.parse(e.gatewayHello),n=bo.parse(e.clientAuth),r=(0,l.createPublicKey)({key:{crv:`X25519`,kty:`OKP`,x:os(as(n.clientEphemeralPublicKey))},format:`jwk`}),i=(0,l.diffieHellman)({privateKey:e.gatewayEphemeralPrivateKey,publicKey:r});return Qo({role:`gateway`,keySchedule:Zo({gatewayId:e.gatewayId,clientHello:vo.parse(e.clientHello),gatewayHello:{gatewayNonce:t.gatewayNonce,gatewayPublicKeyFingerprint:t.gatewayPublicKeyFingerprint,gatewayEphemeralPublicKey:t.gatewayEphemeralPublicKey},clientAuth:{clientEphemeralPublicKey:n.clientEphemeralPublicKey},sharedSecret:new Uint8Array(i),keyEpoch:1})})}function ax(e){return wo.parse({version:1,gatewayId:e.gatewayId,deviceId:e.deviceId,code:e.code,message:e.message,retryable:e.retryable})}function ox(e){if(typeof e.x!=`string`||e.x.length===0)throw Error(`x25519 public key export missing x`);return e.x}var sx=class{OPEN=1;readyState=1;constructor(e){this.onPayload=e}send(e){let t=JSON.parse(e);this.onPayload(t)}close(){this.readyState=3}},cx=class{mobileConnections=new Map;constructor(e){this.dependencies=e}async handleFrame(e){switch(e.type){case`mobile.connected`:this.addMobileConnection(e.mobileId??``,e.payload.deviceId,e.payload.deliveryMode,e.payload.gatewayAvailableAtConnect);return;case`mobile.disconnected`:this.removeMobileConnection(e.mobileId??``);return;case`secure.client_hello`:await this.handleSecureClientHello(e.mobileId,e.payload);return;case`secure.client_auth`:await this.handleSecureClientAuth(e.mobileId,e.payload);return;case`from_mobile`:await this.handleFromMobile(e);return;case`rpc.request`:await this.handleRpcRequest(e);return;case`pairing.claim.forward`:await this.handlePairingClaim(e.requestId,e.payload);return;case`auth.refresh.forward`:await this.handleRefresh(e.requestId,e.payload);return;default:return}}close(){for(let e of this.mobileConnections.keys())this.removeMobileConnection(e)}addMobileConnection(e,t,n,r){e&&(this.removeMobileConnection(e),this.mobileConnections.set(e,{mobileId:e,deviceId:t,handshake:{status:`awaiting_client_hello`}}),this.dependencies.relayTransportSecurityLevel===`e2ee-relay`&&n===`gateway_replay`&&this.dependencies.sendFrame(Go.parse({type:`secure.handshake_required`,gatewayId:this.dependencies.gatewayId,mobileId:e,messageType:`system`,payload:{version:1,gatewayId:this.dependencies.gatewayId,deviceId:t,reason:r?`gateway_restarted`:`gateway_available`,retryable:!0}})))}removeMobileConnection(e){let t=this.mobileConnections.get(e);t&&(t.socket?.close(),t.clientId&&this.dependencies.sessionHub.removeClient(t.clientId),this.mobileConnections.delete(e))}async handleFromMobile(e){let t=e.mobileId;if(!t){this.sendRelayError({code:`BAD_REQUEST`,status:400,message:`from_mobile frame requires mobileId`});return}let n=this.mobileConnections.get(t);if(!n){this.sendRelayError({mobileId:t,code:`BAD_REQUEST`,status:400,message:`Unknown mobile ${t}`});return}if(n.handshake.status!==`ready`||!n.clientId){this.sendSecureError(t,n.deviceId,`transcript_invalid`,`secure handshake not ready`);return}let r=n,i=this.decodeRelayBusinessPayload({connection:r,mobileId:t,frameType:`from_mobile`,messageType:e.messageType,parse:e=>oa.parse(e),payload:e.payload,encryptedPayload:e.encryptedPayload});i&&await this.dependencies.dispatchCommand(i,r.deviceId,r.clientId)}async handlePairingClaim(e,t){try{let n=await this.dependencies.handlePairingClaim(t);this.dependencies.sendFrame(Go.parse({type:`pairing.claim.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...ux(t,`pairing.claim`)})}}async handleRefresh(e,t){try{let n=await this.dependencies.handleRefresh(t);this.dependencies.sendFrame(Go.parse({type:`auth.refresh.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...ux(t,`auth.refresh`)})}}async handleRpcRequest(e){let t=e.mobileId,n=e.requestId,r=this.mobileConnections.get(t);if(!r){this.dependencies.sendFrame({type:`rpc.error`,gatewayId:this.dependencies.gatewayId,mobileId:t,requestId:n,messageType:`rpc`,payload:{...lx(`BAD_REQUEST`,400,`Unknown mobile ${t}`)}});return}if(r.handshake.status!==`ready`){this.sendSecureError(t,r.deviceId,`transcript_invalid`,`secure handshake not ready`);return}let i=r,a=this.decodeRelayBusinessPayload({connection:i,mobileId:t,frameType:`rpc.request`,messageType:e.messageType,requestId:n,parse:e=>To.parse(e),payload:e.payload,encryptedPayload:e.encryptedPayload});if(a)try{let e=await this.dependencies.handleRpcRequest(a,{mobileId:t,deviceId:i.deviceId});this.dependencies.sendFrame(Go.parse({type:`rpc.response`,gatewayId:this.dependencies.gatewayId,mobileId:t,requestId:n,messageType:`rpc`,...this.createRelayBusinessPayloadFields(i,{frameType:`rpc.response`,messageType:`rpc`,requestId:n},e)}))}catch(e){let r=Oo.safeParse(e);this.dependencies.sendFrame({type:`rpc.error`,gatewayId:this.dependencies.gatewayId,mobileId:t,requestId:n,messageType:`rpc`,...this.createRelayBusinessPayloadFields(i,{frameType:`rpc.error`,messageType:`rpc`,requestId:n},{...r.success?r.data:lx(`INTERNAL`,500,String(e)),method:a.method})})}}async handleSecureClientHello(e,t){if(!e){this.sendRelayError({code:`BAD_REQUEST`,status:400,message:`secure.client_hello frame requires mobileId`});return}let n=this.mobileConnections.get(e);if(!n){this.sendRelayError({mobileId:e,code:`BAD_REQUEST`,status:400,message:`Unknown mobile ${e}`});return}if(n.handshake.status!==`awaiting_client_hello`){this.sendSecureError(e,n.deviceId,`counter_replay`,`duplicate secure.client_hello`);return}if(t.deviceId!==n.deviceId){this.sendSecureError(e,n.deviceId,`identity_mismatch`,`deviceId does not match relay token`);return}if(t.version!==1||t.cipherSuite!==`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`){this.sendSecureError(e,n.deviceId,`unsupported_version`,`unsupported secure handshake version`);return}let r=nx({gatewayId:this.dependencies.gatewayId,gatewayIdentity:this.dependencies.gatewayIdentity,privateKeyPem:this.dependencies.gatewayIdentityPrivateKeyPem,clientHello:t});n.handshake={status:`awaiting_client_auth`,clientHello:t,gatewayHello:r.gatewayHello,gatewayEphemeralPrivateKey:r.gatewayEphemeralPrivateKey},this.mobileConnections.set(e,n),this.dependencies.sendFrame(Go.parse({type:`secure.gateway_hello`,gatewayId:this.dependencies.gatewayId,mobileId:e,messageType:`system`,payload:r.gatewayHello}))}async handleSecureClientAuth(e,t){if(!e){this.sendRelayError({code:`BAD_REQUEST`,status:400,message:`secure.client_auth frame requires mobileId`});return}let n=this.mobileConnections.get(e);if(!n){this.sendRelayError({mobileId:e,code:`BAD_REQUEST`,status:400,message:`Unknown mobile ${e}`});return}if(n.handshake.status===`ready`){this.sendSecureError(e,n.deviceId,`counter_replay`,`duplicate secure.client_auth`);return}if(n.handshake.status!==`awaiting_client_auth`){this.sendSecureError(e,n.deviceId,`transcript_invalid`,`secure.client_hello missing`);return}try{rx({gatewayId:this.dependencies.gatewayId,clientHello:n.handshake.clientHello,gatewayHello:n.handshake.gatewayHello,clientAuth:t})}catch(t){this.sendSecureError(e,n.deviceId,dx(t),String(t));return}try{let r=await this.dependencies.verifyDeviceIdentityBinding(n.deviceId,n.handshake.clientHello.deviceIdentity),i=ix({gatewayId:this.dependencies.gatewayId,clientHello:n.handshake.clientHello,gatewayHello:n.handshake.gatewayHello,clientAuth:t,gatewayEphemeralPrivateKey:n.handshake.gatewayEphemeralPrivateKey});this.ensureReadyMobileClient(n),n.handshake={status:`ready`,clientHello:n.handshake.clientHello,gatewayHello:n.handshake.gatewayHello,session:i},this.mobileConnections.set(e,n),this.dependencies.sendFrame(Go.parse({type:`secure.ready`,gatewayId:this.dependencies.gatewayId,mobileId:e,messageType:`system`,payload:{version:1,securityLevel:`e2ee-relay`,cipherSuite:i.cipherSuite,gatewayId:this.dependencies.gatewayId,deviceId:n.deviceId,keyEpoch:i.keyEpoch,deviceIdentityFingerprint:r.publicKeyFingerprint??n.handshake.clientHello.deviceIdentity.publicKeyFingerprint,deviceIdentityStatus:r.identityStatus??`active`}}))}catch(t){this.sendSecureError(e,n.deviceId,px(t),String(t))}}ensureReadyMobileClient(e){if(e.clientId&&e.socket)return;let t=new sx(t=>{try{let n=Go.parse({type:`to_mobile`,gatewayId:this.dependencies.gatewayId,mobileId:e.mobileId,messageType:`event`,...this.createRelayBusinessPayloadFields(e,{frameType:`to_mobile`,messageType:`event`},t)});this.dependencies.sendFrame(n)}catch(t){this.sendSecureError(e.mobileId,e.deviceId,fx(t),`relay secure payload failed: ${String(t)}`)}}),n=this.dependencies.sessionHub.addClient(e.deviceId,t);e.socket=t,e.clientId=n}sendSecureError(e,t,n,r){this.dependencies.sendFrame({type:`secure.error`,gatewayId:this.dependencies.gatewayId,mobileId:e,messageType:`system`,payload:ax({gatewayId:this.dependencies.gatewayId,deviceId:t,code:n,message:r,retryable:n===`transcript_invalid`||n===`unsupported_version`||n===`key_epoch_mismatch`})})}sendRelayError(e){this.dependencies.sendFrame({type:`relay.error`,gatewayId:this.dependencies.gatewayId,...e.mobileId?{mobileId:e.mobileId}:{},...e.requestId?{requestId:e.requestId}:{},messageType:`system`,payload:lx(e.code,e.status,e.message)})}decodeRelayBusinessPayload(e){if(e.payload!==void 0)return this.sendSecureError(e.mobileId,e.connection.deviceId,`decrypt_failed`,`relay secure payload must be encrypted`),null;if(!e.encryptedPayload)return this.sendSecureError(e.mobileId,e.connection.deviceId,`decrypt_failed`,`relay secure payload missing`),null;try{return rs({session:e.connection.handshake.session,metadata:{frameType:e.frameType,messageType:e.messageType,gatewayId:this.dependencies.gatewayId,...e.requestId?{requestId:e.requestId}:{}},encryptedPayload:e.encryptedPayload,parse:e.parse})}catch(t){return this.sendSecureError(e.mobileId,e.connection.deviceId,fx(t),`relay secure payload failed: ${String(t)}`),null}}createRelayBusinessPayloadFields(e,t,n){return e.handshake.status===`ready`?{encryptedPayload:ns({session:e.handshake.session,metadata:{frameType:t.frameType,messageType:t.messageType,gatewayId:this.dependencies.gatewayId,...t.requestId?{requestId:t.requestId}:{}},payload:n})}:{payload:n}}};function lx(e,t,n){return Oo.parse({code:e,status:t,message:n})}function ux(e,t){if(Lg(e))switch(e.code){case`PAIRING_CODE_INVALID`:case`PAIRING_CODE_EXPIRED`:return{code:`BAD_REQUEST`,status:e.status,message:String(e)};case`REFRESH_TOKEN_REVOKED`:case`DEVICE_REVOKED`:case`REFRESH_TOKEN_DEVICE_MISMATCH`:return{code:`UNAUTHORIZED`,status:e.status,message:String(e)};default:return{code:e.status>=500?`INTERNAL`:`BAD_REQUEST`,status:e.status,message:String(e)}}let n=String(e),r=mx(e);return t===`pairing.claim`&&(r===`Invalid pairing code`||r===`Pairing code expired`)?{code:`BAD_REQUEST`,status:400,message:n}:t===`auth.refresh`&&(r===`Refresh token revoked`||r===`Device revoked`||r===`Device revoked or not found`||r===`Refresh token device mismatch`||Zg(e))?{code:`UNAUTHORIZED`,status:401,message:n}:{code:`INTERNAL`,status:500,message:n}}function dx(e){return hx(e,[`identity_mismatch`,`counter_replay`,`unsupported_version`,`transcript_invalid`])??`transcript_invalid`}function fx(e){return hx(e,[`counter_gap_too_large`,`counter_replay`,`key_epoch_mismatch`,`decrypt_failed`])??`decrypt_failed`}function px(e){if(Lg(e))switch(e.code){case`DEVICE_REVOKED`:return`device_revoked`;case`DEVICE_IDENTITY_NOT_REGISTERED`:case`DEVICE_IDENTITY_MISMATCH`:return`identity_mismatch`;default:return`transcript_invalid`}let t=mx(e);return t===`Device revoked`||t===`Device revoked or not found`?`device_revoked`:t===`Device identity mismatch`||t===`Device identity not registered`?`identity_mismatch`:`transcript_invalid`}function mx(e){return e instanceof Error?e.message:typeof e==`string`?e:String(e)}function hx(e,t){let n=mx(e);return t.find(e=>e===n)}var gx=class{logger;reconnectBaseDelayMs;reconnectMaxDelayMs;heartbeatIntervalMs;heartbeatTimeoutMs;webSocketFactory;socket;reconnectTimer;heartbeatIntervalTimer;heartbeatTimeoutTimer;reconnectAttempt=0;connectAttemptId=0;state=`idle`;stopped=!1;constructor(e){this.options=e,this.logger=e.logger??{},this.reconnectBaseDelayMs=e.reconnectBaseDelayMs??1e3,this.reconnectMaxDelayMs=e.reconnectMaxDelayMs??15e3,this.heartbeatIntervalMs=e.heartbeatIntervalMs??15e3,this.heartbeatTimeoutMs=e.heartbeatTimeoutMs??1e4,this.webSocketFactory=e.webSocketFactory??yx}start(){this.stopped&&=!1,!(this.socket||this.reconnectTimer)&&this.connect()}close(){this.stopped=!0,this.state=`stopped`,this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),void 0);let e=this.socket;this.socket=void 0,this.stopHeartbeat(),e?.close(1e3,`Gateway shutting down`)}isConnected(){let e=this.socket;return this.state===`connected`&&!!e&&e.readyState===e.OPEN}send(e){let t=this.socket;if(!t||t.readyState!==t.OPEN)return!1;let n=Go.parse(e);return t.send(JSON.stringify(n)),!0}async connect(){if(this.stopped)return;let e=++this.connectAttemptId,t;try{t=await this.resolveGatewayAccessToken()}catch(e){this.state=`idle`,this.logger.warn?.({err:e},`failed to resolve relay gateway access token`),this.scheduleReconnect();return}if(this.stopped||e!==this.connectAttemptId)return;let n=_x(this.options.relayUrl);this.state=`connecting`;let r=this.webSocketFactory(n);this.socket=r,r.on(`open`,()=>{this.socket!==r||this.stopped||(this.reconnectAttempt=0,this.state=`connected`,this.startHeartbeat(r),this.logger.info?.({relayUrl:this.options.relayUrl,gatewayId:this.options.gatewayId},`relay gateway websocket connected`),this.send({type:`gateway.hello`,gatewayId:this.options.gatewayId,messageType:`system`,payload:{name:this.options.machineName,relayBaseUrl:this.options.relayUrl,directBaseUrls:this.options.directBaseUrls,transportSecurityLevel:`e2ee-relay`,gatewayIdentity:this.options.gatewayIdentity,gatewayAccessToken:t,connectedAt:new Date().toISOString()}}))}),r.on(`message`,e=>{if(this.socket===r){this.ackHeartbeat(r);try{let t=Go.parse(JSON.parse(vx(e)));Promise.resolve(this.options.onFrame(t)).catch(e=>{this.logger.error?.({err:e},`failed to handle relay frame`)})}catch(e){this.logger.warn?.({err:e},`failed to parse relay frame from relay`)}}}),r.on(`error`,e=>{this.socket===r&&this.logger.warn?.({err:e},`relay websocket emitted error`)}),r.on(`pong`,()=>{this.socket===r&&this.ackHeartbeat(r)}),r.on(`close`,(e,t)=>{if(this.socket===r){if(this.socket=void 0,this.stopHeartbeat(),this.stopped){this.state=`stopped`;return}this.logger.warn?.({relayUrl:this.options.relayUrl,gatewayId:this.options.gatewayId,closeCode:e,closeReason:t.toString(`utf8`)},`relay websocket closed`),this.state=`idle`,this.scheduleReconnect()}})}async resolveGatewayAccessToken(){let e=this.options.relayGatewayAccessToken.trim();if(e)return e;let t=this.options.resolveRelayGatewayAccessToken;if(t)return t();throw Error(`Gateway relay access token is not configured`)}scheduleReconnect(){if(this.stopped||this.reconnectTimer)return;let e=Math.min(this.reconnectMaxDelayMs,this.reconnectBaseDelayMs*Math.max(1,2**this.reconnectAttempt));this.reconnectAttempt+=1,this.logger.info?.({delayMs:e},`scheduling relay reconnect`),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},e)}startHeartbeat(e){this.stopHeartbeat(),this.heartbeatIntervalTimer=setInterval(()=>{if(!(this.socket!==e||this.stopped)&&!(e.readyState!==e.OPEN||this.heartbeatTimeoutTimer)){try{e.ping()}catch(t){this.logger.warn?.({err:t},`failed to send relay websocket heartbeat ping`),e.terminate();return}this.heartbeatTimeoutTimer=setTimeout(()=>{this.heartbeatTimeoutTimer=void 0,!(this.socket!==e||this.stopped||e.readyState!==e.OPEN)&&(this.logger.warn?.({relayUrl:this.options.relayUrl,gatewayId:this.options.gatewayId,heartbeatTimeoutMs:this.heartbeatTimeoutMs},`relay websocket heartbeat timed out`),e.terminate())},this.heartbeatTimeoutMs)}},this.heartbeatIntervalMs)}ackHeartbeat(e){this.socket===e&&(this.heartbeatTimeoutTimer&&=(clearTimeout(this.heartbeatTimeoutTimer),void 0))}stopHeartbeat(){this.heartbeatIntervalTimer&&=(clearInterval(this.heartbeatIntervalTimer),void 0),this.heartbeatTimeoutTimer&&=(clearTimeout(this.heartbeatTimeoutTimer),void 0)}};function _x(e){let t=new URL(e);return t.protocol===`http:`?t.protocol=`ws:`:t.protocol===`https:`&&(t.protocol=`wss:`),t.pathname=`/ws/gateway`,t.toString()}function vx(e){return typeof e==`string`?e:e instanceof ArrayBuffer?Buffer.from(e).toString(`utf8`):ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`utf8`):Array.isArray(e)&&e.every(e=>ArrayBuffer.isView(e))?Buffer.concat(e.map(e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength))).toString(`utf8`):String(e)}function yx(e){return new nv(e)}function bx(e){let t={gatewayId:e.gatewayId.trim(),gatewayIdentity:e.gatewayIdentity,requestedAt:e.requestedAt??new Date().toISOString()};if(!t.gatewayId)throw Error(`gatewayId must not be empty when requesting a guest relay gateway access token.`);return{grantType:`guest`,payload:t,signatureAlgorithm:`ed25519`,signature:(0,l.sign)(null,Buffer.from(Ko(t),`utf8`),(0,l.createPrivateKey)(e.privateKeyPem)).toString(`base64`)}}async function xx(e){let t=e.fetchImpl??globalThis.fetch;if(!t)throw Error(`fetch is not available when requesting a guest relay gateway access token.`);let n=await t(Sx(e.relayUrl),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(bx({gatewayId:e.gatewayId,gatewayIdentity:e.gatewayIdentity,privateKeyPem:e.privateKeyPem}))}),r=await n.text();if(!n.ok)throw Error(`Failed to request a guest relay gateway access token (${n.status}): ${r}`);return Po.parse(JSON.parse(r)).token}function Sx(e){let t=new URL(e);return t.protocol===`ws:`?t.protocol=`http:`:t.protocol===`wss:`&&(t.protocol=`https:`),t.pathname=`/api/gateway-token/guest`,t.search=``,t.toString()}function Cx(e){return e?.trim()||void 0}function wx(e){if(e)return{codex:e.codex?{approvalPolicy:e.codex.approvalPolicy,sandboxMode:e.codex.sandboxMode}:void 0,claude:e.claude?{permissionMode:e.claude.permissionMode}:void 0}}function Tx(e,t){return{modeDefault:`default`,model:Cx(t.defaults.model),reasoningEffort:t.defaults.reasoningEffort,execution:e===`codex`?{codex:{approvalPolicy:t.defaults.approvalPolicy??null,sandboxMode:t.defaults.sandboxMode??null}}:{claude:{permissionMode:t.defaults.permissionMode??null}}}}function Ex(e){return{mode:`default`,model:null,reasoningEffort:null,execution:e===`codex`?{codex:{approvalPolicy:null,sandboxMode:null}}:{claude:{permissionMode:null}}}}function Dx(e,t){let n=Ex(e);return t?e===`codex`?{mode:t.mode,model:t.model,reasoningEffort:t.reasoningEffort,execution:{codex:{approvalPolicy:t.execution?.codex?.approvalPolicy??null,sandboxMode:t.execution?.codex?.sandboxMode??null}}}:{mode:t.mode,model:t.model,reasoningEffort:t.reasoningEffort,execution:{claude:{permissionMode:t.execution?.claude?.permissionMode??null}}}:n}function Ox(e,t){return e===`claude`&&t?.permissionMode===`plan`?`plan`:`default`}function kx(e){let t=Dx(e.provider,e.sessionTurnConfig);return e.sessionTurnConfig!==void 0||Cx(e.legacyModel)!==void 0||e.legacySessionConfig!==void 0?Ax({provider:e.provider,providerDefaults:{modeDefault:`default`},currentSessionTurnConfig:t,legacyModel:e.legacyModel,legacySessionConfig:e.legacySessionConfig}).sessionTurnConfig:t}function Ax(e){let t=Dx(e.provider,e.currentSessionTurnConfig),n=e.mode??(e.legacySessionConfig?Ox(e.provider,e.legacySessionConfig):void 0)??t.mode??e.providerDefaults.modeDefault,r=Dx(e.provider,{...t,mode:n});e.config&&(e.config.model!==void 0&&(r.model=e.config.model),e.config.reasoningEffort!==void 0&&(r.reasoningEffort=e.config.reasoningEffort),e.provider===`codex`&&e.config.execution?.codex&&(r.execution={codex:{approvalPolicy:e.config.execution.codex.approvalPolicy,sandboxMode:e.config.execution.codex.sandboxMode}}),e.provider===`claude`&&e.config.execution?.claude&&(r.execution={claude:{permissionMode:e.config.execution.claude.permissionMode}}));let i=Cx(e.legacyModel);i&&(r.model=i),e.legacySessionConfig?.reasoningEffort!==void 0&&(r.reasoningEffort=e.legacySessionConfig.reasoningEffort),e.provider===`codex`&&e.legacySessionConfig&&(r.execution={codex:{approvalPolicy:e.legacySessionConfig.approvalPolicy??r.execution?.codex?.approvalPolicy??null,sandboxMode:e.legacySessionConfig.sandboxMode??r.execution?.codex?.sandboxMode??null}}),e.provider===`claude`&&e.legacySessionConfig&&(r.execution={claude:{permissionMode:e.legacySessionConfig.permissionMode===`plan`?r.execution?.claude?.permissionMode??null:e.legacySessionConfig.permissionMode??r.execution?.claude?.permissionMode??null}});let a=r.model??Cx(e.providerDefaults.model),o={},s=r.reasoningEffort??e.providerDefaults.reasoningEffort;if(s&&(o.reasoningEffort=s),e.provider===`codex`){let t=r.execution?.codex?.approvalPolicy??e.providerDefaults.execution?.codex?.approvalPolicy??void 0,n=r.execution?.codex?.sandboxMode??e.providerDefaults.execution?.codex?.sandboxMode??void 0;t&&(o.approvalPolicy=t),n&&(o.sandboxMode=n)}else{let t=n===`plan`?`plan`:r.execution?.claude?.permissionMode??e.providerDefaults.execution?.claude?.permissionMode??void 0;t&&(o.permissionMode=t)}return{mode:n,model:a,sessionConfig:o,sessionTurnConfig:{mode:r.mode,model:r.model,reasoningEffort:r.reasoningEffort,execution:wx(r.execution)}}}const jx=[],Mx=[{id:`default`,label:`Default`,isDefault:!0,supportedReasoningEfforts:[`low`,`medium`,`high`,`max`]}],Nx=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`],Px=ji.options,Fx=[`read-only`,`workspace-write`,`danger-full-access`],Ix=[`default`,`acceptEdits`,`bypassPermissions`,`plan`,`dontAsk`],Lx={codex:[{version:`codex-mobile-v1`,defaults:{reasoningEffort:`medium`,approvalPolicy:`on-request`,sandboxMode:`workspace-write`}},{version:`codex-mobile-v2`,defaults:{reasoningEffort:`low`,approvalPolicy:`on-request`,sandboxMode:`read-only`}}],claude:[{version:`claude-mobile-v1`,defaults:{model:`default`}}]},Rx={idleTtlMs:900*1e3,sweepIntervalMs:60*1e3,maxSessions:24,maxCodexSessions:8,maxClaudeSessions:16},zx=30*1e3;function Bx(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(1,Math.trunc(n)):t}function Vx(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(0,Math.trunc(n)):t}function Hx(e,t){let n=t?.trim().toLowerCase();return n?(Lx[e]??[]).find(e=>n===e.version.toLowerCase())??null:null}function Ux(e,t,n){return e.some(e=>e.id===t)?e.map(e=>({...e,isDefault:e.id===t})):[{id:t,label:t,isDefault:!0,...n===`codex`?{supportedReasoningEfforts:Nx}:{}},...e.map(e=>({...e,isDefault:!1}))]}function Wx(e){return e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`||e===`max`?e:null}function Gx(e){let t=new Set;for(let n of e){let e=Wx(n);e&&t.add(e)}return[...t]}function Kx(e){return e?.trim()||void 0}function qx(e){let t=Kx(e.runtimeModel);if(t)return t;let n=Kx(e.discoveredModel);if(n)return n;let r=Kx(e.existingModel),i=Kx(e.modelProvider)?.toLowerCase();if(r&&(!i||r.toLowerCase()!==i))return r}function Jx(e){let t=e.filter(e=>!!e.id).map(e=>({id:e.id,label:e.displayName||e.model||e.id,description:e.description,isDefault:e.isDefault,supportedReasoningEfforts:Gx(e.supportedReasoningEfforts)}));return t.length===0?jx:(t.some(e=>e.isDefault)||(t[0]={...t[0],isDefault:!0}),t)}async function Yx(){try{return Jx(await my())}catch{return null}}async function Xx(){try{let e=await import(`@anthropic-ai/claude-agent-sdk`),t=e.query??e.default?.query;if(typeof t!=`function`)return null;let n=t,r=p.default.join(Js(),`claude-capability-probe`);await d.default.mkdir(r,{recursive:!0,mode:448});let i=n({prompt:`/clear`,options:{cwd:r,permissionMode:`plan`,maxTurns:1,includePartialMessages:!1}});try{let e=await i.supportedModels(),t=[];for(let n of e){let e=typeof n.value==`string`?n.value:``;if(!e)continue;let r=Array.isArray(n.supportedEffortLevels)&&n.supportedEffortLevels.length>0,i=Qx(n.description,n.displayName,e),a=n.supportsEffort===!1?[]:n.supportsEffort||r?Gx(n.supportedEffortLevels??[]):i===`haiku`?[]:void 0;t.push({id:e,label:n.displayName||e,description:typeof n.description==`string`&&n.description.trim()?n.description.trim():void 0,isDefault:e===`default`,supportedReasoningEfforts:a})}return t.length===0?null:(t.some(e=>e.isDefault)||(t[0]={...t[0],isDefault:!0}),t)}finally{i.close()}}catch{return null}}function Zx(e){let t=(e.find(e=>e.isDefault)??e[0])?.supportedReasoningEfforts??[];if(t.includes(`medium`))return`medium`;if(t.includes(`high`))return`high`;if(t.length>0)return t[0]}function Qx(...e){for(let t of e){let e=t?.trim().toLowerCase();if(e){if(e.includes(`haiku`))return`haiku`;if(e.includes(`opus`))return`opus`;if(e.includes(`sonnet`)||e.includes(`sonnect`))return`sonnet`}}}var $x=class{sessions=new Map;providerCapabilitiesCache=new Map;providerCapabilitiesInFlight=new Map;nextRawSeqBySession=new Map;runtimeLifecycle;sweepTimer;lastRawEnvelopeTimestampMs=0;shuttingDown=!1;constructor(e){if(this.options=e,this.runtimeLifecycle={idleTtlMs:Bx(e.runtimeLifecycle?.idleTtlMs,Rx.idleTtlMs),sweepIntervalMs:Vx(e.runtimeLifecycle?.sweepIntervalMs,Rx.sweepIntervalMs),maxSessions:Bx(e.runtimeLifecycle?.maxSessions,Rx.maxSessions),maxCodexSessions:Bx(e.runtimeLifecycle?.maxCodexSessions,Rx.maxCodexSessions),maxClaudeSessions:Bx(e.runtimeLifecycle?.maxClaudeSessions,Rx.maxClaudeSessions)},this.runtimeLifecycle.sweepIntervalMs<=0){this.sweepTimer=null;return}this.sweepTimer=setInterval(()=>{this.sweepRuntimeSessions().catch(e=>{console.error(`[session-runtime] sweep failed: ${String(e)}`)})},this.runtimeLifecycle.sweepIntervalMs),this.sweepTimer.unref?.()}async shutdown(){this.shuttingDown=!0,this.sweepTimer&&clearInterval(this.sweepTimer);let e=[...this.sessions.keys()];this.options.logger?.info?.({sessionCount:e.length,sessionIds:e},`session manager shutdown starting`),await Promise.allSettled(e.map(e=>this.closeRuntimeSession(e,`shutdown`))),await Dv(),this.options.logger?.info?.({sessionCount:e.length,sessionIds:e},`session manager shutdown completed`)}async listProjects(){let e=await this.options.projectStore.list(),t=this.buildProjectStatsMap();return e.map(e=>this.attachProjectStats(e,t))}async createProject(e){let t=await this.options.projectStore.upsertByPath(e.path,e.title);return this.attachProjectStats(t,this.buildProjectStatsMap())}async deleteProject(e){if(this.listProjectSessionsWithRuntime(e,`running`).length>0)throw Kg(e);return this.options.projectStore.remove(e)}async getProject(e){return this.options.projectStore.getById(e)}buildProjectStatsMap(){let e=new Map,t=this.listAllSessionsWithRuntime(`all`);for(let n of t){let t=e.get(n.projectId)??{runningCount:0,idleCount:0,totalCount:0,lastSessionAt:void 0};n.status===`running`?t.runningCount+=1:t.idleCount+=1,t.totalCount+=1;let r=n.updatedAt||n.createdAt;(!t.lastSessionAt||r>t.lastSessionAt)&&(t.lastSessionAt=r),e.set(n.projectId,t)}return e}attachProjectStats(e,t){let n=t.get(e.id),r=n?.idleCount??0;return{...e,lastSessionAt:n?.lastSessionAt,runningCount:n?.runningCount??0,idleCount:r,totalCount:n?.totalCount??0,endedCount:r}}async getProviderCapabilities(e,t,n){return(await this.resolveProviderCapabilities(e,t,n)).capabilities}async getAgentConfig(e,t){let n=await this.resolveProviderCapabilities(e,t?.projectId,t?.agentVersion);return{agent:{provider:e,requestedVersion:t?.agentVersion?.trim()||null,resolvedVersion:n.resolvedAgentVersion},capabilities:n.capabilities}}async warmStartupProviderCapabilities(){if(!this.options.preferNativeProviders||this.shuttingDown)return;let e=Lx.claude.length>0?Lx.claude.map(e=>e.version):[void 0];await Promise.allSettled(e.map(e=>this.resolveProviderCapabilities(`claude`,void 0,e)))}async resolveProviderCapabilities(e,t,n){if(t&&!await this.options.projectStore.getById(t))throw Ug(t);let r=Hx(e,n),i=r?.version??`default`,a=`${e}::${i}`,o=Date.now(),s=this.providerCapabilitiesCache.get(a);if(s){if(s.expiresAt>o)return s.value;this.providerCapabilitiesCache.delete(a)}let c=this.providerCapabilitiesInFlight.get(a);if(c)return c;let l=(async()=>{let t=sb(e,{preferNative:this.options.preferNativeProviders,requireNative:!1}),n=this.options.preferNativeProviders?await t.isNativeAvailable().catch(()=>!1):!1,a=n?`native`:`fallback`,o=e===`codex`&&n?await Yx()??jx:jx,s=e===`claude`&&n?await Xx()??Mx:Mx,c=Gx(s.flatMap(e=>e.supportedReasoningEfforts??[])),l=e===`codex`?{provider:e,source:a,models:o,support:{reasoningEffort:!0,approvalPolicy:!0,sandboxMode:!0,permissionMode:!1},options:{reasoningEfforts:Nx,approvalPolicies:Px,sandboxModes:Fx,permissionModes:[]},defaults:{model:o.find(e=>e.isDefault)?.id??o[0]?.id,reasoningEffort:`medium`,approvalPolicy:`on-request`,sandboxMode:`workspace-write`}}:{provider:e,source:a,models:s,support:{reasoningEffort:c.length>0,approvalPolicy:!1,sandboxMode:!1,permissionMode:!0},options:{reasoningEfforts:c,approvalPolicies:[],sandboxModes:[],permissionModes:Ix},defaults:{model:s.find(e=>e.isDefault)?.id??s[0]?.id,reasoningEffort:Zx(s),permissionMode:`default`}};if(!r)return{capabilities:l,resolvedAgentVersion:i};let u={...l.defaults,...r.defaults},d=u.model?.trim(),f=a===`native`?l.models:d?Ux(l.models,d,e):l.models;return{capabilities:{...l,models:f,defaults:u},resolvedAgentVersion:r.version}})();this.providerCapabilitiesInFlight.set(a,l);try{let e=await l;return this.providerCapabilitiesCache.set(a,{value:e,expiresAt:Date.now()+864e5}),e}finally{this.providerCapabilitiesInFlight.delete(a)}}async getProviderDefaults(e,t,n){return Tx(e,await this.getProviderCapabilities(e,t,n))}async listProjectSessions(e,t=`all`,n){let r=await this.options.projectStore.getById(e);if(!r)throw Ug(e);return n?.syncExternal&&(await this.syncCodexSessionsForProject(r),await this.syncClaudeSessionsForProject(r)),this.listProjectSessionsWithRuntime(e,t)}async getProjectSessionSummary(e,t){let n=this.options.historyStore.getProjectSession(e,t);return this.getRuntimeSessionSummary(e,t,n)||n}async getProjectSessionEvents(e,t,n=300,r){let i=await this.options.projectStore.getById(e);if(!i)throw Ug(e);let a=r?.syncExternal===!0,o=this.options.historyStore.getProjectSession(e,t);if(!o&&this.getRuntimeSessionSummary(e,t))return[];if(!o&&a&&this.options.preferNativeProviders?(await this.syncCodexSessionsForProject(i),await this.syncClaudeSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)):o?.provider===`codex`&&a?(await this.syncCodexSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)??o):o?.provider===`claude`&&a&&(await this.syncClaudeSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)??o),!o)throw Wg(e,t);let s=await this.options.historyStore.getSessionEvents(t,Math.max(n,300));if(o.source===`native_discovered`&&!a||o.source!==`native_discovered`&&!a&&s.length>0)return s.slice(-Math.max(1,n));if(o.provider===`claude`){let t=fS(o);if(!t)return s.slice(-Math.max(1,n));try{let r=await db({projectPath:o.projectPath,nativeSessionId:t,provider:o.provider,sessionId:o.id,projectId:e});return o.source===`native_discovered`?nS(r,s.filter(e=>!tS.has(e.type)),n):iS(s,r,tS,n)}catch{return s.slice(-Math.max(1,n))}}if(o.provider!==`codex`)return s.slice(-Math.max(1,n));let c=uS([o.nativeSessionId,o.id]);for(let t of c)try{return iS(s,pS({thread:await py(t,!0),provider:o.provider,sessionId:o.id,projectId:e}),eS,n)}catch{}return s.slice(-Math.max(1,n))}async getProjectSessionRawEvents(e,t,n=300,r){let i=await this.options.projectStore.getById(e);if(!i)throw Ug(e);let a=r?.syncExternal===!0,o=this.options.historyStore.getProjectSession(e,t);if(!o&&this.getRuntimeSessionSummary(e,t))return[];if(!o&&a&&this.options.preferNativeProviders?(await this.syncCodexSessionsForProject(i),await this.syncClaudeSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)):o?.provider===`codex`&&a?(await this.syncCodexSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)??o):o?.provider===`claude`&&a&&(await this.syncClaudeSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)??o),!o)throw Wg(e,t);let s=await this.options.historyStore.getSessionRawEvents(o.id,Math.max(n,300));if(o.source===`native_discovered`&&!a)return s.slice(-Math.max(1,n));let c=await this.maybeSyncExternalRawHistoryForRead(o,e,s,{forceSyncExternal:a});return o.source!==`native_discovered`&&!a&&c.rawEvents===s?s.slice(-Math.max(1,n)):c.rawEvents.slice(-Math.max(1,n))}async getProjectSessionRawEventsCompacted(e,t,n=300,r){let i=await this.resolveProjectSessionForRawRead(e,t,r);return this.options.historyStore.getSessionRawEventsCompacted(i.id,n)}async getProjectSessionRawEventsSinceSeq(e,t,n,r=2e3,i){let a=await this.resolveProjectSessionForRawRead(e,t,i);return this.options.historyStore.getSessionRawEventsSinceSeq(a.id,n,r)}async getProjectSessionRawSeqRange(e,t,n){let r=await this.resolveProjectSessionForRawRead(e,t,n);return this.options.historyStore.getSessionRawSeqRange(r.id)}async resolveProjectSessionForRawRead(e,t,n){let r=await this.options.projectStore.getById(e);if(!r)throw Ug(e);let i=n?.syncExternal===!0,a=this.options.historyStore.getProjectSession(e,t);if(!a&&i&&this.options.preferNativeProviders?(await this.syncCodexSessionsForProject(r),await this.syncClaudeSessionsForProject(r),a=this.options.historyStore.getProjectSession(e,t)):a?.provider===`codex`&&i?(await this.syncCodexSessionsForProject(r),a=this.options.historyStore.getProjectSession(e,t)??a):a?.provider===`claude`&&i&&(await this.syncClaudeSessionsForProject(r),a=this.options.historyStore.getProjectSession(e,t)??a),!a)throw Wg(e,t);let o=await this.options.historyStore.getSessionRawEvents(a.id,2**53-1);return(await this.maybeSyncExternalRawHistoryForRead(a,e,o,{forceSyncExternal:i})).session}async startSession(e){let t=await this.resolveProjectForSessionStart(e.projectId,e.cwd),n=`sess_${ag(10)}`,r=e.provider===`codex`&&this.options.requireNativeCodex,i=sb(e.provider,{preferNative:this.options.preferNativeProviders,requireNative:r}),a=await this.getProviderDefaults(e.provider,t.id),o=e.sessionTurnConfig?Dx(e.provider,e.sessionTurnConfig):kx({provider:e.provider,legacyModel:e.model,legacySessionConfig:e.sessionConfig}),s=Ax({provider:e.provider,providerDefaults:a,currentSessionTurnConfig:o}),c=await i.createSession({sessionId:n,model:s.model,cwd:t.path,sessionConfig:s.sessionConfig,metadata:e.metadata,logger:this.options.logger});if(r&&c.providerMode!==`native`)throw await c.close(),Error(`Native Codex provider is required, but adapter fell back to mock. Check ENABLE_NATIVE_PROVIDERS and Codex app-server availability.`);let l=this.resolveCanonicalSessionId(e.provider,c,n),u=this.resolveNativeSessionId(e.provider,c,l),d=new Date().toISOString(),f=await this.attachRuntimeSession({id:l,nativeSessionId:u,source:`gateway`,projectId:t.id,projectPath:t.path,provider:e.provider,providerMode:c.providerMode,model:s.model,title:void 0,sessionTurnConfig:o,sessionTurnConfigUpdatedAt:d,createdAt:d,updatedAt:d,status:`idle`,providerSession:c,pendingToolApprovals:new Set,pendingUserInputs:new Set,streamReady:!1,bufferedProviderEvents:[],lastActiveAtMs:Date.now(),dispatchInFlight:!1,closing:!1});return this.markSessionStreamReady(f),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`session.start`,deviceId:e.deviceId,sessionId:f.id,detail:{provider:e.provider,model:s.model,sessionConfig:e.sessionConfig,sessionTurnConfig:o,projectId:t.id,projectPath:t.path}}),{sessionId:f.id,projectId:t.id}}async sendInput(e,t,n,r){let i=this.sessions.get(e)??await this.resumeSessionFromHistory(e);if(!i)throw Gg(e);let a=await this.getProviderDefaults(i.provider,i.projectId),o=Ax({provider:i.provider,providerDefaults:a,currentSessionTurnConfig:i.sessionTurnConfig,legacyModel:r?.model,legacySessionConfig:r?.sessionConfig,mode:r?.mode,config:r?.config});i.dispatchInFlight=!0,this.touchSession(i);try{if(await this.options.auditLogger.record({ts:new Date().toISOString(),action:`turn.input`,deviceId:n,sessionId:e,detail:{text:t,model:o.model,sessionConfig:r?.sessionConfig,mode:o.mode,config:r?.config,resolvedSessionConfig:o.sessionConfig}}),this.options.historyStore.getSession(i.id)||await this.persistSessionSnapshot(i),await i.providerSession.sendInput(t,{model:o.model,sessionConfig:o.sessionConfig,mode:o.mode}),!i.title){let e=vS(t);e&&this.setSessionTitle(i,e)}let a=new Date().toISOString();i.sessionTurnConfig=Dx(i.provider,o.sessionTurnConfig),i.sessionTurnConfigUpdatedAt=a,o.model&&i.model!==o.model&&(i.model=o.model),i.updatedAt=a,await this.persistSessionSnapshot(i)}finally{i.dispatchInFlight=!1,this.touchSession(i)}}async respondToolPermission(e,t,n,r,i){let a=this.mustGetSession(e);if(!a.pendingToolApprovals.has(t))throw Error(`Unknown tool approval request: ${t}`);if(typeof a.providerSession.respondToolPermission!=`function`){a.pendingToolApprovals.delete(t),a.updatedAt=new Date().toISOString(),await this.persistSessionSnapshot(a);return}await a.providerSession.respondToolPermission(t,n,r),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`tool.approval.respond`,deviceId:i,sessionId:e,detail:{requestId:t,decision:n,reason:r}})}async respondUserInput(e,t,n,r){let i=this.mustGetSession(e);if(!i.pendingUserInputs.has(t))throw Error(`Unknown user input request: ${t}`);if(typeof i.providerSession.respondUserInput!=`function`){i.pendingUserInputs.delete(t),i.updatedAt=new Date().toISOString(),await this.persistSessionSnapshot(i);return}await i.providerSession.respondUserInput(t,n),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`user.input.respond`,deviceId:r,sessionId:e,detail:{requestId:t,answeredCount:bS(n)}})}async interruptSession(e,t){let n=this.sessions.get(e);n&&await n.providerSession.interrupt(),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`session.interrupt`,deviceId:t,sessionId:e,detail:{runtimeSessionFound:!!n}})}async closeSession(e){throw Error(`session.close is deprecated. Use session.interrupt instead.`)}getSessionExecutionContext(e){let t=this.sessions.get(e);if(t)return{provider:t.provider,projectId:t.projectId,projectPath:t.projectPath};let n=this.options.historyStore.getSession(e);if(!n)throw Gg(e);return{provider:n.provider,projectId:n.projectId,projectPath:n.projectPath}}async emitExternalEvent(e){let t=this.options.historyStore.getSession(e.sessionId),n={v:`1.0`,kind:`provider.raw`,rawSeq:await this.nextRawSeq(e.sessionId),provider:e.provider,sessionId:e.sessionId,projectId:e.projectId??t?.projectId,eventId:`raw_${ag(12)}`,ts:this.nextRawEnvelopeTimestamp(),type:e.type,payload:{raw:{...e.raw,type:e.type}}};this.options.onEnvelope(n),this.options.historyStore.appendRawEvent(n).catch(e=>{console.error(`[session-history] append raw event failed: ${String(e)}`)})}async resumeSessionFromHistory(e){let t=this.options.historyStore.getSession(e);if(!t)return;let n=t.provider===`codex`&&this.options.requireNativeCodex,r=sb(t.provider,{preferNative:this.options.preferNativeProviders,requireNative:n}),i=await this.getProviderDefaults(t.provider,t.projectId),a=Dx(t.provider,t.sessionTurnConfig),o=Ax({provider:t.provider,providerDefaults:i,currentSessionTurnConfig:a}),s=t.provider===`claude`&&t.source===`native_discovered`?t.id:t.nativeSessionId??t.id,c=await r.createSession({sessionId:t.id,model:o.model??t.model,cwd:t.projectPath,resumeSessionId:s,sessionConfig:o.sessionConfig,metadata:{resumeFromHistory:!0},logger:this.options.logger});if(n&&c.providerMode!==`native`)throw await c.close(),Error(`Native Codex provider is required, but adapter fell back to mock. Check ENABLE_NATIVE_PROVIDERS and Codex app-server availability.`);let l=this.resolveCanonicalSessionId(t.provider,c,t.id),u=this.resolveNativeSessionId(t.provider,c,t.nativeSessionId),d=await this.attachRuntimeSession({id:l,nativeSessionId:u,source:t.source??`gateway`,projectId:t.projectId,projectPath:t.projectPath,provider:t.provider,providerMode:c.providerMode,model:o.model??t.model,title:t.title,sessionTurnConfig:a,sessionTurnConfigUpdatedAt:t.sessionTurnConfigUpdatedAt,createdAt:t.createdAt,updatedAt:t.updatedAt||new Date().toISOString(),status:`idle`,providerSession:c,pendingToolApprovals:new Set,pendingUserInputs:new Set,streamReady:!0,bufferedProviderEvents:[],lastActiveAtMs:Date.now(),dispatchInFlight:!1,closing:!1});return await this.persistSessionSnapshot(d),d}async syncCodexSessionsForProject(e){if(!this.options.preferNativeProviders)return;let t;try{t=await dy(e.path)}catch{return}let n=new Set(t.filter(t=>t.cwd===e.path).map(e=>e.id)),r=new Map(this.options.historyStore.listProjectSessions(e.id,`all`).map(e=>[e.id,e])),i=[...r.values()].filter(e=>e.provider===`codex`&&e.source===`native_discovered`&&!this.sessions.has(e.id)&&!n.has(e.nativeSessionId??e.id)).map(e=>e.id);for(let e of i)await this.options.historyStore.removeSession(e),r.delete(e);for(let n of t){if(n.cwd!==e.path)continue;let t=[...r.values()].find(e=>e.provider===`codex`&&(e.id===n.id||e.nativeSessionId===n.id)),i=t?.id??n.id,a=this.sessions.get(i)??this.sessions.get(n.id),o=xS(n.createdAt),s=xS(n.updatedAt),c=a?.status===`running`?`running`:`idle`,l=c===`running`?a?.pendingToolApprovals.size??0:0,u=c===`running`?a?.pendingUserInputs.size??0:0,d={id:i,nativeSessionId:n.id,source:t?.source??`native_discovered`,projectId:e.id,projectPath:e.path,provider:`codex`,providerMode:a?.providerMode??t?.providerMode??`native`,model:qx({runtimeModel:a?.model,discoveredModel:n.model,existingModel:t?.model,modelProvider:n.modelProvider}),title:a?.title??vS(n.preview)??t?.title,sessionTurnConfig:a?.sessionTurnConfig??t?.sessionTurnConfig,sessionTurnConfigUpdatedAt:a?.sessionTurnConfigUpdatedAt??t?.sessionTurnConfigUpdatedAt,createdAt:t?.createdAt??o,updatedAt:c===`running`?a?.updatedAt??s:s,status:c,pendingApprovals:l,pendingUserInputs:u,pendingActions:l+u};await this.options.historyStore.upsertSession(d),r.set(i,d)}}async syncClaudeSessionsForProject(e){if(!this.options.preferNativeProviders)return;let t;try{t=await ub(e.path)}catch{return}let n=new Set(t.map(e=>e.nativeSessionId)),r=new Map(this.options.historyStore.listProjectSessions(e.id,`all`).map(e=>[e.id,e])),i=[...r.values()].filter(e=>e.provider===`claude`&&e.source===`native_discovered`&&!this.sessions.has(e.id)&&!n.has(e.nativeSessionId??e.id)).map(e=>e.id);for(let e of i)await this.options.historyStore.removeSession(e),r.delete(e);for(let n of t){let t=[...r.values()].find(e=>e.provider===`claude`&&(e.id===n.nativeSessionId||e.nativeSessionId===n.nativeSessionId)),i=t?.id??n.nativeSessionId,a=this.sessions.get(i),o=a?.status===`running`?`running`:`idle`,s=o===`running`?a?.pendingToolApprovals.size??0:0,c=o===`running`?a?.pendingUserInputs.size??0:0,l={id:i,nativeSessionId:n.nativeSessionId,source:t?.source??`native_discovered`,projectId:e.id,projectPath:e.path,provider:`claude`,providerMode:a?.providerMode??t?.providerMode??`native`,model:a?.model??t?.model??n.model,title:a?.title??t?.title??n.title,sessionTurnConfig:a?.sessionTurnConfig??t?.sessionTurnConfig,sessionTurnConfigUpdatedAt:a?.sessionTurnConfigUpdatedAt??t?.sessionTurnConfigUpdatedAt,createdAt:t?.createdAt??n.createdAt,updatedAt:o===`running`?a?.updatedAt??n.updatedAt:n.updatedAt,status:o,pendingApprovals:s,pendingUserInputs:c,pendingActions:s+c};await this.options.historyStore.upsertSession(l),r.set(i,l)}}async resolveProjectForSessionStart(e,t){if(!e&&!t)throw Error(`session.start requires projectId or cwd`);if(e&&t){let n=await this.options.projectStore.getById(e);if(!n)throw Ug(e);if((await this.options.projectStore.upsertByPath(t)).id!==n.id)throw Error(`projectId (${e}) does not match cwd (${t})`);return await SS(n.path),n}if(e){let t=await this.options.projectStore.getById(e);if(!t)throw Ug(e);return await SS(t.path),t}return this.options.projectStore.upsertByPath(t)}async attachRuntimeSession(e){let t=this.sessions.get(e.id);t&&await this.closeRuntimeSession(t.id,`replaced`,{suppressAudit:!0});let n={...e,unsubscribe:()=>{}};return await this.initializeRawSeqCursor(n.id),n.unsubscribe=n.providerSession.onEvent(e=>{if(!n.streamReady){n.bufferedProviderEvents.push(e);return}this.handleProviderEvent(n,e)}),this.sessions.set(n.id,n),n}handleProviderEvent(e,t){let n=this.ensureProviderRequestId(t);if(this.emitRawEnvelope(e,n),this.maybePersistUpdatedNativeSessionId(e),e.updatedAt=new Date().toISOString(),this.touchSession(e),n.type===`thread.title.updated`){let t=yS(n.title);t&&this.setSessionTitle(e,t);return}if(n.type===`turn.started`){e.status=`running`,this.persistSessionSnapshot(e);return}if(n.type===`turn.completed`||n.type===`turn.failed`){e.status=`idle`,this.persistSessionSnapshot(e);return}if(n.type===`error.runtime`){let t=yS(n.message);e.status!==`idle`&&this.options.logger?.warn?.({sessionId:e.id,nativeSessionId:e.nativeSessionId,provider:e.provider,providerMode:e.providerMode,projectId:e.projectId,projectPath:e.projectPath,model:e.model,previousStatus:e.status,nextStatus:`idle`,eventType:n.type,errorMessage:t},`provider session forced idle after error event`),e.status=`idle`,this.persistSessionSnapshot(e);return}if(n.type===`tool.permission.requested`){let t=typeof n.requestId==`string`?n.requestId:``;if(!t)return;e.pendingToolApprovals.add(t),this.persistSessionSnapshot(e);return}if(n.type===`tool.permission.resolved`&&typeof n.requestId==`string`){e.pendingToolApprovals.delete(n.requestId),this.persistSessionSnapshot(e);return}if(n.type===`user.input.requested`){let t=typeof n.requestId==`string`?n.requestId:``;if(!t)return;e.pendingUserInputs.add(t),this.persistSessionSnapshot(e);return}if(n.type===`user.input.resolved`&&typeof n.requestId==`string`){e.pendingUserInputs.delete(n.requestId),this.persistSessionSnapshot(e);return}}emitRawEnvelope(e,t){let n={v:`1.0`,kind:`provider.raw`,rawSeq:this.nextRawSeqSync(e.id),provider:e.provider,sessionId:e.id,projectId:e.projectId,eventId:`raw_${ag(12)}`,ts:this.nextRawEnvelopeTimestamp(),type:t.type,payload:{raw:t}};this.options.onEnvelope(n),this.options.historyStore.appendRawEvent(n).catch(e=>{console.error(`[session-history] append raw event failed: ${String(e)}`)})}nextRawEnvelopeTimestamp(){let e=Date.now(),t=e>this.lastRawEnvelopeTimestampMs?e:this.lastRawEnvelopeTimestampMs+1;return this.lastRawEnvelopeTimestampMs=t,new Date(t).toISOString()}async initializeRawSeqCursor(e){if(this.nextRawSeqBySession.has(e))return;let t=await this.options.historyStore.getSessionRawSeqRange(e),n=t?t.max+1:1;this.nextRawSeqBySession.set(e,n)}async nextRawSeq(e){return await this.initializeRawSeqCursor(e),this.nextRawSeqSync(e)}nextRawSeqSync(e){let t=this.nextRawSeqBySession.get(e)??1;return this.nextRawSeqBySession.set(e,t+1),t}touchSession(e){e.lastActiveAtMs=Date.now()}isSessionEvictable(e){return!(e.closing||e.status!==`idle`||e.pendingToolApprovals.size>0||e.pendingUserInputs.size>0||e.dispatchInFlight)}async closeRuntimeSession(e,t,n){let r=this.sessions.get(e);if(!r||r.closing)return!1;r.closing=!0;let i=Date.now();this.options.logger?.info?.({sessionId:e,nativeSessionId:r.nativeSessionId,provider:r.provider,providerMode:r.providerMode,reason:t,statusBefore:r.status,projectId:r.projectId,projectPath:r.projectPath,model:r.model,pendingApprovalCount:r.pendingToolApprovals.size,pendingUserInputCount:r.pendingUserInputs.size,dispatchInFlight:r.dispatchInFlight},`provider runtime session close starting`);try{r.unsubscribe()}catch{}let a;try{await r.providerSession.close()}catch(n){a=n,console.error(`[session-runtime] failed closing session ${e}:`,n),this.options.logger?.error?.({sessionId:e,nativeSessionId:r.nativeSessionId,provider:r.provider,providerMode:r.providerMode,reason:t,projectId:r.projectId,projectPath:r.projectPath,model:r.model,error:String(n),err:n},`provider runtime session close failed`)}finally{r.status=`idle`,r.updatedAt=new Date().toISOString(),r.pendingToolApprovals.clear(),r.pendingUserInputs.clear();try{await this.persistSessionSnapshot(r)}catch(t){console.error(`[session-runtime] failed persisting closed session ${e}: ${String(t)}`)}this.sessions.delete(e),r.dispatchInFlight=!1,r.closing=!1}if(this.options.logger?.info?.({sessionId:e,nativeSessionId:r.nativeSessionId,provider:r.provider,providerMode:r.providerMode,reason:t,projectId:r.projectId,projectPath:r.projectPath,model:r.model,result:a?`error`:`success`,durationMs:Date.now()-i},`provider runtime session close completed`),!n?.suppressAudit)try{await this.options.auditLogger.record({ts:new Date().toISOString(),action:`session.runtime.close`,sessionId:e,detail:{reason:t,provider:r.provider}})}catch(e){console.error(`[session-runtime] failed to record runtime close audit log: ${String(e)}`)}return!0}async sweepRuntimeSessions(){if(this.shuttingDown||this.sessions.size===0)return;let e=Date.now(),t=this.runtimeLifecycle.idleTtlMs,n=[...this.sessions.values()].filter(e=>this.isSessionEvictable(e)).sort((e,t)=>e.lastActiveAtMs-t.lastActiveAtMs);for(let r of n)e-r.lastActiveAtMs<t||await this.closeRuntimeSession(r.id,`idle_ttl`);await this.enforceProviderSessionCap(`codex`,this.runtimeLifecycle.maxCodexSessions),await this.enforceProviderSessionCap(`claude`,this.runtimeLifecycle.maxClaudeSessions),await this.enforceGlobalSessionCap(this.runtimeLifecycle.maxSessions)}async enforceProviderSessionCap(e,t){let n=[...this.sessions.values()].filter(t=>t.provider===e);if(n.length<=t)return;let r=n.length-t,i=n.filter(e=>this.isSessionEvictable(e)).sort((e,t)=>e.lastActiveAtMs-t.lastActiveAtMs),a=0;for(let e of i){if(a>=r)break;await this.closeRuntimeSession(e.id,`lru_cap`)&&(a+=1)}a<r&&console.warn(`[session-runtime] ${e} sessions exceed cap (${n.length}/${t}), no more idle sessions to evict`)}async enforceGlobalSessionCap(e){if(this.sessions.size<=e)return;let t=this.sessions.size-e,n=[...this.sessions.values()].filter(e=>this.isSessionEvictable(e)).sort((e,t)=>e.lastActiveAtMs-t.lastActiveAtMs),r=0;for(let e of n){if(r>=t)break;await this.closeRuntimeSession(e.id,`lru_cap`)&&(r+=1)}r<t&&console.warn(`[session-runtime] session count exceeds cap (${this.sessions.size}/${e}), no more idle sessions to evict`)}ensureProviderRequestId(e){return e.type===`tool.permission.requested`||e.type===`user.input.requested`?typeof e.requestId==`string`&&e.requestId.trim()?e:{...e,requestId:`req_${ag(8)}`}:e}async maybePersistSyncedExternalRawEvents(e,t,n){if(!n)return t;let r=await this.options.historyStore.mergeSessionRawEvents(e.id,t),i=r[r.length-1]?.rawSeq;return typeof i==`number`&&Number.isFinite(i)&&i>0&&this.nextRawSeqBySession.set(e.id,i+1),r}async syncExternalRawHistory(e,t,n){if(e.provider===`claude`){let r=fS(e);if(!r)return n;try{let i=await fb({projectPath:e.projectPath,nativeSessionId:r,provider:e.provider,sessionId:e.id,projectId:t});return this.finalizeExternalRawHistorySync(e,n,i)}catch(t){return e.source===`native_discovered`&&dS(t)&&await this.markExternalHistoryHydrated(e.id,e.updatedAt),n}}if(e.provider!==`codex`)return n;let r=uS([e.nativeSessionId,e.id]);for(let i of r)try{let r=await py(i,!0),a=e.source===`gateway`&&n.length>0?hS({thread:r,provider:e.provider,sessionId:e.id,projectId:t,localEvents:n}):mS({thread:r,provider:e.provider,sessionId:e.id,projectId:t});return this.finalizeExternalRawHistorySync(e,n,a)}catch{}return n}async finalizeExternalRawHistorySync(e,t,n){let r=rS(t,n),i=await this.maybePersistSyncedExternalRawEvents(e,r,!0);return await this.markExternalHistoryHydrated(e.id,e.updatedAt),i}async markExternalHistoryHydrated(e,t){await this.options.historyStore.patchSession(e,{lastHydratedExternalUpdatedAt:t})}shouldAutoSyncGatewayCodexRawHistory(e,t){if(e.provider!==`codex`||e.providerMode!==`native`||e.source!==`gateway`||e.status===`running`)return!1;let n=Date.parse(e.updatedAt);if(!Number.isFinite(n))return!1;let r=e.lastHydratedExternalUpdatedAt?Date.parse(e.lastHydratedExternalUpdatedAt):NaN;if(Number.isFinite(r))return n>r+zx;let i=t[t.length-1]?.ts,a=i?Date.parse(i):NaN;return Number.isFinite(a)?n>a+zx:!1}async maybeSyncExternalRawHistoryForRead(e,t,n,r){if(!(r?.forceSyncExternal===!0||this.shouldAutoSyncGatewayCodexRawHistory(e,n)))return{session:e,rawEvents:n};let i=await this.options.historyStore.getSessionRawEvents(e.id,2**53-1),a=await this.syncExternalRawHistory(e,t,i);return{session:this.options.historyStore.getProjectSession(t,e.id)??e,rawEvents:a}}mustGetSession(e){let t=this.sessions.get(e);if(!t)throw Gg(e);return t}markSessionStreamReady(e){if(e.streamReady||(e.streamReady=!0,e.bufferedProviderEvents.length===0))return;let t=[...e.bufferedProviderEvents];e.bufferedProviderEvents.length=0;for(let n of t)this.handleProviderEvent(e,n)}async persistSessionSnapshot(e){await this.options.historyStore.upsertSession(this.toSessionSummary(e))}listAllSessionsWithRuntime(e=`all`){let t=new Map(this.options.historyStore.listSessions(`all`).map(e=>[e.id,e]));for(let e of this.sessions.values())(!t.get(e.id)||e.status===`running`)&&t.set(e.id,this.toSessionSummary(e));return[...t.values()].filter(t=>e===`all`||t.status===e).sort((e,t)=>{let n=e.updatedAt||e.createdAt;return(t.updatedAt||t.createdAt).localeCompare(n)})}listProjectSessionsWithRuntime(e,t=`all`){return this.listAllSessionsWithRuntime(t).filter(t=>t.projectId===e)}getRuntimeSessionSummary(e,t,n){let r=this.sessions.get(t);if(!(!r||r.projectId!==e)&&!(r.status!==`running`&&n))return this.toSessionSummary(r)}toSessionSummary(e){return{id:e.id,nativeSessionId:e.nativeSessionId,source:e.source,...e.source===`gateway`?{lastHydratedExternalUpdatedAt:e.updatedAt}:{},projectId:e.projectId,projectPath:e.projectPath,provider:e.provider,providerMode:e.providerMode,model:e.model,title:e.title,sessionTurnConfig:e.sessionTurnConfig,sessionTurnConfigUpdatedAt:e.sessionTurnConfigUpdatedAt,createdAt:e.createdAt,updatedAt:e.updatedAt,status:e.status,pendingApprovals:e.pendingToolApprovals.size,pendingUserInputs:e.pendingUserInputs.size,pendingActions:e.pendingToolApprovals.size+e.pendingUserInputs.size}}setSessionTitle(e,t){let n=_S(t);!n||n===e.title||(e.title=n,e.updatedAt=new Date().toISOString(),this.persistSessionSnapshot(e))}resolveCanonicalSessionId(e,t,n){return e===`codex`&&t.getNativeSessionId?.()||n}resolveNativeSessionId(e,t,n){return e!==`codex`&&e!==`claude`?n:t.getNativeSessionId?.()||n}maybePersistUpdatedNativeSessionId(e){let t=this.resolveNativeSessionId(e.provider,e.providerSession,e.nativeSessionId);!t||t===e.nativeSessionId||this.shouldPersistNativeSessionId(e,t)&&(e.nativeSessionId=t,e.updatedAt=new Date().toISOString(),this.persistSessionSnapshot(e))}shouldPersistNativeSessionId(e,t){return e.source===`native_discovered`?!1:e.nativeSessionId?e.nativeSessionId===e.id&&e.id.startsWith(`sess_`)?t!==e.nativeSessionId:!1:!0}};const eS=new Set([`thread.started`,`thread.title.updated`,`turn.started`,`turn.completed`,`turn.failed`,`item.started`,`item.updated`,`item.completed`]),tS=new Set([`thread.started`,`thread.title.updated`,`turn.started`,`turn.completed`,`turn.failed`,`item.started`,`item.updated`,`item.completed`]);function nS(e,t,n){let r=new Map;for(let t of e)r.set(t.eventId,t);for(let e of t)r.set(e.eventId,e);return[...r.values()].sort((e,t)=>e.ts.localeCompare(t.ts)).slice(-Math.max(1,n))}function rS(e,t){let n=new Map;for(let t of e)n.set(t.eventId,t);for(let e of t)n.set(e.eventId,e);return[...n.values()].sort((e,t)=>e.ts.localeCompare(t.ts))}function iS(e,t,n,r){let i=new Map,a=new Map;for(let t of e)if(i.set(t.eventId,t),n.has(t.type)){let e=aS(t);a.set(e,(a.get(e)??0)+1)}for(let e of t){if(!n.has(e.type))continue;let t=aS(e),r=a.get(t)??0;if(r>0){r===1?a.delete(t):a.set(t,r-1);continue}i.set(e.eventId,e)}return[...i.values()].sort((e,t)=>e.ts.localeCompare(t.ts)).slice(-Math.max(1,r))}function aS(e){let t=oS(e.payload.raw),n=oS(t.item),r=oS(t.turn),i=sS(t.turn_id)??sS(t.turnId)??sS(r.id)??``,a=sS(r.status)??sS(t.status)??``,o=sS(t.thread_id)??sS(t.threadId)??``,s=sS(n.type)??``,c=sS(n.phase)??``,l=sS(n.status)??``,u=sS(n.command)??``,d=lS(n),f=cS(t.message)??``,p=cS(t.title)??``;return e.type.startsWith(`item.`)?[e.type,s,c,l,u,d||f].join(`|`):e.type.startsWith(`turn.`)?[e.type,i,a].join(`|`):e.type===`thread.title.updated`?[e.type,p].join(`|`):[e.type,o,i,s,p||f].join(`|`)}function oS(e){return typeof e==`object`&&e?e:{}}function sS(e){return typeof e==`string`&&e.trim()||void 0}function cS(e){if(typeof e==`string`)return e.length>0?e:void 0}function lS(e){let t=cS(e.text);if(t)return t;let n=Array.isArray(e.content)?e.content:[];if(n.length>0){let e=[];for(let t of n){let n=cS(oS(t).text);n&&e.push(n)}if(e.length>0)return e.join(`
|
|
482
|
-
`)}let r=Array.isArray(e.summary)?e.summary:[];if(r.length>0){let e=r.map(e=>
|
|
483
|
-
`)}return``}function
|
|
484
|
-
`);
|
|
485
|
-
`).
|
|
486
|
-
`).map(e=>e.trim()).filter(Boolean),
|
|
487
|
-
`),t=e?`${e}\n`:``;await d.default.writeFile(n,t,`utf8`)}return this.rawEventsCacheBySession.set(e,c),c}readSessionRawEventsFromCache(e){if(!this.hasPendingRawMutation(e))return this.rawEventsCacheBySession.get(e)}readSessionRawEventsCompactedFromCache(e){if(this.hasPendingRawMutation(e))return;let t=this.compactedRawEventsCacheBySession.get(e);if(t)return kS(t);let n=this.rawEventsCacheBySession.get(e);if(!n)return;let r=OS(n);return this.compactedRawEventsCacheBySession.set(e,r),kS(r)}incrementPendingRawMutation(e){this.pendingRawMutationsBySession.set(e,(this.pendingRawMutationsBySession.get(e)??0)+1)}decrementPendingRawMutation(e){let t=(this.pendingRawMutationsBySession.get(e)??0)-1;if(t>0){this.pendingRawMutationsBySession.set(e,t);return}this.pendingRawMutationsBySession.delete(e)}hasPendingRawMutation(e){return(this.pendingRawMutationsBySession.get(e)??0)>0}};function wS(e){return typeof e==`object`&&!!e}function TS(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function ES(e){let t=new WeakSet;return JSON.stringify(e,(e,n)=>{if(typeof n==`bigint`)return n.toString();if(typeof n==`function`)return`[Function ${n.name||`anonymous`}]`;if(typeof n==`object`&&n){if(t.has(n))return`[Circular]`;t.add(n)}return n})}function DS(e){if(e.length===0)return null;let t=e[0],n=e[e.length-1];return!t||!n?null:{min:t.rawSeq,max:n.rawSeq}}function OS(e){let t=Es(e),n=t.map(e=>e),r=new Map;for(let[e,t]of n.entries()){let n=Ds(t);n&&r.set(n.key,e)}return{slots:n,indexByKey:r,dense:t}}function kS(e){return e.dense||=e.slots.filter(e=>e!==null),e.dense}function AS(e,t){let n=Ds(t);if(!n){e.slots.push(t),e.dense=null;return}let r=e.indexByKey.get(n.key);if(r===void 0){e.slots.push(t),e.indexByKey.set(n.key,e.slots.length-1),e.dense=null;return}let i=e.slots[r];if(!i){e.slots.push(t),e.indexByKey.set(n.key,e.slots.length-1),e.dense=null;return}let a=Os(i,t);if(!a){e.slots.push(t),e.indexByKey.set(n.key,e.slots.length-1),e.dense=null;return}e.slots[r]=null,e.slots.push(a),e.indexByKey.set(n.key,e.slots.length-1),e.dense=null}function jS(e,t){let n=e.ts.localeCompare(t.ts);return n===0?e.eventId.localeCompare(t.eventId):n}function MS(e,t){let n=new Map;for(let t of e)n.set(t.eventId,t);for(let e of t)n.set(e.eventId,e);return[...n.values()].sort((e,t)=>{let n=e.ts.localeCompare(t.ts);return n===0?e.eventId.localeCompare(t.eventId):n}).map((e,t)=>({...e,rawSeq:t+1}))}var NS=class{clients=new Map;clientIdsBySessionId=new Map;deliveryStateByClientSession=new Map;addClient(e,t){let n=`ws_${ag(10)}`;return this.clients.set(n,{id:n,deviceId:e,socket:t,subscriptionsBySessionId:new Map}),n}removeClient(e){let t=this.clients.get(e);t&&(this.removeClientFromSessionIndexes(e,t.subscriptionsBySessionId.keys()),this.removeClientDeliveryState(e),this.clients.delete(e))}replaceSubscriptions(e,t,n=!0){let r=this.clients.get(e);if(!r)return[];n&&(this.removeClientFromSessionIndexes(e,r.subscriptionsBySessionId.keys()),this.removeClientSessionDeliveryState(e,r.subscriptionsBySessionId.keys()),r.subscriptionsBySessionId.clear());let i=new Map;for(let e of t)i.set(e.sessionId,e);for(let[t,n]of i){r.subscriptionsBySessionId.set(t,n);let i=this.clientIdsBySessionId.get(t)??new Set;i.add(e),this.clientIdsBySessionId.set(t,i),this.ensureClientSessionDeliveryState(e,t)}return[...r.subscriptionsBySessionId.values()]}getSubscriptions(e){let t=this.clients.get(e);return t?[...t.subscriptionsBySessionId.values()]:[]}routeProviderRaw(e){let t=this.clientIdsBySessionId.get(e.sessionId);if(!t||t.size===0)return;let n=JSON.stringify(e);for(let r of t){let t=this.deliveryStateByClientSession.get(this.clientSessionKey(r,e.sessionId));if(t?.paused){t.queued.push(e);continue}let i=this.clients.get(r);!i||i.socket.readyState!==i.socket.OPEN||i.socket.send(n)}}pauseSession(e,t){let n=this.ensureClientSessionDeliveryState(e,t);n.paused=!0}resumeSession(e,t){let n=this.clientSessionKey(e,t),r=this.deliveryStateByClientSession.get(n);if(!r||(r.paused=!1,r.queued.length===0))return;let i=this.clients.get(e);if(!i||i.socket.readyState!==i.socket.OPEN){r.queued=[];return}let a=[...r.queued].sort((e,t)=>e.rawSeq-t.rawSeq);r.queued=[];for(let e of a)i.socket.send(JSON.stringify(e))}sendStreamMessage(e,t){let n=this.clients.get(e);!n||n.socket.readyState!==n.socket.OPEN||n.socket.send(JSON.stringify(t))}sendSystemMessage(e,t){let n=this.clients.get(e);!n||n.socket.readyState!==n.socket.OPEN||n.socket.send(JSON.stringify(t))}broadcastSystemMessage(e){let t=JSON.stringify(e);for(let e of this.clients.values())e.socket.readyState===e.socket.OPEN&&e.socket.send(t)}count(){return this.clients.size}removeClientFromSessionIndexes(e,t){for(let n of t){let t=this.clientIdsBySessionId.get(n);t&&(t.delete(e),t.size===0&&this.clientIdsBySessionId.delete(n))}}clientSessionKey(e,t){return`${e}::${t}`}ensureClientSessionDeliveryState(e,t){let n=this.clientSessionKey(e,t),r=this.deliveryStateByClientSession.get(n);if(r)return r;let i={paused:!1,queued:[]};return this.deliveryStateByClientSession.set(n,i),i}removeClientSessionDeliveryState(e,t){for(let n of t)this.deliveryStateByClientSession.delete(this.clientSessionKey(e,n))}removeClientDeliveryState(e){let t=`${e}::`;for(let e of this.deliveryStateByClientSession.keys())e.startsWith(t)&&this.deliveryStateByClientSession.delete(e)}};async function PS(e,t={}){await ql(e.gatewayLogPath);let n=IS(e,t),r=FS(e,n.instance);await r.register(eg.default,{origin:!0}),await r.register($h.default);let i=process.env.NODE_ENV!==`production`,a=4e3,o=`[unserializable payload]`,s=new Qg(e);await s.init();let c=new i_(e.auditLogPath),l=new NS,u=new U_,d=new Q_(e.projectStoreDir),f=new CS(e.sessionHistoryDir);await f.init();let m=new Yb(p.default.join(e.sessionHistoryDir,`discovery-v1`));await m.init();let h=new Ib({store:m});await h.init();let g,_=null,v=await zs(e.authStoreDir),y=new $x({preferNativeProviders:e.enableNativeProviders,requireNativeCodex:e.requireNativeCodex,auditLogger:c,projectStore:d,historyStore:f,logger:r.log,runtimeLifecycle:{idleTtlMs:e.runtimeIdleTtlMs,sweepIntervalMs:e.runtimeSweepIntervalMs,maxSessions:e.runtimeMaxSessions,maxCodexSessions:e.runtimeMaxCodexSessions,maxClaudeSessions:e.runtimeMaxClaudeSessions},onEnvelope:e=>{l.routeProviderRaw(e)}});y.warmStartupProviderCapabilities().catch(e=>{r.log.warn({err:e},`startup provider capability warmup failed`)});let b=new pl({packageName:te.packageName,currentVersion:te.version,sessionHub:l,logger:r.log,consoleWrite:e=>{console.log(e)},getRunningSessionCount:async()=>(await y.listProjects()).reduce((e,t)=>e+(t.runningCount??0),0),requestPreparedUpdate:t.onUpdatePrepared});r.addHook(`onClose`,async()=>{r.log.info({hasRelayClient:!!_},`gateway shutdown starting`);try{_?.close(),x.close(),await b.shutdown(),await y.shutdown(),await f.shutdown(),r.log.info(`gateway shutdown completed`)}catch(e){throw r.log.error({err:e},`gateway shutdown failed`),e}finally{n.close()}}),i&&r.addHook(`onSend`,async(e,t,n)=>(r.log.info({method:e.method,url:e.url,statusCode:t.statusCode,responseBody:N(n)},`gateway response (dev)`),n)),r.get(`/health`,async()=>({ok:!0,service:`desktop-gateway`,now:new Date().toISOString(),wsClients:l.count(),machineName:Xc(),gatewayIdentity:v.identity})),r.get(`/api/pairing/descriptor`,async()=>Gc({gatewayId:e.gatewayId,machineName:Xc(),relayBaseUrl:e.relayEnabled?il({relayUrl:e.relayUrl,gatewayHost:e.host}):``,directBaseUrls:nl({protocol:e.httpsEnabled?`https`:`http`,host:e.host,port:e.httpsEnabled?e.httpsPort:e.port}),gatewayIdentity:v.identity})),r.post(`/api/pairing/start`,async(t,n)=>{if(!ee(t))return n.code(401).send({error:`Unauthorized`});try{let t=await s.createPairingCode(e.pairingCodeTtlSeconds);return await c.record({ts:new Date().toISOString(),action:`pairing.start`,detail:{expiresAt:t.expiresAt,source:`api`,ttlSeconds:e.pairingCodeTtlSeconds}}),t}catch(e){return r.log.error({err:e},`failed to generate pairing code via API`),n.code(500).send({error:`Failed to generate pairing code`,detail:String(e)})}}),r.post(`/api/pairing/claim`,async(e,t)=>{let n=ya.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{let e=de(n.data.deviceName),t=await s.claimPairingCode(n.data.code,e,n.data.deviceIdentity);return await c.record({ts:new Date().toISOString(),action:`pairing.claim`,deviceId:t.deviceId,detail:{deviceName:e}}),KS(v,t,n.data.code,n.data.deviceIdentity)}catch(e){return t.code(400).send({error:String(e)})}}),r.post(`/api/auth/refresh`,async(e,t)=>{let n=Sa.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{return await zS({authService:s,execute:()=>s.refreshAccessToken(n.data.refreshToken),logger:r.log,refreshToken:n.data.refreshToken,source:`direct_http`})}catch(e){return t.code(401).send({error:String(e)})}}),r.get(`/api/projects`,async(e,t)=>{if(L(e,t))return{projects:await y.listProjects()}}),r.get(`/api/gateway/update`,async(e,t)=>{if(L(e,t))try{return await b.getOrCheckInfo(`mobile`)}catch(e){return t.code(500).send({error:String(e)})}}),r.post(`/api/gateway/update/apply`,async(e,t)=>{if(!L(e,t))return;let n=e.body,r=Oa.safeParse(n?.requestedBy);try{let e=await b.applyUpdate(r.success?r.data:`mobile`);return Na.parse(e)}catch(e){let n=String(e),r=n.includes(`already up to date`)||n.includes(`does not support self-update`)||n.includes(`requires idle runtime`)?409:500;return t.code(r).send({error:n})}}),r.get(`/api/discovery/projects`,async(e,t)=>{if(L(e,t))try{return await h.getProjects()}catch(e){return t.code(500).send({error:String(e)})}}),r.post(`/api/discovery/projects/refresh`,async(e,t)=>{if(L(e,t))try{return await h.refreshProjects()}catch(e){return t.code(500).send({error:String(e)})}}),r.get(`/api/discovery/projects/sessions`,async(e,t)=>{if(!L(e,t))return;let n=e.query;if(typeof n.projectPath!=`string`||!n.projectPath.trim())return t.code(400).send({error:`projectPath is required and must be a non-empty string`});try{return await h.listProjectSessions(n.projectPath)}catch(e){let n=e instanceof Error?e.message:String(e);return Lg(e)&&e.code===`DISCOVERED_PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):XS(n)?t.code(400).send({error:n}):t.code(500).send({error:n})}}),r.get(`/api/workspace/directories`,async(e,t)=>{if(!L(e,t))return;let n=e.query,r=Number(n.limit??200),i=Number.isFinite(r)?Math.min(500,Math.max(1,r)):200;try{return await u.listDirectoriesUnrestricted(typeof n.path==`string`?n.path:void 0,i)}catch(e){return t.code(400).send({error:String(e)})}}),r.get(`/api/providers/:provider/capabilities`,async(e,t)=>{if(!L(e,t))return;let n=R(e,t);if(n)try{return{capabilities:await y.getProviderCapabilities(n.provider,n.projectId,n.agentVersion)}}catch(e){return Lg(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(400).send({error:String(e)})}}),r.get(`/api/agents/:provider/config`,async(e,t)=>{if(!L(e,t))return;let n=R(e,t);if(n)try{return await y.getAgentConfig(n.provider,{projectId:n.projectId,agentVersion:n.agentVersion})}catch(e){return Lg(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(400).send({error:String(e)})}}),r.post(`/api/projects`,async(e,t)=>{if(!L(e,t))return;let n=e.body;if(typeof n.path!=`string`||!n.path.trim())return t.code(400).send({error:`path is required and must be a non-empty string`});try{return{project:await y.createProject({path:n.path,title:typeof n.title==`string`?n.title:void 0})}}catch(e){return t.code(400).send({error:String(e)})}}),r.delete(`/api/projects/:projectId`,async(e,t)=>{if(!L(e,t))return;let n=e.params;try{return await y.deleteProject(n.projectId)?{removed:!0}:t.code(404).send({error:`Project not found`})}catch(e){return t.code(409).send({error:String(e)})}}),r.get(`/api/projects/:projectId/sessions`,async(e,t)=>{if(!L(e,t))return;let n=e.params,r=e.query,i=ie(r.status,t);if(!i)return;let a=ae(r.syncExternal);try{return{sessions:await y.listProjectSessions(n.projectId,i,{syncExternal:a})}}catch(e){return Lg(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(500).send({error:String(e)})}}),r.get(`/api/projects/:projectId/sessions/:sessionId`,async(e,t)=>{if(!L(e,t))return;let n=e.params,r=await y.getProjectSessionSummary(n.projectId,n.sessionId);return r?{session:r}:t.code(404).send({error:`Session not found`})}),r.get(`/api/projects/:projectId/sessions/:sessionId/events`,async(e,t)=>t.code(410).send({error:`Session events endpoint is deprecated. Use /api/projects/:projectId/sessions/:sessionId/raw-events`})),r.get(`/api/projects/:projectId/sessions/:sessionId/raw-events`,async(e,t)=>{if(!L(e,t))return;let n=e.params,r=e.query,i=(typeof r.limit==`string`?r.limit.trim().toLowerCase():``)===`all`?2**53-1:(()=>{let e=Number(r.limit??300);return Number.isFinite(e)?Math.min(2e3,Math.max(1,e)):300})(),a=ae(r.syncExternal);try{return{events:await y.getProjectSessionRawEvents(n.projectId,n.sessionId,i,{syncExternal:a})}}catch(e){return Lg(e)&&(e.code===`PROJECT_NOT_FOUND`||e.code===`PROJECT_SESSION_NOT_FOUND`)?t.code(e.status).send({error:String(e)}):t.code(500).send({error:String(e)})}}),r.get(`/api/projects/:projectId/fs/tree`,async(e,t)=>{if(!L(e,t))return;let n=e.params,r=e.query,i=await y.getProject(n.projectId);if(!i)return t.code(404).send({error:`Project not found`});try{return await u.listTree(i.path,r.path??`.`)}catch(e){return t.code(400).send({error:String(e)})}}),r.get(`/api/sessions`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/sessions`})),r.get(`/api/sessions/:sessionId`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/sessions/:sessionId`})),r.get(`/api/sessions/:sessionId/events`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/sessions/:sessionId/raw-events`})),r.get(`/api/fs/tree`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/fs/tree`})),r.get(`/api/devices`,async(e,t)=>ee(e)?{devices:s.listDevices()}:t.code(401).send({error:`Unauthorized`})),r.post(`/api/devices/:deviceId/revoke`,async(e,t)=>{if(!ee(e))return t.code(401).send({error:`Unauthorized`});let n=e.params;return await s.revokeDevice(n.deviceId)?(await c.record({ts:new Date().toISOString(),action:`device.revoke`,deviceId:n.deviceId}),{revoked:!0}):t.code(404).send({error:`Device not found`})}),r.get(`/ws`,{websocket:!0},(e,t)=>{let n=oe(t.headers.authorization)??se(t.url);if(!n){e.close(1008,`Missing access token`);return}let r;try{r=s.verifyAccessToken(n)}catch(t){e.close(1008,`Unauthorized: ${String(t)}`);return}let i=l.addClient(r.sub,e);e.on(`message`,async e=>{let t=e.toString(),n;try{let e=JSON.parse(t);e&&typeof e==`object`&&(n=e),await C(sa(e),r.sub,i)}catch(e){await w({deviceId:r.sub,clientId:i,rawCommand:t,parsedInput:n,error:e})}}),e.on(`close`,()=>{l.removeClient(i)})});let x=new cx({gatewayId:e.gatewayId,relayTransportSecurityLevel:e.relayEnabled?`e2ee-relay`:`plaintext-relay`,gatewayIdentity:v.identity,gatewayIdentityPrivateKeyPem:v.privateKeyPem,sessionHub:l,handlePairingClaim:async e=>{let t=de(e.deviceName);return KS(v,await s.claimPairingCode(e.code,t,e.deviceIdentity),e.code,e.deviceIdentity)},handleRefresh:async t=>{let n=await zS({authService:s,execute:()=>s.refreshAccessToken(t.refreshToken),logger:r.log,refreshToken:t.refreshToken,requestedDeviceId:t.deviceId,source:`relay_http_forward`});return RS(t.deviceId,n.deviceId),{gatewayId:e.gatewayId,...n}},verifyDeviceIdentityBinding:async(e,t)=>s.verifyDeviceIdentityBinding(e,t),handleRpcRequest:async(e,t)=>WS(e,{authService:s,logger:r.log,sessionManager:y,projectDiscoveryService:h,fsService:u,updateService:b,relayDeviceId:t.deviceId}),sendFrame:e=>_?.send(e)??!1,dispatchCommand:async(e,t,n)=>{try{await C(e,t,n)}catch(r){await w({deviceId:t,clientId:n,rawCommand:JSON.stringify(e),parsedInput:e,error:r})}}}),S=async(e,t,n)=>{switch(e.type){case`session.start`:{let r=await y.startSession({...e.payload,deviceId:t});l.sendSystemMessage(n,{type:`command.ack`,commandType:e.type,commandId:e.commandId,payload:r});return}case`turn.input`:await y.sendInput(e.payload.sessionId,e.payload.text,t,{model:e.payload.model,sessionConfig:e.payload.sessionConfig,mode:e.payload.mode,config:e.payload.config});return;case`review.start`:throw Error(`review.start is not implemented yet.`);case`tool.approval.respond`:await y.respondToolPermission(e.payload.sessionId,e.payload.requestId,e.payload.decision,e.payload.reason,t);return;case`user.input.respond`:await y.respondUserInput(e.payload.sessionId,e.payload.requestId,e.payload.answers,t);return;case`session.interrupt`:await y.interruptSession(e.payload.sessionId,t);return;case`session.close`:throw Error(`session.close is deprecated. Use session.interrupt instead.`);case`session.stream.subscribe`:{let t=e.payload.sessions.map(e=>({sessionId:e.sessionId,projectId:e.projectId,cursor:e.cursor.kind===`raw_seq`?{kind:`raw_seq`,rawSeq:e.cursor.rawSeq}:{kind:`all`}}));await T(n,t,e.payload.replace),l.sendSystemMessage(n,{type:`command.ack`,commandType:e.type,commandId:e.commandId,payload:{replace:e.payload.replace,sessions:t.map(e=>e.sessionId)}});return}case`fs.read`:{let t=y.getSessionExecutionContext(e.payload.sessionId),n=await u.readFile(t.projectPath,e.payload.path);await y.emitExternalEvent({provider:t.provider,sessionId:e.payload.sessionId,projectId:t.projectId,type:`file.changed`,raw:{path:n.path,content:n.content}});return}case`fs.diff`:{let t=y.getSessionExecutionContext(e.payload.sessionId),n=await u.diffFile(t.projectPath,e.payload.path,e.payload.baseContent??``);await y.emitExternalEvent({provider:t.provider,sessionId:e.payload.sessionId,projectId:t.projectId,type:`file.diff.ready`,raw:{path:n.path,diff:n.diff,currentContent:n.currentContent}});return}default:{let t=e;throw Error(`Unhandled command: ${JSON.stringify(t)}`)}}},C=async(e,t,n)=>{await S(e,t,n)},w=async e=>{r.log.warn({deviceId:e.deviceId,rawCommand:e.rawCommand,err:e.error},`ws command failed`);let t=typeof e.parsedInput?.commandId==`string`?e.parsedInput.commandId:void 0,n=typeof e.parsedInput?.type==`string`?e.parsedInput.type:void 0;l.sendSystemMessage(e.clientId,{type:`command.error`,commandId:t,commandType:n,message:String(e.error)}),await y.emitExternalEvent({provider:`codex`,sessionId:`system`,type:`error.runtime`,raw:{message:String(e.error),source:`ws.command`}})},T=async(e,t,n)=>{let r=E(t),i=new Set(r.map(e=>e.sessionId));for(let t of i)l.pauseSession(e,t);l.replaceSubscriptions(e,r,n);try{for(let t of r)await D(e,t)}finally{for(let t of i)l.resumeSession(e,t)}},E=e=>{let t=new Map;for(let n of e)t.set(n.sessionId,n);return[...t.values()]},D=async(e,t)=>{let n=await O(t);if(t.cursor.kind===`all`){await k(e,n,`cursor_all`);return}let r=await y.getProjectSessionRawSeqRange(n.projectId,n.sessionId);if(!r){await k(e,n,`empty_history_snapshot`);return}let i=t.cursor.rawSeq;if(i<Math.max(0,r.min-1)||i>r.max){await k(e,n,`cursor_out_of_range_snapshot`);return}let a=await y.getProjectSessionRawEventsSinceSeq(n.projectId,n.sessionId,i,2**53-1),o=a[a.length-1]?.rawSeq??i;l.sendStreamMessage(e,j({provider:n.provider,sessionId:n.sessionId,projectId:n.projectId,decision:`delta`,reason:n.status===`running`?`cursor_resumed_delta`:`session_idle_delta`,fromRawSeq:i,toRawSeq:o}));for(let t of a)l.sendStreamMessage(e,t)},O=async e=>{let t=e.sessionId;if(!t)throw Error(`session.stream.subscribe requires sessionId`);let n=e.projectId?.trim()??``;if(n){let e=await y.getProjectSessionSummary(n,t);if(!e)throw Wg(n,t);return{sessionId:t,projectId:n,provider:e.provider,status:e.status}}let r=y.getSessionExecutionContext(t),i=await y.getProjectSessionSummary(r.projectId,t);return{sessionId:t,projectId:r.projectId,provider:i?.provider??r.provider,status:i?.status??`idle`}},k=async(e,t,n)=>{let r=`snap_${ag(12)}`,i=await y.getProjectSessionRawEventsCompacted(t.projectId,t.sessionId,2**53-1),a=i[i.length-1]?.rawSeq;l.sendStreamMessage(e,j({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,decision:`snapshot`,reason:n,snapshotId:r,...a===void 0?{}:{toRawSeq:a}}));let o=A(i,100),s=o.length;for(let n=0;n<o.length;n+=1){let i=o[n]??[];l.sendStreamMessage(e,M({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,snapshotId:r,chunkIndex:n,totalChunks:s,events:i}))}},A=(e,t)=>{if(e.length===0)return[[]];let n=Math.max(1,Math.floor(t)),r=[];for(let t=0;t<e.length;t+=n)r.push(e.slice(t,t+n));return r},j=e=>({v:`1.0`,kind:`session.stream.sync`,type:`session.stream.sync`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`stream_sync_${ag(12)}`,ts:new Date().toISOString(),payload:{raw:{decision:e.decision,reason:e.reason,snapshotId:e.snapshotId,fromRawSeq:e.fromRawSeq,toRawSeq:e.toRawSeq}}}),M=e=>({v:`1.0`,kind:`session.stream.snapshot.chunk`,type:`session.stream.snapshot.chunk`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`stream_snapshot_${e.snapshotId}_${e.chunkIndex}`,ts:new Date().toISOString(),payload:{raw:{snapshotId:e.snapshotId,chunkIndex:e.chunkIndex,totalChunks:e.totalChunks,events:e.events}}}),ee=t=>t.headers[`x-api-key`]===e.apiKey,N=e=>{if(e==null)return e;if(typeof e==`string`){let t=P(e);return t===void 0?ne(e,a):I(F(t))}if(Buffer.isBuffer(e)){let t=e.toString(`utf8`),n=P(t);return n===void 0?ne(t,a):I(F(n))}return typeof e==`object`?I(F(e)):String(e)},P=e=>{try{return JSON.parse(e)}catch{return}},ne=(e,t)=>e.length<=t?e:`${e.slice(0,t)}...<truncated>`,F=e=>{if(Array.isArray(e))return e.map(e=>F(e));if(e&&typeof e==`object`){let t=e,n={};for(let[e,r]of Object.entries(t)){let t=e.toLowerCase();t.includes(`token`)||t.includes(`secret`)||t.includes(`password`)||t.includes(`authorization`)?n[e]=`[REDACTED]`:n[e]=F(r)}return n}return e},I=e=>{let t=re(e);return t===o?t:t.length<=a?e:{truncated:!0,preview:ne(t,a)}},re=e=>{try{return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t)}catch{return o}},L=(e,t)=>{let n=oe(e.headers.authorization);if(!n)return t.code(401).send({error:`Missing bearer token`}),null;try{return s.verifyAccessToken(n)}catch(e){return t.code(401).send({error:String(e)}),null}},ie=(e,t)=>{let n=e??`all`;return[`running`,`idle`,`all`].includes(n)?n:(t.code(400).send({error:`Invalid status filter`}),null)},ae=e=>{let t=e?.trim().toLowerCase();return t===`true`||t===`1`},R=(e,t)=>{let n=e.params,r=e.query,i=ki.safeParse(n.provider);return i.success?{provider:i.data,projectId:typeof r.projectId==`string`?r.projectId:void 0,agentVersion:typeof r.agentVersion==`string`?r.agentVersion:void 0}:(t.code(400).send({error:`Invalid provider`}),null)},oe=e=>{if(!e)return null;let[t,n]=e.split(` `);return t?.toLowerCase()!==`bearer`||!n?null:n},se=e=>{try{return new URL(e,`http://localhost`).searchParams.get(`token`)}catch{return null}},ce=e.httpsEnabled?e.httpsPort:e.port,le=e.httpsEnabled?`https`:`http`,ue=Xc(),de=e=>e?.trim()||ue||`Gateway`;await r.listen({host:e.host,port:ce});let z=r.server.address(),fe=typeof z==`object`&&z?z.port:ce;if(r.log.info({host:e.host,port:fe,protocol:le,machineName:ue},LS(le,e.host,fe)),e.relayEnabled&&(_=new gx({gatewayId:e.gatewayId,machineName:ue,relayUrl:e.relayUrl,relayGatewayAccessToken:e.relayGatewayAccessToken,resolveRelayGatewayAccessToken:e.relayGatewayAccessToken.trim()?void 0:()=>xx({gatewayId:e.gatewayId,relayUrl:e.relayUrl,gatewayIdentity:v.identity,privateKeyPem:v.privateKeyPem}),gatewayIdentity:v.identity,directBaseUrls:nl({protocol:le,host:e.host,port:fe}),logger:r.log,onFrame:async e=>{await x.handleFrame(e)}}),_.start()),e.bootstrapPairingCodeOnStart)try{let t=await s.createPairingCode(e.pairingCodeTtlSeconds);g={code:t.code,expiresAt:t.expiresAt},await c.record({ts:new Date().toISOString(),action:`pairing.start`,detail:{expiresAt:t.expiresAt,source:`startup`,ttlSeconds:e.pairingCodeTtlSeconds}}),r.log.info({expiresAt:t.expiresAt},`startup pairing code generated`)}catch(e){r.log.error({err:e},`failed to generate startup pairing code`)}return await b.start(),{protocol:le,listenPort:fe,machineName:ue,gatewayIdentity:v.identity,close:()=>r.close(),getGatewayUpdateInfo:()=>b.getInfo(),requestGatewayUpdate:(e=`console`)=>b.applyUpdate(e),startupPairingCode:g}}function FS(e,t){let n=t;if(!e.httpsEnabled)return(0,tg.default)({disableRequestLogging:!0,loggerInstance:n});if(!e.tlsKeyPath||!e.tlsCertPath)throw Error(`TLS key/cert path is required when HTTPS is enabled.`);return(0,tg.default)({disableRequestLogging:!0,loggerInstance:n,https:{key:(0,u.readFileSync)(e.tlsKeyPath),cert:(0,u.readFileSync)(e.tlsCertPath),...e.tlsCaPath?{ca:(0,u.readFileSync)(e.tlsCaPath)}:{}}})}function IS(e,t){let n=process.env.NODE_ENV!==`production`,r=Fg.default.destination({dest:e.gatewayLogPath,mkdir:!0,sync:!1}),i=t.logToConsole?Fg.default.multistream([{stream:r},{stream:process.stdout}]):r;return{instance:(0,Fg.default)({level:n?`debug`:`info`},i),close:()=>{try{r.flushSync()}catch{}r.end()}}}function LS(e,t,n){return`desktop-gateway listening on ${e}://${t}:${n}`}function RS(e,t){if(e&&e!==t)throw Hg()}async function zS(e){let t=BS(e.authService,e.refreshToken);e.logger?.info?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshToken:VS(t)},`auth refresh attempt`);try{let t=await e.execute(),n=BS(e.authService,e.refreshToken),r=BS(e.authService,t.refreshToken);return e.logger?.info?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshedDeviceId:t.deviceId,previousRefreshToken:VS(n),nextRefreshToken:VS(r)},`auth refresh succeeded`),t}catch(t){let n=BS(e.authService,e.refreshToken);throw e.logger?.warn?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshToken:VS(n),error:HS(t)},`auth refresh failed`),t}}function BS(e,t){return e.inspectRefreshToken?.(t)??{tokenRecordState:`missing`}}function VS(e){return{claimDeviceId:e.claimDeviceId??null,claimExpAt:e.claimExpAt??null,claimIssuedAt:e.claimIssuedAt??null,claimJtiSuffix:US(e.claimJti),claimType:e.claimType??null,latestActiveTokenCreatedAt:e.latestActiveTokenCreatedAt??null,latestActiveTokenJtiSuffix:US(e.latestActiveTokenJti),tokenRecordCreatedAt:e.tokenRecordCreatedAt??null,tokenRecordDeviceId:e.tokenRecordDeviceId??null,tokenRecordRevokedAt:e.tokenRecordRevokedAt??null,tokenRecordState:e.tokenRecordState}}function HS(e){return Lg(e)?{code:e.code,message:String(e),status:e.status}:e instanceof Error?{message:e.message,name:e.name}:{message:String(e)}}function US(e){return e?e.slice(-8):null}async function WS(e,t){try{let n=To.parse(e);switch(n.method){case`auth.refresh`:{let e=await zS({authService:t.authService,execute:()=>t.authService.refreshAccessToken(n.params.refreshToken),logger:t.logger,refreshToken:n.params.refreshToken,requestedDeviceId:n.params.deviceId??t.relayDeviceId,source:`relay_rpc`});return RS(n.params.deviceId??t.relayDeviceId,e.deviceId),Eo.parse({method:n.method,result:e})}case`projects.list`:{let e=await t.sessionManager.listProjects();return Eo.parse({method:n.method,result:{projects:e}})}case`gateway.update.get`:{let e=await t.updateService.getOrCheckInfo(`mobile`);return Eo.parse({method:n.method,result:e})}case`gateway.update.apply`:{let e=await t.updateService.applyUpdate(n.params.requestedBy??`mobile`);return Eo.parse({method:n.method,result:e})}case`projects.discovery.get`:{let e=await t.projectDiscoveryService.getProjects();return Eo.parse({method:n.method,result:e})}case`projects.discovery.refresh`:{let e=await t.projectDiscoveryService.refreshProjects();return Eo.parse({method:n.method,result:e})}case`projects.create`:{let e=await t.sessionManager.createProject({path:n.params.path,title:n.params.title});return Eo.parse({method:n.method,result:{project:e}})}case`projects.delete`:if(!await t.sessionManager.deleteProject(n.params.projectId))throw JS(n.method,`NOT_FOUND`,404,`Project not found`);return Eo.parse({method:n.method,result:{removed:!0}});case`workspace.directories.list`:{let e=await t.fsService.listDirectoriesUnrestricted(n.params.path,n.params.limit??200);return Eo.parse({method:n.method,result:e})}case`sessions.list`:{let e=await t.sessionManager.listProjectSessions(n.params.projectId,n.params.status??`all`,{syncExternal:n.params.syncExternal});return Eo.parse({method:n.method,result:{sessions:e}})}case`sessions.discovery.list`:{let e=await t.projectDiscoveryService.listProjectSessions(n.params.projectPath);return Eo.parse({method:n.method,result:e})}case`sessions.get`:{let e=await t.sessionManager.getProjectSessionSummary(n.params.projectId,n.params.sessionId);if(!e)throw JS(n.method,`NOT_FOUND`,404,`Session ${n.params.sessionId} not found in project ${n.params.projectId}`);return Eo.parse({method:n.method,result:{session:e}})}case`sessions.rawEvents.list`:{let e=await t.sessionManager.getProjectSessionRawEvents(n.params.projectId,n.params.sessionId,n.params.limit===`all`?2**53-1:n.params.limit,{syncExternal:n.params.syncExternal});return Eo.parse({method:n.method,result:{events:e}})}case`providers.capabilities.get`:{let e=await t.sessionManager.getProviderCapabilities(n.params.provider,n.params.projectId??void 0,n.params.agentVersion??void 0);return Eo.parse({method:n.method,result:{capabilities:e}})}case`agents.config.get`:{let e=await t.sessionManager.getAgentConfig(n.params.provider,{projectId:n.params.projectId??void 0,agentVersion:n.params.agentVersion??void 0});return Eo.parse({method:n.method,result:e})}case`devices.list`:return Eo.parse({method:n.method,result:{devices:t.authService.listDevices()}});case`devices.revoke`:if(!await t.authService.revokeDevice(n.params.deviceId))throw JS(n.method,`NOT_FOUND`,404,`Device ${n.params.deviceId} not found`);return Eo.parse({method:n.method,result:{revoked:!0}});default:{let e=n;throw JS(void 0,`INTERNAL`,500,`Unhandled relay RPC method: ${JSON.stringify(e)}`)}}}catch(e){throw GS(e)}}function GS(e){if(Lg(e))switch(e.code){case`REFRESH_TOKEN_REVOKED`:case`DEVICE_REVOKED`:case`REFRESH_TOKEN_DEVICE_MISMATCH`:return JS(`UNAUTHORIZED`,e.status,String(e),e.details);case`PROJECT_NOT_FOUND`:case`DISCOVERED_PROJECT_NOT_FOUND`:case`PROJECT_SESSION_NOT_FOUND`:case`SESSION_NOT_FOUND`:return JS(`NOT_FOUND`,e.status,String(e),e.details);case`PROJECT_DELETE_CONFLICT`:return JS(`BAD_REQUEST`,e.status,String(e),e.details);default:return JS(e.status>=500?`INTERNAL`:`BAD_REQUEST`,e.status,String(e),e.details)}let t=Oo.safeParse(e);if(t.success)return t.data;let n=Do.safeParse(e);if(n.success)return JS(void 0,n.data.code,n.data.status,n.data.message,n.data.details);if(e&&typeof e==`object`&&`code`in e&&`status`in e&&`message`in e&&typeof e.code==`string`&&typeof e.status==`number`&&typeof e.message==`string`){let t=e;return JS(t.code,t.status,t.message,t.details)}let r=String(e);return e instanceof Error&&e.name===`ZodError`?JS(`BAD_REQUEST`,400,r):YS(e)?JS(`UNAUTHORIZED`,401,r):XS(r)?JS(`BAD_REQUEST`,400,r):JS(`INTERNAL`,500,r)}function KS(e,t,n,r){if(!r)return t;let i={gatewayId:t.gatewayId,deviceId:t.deviceId,mobilePublicKey:r.publicKey,pairingContext:{pairingCode:qS(n),signedAt:new Date().toISOString()}};return{...t,gatewayIdentity:e.identity,pairingConfirmation:Hs(e.identity,e.privateKeyPem,i)}}function qS(e){return e.replace(/\s+/gu,``).toUpperCase()}function JS(e,t,n,r,i){let a=typeof t==`string`,o=a?e:void 0,s=a?t:e,c=a?n:t,l=a?r:n,u=a?i:r;return Oo.parse({...o?{method:o}:{},code:s,status:c,message:l,...u===void 0?{}:{details:u}})}function YS(e){return Lg(e)&&(e.code===`REFRESH_TOKEN_REVOKED`||e.code===`DEVICE_REVOKED`||e.code===`REFRESH_TOKEN_DEVICE_MISMATCH`)||Zg(e)}function XS(e){let t=e.trim();return t===`Invalid provider`||t.startsWith(`Invalid provider:`)||t.startsWith(`Project path must be absolute:`)||t.startsWith(`Project path does not exist:`)||t.startsWith(`Project path is not a directory:`)||t.startsWith(`ZodError:`)}async function ZS(e){let t=await Zs({configPath:e.configPath,ensureConfigFile:!0});tc(t.config);let n=await PS(t.config,{logToConsole:e.logToConsole,onUpdatePrepared:async e=>{$S({type:`worker.update.prepared`,payload:e})}});$S({type:`worker.ready`,payload:QS(n)});let r=null,i=e=>r||(r=Promise.resolve(n.close?.()).catch(e=>{console.error(`[gateway] worker shutdown failed: ${String(e)}`)}).finally(()=>{process.exit(e)}),r);process.on(`message`,e=>{let t=eC(e);if(t)switch(t.type){case`supervisor.request`:a(t);return;case`supervisor.shutdown`:i(0);return}}),process.on(`disconnect`,()=>{i(0)}),process.on(`SIGINT`,()=>{i(0)}),process.on(`SIGTERM`,()=>{i(0)}),process.on(`uncaughtException`,e=>{console.error(`[gateway] worker uncaught exception: ${String(e)}`),i(1)}),process.on(`unhandledRejection`,e=>{console.error(`[gateway] worker unhandled rejection: ${String(e)}`),i(1)});async function a(e){try{switch(e.method){case`gateway.update.apply`:{if(!n.requestGatewayUpdate)throw Error(`gateway update is unavailable`);let t=await n.requestGatewayUpdate(e.requestedBy);$S({type:`worker.response`,id:e.id,ok:!0,result:t});return}}}catch(t){$S({type:`worker.response`,id:e.id,ok:!1,error:String(t)})}}await new Promise(()=>{})}function QS(e){return{protocol:e.protocol,listenPort:e.listenPort,machineName:e.machineName,gatewayIdentity:e.gatewayIdentity,startupPairingCode:e.startupPairingCode}}function $S(e){process.send&&process.send(e)}function eC(e){if(!tC(e)||typeof e.type!=`string`)return null;switch(e.type){case`supervisor.shutdown`:return e.reason!==`signal`&&e.reason!==`update`?null:{type:`supervisor.shutdown`,reason:e.reason};case`supervisor.request`:return typeof e.id!=`string`||e.method!==`gateway.update.apply`||e.requestedBy!==`console`&&e.requestedBy!==`mobile`&&e.requestedBy!==`system`?null:{type:`supervisor.request`,id:e.id,method:`gateway.update.apply`,requestedBy:e.requestedBy};default:return null}}function tC(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}nC(process.argv.slice(2)).catch(e=>{console.error(String(e)),process.exit(1)});async function nC(e){let t=P(e);switch(t.command){case`help`:sC();return;case`version`:console.log(te.version);return;case`init`:await iC(t);return;case`doctor`:await aC(t);return;case`start`:await rC(t);return;case`__worker`:await oC(t);return;default:{let e=t.command;throw Error(`Unsupported command: ${e}`)}}}async function rC(e){let t=await Zs({configPath:e.configPath,ensureConfigFile:!0});tc(t.config);let n=await yc({configPath:t.configPath,configExists:t.configExists,config:t.config});try{await zl({args:e,loaded:t,doctorReport:n})}catch(e){throw Error(Jl(e,t.config))}bc(n)&&console.warn(`[doctor] startup continued despite bundled runtime check failures.`)}async function iC(e){let t=await Xs({configPath:e.configPath,overwrite:e.force});t.created?console.log(`[gateway] wrote config to ${t.configPath}`):(console.log(`[gateway] config already exists at ${t.configPath}`),console.log(`[gateway] rerun with --force to overwrite`));let n=await Zs({configPath:t.configPath,ensureConfigFile:!1}),r=await yc({configPath:n.configPath,configExists:n.configExists,config:n.config});console.log(xc(r))}async function aC(e){let t=await Zs({configPath:Ys(e.configPath),ensureConfigFile:!1,syncGatewayIdentityConfig:!1}),n=await yc({configPath:t.configPath,configExists:t.configExists,config:t.configExists?t.config:void 0});console.log(xc(n)),bc(n)&&(process.exitCode=1)}async function oC(e){try{await ZS(e)}catch(t){let n=await Zs({configPath:e.configPath,ensureConfigFile:!0});throw Error(Jl(t,n.config))}}function sC(){console.log(`${te.cliName} ${te.version}`),console.log(``),console.log(`Usage:`),console.log(` ${te.cliName} [start] [--config <path>] [--log]`),console.log(` ${te.cliName} init [--config <path>] [--force]`),console.log(` ${te.cliName} doctor [--config <path>]`),console.log(` ${te.cliName} --version`)}exports.runCli=nC;
|
|
476
|
+
`);if(e<0)break;let t=this.stdoutBuffer.slice(0,e).trim();if(this.stdoutBuffer=this.stdoutBuffer.slice(e+1),t)for(let e of this.messageListeners)e(t)}}fail(e){if(!this.closed){this.closed=!0;for(let t of this.failureListeners)t(e)}}};async function fy(e){let t=[],n=null;do{let r=await py({cwd:e,archived:!1,cursor:n,limit:100});t.push(...r.threads),n=r.nextCursor}while(n);return t}async function py(e){return cy(async t=>{let n=await t.sendRequest(`thread/list`,e);return{threads:n.data.map(e=>gy(e)),nextCursor:n.nextCursor}})}async function my(e,t=!0){return cy(async n=>gy((await n.sendRequest(`thread/read`,{threadId:e,includeTurns:t})).thread))}async function hy(){let e=[],t=null;do{let n=await cy(async e=>e.sendRequest(`model/list`,{cursor:t,limit:100}));e.push(...n.data.map(e=>_y(e))),t=n.nextCursor}while(t);return e}function gy(e){let t=Q(fv(e).model)?.trim()||void 0;return{id:e.id,name:e.name??void 0,preview:e.preview,model:t,modelProvider:e.modelProvider,createdAt:e.createdAt,updatedAt:e.updatedAt,path:e.path,cwd:e.cwd,cliVersion:e.cliVersion,source:yy(e.source),gitInfo:e.gitInfo?fv(uv(e.gitInfo)):null,turns:e.turns.map(e=>vy(e))}}function _y(e){return{id:e.id,model:e.model,displayName:e.displayName,description:e.description,isDefault:e.isDefault,defaultReasoningEffort:e.defaultReasoningEffort??void 0,supportedReasoningEfforts:(e.supportedReasoningEfforts??[]).map(e=>e.reasoningEffort)}}function vy(e){return{id:e.id,status:e.status,error:e.error?fv(uv(e.error)):null,items:e.items.map(e=>cv(e))}}function yy(e){if(typeof e==`string`)return e;if(typeof e==`object`&&e){let[t,n]=Object.entries(e)[0]??[];return t?typeof n==`string`&&n?`${t}:${n}`:t:`unknown`}return`unknown`}var by=class{constructor(e,t,n,r,i){this.createQuery=n,this.id=e,this.model=t,this.activeModel=t,this.activeSessionConfig={},this.resumeSessionId=r,this.cwd=i?.cwd}id;provider=`claude`;providerMode=`native`;model;listeners=new Set;cwd;closed=!1;turnInProgress=!1;turnSequence=0;activeTurnId=null;activeAssistantItemId=null;assistantStarted=!1;assistantCompleted=!1;activeToolItemId=null;toolStarted=!1;activeQuery=null;activeAbortController=null;resumeSessionId;threadStartedEmitted=!1;activeModel;activeSessionConfig;interruptRequested=!1;pendingToolPermissionRequests=new Map;pendingUserInputRequests=new Map;pendingClaudeToolUses=new Map;activeTurnStarted=!1;closePromise=null;onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getNativeSessionId(){return this.resumeSessionId}async sendInput(e,t){if(this.ensureOpen(),this.turnInProgress)throw Error(`A turn is already in progress`);this.turnInProgress=!0,this.turnSequence+=1,this.activeTurnId=`claude_turn_${this.turnSequence}`,this.activeAssistantItemId=null,this.assistantStarted=!1,this.assistantCompleted=!1,this.activeToolItemId=null,this.toolStarted=!1,this.pendingClaudeToolUses.clear(),this.interruptRequested=!1,this.activeTurnStarted=!1,this.activeModel=t?.model??this.activeModel,this.activeSessionConfig=vv(this.activeSessionConfig,t?.sessionConfig),t?.mode===`plan`&&(this.activeSessionConfig.permissionMode=`plan`);let n=new AbortController,r=this.createQuery({prompt:e,model:this.activeModel,sessionConfig:this.activeSessionConfig,resume:this.resumeSessionId,abortController:n,canUseTool:this.handleCanUseTool});this.activeAbortController=n,this.activeQuery=r,this.emitSyntheticUserInputEvents(e),this.startQueryLoop(r)}async interrupt(){if(!this.turnInProgress||this.closed)return;this.interruptRequested=!0,this.activeAbortController&&this.activeAbortController.abort();let e=this.activeQuery;if(e){if(typeof e.interrupt==`function`)try{await e.interrupt()}catch{}typeof e.close==`function`&&e.close()}}async close(){if(this.closePromise)return this.closePromise;this.closePromise=this.closeInternal(),await this.closePromise}async respondToolPermission(e,t,n){let r=this.pendingToolPermissionRequests.get(e);if(!r)throw Error(`Unknown tool approval request: ${e}`);this.pendingToolPermissionRequests.delete(e),t===`allow`?r.resolve({behavior:`allow`,updatedInput:r.input}):r.resolve({behavior:`deny`,message:n?.trim()||`Permission denied`}),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n,toolName:r.toolName,itemId:r.toolUseID,turn_id:this.activeTurnId,source_event_type:`can_use_tool`})}async respondUserInput(e,t){let n=this.pendingUserInputRequests.get(e);if(!n)throw Error(`Unknown user input request: ${e}`);this.pendingUserInputRequests.delete(e);let r=Ty(t),i={...n.input,answers:r};n.resolve({behavior:`allow`,updatedInput:i}),this.emit({type:`user.input.resolved`,requestId:e,status:`submitted`,answeredCount:yv(r),questions:Cy(n.input),answers:r,source_event_type:`can_use_tool`})}startQueryLoop(e){(async()=>{try{for await(let t of e){if(this.closed||this.activeQuery!==e)return;let n=Wy(t);this.captureResumeSessionId(t),this.emit({type:`native.raw`,source:`claude.query`,native_type:Gy(n.type),message:t});let r=this.mapClaudeMessage(t);for(let e of r)this.emit(e)}}catch(t){if(this.closed||this.activeQuery!==e)return;let n=t instanceof Error?t.message:String(t);this.interruptRequested||this.emit({type:`error`,message:n})}finally{if(this.closed||this.activeQuery!==e)return;this.turnInProgress=!1,this.interruptRequested=!1,this.activeQuery=null,this.activeAbortController=null,this.expirePendingToolPermissionRequests(`Turn finished`),this.expirePendingUserInputRequests(`Turn finished`),this.clearTurnState()}})()}async closeInternal(){if(this.closed)return;this.closed=!0,this.interruptRequested=!0,this.activeAbortController&&=(this.activeAbortController.abort(),null);let e=this.activeQuery;if(this.activeQuery=null,typeof e?.interrupt==`function`)try{await e.interrupt()}catch{}typeof e?.close==`function`&&e.close(),this.turnInProgress=!1,this.clearTurnState(),this.expirePendingToolPermissionRequests(`Session closed`),this.expirePendingUserInputRequests(`Session closed`)}handleCanUseTool=async(e,t,n)=>Sy(e,t)?this.requestUserInput(e,t,n):xy(n)?this.requestToolPermission(e,t,n):{behavior:`allow`};requestToolPermission(e,t,n){let r=`req_${og(8)}`;return this.emit({type:`tool.permission.requested`,requestId:r,toolName:e,reason:n.decisionReason,blockedPath:n.blockedPath,suggestions:n.suggestions,agentId:n.agentID,itemId:n.toolUseID,turn_id:this.activeTurnId,source_event_type:`can_use_tool`}),new Promise((i,a)=>{if(n.signal.aborted){i({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:r,decision:`deny`,reason:`Operation aborted`,toolName:e,itemId:n.toolUseID,source_event_type:`abort`});return}let o=()=>{n.signal.removeEventListener(`abort`,o);let e=this.pendingToolPermissionRequests.get(r);e&&(this.pendingToolPermissionRequests.delete(r),i({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:r,decision:`deny`,reason:`Operation aborted`,toolName:e.toolName,itemId:e.toolUseID,source_event_type:`abort`}))};n.signal.addEventListener(`abort`,o,{once:!0}),this.pendingToolPermissionRequests.set(r,{toolName:e,toolUseID:n.toolUseID,input:t,resolve:e=>{n.signal.removeEventListener(`abort`,o),i(e)},reject:e=>{n.signal.removeEventListener(`abort`,o),a(e)}})})}requestUserInput(e,t,n){let r=Cy(t),i=`req_${og(8)}`;return this.emit({type:`user.input.requested`,requestId:i,tool_name:e,turn_id:this.activeTurnId,questions:r,source_event_type:`can_use_tool`}),new Promise((e,r)=>{if(n.signal.aborted){e({behavior:`deny`,message:`Operation aborted`,interrupt:!0});return}let a=()=>{n.signal.removeEventListener(`abort`,a),this.pendingUserInputRequests.has(i)&&(this.pendingUserInputRequests.delete(i),e({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emit({type:`user.input.resolved`,requestId:i,status:`expired`,answeredCount:0,source_event_type:`abort`}))};n.signal.addEventListener(`abort`,a,{once:!0}),this.pendingUserInputRequests.set(i,{input:t,resolve:t=>{n.signal.removeEventListener(`abort`,a),e(t)},reject:e=>{n.signal.removeEventListener(`abort`,a),r(e)}})})}expirePendingToolPermissionRequests(e){for(let[t,n]of this.pendingToolPermissionRequests.entries())n.resolve({behavior:`deny`,message:e,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:t,decision:`deny`,reason:e,toolName:n.toolName,itemId:n.toolUseID,source_event_type:`session_end`});this.pendingToolPermissionRequests.clear()}expirePendingUserInputRequests(e){for(let[t,n]of this.pendingUserInputRequests.entries())n.resolve({behavior:`deny`,message:e,interrupt:!0}),this.emit({type:`user.input.resolved`,requestId:t,status:`expired`,answeredCount:0,source_event_type:`session_end`});this.pendingUserInputRequests.clear()}emit(e){for(let t of this.listeners)t(e)}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}clearTurnState(){this.activeTurnId=null,this.activeAssistantItemId=null,this.assistantStarted=!1,this.assistantCompleted=!1,this.activeToolItemId=null,this.toolStarted=!1,this.activeTurnStarted=!1}captureResumeSessionId(e){let t=Wy(e),n=Gy(t.session_id)??Gy(t.sessionId);n&&(this.resumeSessionId=n)}emitSyntheticUserInputEvents(e){if(!e.trim())return;let t=new Date().toISOString(),n=this.resumeSessionId??this.id,r=`claude_user_${og(10)}`,i={parentUuid:null,isSidechain:!1,userType:`external`,cwd:this.cwd,sessionId:n,session_id:n,version:`synthetic`,type:`user`,message:{role:`user`,content:[{type:`text`,text:e}]},uuid:r,timestamp:t,permissionMode:this.activeSessionConfig.permissionMode??`default`,source_event_type:`claude.synthetic.user_input`};this.emit({type:`native.raw`,source:`claude.synthetic.user_input`,native_type:`user`,message:i});let a=this.mapClaudeMessage(i);for(let e of a)this.emit(e)}ensureAssistantItemId(e){let t=Yy(e);if(t)return this.activeAssistantItemId=t,t;if(this.activeAssistantItemId)return this.activeAssistantItemId;let n=this.activeTurnId?`claude_assistant_${this.activeTurnId}`:`claude_assistant_${Date.now()}`;return this.activeAssistantItemId=n,n}ensureToolItemId(e){let t=Gy(e.tool_id)??Gy(e.tool_use_id)??qy(e.preceding_tool_use_ids);if(t)return this.activeToolItemId=t,t;let n=Gy(e.uuid);if(n)return this.activeToolItemId=n,n;let r=Xy(Gy(e.tool_name)??`tool`),i=this.activeTurnId?`claude_tool_${this.activeTurnId}_${r}`:`claude_tool_${r}_${Date.now()}`;return this.activeToolItemId=i,i}buildAssistantCompletionTailEvent(){if(!this.assistantStarted||this.assistantCompleted)return[];let e=this.activeAssistantItemId;return e?(this.assistantCompleted=!0,[{type:`item.completed`,item:{id:e,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`stream_end`}}]):[]}mapClaudeMessage(e){let t=Wy(e),n=Gy(t.type);if(n===`user`){let e=this.mapStructuredClaudeToolResult(t);if(e.length>0)return e;if(!zy(t))return[];let n=By(Wy(t.message));return n?[{type:`item.completed`,item:{id:Gy(t.uuid)??`claude_user_${Date.now()}`,type:`user_message`,text:n,turn_id:this.activeTurnId,source_event_type:Gy(t.source_event_type)??`user`}}]:[]}if(n===`assistant`){let e=this.mapStructuredClaudeToolUse(t);if(e.length>0)return e;let n=this.activeAssistantItemId,r=this.ensureAssistantItemId(t);n&&n!==r&&(this.assistantStarted=!1,this.assistantCompleted=!1);let i=Ry(t),a=[...this.maybeEmitTurnStarted(`assistant`)];return this.assistantStarted||=(a.push({type:`item.started`,item:{id:r,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`assistant`}}),!0),a.push({type:`item.completed`,item:{id:r,type:`agent_message`,text:i,turn_id:this.activeTurnId,source_event_type:`assistant`}}),this.assistantCompleted=!0,a}if(n===`stream_event`){let e=Wy(t.event);if(Gy(e.type)===`message_start`){let t=Yy(e);return t&&(this.activeAssistantItemId=t,this.assistantStarted=!1,this.assistantCompleted=!1),[]}let n=Vy(t);if(!n)return[];let r=this.activeAssistantItemId,i=this.ensureAssistantItemId(t);r&&r!==i&&(this.assistantStarted=!1,this.assistantCompleted=!1);let a=[];return a.push(...this.maybeEmitTurnStarted(`stream_event`)),this.assistantStarted||=(a.push({type:`item.started`,item:{id:i,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`stream_event`}}),!0),a.push({type:`item.updated`,item:{id:i,type:`agent_message`,text:n,turn_id:this.activeTurnId,source_event_type:`stream_event`}}),a}if(n===`result`){let e=this.maybeEmitTurnStarted(`result`);if(t.is_error===!0||Gy(t.subtype)?.startsWith(`error_`)===!0){let n=Hy(t);return[...e,{type:`turn.failed`,error:{message:n},usage:Uy(t.usage),turn_id:this.activeTurnId,source_event_type:`result`}]}return[...e,...this.buildAssistantCompletionTailEvent(),{type:`turn.completed`,usage:Uy(t.usage),turn_id:this.activeTurnId,source_event_type:`result`}]}if(n===`tool_use_summary`){let e=this.activeToolItemId,n=this.ensureToolItemId(t);e&&e!==n&&(this.toolStarted=!1);let r=Gy(t.summary)??`tool summary`,i=Gy(t.tool_name)??`tool`,a=[];return a.push(...this.maybeEmitTurnStarted(`tool_use_summary`)),this.toolStarted||=(a.push({type:`item.started`,item:{id:n,type:`tool_status`,tool_name:i,turn_id:this.activeTurnId,source_event_type:`tool_use_summary`}}),!0),a.push({type:`item.updated`,item:{id:n,type:`tool_status`,text:r,status:`running`,tool_name:i,turn_id:this.activeTurnId,source_event_type:`tool_use_summary`}}),a.push({type:`item.completed`,item:{id:n,type:`tool_status`,text:r,status:`completed`,tool_name:i,turn_id:this.activeTurnId,source_event_type:`tool_use_summary`}}),this.activeToolItemId=null,this.toolStarted=!1,a}if(n===`tool_progress`){let e=this.activeToolItemId,n=this.ensureToolItemId(t);e&&e!==n&&(this.toolStarted=!1);let r=Gy(t.tool_name)??`tool`,i=Gy(t.message)??`${r} running`,a=[];return a.push(...this.maybeEmitTurnStarted(`tool_progress`)),this.toolStarted||=(a.push({type:`item.started`,item:{id:n,type:`tool_status`,tool_name:r,status:`running`,turn_id:this.activeTurnId,source_event_type:`tool_progress`}}),!0),a.push({type:`item.updated`,item:{id:n,type:`tool_status`,text:i,status:`running`,tool_name:r,turn_id:this.activeTurnId,source_event_type:`tool_progress`}}),a}if(n===`system`){let e=Gy(t.subtype);if(e===`init`){let e=this.maybeCreateThreadStartedEvent(Gy(t.session_id)??Gy(t.sessionId),`claude.system.init`);return e?[e]:[]}return e===`status`?[{type:`status.progress`,message:Gy(t.status)??`status update`}]:[{type:`status.progress`,message:e?`system.${e}`:`system event`}]}if(n===`auth_status`){let e=Gy(t.error);return e?[{type:`error`,message:e}]:[{type:`status.progress`,message:`auth status update`}]}return[]}mapStructuredClaudeToolUse(e){let t=Ey(e);if(t.length===0)return[];let n=[];n.push(...this.maybeEmitTurnStarted(`assistant.tool_use`));for(let e of t)this.pendingClaudeToolUses.set(e.id,e),n.push({type:`item.started`,item:{id:e.id,type:`tool_status`,turn_id:this.activeTurnId,tool_name:e.toolName,title:e.title,text:e.title,status:`running`,status_label:e.pendingStatusLabel,display_as:`tool_card`,response_label:e.responseLabel,prompt:e.prompt,subagent_type:e.subagentType,description:e.description,file_path:e.filePath,source_event_type:`assistant.tool_use`}});return n}mapStructuredClaudeToolResult(e){let t=Dy(e);if(!t)return[];let n=this.pendingClaudeToolUses.get(t.toolUseId);if(!n)return[];this.pendingClaudeToolUses.delete(t.toolUseId);let r=Oy({toolUse:n,toolUseId:t.toolUseId,raw:e,turnId:this.activeTurnId});return r?[...this.maybeEmitTurnStarted(`user.tool_use_result`),{type:`item.completed`,item:r}]:[]}maybeCreateThreadStartedEvent(e,t){return this.threadStartedEmitted?null:(this.threadStartedEmitted=!0,{type:`thread.started`,thread_id:e??this.resumeSessionId??this.id,source:t})}maybeEmitTurnStarted(e){return this.activeTurnStarted||!this.activeTurnId?[]:(this.activeTurnStarted=!0,[{type:`turn.started`,turn_id:this.activeTurnId,source_event_type:e}])}};function xy(e){return typeof e.decisionReason==`string`&&e.decisionReason.trim().length>0||typeof e.blockedPath==`string`&&e.blockedPath.trim().length>0?!0:Array.isArray(e.suggestions)&&e.suggestions.length>0}function Sy(e,t){let n=e.toLowerCase();return n.includes(`askuserquestion`)||n.includes(`request_user_input`)?!0:Array.isArray(t.questions)}function Cy(e){return(Array.isArray(e.questions)?e.questions:[{id:`question_1`,header:`Question`,question:typeof e.question==`string`?e.question:`Please provide input`,multiSelect:!1,isOther:e.isOther===!0,isSecret:e.isSecret===!0,options:e.options}]).map((e,t)=>{if(typeof e!=`object`||!e)return null;let n=e,r=typeof n.id==`string`&&n.id?n.id:`question_${t+1}`,i=typeof n.header==`string`&&n.header?n.header:`Question`,a=typeof n.question==`string`&&n.question?n.question:`Please provide input`,o=wy(n.options);return{id:r,header:i,question:a,multiSelect:n.multiSelect===!0,isOther:n.isOther===!0,isSecret:n.isSecret===!0,options:o}}).filter(e=>e!==null)}function wy(e){if(!Array.isArray(e))return null;let t=e.map(e=>{if(typeof e==`string`)return{label:e,description:e};if(typeof e!=`object`||!e)return null;let t=e,n=typeof t.label==`string`?t.label:``,r=typeof t.description==`string`?t.description:n,i=typeof t.markdown==`string`&&t.markdown.length>0?t.markdown:void 0;return n?{label:n,description:r,markdown:i}:null}).filter(e=>e!==null);return t.length>0?t:null}function Ty(e){let t={};for(let[n,r]of Object.entries(e??{}))t[n]=Array.isArray(r)?r.map(e=>String(e)):[];return t}function Ey(e){let t=Wy(e.message),n=Array.isArray(t.content)?t.content:[],r=[];for(let e of n){let t=Wy(e);if(t.type!==`tool_use`)continue;let n=Gy(t.id),i=Gy(t.name),a=Wy(t.input);if(!(!n||!i)){if(i===`Task`){let e=Gy(a.subagent_type),t=Gy(a.description)??e??`任务`;r.push({id:n,toolName:`Task`,title:`${e??`Task`}(${t})`,pendingStatusLabel:`运行中`,prompt:Gy(a.prompt),responseLabel:`Response`,subagentType:e,description:t});continue}if(i===`Read`){let e=Gy(a.file_path);r.push({id:n,toolName:`Read`,title:`Read 1 file`,pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:e});continue}if(i===`Write`){let e=Gy(a.file_path);r.push({id:n,toolName:`Write`,title:Ny(e),pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:e})}}}return r}function Dy(e){let t=Wy(e.message),n=Array.isArray(t.content)?t.content:[];for(let e of n){let t=Wy(e);if(t.type!==`tool_result`)continue;let n=Gy(t.tool_use_id);if(n)return{toolUseId:n}}return null}function Oy(e){let t=Wy(e.raw.tool_use_result),n=ky(t.content)??By(Wy(e.raw.message)),r=Wy(t.usage),i=Jy(t.totalTokens)??Jy(r.total_tokens)??Jy(r.output_tokens),a=Jy(t.totalToolUseCount),o=Jy(t.totalDurationMs),s=Gy(t.agentId),c=Gy(t.filePath)??e.toolUse.filePath;if(e.toolUse.toolName===`Task`){let t=jy(a,i,o);return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:t,status:`completed`,status_label:t,display_as:`tool_card`,prompt:e.toolUse.prompt,response:n,response_label:e.toolUse.responseLabel,subagent_type:e.toolUse.subagentType,description:e.toolUse.description,agent_id:s,total_tokens:i,total_tool_uses:a,duration_ms:o,source_event_type:`user.tool_use_result`}}if(e.toolUse.toolName===`Read`){let r=Ay(t)??n;return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:`Done`,status:`completed`,status_label:`Done`,display_as:`tool_card`,response:r,response_label:e.toolUse.responseLabel,file_path:c,total_tokens:i,duration_ms:o,source_event_type:`user.tool_use_result`}}if(e.toolUse.toolName===`Write`){let n=Ky(t.content),r=My(Fy(n),c);return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:r,status:`completed`,status_label:r,display_as:`tool_card`,response:n,response_label:e.toolUse.responseLabel,file_path:c,total_tokens:i,duration_ms:o,source_event_type:`user.tool_use_result`}}return null}function ky(e){if(typeof e==`string`&&e.length>0)return e;if(!Array.isArray(e))return;let t=[];for(let n of e){let e=Wy(n);e.type===`text`&&typeof e.text==`string`&&e.text.length>0&&t.push(e.text)}return t.length>0?t.join(`
|
|
477
|
+
`):void 0}function Ay(e){return Ky(Wy(e.file).content)||ky(e.content)}function jy(e,t,n){let r=[`Done`];return typeof e==`number`&&r.push(`${e} tool uses`),typeof t==`number`&&r.push(`${Iy(t)} tokens`),typeof n==`number`&&r.push(Ly(n)),r.join(` · `)}function My(e,t){let n=typeof e==`number`?`Wrote ${e} lines`:`Wrote file`;return t?`${n} to ${t}`:n}function Ny(e){return typeof e==`string`&&e.includes(`/.claude/plans/`)?`Updated plan`:typeof e==`string`?`Write(${Py(e)})`:`Write`}function Py(e){let t=e.split(`/`);return t[t.length-1]||e}function Fy(e){if(e)return e.split(`
|
|
478
|
+
`).length}function Iy(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`}function Ly(e){let t=Math.max(1,Math.round(e/1e3));if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return r===0?`${n}m`:`${n}m ${r}s`}function Ry(e){return By(Wy(e.message))||(Ky(e.result)??``)}function zy(e){if(typeof e.parent_tool_use_id==`string`&&e.parent_tool_use_id.length>0||e.isSidechain===!0)return!1;let t=Wy(e.message);return!(Array.isArray(t.content)?t.content:[]).some(e=>Wy(e).type===`tool_result`)}function By(e){let t=Ky(e.content);if(t)return t;let n=Ky(e.text)??Ky(e.prompt);if(n)return n;let r=Array.isArray(e.content)?e.content:[],i=[];for(let e of r){let t=Wy(e);t.type===`text`&&typeof t.text==`string`&&t.text.length>0&&i.push(t.text)}if(i.length>0)return i.join(`
|
|
479
|
+
`)}function Vy(e){let t=Wy(Wy(e.event).delta);if(typeof t.text==`string`&&t.text.length>0)return t.text}function Hy(e){let t=Array.isArray(e.errors)?e.errors.filter(e=>typeof e==`string`):[];return t.length>0?t.join(`; `):Gy(e.subtype)||`Claude turn failed`}function Uy(e){let t=Wy(e);return{input_tokens:Jy(t.input_tokens)??Jy(t.inputTokens)??0,cached_input_tokens:Jy(t.cached_input_tokens)??Jy(t.cache_read_input_tokens)??Jy(t.cacheReadInputTokens)??0,output_tokens:Jy(t.output_tokens)??Jy(t.outputTokens)??0}}function Wy(e){return typeof e==`object`&&e?e:{}}function Gy(e){if(typeof e==`string`&&e.trim())return e}function Ky(e){if(typeof e==`string`&&e.length>0)return e}function qy(e){if(Array.isArray(e)){for(let t of e)if(typeof t==`string`&&t.trim())return t}}function Jy(e){if(typeof e==`number`&&Number.isFinite(e))return e}function Yy(e){let t=Gy(Wy(e.message).id);if(t)return t;let n=Gy(Wy(Wy(e.event).message).id);if(n)return n}function Xy(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`_`);return t?t.replace(/^_+|_+$/g,``):`tool`}var Zy=class{constructor(e,t,n,r){this.nativeSession=r,this.provider=e,this.id=t,this.model=n,this.bindNativeEvents(r)}id;provider;providerMode=`native`;model;listeners=new Set;unsubscribe;onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async sendInput(e,t){if(typeof this.nativeSession?.sendInput==`function`){await this.nativeSession.sendInput(e);return}if(typeof this.nativeSession?.input==`function`){await this.nativeSession.input(e);return}if(typeof this.nativeSession?.turn==`function`){await this.nativeSession.turn({input:e});return}throw Error(`Native session does not expose a known input method`)}async interrupt(){if(typeof this.nativeSession?.interrupt==`function`){await this.nativeSession.interrupt();return}if(typeof this.nativeSession?.cancel==`function`){await this.nativeSession.cancel();return}throw Error(`Native session does not expose interrupt/cancel`)}async close(){if(typeof this.unsubscribe==`function`&&(this.unsubscribe(),this.unsubscribe=void 0),typeof this.nativeSession?.close==`function`){await this.nativeSession.close();return}if(typeof this.nativeSession?.dispose==`function`){await this.nativeSession.dispose();return}}async respondToolPermission(e,t,n){if(typeof this.nativeSession?.respondToolPermission==`function`){await this.nativeSession.respondToolPermission({requestId:e,decision:t,reason:n});return}if(typeof this.nativeSession?.approveToolCall==`function`){await this.nativeSession.approveToolCall({requestId:e,approved:t===`allow`,reason:n});return}throw Error(`Native session does not expose tool approval response method`)}bindNativeEvents(e){let t=e=>{let t=Qy(e);for(let e of this.listeners)e(t)};if(typeof e?.subscribe==`function`){let n=e.subscribe(e=>t(e));typeof n==`function`&&(this.unsubscribe=n);return}if(typeof e?.on==`function`){let n=e=>t(e);e.on(`event`,n),this.unsubscribe=()=>{typeof e?.off==`function`&&e.off(`event`,n)};return}throw Error(`Native session does not expose a known event subscription API`)}};function Qy(e){return typeof e==`object`&&e&&`type`in e?e:{type:`status.progress`,nativeEvent:e}}var $y=`@anthropic-ai/claude-agent-sdk`,eb=`claude-sonnet-4-6`,tb=1e4,nb=class{constructor(e,t){this.preferNative=e,this.requireNative=t}provider=`claude`;async isNativeAvailable(){try{return await import($y),!0}catch{return!1}}async createSession(e){if(!this.preferNative)throw Error(`Claude native provider is disabled. Set ENABLE_NATIVE_PROVIDERS=true to use Claude sessions.`);try{let t=await import($y),n=await rb(ib(t,e),tb,`Claude native query session creation timed out`);if(n)return n;let r=await rb(ab(t,e),tb,`Claude legacy native session creation timed out`);if(r)return r;throw this.requireNative,Error(`Claude SDK loaded but no supported stable session API was found`)}catch(e){throw Error(`Claude native session creation failed: ${String(e)}`)}}};async function rb(e,t,n){if(!Number.isFinite(t)||t<=0)return e;let r,i=new Promise((e,i)=>{r=setTimeout(()=>{i(Error(n))},t)});try{return await Promise.race([e,i])}finally{r&&clearTimeout(r)}}async function ib(e,t){let n=ob(e);if(!n)return null;let r=t.model??eb;return new by(t.sessionId,r,({prompt:e,model:i,sessionConfig:a,resume:o,abortController:s,canUseTool:c})=>{let l=a?.permissionMode??t.sessionConfig?.permissionMode??`default`,u={model:i??r,includePartialMessages:!0,abortController:s,canUseTool:c,permissionMode:l},d=sb(a?.reasoningEffort??t.sessionConfig?.reasoningEffort);return d&&(u.effort=d),l===`bypassPermissions`&&(u.allowDangerouslySkipPermissions=!0),t.cwd&&(u.cwd=t.cwd),o&&(u.resume=o,u.forkSession=!1),n({prompt:e,options:u})},t.resumeSessionId,{cwd:t.cwd})}async function ab(e,t){if(typeof e?.createSession==`function`){let n=await e.createSession({model:t.model,cwd:t.cwd,metadata:t.metadata,sessionId:t.sessionId});return new Zy(`claude`,t.sessionId,t.model,n)}if(typeof e?.ClaudeAgentClient==`function`){let n=new e.ClaudeAgentClient;if(typeof n?.createSession==`function`){let e=await n.createSession({model:t.model,cwd:t.cwd,metadata:t.metadata,sessionId:t.sessionId});return new Zy(`claude`,t.sessionId,t.model,e)}}if(typeof e?.default?.createSession==`function`){let n=await e.default.createSession({model:t.model,cwd:t.cwd,metadata:t.metadata,sessionId:t.sessionId});return new Zy(`claude`,t.sessionId,t.model,n)}return null}function ob(e){if(typeof e?.query==`function`)return e.query;if(typeof e?.default?.query==`function`)return e.default.query}function sb(e){if(e){if(e===`max`)return`max`;if(e===`high`||e===`medium`||e===`low`)return e;if(e===`xhigh`)return`max`;if(e===`minimal`||e===`none`)return`low`}}function cb(e,t={}){let n=t.preferNative??!1,r=t.requireNative??!1;return e===`codex`?new iy(n,r):new nb(n,r)}const lb=p.default.join(`.claude`,`projects`),ub=/\u001B\[[0-?]*[ -/]*[@-~]/g;async function db(e){return(await(0,w.listSessions)(typeof e==`number`?{limit:e}:void 0)).map(e=>vb(e)).filter(e=>typeof e.cwd==`string`).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}async function fb(e,t){let n=gb(e,t?.homeDir),r=p.default.resolve(e),i=[];try{i=await d.default.readdir(n,{withFileTypes:!0})}catch(e){if(e.code!==`ENOENT`)throw e}let a=[];for(let e of i){if(!e.isFile()||!e.name.endsWith(`.jsonl`))continue;let t=p.default.join(n,e.name),r=e.name.slice(0,-6),i=await Tb(t);if(!Sb(i))continue;let o=await d.default.stat(t),s=xb(i,{createdAtFallbackMs:o.birthtimeMs,updatedAtFallbackMs:o.mtimeMs});a.push({nativeSessionId:r,model:s.model,title:s.title,createdAt:s.createdAt,updatedAt:s.updatedAt})}let o;try{o=new Map((await(0,w.listSessions)({dir:e})).map(e=>vb(e)).filter(e=>typeof e.cwd==`string`?p.default.resolve(e.cwd)===r:!1).map(e=>[e.nativeSessionId,e]))}catch{}if(o)for(let e=0;e<a.length;e+=1){let t=a[e];if(!t)continue;let n=o.get(t.nativeSessionId);n&&(a[e]={...t,title:n.title??t.title,updatedAt:n.updatedAt})}return a.sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}async function pb(e){let t=await Eb(e.nativeSessionId,e.projectPath),n=await Db(e.projectPath,e.nativeSessionId,e.homeDir);return yb({rows:t,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,nativeSessionId:e.nativeSessionId,createdAtFallbackMs:n.birthtimeMs,updatedAtFallbackMs:n.mtimeMs})}async function mb(e){let t=await Eb(e.nativeSessionId,e.projectPath),n=await Db(e.projectPath,e.nativeSessionId,e.homeDir);return bb({rows:t,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,nativeSessionId:e.nativeSessionId,createdAtFallbackMs:n.birthtimeMs,updatedAtFallbackMs:n.mtimeMs})}function hb(e,t,n){return p.default.join(gb(e,n),`${t}.jsonl`)}function gb(e,t){let n=t??f.default.homedir();return p.default.join(n,lb,_b(e))}function _b(e){let t=p.default.resolve(e).replace(/\\/g,`/`).replace(/:/g,`-`).replace(/\//g,`-`);return t.startsWith(`-`)?t:`-${t}`}function vb(e){let t=Ib(e.customTitle)??Ib(e.summary)??Ib(e.firstPrompt),n=wb(e.lastModified);return{nativeSessionId:e.sessionId,cwd:Cb(e.cwd),title:t,createdAt:n,updatedAt:n}}function yb(e){let t=[],n=xb(e.rows,{createdAtFallbackMs:e.createdAtFallbackMs,updatedAtFallbackMs:e.updatedAtFallbackMs}),r=Date.parse(n.createdAt),i=0,a=Number.isFinite(r)?r:0,o=0,s,c=e=>{if(e){let t=Date.parse(e);if(Number.isFinite(t))return a=Math.max(a+1,t),new Date(t).toISOString()}return a+=1,new Date(a).toISOString()},l=(n,r,a)=>{i+=1,t.push({v:`1.0`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`hist_claude_${e.sessionId}_${i.toString().padStart(6,`0`)}_${n.replace(/\./g,`_`)}`,ts:c(a),type:n,payload:{raw:r}})},u=(e,t)=>s||(o+=1,s={id:`claude_hist_turn_${o}`,terminal:!1,failed:!1},l(`turn.started`,{turn_id:s.id,source_event_type:`claude.history`,source_line:t},e),s),d=(e,t)=>{if(!s||s.terminal){s=void 0;return}s.terminal=!0,l(`turn.completed`,{turn_id:s.id,source_event_type:`claude.history`,source_line:t},e),s=void 0},f=(e,t,n)=>{let r=u(t,n);r.terminal||(r.terminal=!0,r.failed=!0,l(`turn.failed`,{turn_id:r.id,source_event_type:`claude.history`,source_line:n,error:{message:e}},t),s=void 0)};l(`thread.started`,{thread_id:e.nativeSessionId,source:`claude.history.getSessionMessages`},n.createdAt),n.title&&l(`thread.title.updated`,{title:n.title,source:`claude.history.first_user_message`,thread_id:e.nativeSessionId},n.createdAt);for(let t of e.rows){let e=t.type;if(!e||e===`queue-operation`)continue;if(e===`user`){let e=Pb(t.raw.message),n=jb(e),r=Ab(e);if(n){d(t.timestamp,t.line);let e=u(t.timestamp,t.line);l(`item.completed`,{item:{id:Fb(t.raw.uuid)??`claude_user_${t.line}`,type:`user_message`,text:n,turn_id:e.id,source_event_type:`claude.user`},source_line:t.line},t.timestamp)}for(let e=0;e<r.length;e+=1){let n=r[e],i=u(t.timestamp,t.line);l(`item.completed`,{item:{id:n.toolUseId??`claude_tool_result_${t.line}_${e+1}`,type:`tool_status`,status:n.isError?`failed`:`completed`,tool_name:n.toolName??`tool`,text:n.text,turn_id:i.id,source_event_type:`claude.tool_result`},source_line:t.line},t.timestamp)}continue}if(e!==`assistant`)continue;let n=Pb(t.raw.message),r=u(t.timestamp,t.line),i=kb(n);for(let e=0;e<i.length;e+=1){let n=i[e];l(`item.started`,{item:{id:n.id??`claude_tool_use_${t.line}_${e+1}`,type:`tool_status`,status:`running`,tool_name:n.name,text:n.summary,command:n.command,turn_id:r.id,source_event_type:`claude.tool_use`},source_line:t.line},t.timestamp)}let a=jb(n);a&&l(`item.completed`,{item:{id:Fb(n.id)??Fb(t.raw.uuid)??`claude_assistant_${t.line}`,type:`agent_message`,text:a,turn_id:r.id,source_event_type:`claude.assistant`},source_line:t.line},t.timestamp);let o=Fb(t.raw.error);o&&f(o,t.timestamp,t.line)}return d(n.updatedAt),t}function bb(e){let t=[],n=xb(e.rows,{createdAtFallbackMs:e.createdAtFallbackMs,updatedAtFallbackMs:e.updatedAtFallbackMs}),r=Date.parse(n.createdAt),i=0,a=Number.isFinite(r)?r:0,o=e=>{if(e){let t=Date.parse(e);if(Number.isFinite(t))return a=Math.max(a+1,t),new Date(t).toISOString()}return a+=1,new Date(a).toISOString()};for(let n of e.rows)i+=1,t.push({v:`1.0`,kind:`provider.raw`,rawSeq:i,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`raw_hist_claude_${e.sessionId}_${i.toString().padStart(6,`0`)}`,ts:o(n.timestamp),type:`native.raw`,payload:{raw:{source:`claude.history.getSessionMessages`,native_type:n.type??`unknown`,message:n.raw,historyReplay:!0,replaySynthetic:!1,source_line:n.line,native_session_id:e.nativeSessionId}}});return t}function xb(e,t){let n,r,i,a;for(let t of e)t.timestampMs!==void 0&&(i=i===void 0?t.timestampMs:Math.min(i,t.timestampMs),a=a===void 0?t.timestampMs:Math.max(a,t.timestampMs)),!r&&t.type===`user`&&(r=Nb(jb(Pb(t.raw.message)))),!n&&t.type===`assistant`&&(n=Fb(Pb(t.raw.message).model));let o=i??Bb(t.createdAtFallbackMs)??0,s=a??Bb(t.updatedAtFallbackMs)??o;return{model:n,title:r,createdAt:new Date(o).toISOString(),updatedAt:new Date(s).toISOString()}}function Sb(e){for(let t of e){if(t.type===`user`){let e=Pb(t.raw.message);if(jb(e)||Ab(e).length>0)return!0;continue}if(t.type!==`assistant`)continue;let e=Pb(t.raw.message);if(jb(e)||kb(e).length>0||Fb(t.raw.error))return!0}return!1}function Cb(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function wb(e){return Number.isFinite(e)?new Date(e).toISOString():new Date(0).toISOString()}async function Tb(e){let t=(await d.default.readFile(e,`utf8`)).split(`
|
|
480
|
+
`),n=[];for(let e=0;e<t.length;e+=1){let r=t[e]?.trim();if(!r)continue;let i;try{i=JSON.parse(r)}catch{continue}let a=Pb(i),o=Fb(a.timestamp),s=o?zb(o):void 0;n.push({line:e+1,raw:a,type:Fb(a.type),timestamp:o,timestampMs:s})}return n}async function Eb(e,t){let n=await(0,w.getSessionMessages)(e,{dir:t});if(n.length===0)throw Error(`Claude session ${e} returned no messages from getSessionMessages`);return n.map((e,t)=>Ob(e,t+1))}async function Db(e,t,n){let r=hb(e,t,n);try{return await d.default.stat(r)}catch{let e=Date.now();return{birthtimeMs:e,mtimeMs:e}}}function Ob(e,t){let n=Pb(e),r=Pb(n.message),i=Fb(n.timestamp)??Fb(r.timestamp)??Fb(r.created_at)??Fb(r.createdAt);return{line:t,raw:{...n,message:r},type:Fb(n.type),timestamp:i,timestampMs:i?zb(i):void 0}}function kb(e){let t=Array.isArray(e.content)?e.content:[],n=[];for(let e of t){let t=Pb(e);if(Fb(t.type)!==`tool_use`)continue;let r=Pb(t.input),i=Fb(r.command),a=Fb(t.name)??`tool`,o=Fb(r.description);n.push({id:Fb(t.id),name:a,command:i,summary:o??i??`${a} started`})}return n}function Ab(e){let t=Array.isArray(e.content)?e.content:[],n=[];for(let e of t){let t=Pb(e);if(Fb(t.type)!==`tool_result`)continue;let r=Lb(Fb(t.content)??Fb(Pb(t.toolUseResult).stdout)??Fb(Pb(t.tool_use_result).stdout)??Fb(t.text));n.push({toolUseId:Fb(t.tool_use_id)??Fb(t.toolUseId),toolName:Fb(t.tool_name)??Fb(t.toolName),text:r,isError:t.is_error===!0})}return n}function jb(e){let t=Fb(e.content);if(t)return Lb(t);let n=Fb(e.text)??Fb(e.prompt);if(n)return Lb(n);let r=Array.isArray(e.content)?e.content:[],i=[];for(let e of r){if(typeof e==`string`&&e.trim()){i.push(e);continue}let t=Pb(e),n=Fb(t.type);if(n&&n!==`text`)continue;let r=Fb(t.text)??Fb(t.content)??Mb(t);r&&i.push(r)}if(i.length!==0)return Lb(i.join(`
|
|
481
|
+
`))}function Mb(e){let t=Array.isArray(e.text_elements)?e.text_elements:Array.isArray(e.textElements)?e.textElements:[];if(t.length===0)return;let n=[];for(let e of t){let t=Pb(e),r=Fb(t.text)??Fb(t.value);r&&n.push(r)}return n.length>0?n.join(``):void 0}function Nb(e,t=60){if(!e)return;let n=Rb(e).replace(/\s+/g,` `).trim();if(!n)return;let r=Array.from(n);return r.length<=t?n:r.slice(0,t).join(``).trimEnd()}function Pb(e){return typeof e==`object`&&e?e:{}}function Fb(e){return typeof e==`string`&&e.trim()||void 0}function Ib(e){if(typeof e==`string`)return Lb(e)}function Lb(e){if(!e)return;let t=Rb(e).trim();return t.length>0?t:void 0}function Rb(e){return e.replace(ub,``)}function zb(e){let t=Date.parse(e);if(Number.isFinite(t))return t}function Bb(e){if(!(!Number.isFinite(e)||e<=0))return Math.round(e)}var Vb=class{constructor(e){this.options=e}async init(){await this.options.store.init()}async getProjects(){await this.init();let e=await this.options.store.getIndex();return e?{generatedAt:e.generatedAt,source:`cache`,providers:e.providers,projects:e.projects}:this.refreshProjects()}async refreshProjects(){await this.init();let e=new Map,[t,n]=await Promise.all([this.scanCodexSessions(e),this.scanClaudeSessions(e)]),r=new Date().toISOString(),i={codex:t.status,claude:n.status},{projects:a,projectSessions:o}=Ub(r,[t,n]);if(Wb(i)){let e=await this.options.store.getSnapshot();if(e)return await this.options.store.writeSnapshot({...e,providers:i}),{generatedAt:e.generatedAt,source:`cache`,providers:i,projects:e.projects}}return await this.options.store.writeSnapshot({generatedAt:r,providers:i,projects:a,projectSessions:o}),{generatedAt:r,source:`fresh_scan`,providers:i,projects:a}}async listProjectSessions(e){await this.init();let t=e.trim(),n=await this.options.store.getIndex(),r=!1;n||(n=Kb(await this.refreshProjects()),r=!0);let i=await Gb(n.projects,t);if(!i)throw Jg(t);let a=await this.options.store.getProject(i.key);if(!a&&!r){if(n=Kb(await this.refreshProjects()),i=await Gb(n.projects,t),!i)throw Jg(t);if(a=await this.options.store.getProject(i.key),!a)throw Error(`Discovery cache missing project sessions: ${i.path}`)}if(!a)throw Error(`Discovery cache missing project sessions: ${i.path}`);return{canonicalProjectPath:i.path,project:a.project,providers:a.providers,sessions:a.sessions}}async scanCodexSessions(e){let t=new Date().toISOString();try{let n=new Map;for(let e of[!1,!0]){let t=null;do{let r=await py({archived:e,cursor:t,limit:100});for(let e of r.threads)n.set(e.id,e);t=r.nextCursor}while(t)}let r=await Hb({sessions:[...n.values()],canonicalPathCache:e,getRawPath:e=>Yb(e.cwd),mapSession:e=>{let t=Xb(e.createdAt),n=Xb(e.updatedAt,t);return{provider:`codex`,nativeSessionId:e.id,title:Yb(e.name)??Yb(e.preview),model:Yb(e.model),createdAt:t,updatedAt:n}}});return{records:r.records,status:{scannedAt:t,sessionCount:r.records.length,status:r.skippedCount>0?`partial`:`ready`,...r.skippedCount>0?{error:`Skipped ${r.skippedCount} Codex session(s) with missing or invalid cwd`}:{}}}}catch(e){return{records:[],status:{scannedAt:t,sessionCount:0,status:`failed`,error:String(e)}}}}async scanClaudeSessions(e){let t=new Date().toISOString();try{let n=await Hb({sessions:await db(),canonicalPathCache:e,getRawPath:e=>Yb(e.cwd),mapSession:e=>({provider:`claude`,nativeSessionId:e.nativeSessionId,title:Yb(e.title),model:Yb(e.model),createdAt:Yb(e.createdAt),updatedAt:e.updatedAt})});return{records:n.records,status:{scannedAt:t,sessionCount:n.records.length,status:n.skippedCount>0?`partial`:`ready`,...n.skippedCount>0?{error:`Skipped ${n.skippedCount} Claude session(s) with missing or invalid cwd`}:{}}}}catch(e){return{records:[],status:{scannedAt:t,sessionCount:0,status:`failed`,error:String(e)}}}}};async function Hb(e){let t=[],n=0;for(let r of e.sessions){let i=e.getRawPath(r);if(!i){n+=1;continue}try{let n=await qb(i,e.canonicalPathCache);t.push({canonicalProjectPath:n,session:e.mapSession(r)})}catch{n+=1}}return{records:t,skippedCount:n}}function Ub(e,t){let n=new Map;for(let e of t)for(let t of e.records){let e=n.get(t.canonicalProjectPath);e||(e={path:t.canonicalProjectPath,key:Jb(t.canonicalProjectPath),title:p.default.basename(t.canonicalProjectPath)||t.canonicalProjectPath,providerCounts:{codex:0,claude:0},sessionsByKey:new Map},n.set(t.canonicalProjectPath,e));let r=`${t.session.provider}:${t.session.nativeSessionId}`,i=e.sessionsByKey.get(r);i||(e.providerCounts[t.session.provider]+=1);let a=Zb(i,t.session);e.sessionsByKey.set(r,a),(!e.lastSessionAt||t.session.updatedAt>e.lastSessionAt)&&(e.lastSessionAt=t.session.updatedAt)}let r=[...n.values()].map(t=>({project:{key:t.key,path:t.path,title:t.title,lastSessionAt:t.lastSessionAt,sessionCount:t.sessionsByKey.size,providerCounts:t.providerCounts,lastDiscoveryAt:e},sessions:[...t.sessionsByKey.values()].sort($b)})).sort((e,t)=>Qb(e.project,t.project));return{projects:r.map(e=>e.project),projectSessions:r}}function Wb(e){return Object.values(e).some(e=>e?.status===`failed`)}async function Gb(e,t){let n=e.find(e=>e.path===t);if(n)return n;let r=await tv(t);return e.find(e=>e.path===r)}function Kb(e){return{v:1,generatedAt:e.generatedAt,providers:e.providers,projects:e.projects}}async function qb(e,t){let n=t.get(e);return n||(n=tv(e),t.set(e,n)),n}function Jb(e){return(0,l.createHash)(`sha256`).update(e).digest(`hex`).slice(0,16)}function Yb(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Xb(e,t){return!Number.isFinite(e)||e<=0?t??new Date(0).toISOString():new Date(e*1e3).toISOString()}function Zb(e,t){return e&&e.updatedAt>=t.updatedAt?e:t}function Qb(e,t){let n=e.lastSessionAt??e.lastDiscoveryAt,r=t.lastSessionAt??t.lastDiscoveryAt;return n===r?e.path.localeCompare(t.path):r.localeCompare(n)}function $b(e,t){return e.updatedAt===t.updatedAt?`${e.provider}:${e.nativeSessionId}`.localeCompare(`${t.provider}:${t.nativeSessionId}`):t.updatedAt.localeCompare(e.updatedAt)}var ex=class{indexPath;projectsDir;ready;writeQueue=Promise.resolve();indexCache=null;projectCache=new Map;constructor(e){this.baseDir=e,this.indexPath=p.default.join(e,`discovery-index.json`),this.projectsDir=p.default.join(e,`discovery-projects`),this.ready=this.loadFromDisk()}async init(){await this.ready}async getIndex(){return await this.ready,this.indexCache?structuredClone(this.indexCache):null}async getProject(e){await this.ready;let t=this.projectCache.get(e);if(t)return structuredClone(t);let n=await tx(this.getProjectPath(e),ix);return n?(this.projectCache.set(e,n),structuredClone(n)):null}async getSnapshot(){if(await this.ready,!this.indexCache)return null;let e=[];for(let t of this.indexCache.projects){let n=await this.getProject(t.key);if(!n)return null;e.push({project:n.project,sessions:n.sessions})}return{generatedAt:this.indexCache.generatedAt,providers:structuredClone(this.indexCache.providers),projects:structuredClone(this.indexCache.projects),projectSessions:e}}async writeSnapshot(e){await this.ready;let t={v:1,generatedAt:e.generatedAt,providers:e.providers,projects:e.projects},n=e.projectSessions.map(t=>({v:1,projectKey:t.project.key,canonicalProjectPath:t.project.path,project:t.project,providers:e.providers,sessions:t.sessions}));await this.enqueueWrite(async()=>{await d.default.mkdir(this.projectsDir,{recursive:!0});let e=new Set(n.map(e=>e.projectKey)),r=[];try{r=await d.default.readdir(this.projectsDir,{withFileTypes:!0})}catch(e){if(e.code!==`ENOENT`)throw e}await Promise.all(n.map(async e=>{await nx(this.getProjectPath(e.projectKey),e)})),await Promise.all(r.map(async t=>{if(!t.isFile()||!t.name.endsWith(`.json`))return;let n=t.name.slice(0,-5);e.has(n)||(await d.default.rm(p.default.join(this.projectsDir,t.name),{force:!0}),this.projectCache.delete(n))})),await nx(this.indexPath,t),this.indexCache=t,this.projectCache.clear();for(let e of n)this.projectCache.set(e.projectKey,e)})}async loadFromDisk(){await d.default.mkdir(this.baseDir,{recursive:!0}),await d.default.mkdir(this.projectsDir,{recursive:!0}),this.indexCache=await tx(this.indexPath,rx)}getProjectPath(e){return p.default.join(this.projectsDir,`${e}.json`)}enqueueWrite(e){return this.writeQueue=this.writeQueue.then(e,e),this.writeQueue}};async function tx(e,t){try{let n=await d.default.readFile(e,`utf8`),r=JSON.parse(n);return t(r)?r:null}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function nx(e,t){let n=`${JSON.stringify(t,null,2)}\n`;try{if(await d.default.readFile(e,`utf8`)===n)return}catch(e){if(e.code!==`ENOENT`)throw e}await d.default.mkdir(p.default.dirname(e),{recursive:!0});let r=`${e}.${process.pid}.${Date.now()}.tmp`;await d.default.writeFile(r,n,`utf8`),await d.default.rename(r,e)}function rx(e){return!ax(e)||e.v!==1||typeof e.generatedAt!=`string`||!Wa.safeParse(e.providers).success||!Array.isArray(e.projects)?!1:e.projects.every(e=>Ga.safeParse(e).success)}function ix(e){return!ax(e)||e.v!==1||typeof e.projectKey!=`string`||e.projectKey.length===0||typeof e.canonicalProjectPath!=`string`||e.canonicalProjectPath.length===0||!Ga.safeParse(e.project).success||!Wa.safeParse(e.providers).success||!Array.isArray(e.sessions)?!1:e.sessions.every(e=>Ka.safeParse(e).success)}function ax(e){return typeof e==`object`&&!!e}const ox=Buffer.from([48,42,48,5,6,3,43,101,112,3,33,0]);function sx(e){let t=vo.parse(e.clientHello),n=(0,l.randomBytes)(32).toString(`base64`),{privateKey:r,publicKey:i}=(0,l.generateKeyPairSync)(`x25519`),a=is(ss(dx(i.export({format:`jwk`})))),o=Jo({gatewayId:e.gatewayId,clientHello:t,gatewayHello:{gatewayNonce:n,gatewayPublicKeyFingerprint:e.gatewayIdentity.publicKeyFingerprint,gatewayEphemeralPublicKey:a}}),s=(0,l.sign)(null,Buffer.from(o,`utf8`),(0,l.createPrivateKey)(e.privateKeyPem)).toString(`base64`);return{gatewayHello:yo.parse({version:t.version,securityLevel:t.securityLevel,cipherSuite:t.cipherSuite,gatewayId:e.gatewayId,deviceId:t.deviceId,clientNonce:t.clientNonce,gatewayNonce:n,gatewayPublicKeyFingerprint:e.gatewayIdentity.publicKeyFingerprint,gatewayEphemeralPublicKey:a,signatureAlgorithm:`ed25519`,signature:s}),gatewayEphemeralPrivateKey:r}}function cx(e){let t=vo.parse(e.clientHello),n=yo.parse(e.gatewayHello),r=bo.parse(e.clientAuth);if(t.version!==n.version||r.version!==t.version||!so.safeParse(t.cipherSuite).success||n.cipherSuite!==t.cipherSuite||t.cipherSuite!==`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`)throw Error(`unsupported_version`);if(r.gatewayId!==e.gatewayId||n.gatewayId!==e.gatewayId)throw Error(`transcript_invalid`);if(r.deviceId!==t.deviceId||n.deviceId!==t.deviceId||r.deviceIdentityFingerprint!==t.deviceIdentity.publicKeyFingerprint)throw Error(`identity_mismatch`);let i=(0,l.createPublicKey)({format:`der`,type:`spki`,key:Buffer.concat([ox,as(t.deviceIdentity.publicKey)])});if(!(0,l.verify)(null,Buffer.from(Yo({gatewayId:e.gatewayId,clientHello:t,gatewayHello:{gatewayNonce:n.gatewayNonce,gatewayPublicKeyFingerprint:n.gatewayPublicKeyFingerprint,gatewayEphemeralPublicKey:n.gatewayEphemeralPublicKey},clientAuth:{clientEphemeralPublicKey:r.clientEphemeralPublicKey}}),`utf8`),i,as(r.signature)))throw Error(`transcript_invalid`)}function lx(e){let t=yo.parse(e.gatewayHello),n=bo.parse(e.clientAuth),r=(0,l.createPublicKey)({key:{crv:`X25519`,kty:`OKP`,x:os(as(n.clientEphemeralPublicKey))},format:`jwk`}),i=(0,l.diffieHellman)({privateKey:e.gatewayEphemeralPrivateKey,publicKey:r});return Qo({role:`gateway`,keySchedule:Zo({gatewayId:e.gatewayId,clientHello:vo.parse(e.clientHello),gatewayHello:{gatewayNonce:t.gatewayNonce,gatewayPublicKeyFingerprint:t.gatewayPublicKeyFingerprint,gatewayEphemeralPublicKey:t.gatewayEphemeralPublicKey},clientAuth:{clientEphemeralPublicKey:n.clientEphemeralPublicKey},sharedSecret:new Uint8Array(i),keyEpoch:1})})}function ux(e){return wo.parse({version:1,gatewayId:e.gatewayId,deviceId:e.deviceId,code:e.code,message:e.message,retryable:e.retryable})}function dx(e){if(typeof e.x!=`string`||e.x.length===0)throw Error(`x25519 public key export missing x`);return e.x}var fx=class{OPEN=1;readyState=1;constructor(e){this.onPayload=e}send(e){let t=JSON.parse(e);this.onPayload(t)}close(){this.readyState=3}},px=class{mobileConnections=new Map;constructor(e){this.dependencies=e}async handleFrame(e){switch(e.type){case`mobile.connected`:this.addMobileConnection(e.mobileId??``,e.payload.deviceId,e.payload.deliveryMode,e.payload.gatewayAvailableAtConnect);return;case`mobile.disconnected`:this.removeMobileConnection(e.mobileId??``);return;case`secure.client_hello`:await this.handleSecureClientHello(e.mobileId,e.payload);return;case`secure.client_auth`:await this.handleSecureClientAuth(e.mobileId,e.payload);return;case`from_mobile`:await this.handleFromMobile(e);return;case`rpc.request`:await this.handleRpcRequest(e);return;case`pairing.claim.forward`:await this.handlePairingClaim(e.requestId,e.payload);return;case`auth.refresh.forward`:await this.handleRefresh(e.requestId,e.payload);return;default:return}}close(){for(let e of this.mobileConnections.keys())this.removeMobileConnection(e)}addMobileConnection(e,t,n,r){e&&(this.removeMobileConnection(e),this.mobileConnections.set(e,{mobileId:e,deviceId:t,handshake:{status:`awaiting_client_hello`}}),this.dependencies.relayTransportSecurityLevel===`e2ee-relay`&&n===`gateway_replay`&&this.dependencies.sendFrame(Go.parse({type:`secure.handshake_required`,gatewayId:this.dependencies.gatewayId,mobileId:e,messageType:`system`,payload:{version:1,gatewayId:this.dependencies.gatewayId,deviceId:t,reason:r?`gateway_restarted`:`gateway_available`,retryable:!0}})))}removeMobileConnection(e){let t=this.mobileConnections.get(e);t&&(t.socket?.close(),t.clientId&&this.dependencies.sessionHub.removeClient(t.clientId),this.mobileConnections.delete(e))}async handleFromMobile(e){let t=e.mobileId;if(!t){this.sendRelayError({code:`BAD_REQUEST`,status:400,message:`from_mobile frame requires mobileId`});return}let n=this.mobileConnections.get(t);if(!n){this.sendRelayError({mobileId:t,code:`BAD_REQUEST`,status:400,message:`Unknown mobile ${t}`});return}if(n.handshake.status!==`ready`||!n.clientId){this.sendSecureError(t,n.deviceId,`transcript_invalid`,`secure handshake not ready`);return}let r=n,i=this.decodeRelayBusinessPayload({connection:r,mobileId:t,frameType:`from_mobile`,messageType:e.messageType,parse:e=>oa.parse(e),payload:e.payload,encryptedPayload:e.encryptedPayload});i&&await this.dependencies.dispatchCommand(i,r.deviceId,r.clientId)}async handlePairingClaim(e,t){try{let n=await this.dependencies.handlePairingClaim(t);this.dependencies.sendFrame(Go.parse({type:`pairing.claim.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...hx(t,`pairing.claim`)})}}async handleRefresh(e,t){try{let n=await this.dependencies.handleRefresh(t);this.dependencies.sendFrame(Go.parse({type:`auth.refresh.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...hx(t,`auth.refresh`)})}}async handleRpcRequest(e){let t=e.mobileId,n=e.requestId,r=this.mobileConnections.get(t);if(!r){this.dependencies.sendFrame({type:`rpc.error`,gatewayId:this.dependencies.gatewayId,mobileId:t,requestId:n,messageType:`rpc`,payload:{...mx(`BAD_REQUEST`,400,`Unknown mobile ${t}`)}});return}if(r.handshake.status!==`ready`){this.sendSecureError(t,r.deviceId,`transcript_invalid`,`secure handshake not ready`);return}let i=r,a=this.decodeRelayBusinessPayload({connection:i,mobileId:t,frameType:`rpc.request`,messageType:e.messageType,requestId:n,parse:e=>To.parse(e),payload:e.payload,encryptedPayload:e.encryptedPayload});if(a)try{let e=await this.dependencies.handleRpcRequest(a,{mobileId:t,deviceId:i.deviceId});this.dependencies.sendFrame(Go.parse({type:`rpc.response`,gatewayId:this.dependencies.gatewayId,mobileId:t,requestId:n,messageType:`rpc`,...this.createRelayBusinessPayloadFields(i,{frameType:`rpc.response`,messageType:`rpc`,requestId:n},e)}))}catch(e){let r=Oo.safeParse(e);this.dependencies.sendFrame({type:`rpc.error`,gatewayId:this.dependencies.gatewayId,mobileId:t,requestId:n,messageType:`rpc`,...this.createRelayBusinessPayloadFields(i,{frameType:`rpc.error`,messageType:`rpc`,requestId:n},{...r.success?r.data:mx(`INTERNAL`,500,String(e)),method:a.method})})}}async handleSecureClientHello(e,t){if(!e){this.sendRelayError({code:`BAD_REQUEST`,status:400,message:`secure.client_hello frame requires mobileId`});return}let n=this.mobileConnections.get(e);if(!n){this.sendRelayError({mobileId:e,code:`BAD_REQUEST`,status:400,message:`Unknown mobile ${e}`});return}if(n.handshake.status!==`awaiting_client_hello`){this.sendSecureError(e,n.deviceId,`counter_replay`,`duplicate secure.client_hello`);return}if(t.deviceId!==n.deviceId){this.sendSecureError(e,n.deviceId,`identity_mismatch`,`deviceId does not match relay token`);return}if(t.version!==1||t.cipherSuite!==`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`){this.sendSecureError(e,n.deviceId,`unsupported_version`,`unsupported secure handshake version`);return}let r=sx({gatewayId:this.dependencies.gatewayId,gatewayIdentity:this.dependencies.gatewayIdentity,privateKeyPem:this.dependencies.gatewayIdentityPrivateKeyPem,clientHello:t});n.handshake={status:`awaiting_client_auth`,clientHello:t,gatewayHello:r.gatewayHello,gatewayEphemeralPrivateKey:r.gatewayEphemeralPrivateKey},this.mobileConnections.set(e,n),this.dependencies.sendFrame(Go.parse({type:`secure.gateway_hello`,gatewayId:this.dependencies.gatewayId,mobileId:e,messageType:`system`,payload:r.gatewayHello}))}async handleSecureClientAuth(e,t){if(!e){this.sendRelayError({code:`BAD_REQUEST`,status:400,message:`secure.client_auth frame requires mobileId`});return}let n=this.mobileConnections.get(e);if(!n){this.sendRelayError({mobileId:e,code:`BAD_REQUEST`,status:400,message:`Unknown mobile ${e}`});return}if(n.handshake.status===`ready`){this.sendSecureError(e,n.deviceId,`counter_replay`,`duplicate secure.client_auth`);return}if(n.handshake.status!==`awaiting_client_auth`){this.sendSecureError(e,n.deviceId,`transcript_invalid`,`secure.client_hello missing`);return}try{cx({gatewayId:this.dependencies.gatewayId,clientHello:n.handshake.clientHello,gatewayHello:n.handshake.gatewayHello,clientAuth:t})}catch(t){this.sendSecureError(e,n.deviceId,gx(t),String(t));return}try{let r=await this.dependencies.verifyDeviceIdentityBinding(n.deviceId,n.handshake.clientHello.deviceIdentity),i=lx({gatewayId:this.dependencies.gatewayId,clientHello:n.handshake.clientHello,gatewayHello:n.handshake.gatewayHello,clientAuth:t,gatewayEphemeralPrivateKey:n.handshake.gatewayEphemeralPrivateKey});this.ensureReadyMobileClient(n),n.handshake={status:`ready`,clientHello:n.handshake.clientHello,gatewayHello:n.handshake.gatewayHello,session:i},this.mobileConnections.set(e,n),this.dependencies.sendFrame(Go.parse({type:`secure.ready`,gatewayId:this.dependencies.gatewayId,mobileId:e,messageType:`system`,payload:{version:1,securityLevel:`e2ee-relay`,cipherSuite:i.cipherSuite,gatewayId:this.dependencies.gatewayId,deviceId:n.deviceId,keyEpoch:i.keyEpoch,deviceIdentityFingerprint:r.publicKeyFingerprint??n.handshake.clientHello.deviceIdentity.publicKeyFingerprint,deviceIdentityStatus:r.identityStatus??`active`}}))}catch(t){this.sendSecureError(e,n.deviceId,vx(t),String(t))}}ensureReadyMobileClient(e){if(e.clientId&&e.socket)return;let t=new fx(t=>{try{let n=Go.parse({type:`to_mobile`,gatewayId:this.dependencies.gatewayId,mobileId:e.mobileId,messageType:`event`,...this.createRelayBusinessPayloadFields(e,{frameType:`to_mobile`,messageType:`event`},t)});this.dependencies.sendFrame(n)}catch(t){this.sendSecureError(e.mobileId,e.deviceId,_x(t),`relay secure payload failed: ${String(t)}`)}}),n=this.dependencies.sessionHub.addClient(e.deviceId,t);e.socket=t,e.clientId=n}sendSecureError(e,t,n,r){this.dependencies.sendFrame({type:`secure.error`,gatewayId:this.dependencies.gatewayId,mobileId:e,messageType:`system`,payload:ux({gatewayId:this.dependencies.gatewayId,deviceId:t,code:n,message:r,retryable:n===`transcript_invalid`||n===`unsupported_version`||n===`key_epoch_mismatch`})})}sendRelayError(e){this.dependencies.sendFrame({type:`relay.error`,gatewayId:this.dependencies.gatewayId,...e.mobileId?{mobileId:e.mobileId}:{},...e.requestId?{requestId:e.requestId}:{},messageType:`system`,payload:mx(e.code,e.status,e.message)})}decodeRelayBusinessPayload(e){if(e.payload!==void 0)return this.sendSecureError(e.mobileId,e.connection.deviceId,`decrypt_failed`,`relay secure payload must be encrypted`),null;if(!e.encryptedPayload)return this.sendSecureError(e.mobileId,e.connection.deviceId,`decrypt_failed`,`relay secure payload missing`),null;try{return rs({session:e.connection.handshake.session,metadata:{frameType:e.frameType,messageType:e.messageType,gatewayId:this.dependencies.gatewayId,...e.requestId?{requestId:e.requestId}:{}},encryptedPayload:e.encryptedPayload,parse:e.parse})}catch(t){return this.sendSecureError(e.mobileId,e.connection.deviceId,_x(t),`relay secure payload failed: ${String(t)}`),null}}createRelayBusinessPayloadFields(e,t,n){return e.handshake.status===`ready`?{encryptedPayload:ns({session:e.handshake.session,metadata:{frameType:t.frameType,messageType:t.messageType,gatewayId:this.dependencies.gatewayId,...t.requestId?{requestId:t.requestId}:{}},payload:n})}:{payload:n}}};function mx(e,t,n){return Oo.parse({code:e,status:t,message:n})}function hx(e,t){if(Rg(e))switch(e.code){case`PAIRING_CODE_INVALID`:case`PAIRING_CODE_EXPIRED`:return{code:`BAD_REQUEST`,status:e.status,message:String(e)};case`REFRESH_TOKEN_REVOKED`:case`DEVICE_REVOKED`:case`REFRESH_TOKEN_DEVICE_MISMATCH`:return{code:`UNAUTHORIZED`,status:e.status,message:String(e)};default:return{code:e.status>=500?`INTERNAL`:`BAD_REQUEST`,status:e.status,message:String(e)}}let n=String(e),r=yx(e);return t===`pairing.claim`&&(r===`Invalid pairing code`||r===`Pairing code expired`)?{code:`BAD_REQUEST`,status:400,message:n}:t===`auth.refresh`&&(r===`Refresh token revoked`||r===`Device revoked`||r===`Device revoked or not found`||r===`Refresh token device mismatch`||Qg(e))?{code:`UNAUTHORIZED`,status:401,message:n}:{code:`INTERNAL`,status:500,message:n}}function gx(e){return bx(e,[`identity_mismatch`,`counter_replay`,`unsupported_version`,`transcript_invalid`])??`transcript_invalid`}function _x(e){return bx(e,[`counter_gap_too_large`,`counter_replay`,`key_epoch_mismatch`,`decrypt_failed`])??`decrypt_failed`}function vx(e){if(Rg(e))switch(e.code){case`DEVICE_REVOKED`:return`device_revoked`;case`DEVICE_IDENTITY_NOT_REGISTERED`:case`DEVICE_IDENTITY_MISMATCH`:return`identity_mismatch`;default:return`transcript_invalid`}let t=yx(e);return t===`Device revoked`||t===`Device revoked or not found`?`device_revoked`:t===`Device identity mismatch`||t===`Device identity not registered`?`identity_mismatch`:`transcript_invalid`}function yx(e){return e instanceof Error?e.message:typeof e==`string`?e:String(e)}function bx(e,t){let n=yx(e);return t.find(e=>e===n)}var xx=class{logger;reconnectBaseDelayMs;reconnectMaxDelayMs;heartbeatIntervalMs;heartbeatTimeoutMs;webSocketFactory;socket;reconnectTimer;heartbeatIntervalTimer;heartbeatTimeoutTimer;reconnectAttempt=0;connectAttemptId=0;state=`idle`;stopped=!1;constructor(e){this.options=e,this.logger=e.logger??{},this.reconnectBaseDelayMs=e.reconnectBaseDelayMs??1e3,this.reconnectMaxDelayMs=e.reconnectMaxDelayMs??15e3,this.heartbeatIntervalMs=e.heartbeatIntervalMs??15e3,this.heartbeatTimeoutMs=e.heartbeatTimeoutMs??1e4,this.webSocketFactory=e.webSocketFactory??wx}start(){this.stopped&&=!1,!(this.socket||this.reconnectTimer)&&this.connect()}close(){this.stopped=!0,this.state=`stopped`,this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),void 0);let e=this.socket;this.socket=void 0,this.stopHeartbeat(),e?.close(1e3,`Gateway shutting down`)}isConnected(){let e=this.socket;return this.state===`connected`&&!!e&&e.readyState===e.OPEN}send(e){let t=this.socket;if(!t||t.readyState!==t.OPEN)return!1;let n=Go.parse(e);return t.send(JSON.stringify(n)),!0}async connect(){if(this.stopped)return;let e=++this.connectAttemptId,t;try{t=await this.resolveGatewayAccessToken()}catch(e){this.state=`idle`,this.logger.warn?.({err:e},`failed to resolve relay gateway access token`),this.scheduleReconnect();return}if(this.stopped||e!==this.connectAttemptId)return;let n=Sx(this.options.relayUrl);this.state=`connecting`;let r=this.webSocketFactory(n);this.socket=r,r.on(`open`,()=>{this.socket!==r||this.stopped||(this.reconnectAttempt=0,this.state=`connected`,this.startHeartbeat(r),this.logger.info?.({relayUrl:this.options.relayUrl,gatewayId:this.options.gatewayId},`relay gateway websocket connected`),this.send({type:`gateway.hello`,gatewayId:this.options.gatewayId,messageType:`system`,payload:{name:this.options.machineName,relayBaseUrl:this.options.relayUrl,directBaseUrls:this.options.directBaseUrls,transportSecurityLevel:`e2ee-relay`,gatewayIdentity:this.options.gatewayIdentity,gatewayAccessToken:t,connectedAt:new Date().toISOString()}}))}),r.on(`message`,e=>{if(this.socket===r){this.ackHeartbeat(r);try{let t=Go.parse(JSON.parse(Cx(e)));Promise.resolve(this.options.onFrame(t)).catch(e=>{this.logger.error?.({err:e},`failed to handle relay frame`)})}catch(e){this.logger.warn?.({err:e},`failed to parse relay frame from relay`)}}}),r.on(`error`,e=>{this.socket===r&&this.logger.warn?.({err:e},`relay websocket emitted error`)}),r.on(`pong`,()=>{this.socket===r&&this.ackHeartbeat(r)}),r.on(`close`,(e,t)=>{if(this.socket===r){if(this.socket=void 0,this.stopHeartbeat(),this.stopped){this.state=`stopped`;return}this.logger.warn?.({relayUrl:this.options.relayUrl,gatewayId:this.options.gatewayId,closeCode:e,closeReason:t.toString(`utf8`)},`relay websocket closed`),this.state=`idle`,this.scheduleReconnect()}})}async resolveGatewayAccessToken(){let e=this.options.relayGatewayAccessToken.trim();if(e)return e;let t=this.options.resolveRelayGatewayAccessToken;if(t)return t();throw Error(`Gateway relay access token is not configured`)}scheduleReconnect(){if(this.stopped||this.reconnectTimer)return;let e=Math.min(this.reconnectMaxDelayMs,this.reconnectBaseDelayMs*Math.max(1,2**this.reconnectAttempt));this.reconnectAttempt+=1,this.logger.info?.({delayMs:e},`scheduling relay reconnect`),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},e)}startHeartbeat(e){this.stopHeartbeat(),this.heartbeatIntervalTimer=setInterval(()=>{if(!(this.socket!==e||this.stopped)&&!(e.readyState!==e.OPEN||this.heartbeatTimeoutTimer)){try{e.ping()}catch(t){this.logger.warn?.({err:t},`failed to send relay websocket heartbeat ping`),e.terminate();return}this.heartbeatTimeoutTimer=setTimeout(()=>{this.heartbeatTimeoutTimer=void 0,!(this.socket!==e||this.stopped||e.readyState!==e.OPEN)&&(this.logger.warn?.({relayUrl:this.options.relayUrl,gatewayId:this.options.gatewayId,heartbeatTimeoutMs:this.heartbeatTimeoutMs},`relay websocket heartbeat timed out`),e.terminate())},this.heartbeatTimeoutMs)}},this.heartbeatIntervalMs)}ackHeartbeat(e){this.socket===e&&(this.heartbeatTimeoutTimer&&=(clearTimeout(this.heartbeatTimeoutTimer),void 0))}stopHeartbeat(){this.heartbeatIntervalTimer&&=(clearInterval(this.heartbeatIntervalTimer),void 0),this.heartbeatTimeoutTimer&&=(clearTimeout(this.heartbeatTimeoutTimer),void 0)}};function Sx(e){let t=new URL(e);return t.protocol===`http:`?t.protocol=`ws:`:t.protocol===`https:`&&(t.protocol=`wss:`),t.pathname=`/ws/gateway`,t.toString()}function Cx(e){return typeof e==`string`?e:e instanceof ArrayBuffer?Buffer.from(e).toString(`utf8`):ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`utf8`):Array.isArray(e)&&e.every(e=>ArrayBuffer.isView(e))?Buffer.concat(e.map(e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength))).toString(`utf8`):String(e)}function wx(e){return new rv(e)}function Tx(e){let t={gatewayId:e.gatewayId.trim(),gatewayIdentity:e.gatewayIdentity,requestedAt:e.requestedAt??new Date().toISOString()};if(!t.gatewayId)throw Error(`gatewayId must not be empty when requesting a guest relay gateway access token.`);return{grantType:`guest`,payload:t,signatureAlgorithm:`ed25519`,signature:(0,l.sign)(null,Buffer.from(Ko(t),`utf8`),(0,l.createPrivateKey)(e.privateKeyPem)).toString(`base64`)}}async function Ex(e){let t=e.fetchImpl??globalThis.fetch;if(!t)throw Error(`fetch is not available when requesting a guest relay gateway access token.`);let n=await t(Dx(e.relayUrl),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(Tx({gatewayId:e.gatewayId,gatewayIdentity:e.gatewayIdentity,privateKeyPem:e.privateKeyPem}))}),r=await n.text();if(!n.ok)throw Error(`Failed to request a guest relay gateway access token (${n.status}): ${r}`);return Po.parse(JSON.parse(r)).token}function Dx(e){let t=new URL(e);return t.protocol===`ws:`?t.protocol=`http:`:t.protocol===`wss:`&&(t.protocol=`https:`),t.pathname=`/api/gateway-token/guest`,t.search=``,t.toString()}function Ox(e){return e?.trim()||void 0}function kx(e){if(e)return{codex:e.codex?{approvalPolicy:e.codex.approvalPolicy,sandboxMode:e.codex.sandboxMode}:void 0,claude:e.claude?{permissionMode:e.claude.permissionMode}:void 0}}function Ax(e,t){return{modeDefault:`default`,model:Ox(t.defaults.model),reasoningEffort:t.defaults.reasoningEffort,execution:e===`codex`?{codex:{approvalPolicy:t.defaults.approvalPolicy??null,sandboxMode:t.defaults.sandboxMode??null}}:{claude:{permissionMode:t.defaults.permissionMode??null}}}}function jx(e){return{mode:`default`,model:null,reasoningEffort:null,execution:e===`codex`?{codex:{approvalPolicy:null,sandboxMode:null}}:{claude:{permissionMode:null}}}}function Mx(e,t){let n=jx(e);return t?e===`codex`?{mode:t.mode,model:t.model,reasoningEffort:t.reasoningEffort,execution:{codex:{approvalPolicy:t.execution?.codex?.approvalPolicy??null,sandboxMode:t.execution?.codex?.sandboxMode??null}}}:{mode:t.mode,model:t.model,reasoningEffort:t.reasoningEffort,execution:{claude:{permissionMode:t.execution?.claude?.permissionMode??null}}}:n}function Nx(e,t){return e===`claude`&&t?.permissionMode===`plan`?`plan`:`default`}function Px(e){let t=Mx(e.provider,e.sessionTurnConfig);return e.sessionTurnConfig!==void 0||Ox(e.legacyModel)!==void 0||e.legacySessionConfig!==void 0?Fx({provider:e.provider,providerDefaults:{modeDefault:`default`},currentSessionTurnConfig:t,legacyModel:e.legacyModel,legacySessionConfig:e.legacySessionConfig}).sessionTurnConfig:t}function Fx(e){let t=Mx(e.provider,e.currentSessionTurnConfig),n=e.mode??(e.legacySessionConfig?Nx(e.provider,e.legacySessionConfig):void 0)??t.mode??e.providerDefaults.modeDefault,r=Mx(e.provider,{...t,mode:n});e.config&&(e.config.model!==void 0&&(r.model=e.config.model),e.config.reasoningEffort!==void 0&&(r.reasoningEffort=e.config.reasoningEffort),e.provider===`codex`&&e.config.execution?.codex&&(r.execution={codex:{approvalPolicy:e.config.execution.codex.approvalPolicy,sandboxMode:e.config.execution.codex.sandboxMode}}),e.provider===`claude`&&e.config.execution?.claude&&(r.execution={claude:{permissionMode:e.config.execution.claude.permissionMode}}));let i=Ox(e.legacyModel);i&&(r.model=i),e.legacySessionConfig?.reasoningEffort!==void 0&&(r.reasoningEffort=e.legacySessionConfig.reasoningEffort),e.provider===`codex`&&e.legacySessionConfig&&(r.execution={codex:{approvalPolicy:e.legacySessionConfig.approvalPolicy??r.execution?.codex?.approvalPolicy??null,sandboxMode:e.legacySessionConfig.sandboxMode??r.execution?.codex?.sandboxMode??null}}),e.provider===`claude`&&e.legacySessionConfig&&(r.execution={claude:{permissionMode:e.legacySessionConfig.permissionMode===`plan`?r.execution?.claude?.permissionMode??null:e.legacySessionConfig.permissionMode??r.execution?.claude?.permissionMode??null}});let a=r.model??Ox(e.providerDefaults.model),o={},s=r.reasoningEffort??e.providerDefaults.reasoningEffort;if(s&&(o.reasoningEffort=s),e.provider===`codex`){let t=r.execution?.codex?.approvalPolicy??e.providerDefaults.execution?.codex?.approvalPolicy??void 0,n=r.execution?.codex?.sandboxMode??e.providerDefaults.execution?.codex?.sandboxMode??void 0;t&&(o.approvalPolicy=t),n&&(o.sandboxMode=n)}else{let t=n===`plan`?`plan`:r.execution?.claude?.permissionMode??e.providerDefaults.execution?.claude?.permissionMode??void 0;t&&(o.permissionMode=t)}return{mode:n,model:a,sessionConfig:o,sessionTurnConfig:{mode:r.mode,model:r.model,reasoningEffort:r.reasoningEffort,execution:kx(r.execution)}}}const Ix=[],Lx=[{id:`default`,label:`Default`,isDefault:!0,supportedReasoningEfforts:[`low`,`medium`,`high`,`max`]}],Rx=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`],zx=ji.options,Bx=[`read-only`,`workspace-write`,`danger-full-access`],Vx=[`default`,`acceptEdits`,`bypassPermissions`,`plan`,`dontAsk`],Hx=process.env.SESSION_FETCH_DEBUG===`1`||process.env.EXPO_PUBLIC_SESSION_FETCH_DEBUG===`1`;function Ux(e,t){Hx&&console.log(`[session-fetch][gateway] ${e}`,t)}const Wx={codex:[{version:`codex-mobile-v1`,defaults:{reasoningEffort:`medium`,approvalPolicy:`on-request`,sandboxMode:`workspace-write`}},{version:`codex-mobile-v2`,defaults:{reasoningEffort:`low`,approvalPolicy:`on-request`,sandboxMode:`read-only`}}],claude:[{version:`claude-mobile-v1`,defaults:{model:`default`}}]},Gx={idleTtlMs:900*1e3,sweepIntervalMs:60*1e3,maxSessions:24,maxCodexSessions:8,maxClaudeSessions:16},Kx=30*1e3;function qx(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(1,Math.trunc(n)):t}function Jx(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(0,Math.trunc(n)):t}function Yx(e,t){let n=t?.trim().toLowerCase();return n?(Wx[e]??[]).find(e=>n===e.version.toLowerCase())??null:null}function Xx(e,t,n){return e.some(e=>e.id===t)?e.map(e=>({...e,isDefault:e.id===t})):[{id:t,label:t,isDefault:!0,...n===`codex`?{supportedReasoningEfforts:Rx}:{}},...e.map(e=>({...e,isDefault:!1}))]}function Zx(e){return e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`||e===`max`?e:null}function Qx(e){let t=new Set;for(let n of e){let e=Zx(n);e&&t.add(e)}return[...t]}function $x(e){return e?.trim()||void 0}function eS(e){let t=$x(e.runtimeModel);if(t)return t;let n=$x(e.discoveredModel);if(n)return n;let r=$x(e.existingModel),i=$x(e.modelProvider)?.toLowerCase();if(r&&(!i||r.toLowerCase()!==i))return r}function tS(e){let t=e.filter(e=>!!e.id).map(e=>({id:e.id,label:e.displayName||e.model||e.id,description:e.description,isDefault:e.isDefault,supportedReasoningEfforts:Qx(e.supportedReasoningEfforts)}));return t.length===0?Ix:(t.some(e=>e.isDefault)||(t[0]={...t[0],isDefault:!0}),t)}async function nS(){try{return tS(await hy())}catch{return null}}async function rS(){try{let e=await import(`@anthropic-ai/claude-agent-sdk`),t=e.query??e.default?.query;if(typeof t!=`function`)return null;let n=t,r=p.default.join(Js(),`claude-capability-probe`);await d.default.mkdir(r,{recursive:!0,mode:448});let i=n({prompt:`/clear`,options:{cwd:r,permissionMode:`plan`,maxTurns:1,includePartialMessages:!1}});try{let e=await i.supportedModels(),t=[];for(let n of e){let e=typeof n.value==`string`?n.value:``;if(!e)continue;let r=Array.isArray(n.supportedEffortLevels)&&n.supportedEffortLevels.length>0,i=aS(n.description,n.displayName,e),a=n.supportsEffort===!1?[]:n.supportsEffort||r?Qx(n.supportedEffortLevels??[]):i===`haiku`?[]:void 0;t.push({id:e,label:n.displayName||e,description:typeof n.description==`string`&&n.description.trim()?n.description.trim():void 0,isDefault:e===`default`,supportedReasoningEfforts:a})}return t.length===0?null:(t.some(e=>e.isDefault)||(t[0]={...t[0],isDefault:!0}),t)}finally{i.close()}}catch{return null}}function iS(e){let t=(e.find(e=>e.isDefault)??e[0])?.supportedReasoningEfforts??[];if(t.includes(`medium`))return`medium`;if(t.includes(`high`))return`high`;if(t.length>0)return t[0]}function aS(...e){for(let t of e){let e=t?.trim().toLowerCase();if(e){if(e.includes(`haiku`))return`haiku`;if(e.includes(`opus`))return`opus`;if(e.includes(`sonnet`)||e.includes(`sonnect`))return`sonnet`}}}var oS=class{sessions=new Map;providerCapabilitiesCache=new Map;providerCapabilitiesInFlight=new Map;nextRawSeqBySession=new Map;runtimeLifecycle;sweepTimer;lastRawEnvelopeTimestampMs=0;shuttingDown=!1;constructor(e){if(this.options=e,this.runtimeLifecycle={idleTtlMs:qx(e.runtimeLifecycle?.idleTtlMs,Gx.idleTtlMs),sweepIntervalMs:Jx(e.runtimeLifecycle?.sweepIntervalMs,Gx.sweepIntervalMs),maxSessions:qx(e.runtimeLifecycle?.maxSessions,Gx.maxSessions),maxCodexSessions:qx(e.runtimeLifecycle?.maxCodexSessions,Gx.maxCodexSessions),maxClaudeSessions:qx(e.runtimeLifecycle?.maxClaudeSessions,Gx.maxClaudeSessions)},this.runtimeLifecycle.sweepIntervalMs<=0){this.sweepTimer=null;return}this.sweepTimer=setInterval(()=>{this.sweepRuntimeSessions().catch(e=>{console.error(`[session-runtime] sweep failed: ${String(e)}`)})},this.runtimeLifecycle.sweepIntervalMs),this.sweepTimer.unref?.()}async shutdown(){this.shuttingDown=!0,this.sweepTimer&&clearInterval(this.sweepTimer);let e=[...this.sessions.keys()];this.options.logger?.info?.({sessionCount:e.length,sessionIds:e},`session manager shutdown starting`),await Promise.allSettled(e.map(e=>this.closeRuntimeSession(e,`shutdown`))),await Ov(),this.options.logger?.info?.({sessionCount:e.length,sessionIds:e},`session manager shutdown completed`)}async listProjects(){let e=await this.options.projectStore.list(),t=this.buildProjectStatsMap();return e.map(e=>this.attachProjectStats(e,t))}async createProject(e){let t=await this.options.projectStore.upsertByPath(e.path,e.title);return this.attachProjectStats(t,this.buildProjectStatsMap())}async deleteProject(e){if(this.listProjectSessionsWithRuntime(e,`running`).length>0)throw qg(e);return this.options.projectStore.remove(e)}async getProject(e){return this.options.projectStore.getById(e)}buildProjectStatsMap(){let e=new Map,t=this.listAllSessionsWithRuntime(`all`);for(let n of t){let t=e.get(n.projectId)??{runningCount:0,idleCount:0,totalCount:0,lastSessionAt:void 0};n.status===`running`?t.runningCount+=1:t.idleCount+=1,t.totalCount+=1;let r=n.updatedAt||n.createdAt;(!t.lastSessionAt||r>t.lastSessionAt)&&(t.lastSessionAt=r),e.set(n.projectId,t)}return e}attachProjectStats(e,t){let n=t.get(e.id),r=n?.idleCount??0;return{...e,lastSessionAt:n?.lastSessionAt,runningCount:n?.runningCount??0,idleCount:r,totalCount:n?.totalCount??0,endedCount:r}}async getProviderCapabilities(e,t,n){return(await this.resolveProviderCapabilities(e,t,n)).capabilities}async getAgentConfig(e,t){let n=await this.resolveProviderCapabilities(e,t?.projectId,t?.agentVersion);return{agent:{provider:e,requestedVersion:t?.agentVersion?.trim()||null,resolvedVersion:n.resolvedAgentVersion},capabilities:n.capabilities}}async warmStartupProviderCapabilities(){if(!this.options.preferNativeProviders||this.shuttingDown)return;let e=Wx.claude.length>0?Wx.claude.map(e=>e.version):[void 0];await Promise.allSettled(e.map(e=>this.resolveProviderCapabilities(`claude`,void 0,e)))}async resolveProviderCapabilities(e,t,n){if(t&&!await this.options.projectStore.getById(t))throw Wg(t);let r=Yx(e,n),i=r?.version??`default`,a=`${e}::${i}`,o=Date.now(),s=this.providerCapabilitiesCache.get(a);if(s){if(s.expiresAt>o)return s.value;this.providerCapabilitiesCache.delete(a)}let c=this.providerCapabilitiesInFlight.get(a);if(c)return c;let l=(async()=>{let t=cb(e,{preferNative:this.options.preferNativeProviders,requireNative:!1}),n=this.options.preferNativeProviders?await t.isNativeAvailable().catch(()=>!1):!1,a=n?`native`:`fallback`,o=e===`codex`&&n?await nS()??Ix:Ix,s=e===`claude`&&n?await rS()??Lx:Lx,c=Qx(s.flatMap(e=>e.supportedReasoningEfforts??[])),l=e===`codex`?{provider:e,source:a,models:o,support:{reasoningEffort:!0,approvalPolicy:!0,sandboxMode:!0,permissionMode:!1},options:{reasoningEfforts:Rx,approvalPolicies:zx,sandboxModes:Bx,permissionModes:[]},defaults:{model:o.find(e=>e.isDefault)?.id??o[0]?.id,reasoningEffort:`medium`,approvalPolicy:`on-request`,sandboxMode:`workspace-write`}}:{provider:e,source:a,models:s,support:{reasoningEffort:c.length>0,approvalPolicy:!1,sandboxMode:!1,permissionMode:!0},options:{reasoningEfforts:c,approvalPolicies:[],sandboxModes:[],permissionModes:Vx},defaults:{model:s.find(e=>e.isDefault)?.id??s[0]?.id,reasoningEffort:iS(s),permissionMode:`default`}};if(!r)return{capabilities:l,resolvedAgentVersion:i};let u={...l.defaults,...r.defaults},d=u.model?.trim(),f=a===`native`?l.models:d?Xx(l.models,d,e):l.models;return{capabilities:{...l,models:f,defaults:u},resolvedAgentVersion:r.version}})();this.providerCapabilitiesInFlight.set(a,l);try{let e=await l;return this.providerCapabilitiesCache.set(a,{value:e,expiresAt:Date.now()+864e5}),e}finally{this.providerCapabilitiesInFlight.delete(a)}}async getProviderDefaults(e,t,n){return Ax(e,await this.getProviderCapabilities(e,t,n))}async listProjectSessions(e,t=`all`,n){let r=await this.options.projectStore.getById(e);if(!r)throw Wg(e);return n?.syncExternal&&(await this.syncCodexSessionsForProject(r),await this.syncClaudeSessionsForProject(r)),this.listProjectSessionsWithRuntime(e,t)}async getProjectSessionSummary(e,t){let n=this.options.historyStore.getProjectSession(e,t);return this.getRuntimeSessionSummary(e,t,n)||n}async getProjectSessionEvents(e,t,n=300,r){let i=await this.options.projectStore.getById(e);if(!i)throw Wg(e);let a=r?.syncExternal===!0,o=this.options.historyStore.getProjectSession(e,t);if(!o&&this.getRuntimeSessionSummary(e,t))return[];if(!o&&a&&this.options.preferNativeProviders&&(await this.syncCodexSessionsForProject(i),await this.syncClaudeSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)),!o)throw Gg(e,t);let s=await this.options.historyStore.getSessionEvents(t,Math.max(n,300));if(o.source===`native_discovered`&&!a||o.source!==`native_discovered`&&!a&&s.length>0)return s.slice(-Math.max(1,n));if(o.provider===`claude`){let t=TS(o);if(!t)return s.slice(-Math.max(1,n));try{let r=await pb({projectPath:o.projectPath,nativeSessionId:t,provider:o.provider,sessionId:o.id,projectId:e});return o.source===`native_discovered`?uS(r,s.filter(e=>!cS.has(e.type)),n):fS(s,r,cS,n)}catch{return s.slice(-Math.max(1,n))}}if(o.provider!==`codex`)return s.slice(-Math.max(1,n));let c=CS([o.nativeSessionId,o.id]);for(let t of c)try{return fS(s,ES({thread:await my(t,!0),provider:o.provider,sessionId:o.id,projectId:e}),sS,n)}catch(n){Ux(`sync-external.codex.error`,{projectId:e,sessionId:o.id,source:o.source,threadId:t,localEventCount:s.length,error:n instanceof Error?n.message:String(n)})}return s.slice(-Math.max(1,n))}async getProjectSessionRawEvents(e,t,n=300,r){let i=Date.now(),a=await this.options.projectStore.getById(e);if(!a)throw Wg(e);let o=r?.syncExternal===!0,s=0,c=0,l=0,u=0,d,f=(r,a)=>{Ux(`raw-events.read`,{projectId:e,sessionId:t,limit:n,syncExternal:o,provider:d?.provider,source:d?.source,providerMode:d?.providerMode,syncProjectSessionsDurationMs:s,localReadDurationMs:c,syncExternalReadDurationMs:l,finalCount:u,outcome:r,totalDurationMs:Date.now()-i,...a})},p=this.options.historyStore.getProjectSession(e,t);if(!p&&this.getRuntimeSessionSummary(e,t))return f(`runtime_session_empty`),[];if(!p&&o&&this.options.preferNativeProviders){let n=Date.now();await this.syncCodexSessionsForProject(a),await this.syncClaudeSessionsForProject(a),s=Date.now()-n,p=this.options.historyStore.getProjectSession(e,t)}if(!p)throw Gg(e,t);d=p;let m=Date.now(),h=await this.options.historyStore.getSessionRawEvents(p.id,Math.max(n,300));if(c=Date.now()-m,p.source===`native_discovered`&&!o)return u=h.slice(-Math.max(1,n)).length,f(`local_only_native_discovered`,{localEventCount:h.length}),h.slice(-Math.max(1,n));let g=Date.now(),_=await this.maybeSyncExternalRawHistoryForRead(p,e,h,{forceSyncExternal:o});return l=Date.now()-g,p.source!==`native_discovered`&&!o&&_.rawEvents===h?(u=h.slice(-Math.max(1,n)).length,f(`local_only_cached`,{localEventCount:h.length,syncedEventCount:_.rawEvents.length}),h.slice(-Math.max(1,n))):(u=_.rawEvents.slice(-Math.max(1,n)).length,f(o?`sync_external`:`merged_or_local`,{localEventCount:h.length,syncedEventCount:_.rawEvents.length}),_.rawEvents.slice(-Math.max(1,n)))}async getProjectSessionRawEventsCompacted(e,t,n=300,r){let i=await this.resolveProjectSessionForRawRead(e,t,r);return this.options.historyStore.getSessionRawEventsCompacted(i.id,n)}async getProjectSessionRawEventsSinceSeq(e,t,n,r=2e3,i){let a=await this.resolveProjectSessionForRawRead(e,t,i);return this.options.historyStore.getSessionRawEventsSinceSeq(a.id,n,r)}async getProjectSessionRawSeqRange(e,t,n){let r=await this.resolveProjectSessionForRawRead(e,t,n);return this.options.historyStore.getSessionRawSeqRange(r.id)}async resolveProjectSessionForRawRead(e,t,n){let r=await this.options.projectStore.getById(e);if(!r)throw Wg(e);let i=n?.syncExternal===!0,a=this.options.historyStore.getProjectSession(e,t);if(!a&&i&&this.options.preferNativeProviders&&(await this.syncCodexSessionsForProject(r),await this.syncClaudeSessionsForProject(r),a=this.options.historyStore.getProjectSession(e,t)),!a)throw Gg(e,t);let o=await this.options.historyStore.getSessionRawEvents(a.id,2**53-1);return(await this.maybeSyncExternalRawHistoryForRead(a,e,o,{forceSyncExternal:i})).session}async startSession(e){let t=await this.resolveProjectForSessionStart(e.projectId,e.cwd),n=`sess_${og(10)}`,r=e.provider===`codex`&&this.options.requireNativeCodex,i=cb(e.provider,{preferNative:this.options.preferNativeProviders,requireNative:r}),a=await this.getProviderDefaults(e.provider,t.id),o=e.sessionTurnConfig?Mx(e.provider,e.sessionTurnConfig):Px({provider:e.provider,legacyModel:e.model,legacySessionConfig:e.sessionConfig}),s=Fx({provider:e.provider,providerDefaults:a,currentSessionTurnConfig:o}),c=await i.createSession({sessionId:n,model:s.model,cwd:t.path,sessionConfig:s.sessionConfig,metadata:e.metadata,logger:this.options.logger});if(r&&c.providerMode!==`native`)throw await c.close(),Error(`Native Codex provider is required, but adapter fell back to mock. Check ENABLE_NATIVE_PROVIDERS and Codex app-server availability.`);let l=this.resolveCanonicalSessionId(e.provider,c,n),u=this.resolveNativeSessionId(e.provider,c,l),d=new Date().toISOString(),f=await this.attachRuntimeSession({id:l,nativeSessionId:u,source:`gateway`,projectId:t.id,projectPath:t.path,provider:e.provider,providerMode:c.providerMode,model:s.model,title:void 0,sessionTurnConfig:o,sessionTurnConfigUpdatedAt:d,createdAt:d,updatedAt:d,status:`idle`,providerSession:c,pendingToolApprovals:new Set,pendingUserInputs:new Set,streamReady:!1,bufferedProviderEvents:[],lastActiveAtMs:Date.now(),dispatchInFlight:!1,closing:!1});return this.markSessionStreamReady(f),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`session.start`,deviceId:e.deviceId,sessionId:f.id,detail:{provider:e.provider,model:s.model,sessionConfig:e.sessionConfig,sessionTurnConfig:o,projectId:t.id,projectPath:t.path}}),{sessionId:f.id,projectId:t.id}}async sendInput(e,t,n,r){let i=this.sessions.get(e)??await this.resumeSessionFromHistory(e);if(!i)throw Kg(e);let a=await this.getProviderDefaults(i.provider,i.projectId),o=Fx({provider:i.provider,providerDefaults:a,currentSessionTurnConfig:i.sessionTurnConfig,legacyModel:r?.model,legacySessionConfig:r?.sessionConfig,mode:r?.mode,config:r?.config});i.dispatchInFlight=!0,this.touchSession(i);try{if(await this.options.auditLogger.record({ts:new Date().toISOString(),action:`turn.input`,deviceId:n,sessionId:e,detail:{text:t,model:o.model,sessionConfig:r?.sessionConfig,mode:o.mode,config:r?.config,resolvedSessionConfig:o.sessionConfig}}),this.options.historyStore.getSession(i.id)||await this.persistSessionSnapshot(i),await i.providerSession.sendInput(t,{model:o.model,sessionConfig:o.sessionConfig,mode:o.mode}),!i.title){let e=MS(t);e&&this.setSessionTitle(i,e)}let a=new Date().toISOString();i.sessionTurnConfig=Mx(i.provider,o.sessionTurnConfig),i.sessionTurnConfigUpdatedAt=a,o.model&&i.model!==o.model&&(i.model=o.model),i.updatedAt=a,await this.persistSessionSnapshot(i)}finally{i.dispatchInFlight=!1,this.touchSession(i)}}async respondToolPermission(e,t,n,r,i){let a=this.mustGetSession(e);if(!a.pendingToolApprovals.has(t))throw Error(`Unknown tool approval request: ${t}`);if(typeof a.providerSession.respondToolPermission!=`function`){a.pendingToolApprovals.delete(t),a.updatedAt=new Date().toISOString(),await this.persistSessionSnapshot(a);return}await a.providerSession.respondToolPermission(t,n,r),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`tool.approval.respond`,deviceId:i,sessionId:e,detail:{requestId:t,decision:n,reason:r}})}async respondUserInput(e,t,n,r){let i=this.mustGetSession(e);if(!i.pendingUserInputs.has(t))throw Error(`Unknown user input request: ${t}`);if(typeof i.providerSession.respondUserInput!=`function`){i.pendingUserInputs.delete(t),i.updatedAt=new Date().toISOString(),await this.persistSessionSnapshot(i);return}await i.providerSession.respondUserInput(t,n),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`user.input.respond`,deviceId:r,sessionId:e,detail:{requestId:t,answeredCount:PS(n)}})}async interruptSession(e,t){let n=this.sessions.get(e);n&&await n.providerSession.interrupt(),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`session.interrupt`,deviceId:t,sessionId:e,detail:{runtimeSessionFound:!!n}})}async closeSession(e){throw Error(`session.close is deprecated. Use session.interrupt instead.`)}getSessionExecutionContext(e){let t=this.sessions.get(e);if(t)return{provider:t.provider,projectId:t.projectId,projectPath:t.projectPath};let n=this.options.historyStore.getSession(e);if(!n)throw Kg(e);return{provider:n.provider,projectId:n.projectId,projectPath:n.projectPath}}async emitExternalEvent(e){let t=this.options.historyStore.getSession(e.sessionId),n={v:`1.0`,kind:`provider.raw`,rawSeq:await this.nextRawSeq(e.sessionId),provider:e.provider,sessionId:e.sessionId,projectId:e.projectId??t?.projectId,eventId:`raw_${og(12)}`,ts:this.nextRawEnvelopeTimestamp(),type:e.type,payload:{raw:{...e.raw,type:e.type}}};this.options.onEnvelope(n),this.options.historyStore.appendRawEvent(n).catch(e=>{console.error(`[session-history] append raw event failed: ${String(e)}`)})}async resumeSessionFromHistory(e){let t=this.options.historyStore.getSession(e);if(!t)return;let n=t.provider===`codex`&&this.options.requireNativeCodex,r=cb(t.provider,{preferNative:this.options.preferNativeProviders,requireNative:n}),i=await this.getProviderDefaults(t.provider,t.projectId),a=Mx(t.provider,t.sessionTurnConfig),o=Fx({provider:t.provider,providerDefaults:i,currentSessionTurnConfig:a}),s=t.provider===`claude`&&t.source===`native_discovered`?t.id:t.nativeSessionId??t.id,c=await r.createSession({sessionId:t.id,model:o.model??t.model,cwd:t.projectPath,resumeSessionId:s,sessionConfig:o.sessionConfig,metadata:{resumeFromHistory:!0},logger:this.options.logger});if(n&&c.providerMode!==`native`)throw await c.close(),Error(`Native Codex provider is required, but adapter fell back to mock. Check ENABLE_NATIVE_PROVIDERS and Codex app-server availability.`);let l=this.resolveCanonicalSessionId(t.provider,c,t.id),u=this.resolveNativeSessionId(t.provider,c,t.nativeSessionId),d=await this.attachRuntimeSession({id:l,nativeSessionId:u,source:t.source??`gateway`,projectId:t.projectId,projectPath:t.projectPath,provider:t.provider,providerMode:c.providerMode,model:o.model??t.model,title:t.title,sessionTurnConfig:a,sessionTurnConfigUpdatedAt:t.sessionTurnConfigUpdatedAt,createdAt:t.createdAt,updatedAt:t.updatedAt||new Date().toISOString(),status:`idle`,providerSession:c,pendingToolApprovals:new Set,pendingUserInputs:new Set,streamReady:!0,bufferedProviderEvents:[],lastActiveAtMs:Date.now(),dispatchInFlight:!1,closing:!1});return await this.persistSessionSnapshot(d),d}async syncCodexSessionsForProject(e){if(!this.options.preferNativeProviders)return;let t;try{t=await fy(e.path)}catch{return}let n=new Set(t.filter(t=>t.cwd===e.path).map(e=>e.id)),r=new Map(this.options.historyStore.listProjectSessions(e.id,`all`).map(e=>[e.id,e])),i=[...r.values()].filter(e=>e.provider===`codex`&&e.source===`native_discovered`&&!this.sessions.has(e.id)&&!n.has(e.nativeSessionId??e.id)).map(e=>e.id);for(let e of i)await this.options.historyStore.removeSession(e),r.delete(e);for(let n of t){if(n.cwd!==e.path)continue;let t=[...r.values()].find(e=>e.provider===`codex`&&(e.id===n.id||e.nativeSessionId===n.id)),i=t?.id??n.id,a=this.sessions.get(i)??this.sessions.get(n.id),o=FS(n.createdAt),s=FS(n.updatedAt),c=a?.status===`running`?`running`:`idle`,l=c===`running`?a?.pendingToolApprovals.size??0:0,u=c===`running`?a?.pendingUserInputs.size??0:0,d={id:i,nativeSessionId:n.id,source:t?.source??`native_discovered`,projectId:e.id,projectPath:e.path,provider:`codex`,providerMode:a?.providerMode??t?.providerMode??`native`,model:eS({runtimeModel:a?.model,discoveredModel:n.model,existingModel:t?.model,modelProvider:n.modelProvider}),title:a?.title??MS(n.name??n.preview)??t?.title,sessionTurnConfig:a?.sessionTurnConfig??t?.sessionTurnConfig,sessionTurnConfigUpdatedAt:a?.sessionTurnConfigUpdatedAt??t?.sessionTurnConfigUpdatedAt,createdAt:t?.createdAt??o,updatedAt:c===`running`?a?.updatedAt??s:s,status:c,pendingApprovals:l,pendingUserInputs:u,pendingActions:l+u};await this.options.historyStore.upsertSession(d),r.set(i,d)}}async syncClaudeSessionsForProject(e){if(!this.options.preferNativeProviders)return;let t;try{t=await fb(e.path)}catch{return}let n=new Set(t.map(e=>e.nativeSessionId)),r=new Map(this.options.historyStore.listProjectSessions(e.id,`all`).map(e=>[e.id,e])),i=[...r.values()].filter(e=>e.provider===`claude`&&e.source===`native_discovered`&&!this.sessions.has(e.id)&&!n.has(e.nativeSessionId??e.id)).map(e=>e.id);for(let e of i)await this.options.historyStore.removeSession(e),r.delete(e);for(let n of t){let t=[...r.values()].find(e=>e.provider===`claude`&&(e.id===n.nativeSessionId||e.nativeSessionId===n.nativeSessionId)),i=t?.id??n.nativeSessionId,a=this.sessions.get(i),o=a?.status===`running`?`running`:`idle`,s=o===`running`?a?.pendingToolApprovals.size??0:0,c=o===`running`?a?.pendingUserInputs.size??0:0,l={id:i,nativeSessionId:n.nativeSessionId,source:t?.source??`native_discovered`,projectId:e.id,projectPath:e.path,provider:`claude`,providerMode:a?.providerMode??t?.providerMode??`native`,model:a?.model??t?.model??n.model,title:a?.title??n.title??t?.title,sessionTurnConfig:a?.sessionTurnConfig??t?.sessionTurnConfig,sessionTurnConfigUpdatedAt:a?.sessionTurnConfigUpdatedAt??t?.sessionTurnConfigUpdatedAt,createdAt:t?.createdAt??n.createdAt,updatedAt:o===`running`?a?.updatedAt??n.updatedAt:n.updatedAt,status:o,pendingApprovals:s,pendingUserInputs:c,pendingActions:s+c};await this.options.historyStore.upsertSession(l),r.set(i,l)}}async resolveProjectForSessionStart(e,t){if(!e&&!t)throw Error(`session.start requires projectId or cwd`);if(e&&t){let n=await this.options.projectStore.getById(e);if(!n)throw Wg(e);if((await this.options.projectStore.upsertByPath(t)).id!==n.id)throw Error(`projectId (${e}) does not match cwd (${t})`);return await IS(n.path),n}if(e){let t=await this.options.projectStore.getById(e);if(!t)throw Wg(e);return await IS(t.path),t}return this.options.projectStore.upsertByPath(t)}async attachRuntimeSession(e){let t=this.sessions.get(e.id);t&&await this.closeRuntimeSession(t.id,`replaced`,{suppressAudit:!0});let n={...e,unsubscribe:()=>{}};return await this.initializeRawSeqCursor(n.id),n.unsubscribe=n.providerSession.onEvent(e=>{if(!n.streamReady){n.bufferedProviderEvents.push(e);return}this.handleProviderEvent(n,e)}),this.sessions.set(n.id,n),n}handleProviderEvent(e,t){let n=this.ensureProviderRequestId(t);if(this.emitRawEnvelope(e,n),this.maybePersistUpdatedNativeSessionId(e),e.updatedAt=new Date().toISOString(),this.touchSession(e),n.type===`thread.title.updated`){let t=NS(n.title);t&&this.setSessionTitle(e,t);return}if(n.type===`turn.started`){e.status=`running`,this.persistSessionSnapshot(e);return}if(n.type===`turn.completed`||n.type===`turn.failed`){e.status=`idle`,this.persistSessionSnapshot(e);return}if(n.type===`error.runtime`){let t=NS(n.message);e.status!==`idle`&&this.options.logger?.warn?.({sessionId:e.id,nativeSessionId:e.nativeSessionId,provider:e.provider,providerMode:e.providerMode,projectId:e.projectId,projectPath:e.projectPath,model:e.model,previousStatus:e.status,nextStatus:`idle`,eventType:n.type,errorMessage:t},`provider session forced idle after error event`),e.status=`idle`,this.persistSessionSnapshot(e);return}if(n.type===`tool.permission.requested`){let t=typeof n.requestId==`string`?n.requestId:``;if(!t)return;e.pendingToolApprovals.add(t),this.persistSessionSnapshot(e);return}if(n.type===`tool.permission.resolved`&&typeof n.requestId==`string`){e.pendingToolApprovals.delete(n.requestId),this.persistSessionSnapshot(e);return}if(n.type===`user.input.requested`){let t=typeof n.requestId==`string`?n.requestId:``;if(!t)return;e.pendingUserInputs.add(t),this.persistSessionSnapshot(e);return}if(n.type===`user.input.resolved`&&typeof n.requestId==`string`){e.pendingUserInputs.delete(n.requestId),this.persistSessionSnapshot(e);return}}emitRawEnvelope(e,t){let n={v:`1.0`,kind:`provider.raw`,rawSeq:this.nextRawSeqSync(e.id),provider:e.provider,sessionId:e.id,projectId:e.projectId,eventId:`raw_${og(12)}`,ts:this.nextRawEnvelopeTimestamp(),type:t.type,payload:{raw:t}};this.options.onEnvelope(n),this.options.historyStore.appendRawEvent(n).catch(e=>{console.error(`[session-history] append raw event failed: ${String(e)}`)})}nextRawEnvelopeTimestamp(){let e=Date.now(),t=e>this.lastRawEnvelopeTimestampMs?e:this.lastRawEnvelopeTimestampMs+1;return this.lastRawEnvelopeTimestampMs=t,new Date(t).toISOString()}async initializeRawSeqCursor(e){if(this.nextRawSeqBySession.has(e))return;let t=await this.options.historyStore.getSessionRawSeqRange(e),n=t?t.max+1:1;this.nextRawSeqBySession.set(e,n)}async nextRawSeq(e){return await this.initializeRawSeqCursor(e),this.nextRawSeqSync(e)}nextRawSeqSync(e){let t=this.nextRawSeqBySession.get(e)??1;return this.nextRawSeqBySession.set(e,t+1),t}touchSession(e){e.lastActiveAtMs=Date.now()}isSessionEvictable(e){return!(e.closing||e.status!==`idle`||e.pendingToolApprovals.size>0||e.pendingUserInputs.size>0||e.dispatchInFlight)}async closeRuntimeSession(e,t,n){let r=this.sessions.get(e);if(!r||r.closing)return!1;r.closing=!0;let i=Date.now();this.options.logger?.info?.({sessionId:e,nativeSessionId:r.nativeSessionId,provider:r.provider,providerMode:r.providerMode,reason:t,statusBefore:r.status,projectId:r.projectId,projectPath:r.projectPath,model:r.model,pendingApprovalCount:r.pendingToolApprovals.size,pendingUserInputCount:r.pendingUserInputs.size,dispatchInFlight:r.dispatchInFlight},`provider runtime session close starting`);try{r.unsubscribe()}catch{}let a;try{await r.providerSession.close()}catch(n){a=n,console.error(`[session-runtime] failed closing session ${e}:`,n),this.options.logger?.error?.({sessionId:e,nativeSessionId:r.nativeSessionId,provider:r.provider,providerMode:r.providerMode,reason:t,projectId:r.projectId,projectPath:r.projectPath,model:r.model,error:String(n),err:n},`provider runtime session close failed`)}finally{r.status=`idle`,r.updatedAt=new Date().toISOString(),r.pendingToolApprovals.clear(),r.pendingUserInputs.clear();try{await this.persistSessionSnapshot(r)}catch(t){console.error(`[session-runtime] failed persisting closed session ${e}: ${String(t)}`)}this.sessions.delete(e),r.dispatchInFlight=!1,r.closing=!1}if(this.options.logger?.info?.({sessionId:e,nativeSessionId:r.nativeSessionId,provider:r.provider,providerMode:r.providerMode,reason:t,projectId:r.projectId,projectPath:r.projectPath,model:r.model,result:a?`error`:`success`,durationMs:Date.now()-i},`provider runtime session close completed`),!n?.suppressAudit)try{await this.options.auditLogger.record({ts:new Date().toISOString(),action:`session.runtime.close`,sessionId:e,detail:{reason:t,provider:r.provider}})}catch(e){console.error(`[session-runtime] failed to record runtime close audit log: ${String(e)}`)}return!0}async sweepRuntimeSessions(){if(this.shuttingDown||this.sessions.size===0)return;let e=Date.now(),t=this.runtimeLifecycle.idleTtlMs,n=[...this.sessions.values()].filter(e=>this.isSessionEvictable(e)).sort((e,t)=>e.lastActiveAtMs-t.lastActiveAtMs);for(let r of n)e-r.lastActiveAtMs<t||await this.closeRuntimeSession(r.id,`idle_ttl`);await this.enforceProviderSessionCap(`codex`,this.runtimeLifecycle.maxCodexSessions),await this.enforceProviderSessionCap(`claude`,this.runtimeLifecycle.maxClaudeSessions),await this.enforceGlobalSessionCap(this.runtimeLifecycle.maxSessions)}async enforceProviderSessionCap(e,t){let n=[...this.sessions.values()].filter(t=>t.provider===e);if(n.length<=t)return;let r=n.length-t,i=n.filter(e=>this.isSessionEvictable(e)).sort((e,t)=>e.lastActiveAtMs-t.lastActiveAtMs),a=0;for(let e of i){if(a>=r)break;await this.closeRuntimeSession(e.id,`lru_cap`)&&(a+=1)}a<r&&console.warn(`[session-runtime] ${e} sessions exceed cap (${n.length}/${t}), no more idle sessions to evict`)}async enforceGlobalSessionCap(e){if(this.sessions.size<=e)return;let t=this.sessions.size-e,n=[...this.sessions.values()].filter(e=>this.isSessionEvictable(e)).sort((e,t)=>e.lastActiveAtMs-t.lastActiveAtMs),r=0;for(let e of n){if(r>=t)break;await this.closeRuntimeSession(e.id,`lru_cap`)&&(r+=1)}r<t&&console.warn(`[session-runtime] session count exceeds cap (${this.sessions.size}/${e}), no more idle sessions to evict`)}ensureProviderRequestId(e){return e.type===`tool.permission.requested`||e.type===`user.input.requested`?typeof e.requestId==`string`&&e.requestId.trim()?e:{...e,requestId:`req_${og(8)}`}:e}async maybePersistSyncedExternalRawEvents(e,t,n){if(!n)return t;let r=await this.options.historyStore.mergeSessionRawEvents(e.id,t),i=r[r.length-1]?.rawSeq;return typeof i==`number`&&Number.isFinite(i)&&i>0&&this.nextRawSeqBySession.set(e.id,i+1),r}async syncExternalRawHistory(e,t,n){if(e.provider===`claude`){let r=TS(e);if(!r)return n;try{let i=Date.now(),a=await mb({projectPath:e.projectPath,nativeSessionId:r,provider:e.provider,sessionId:e.id,projectId:t}),o=Date.now(),s=await this.finalizeExternalRawHistorySync(e,n,a);return Ux(`sync-external.claude`,{projectId:t,sessionId:e.id,source:e.source,localEventCount:n.length,historyEventCount:a.length,resultEventCount:s.length,readHistoryDurationMs:o-i,finalizeDurationMs:Date.now()-o}),s}catch(r){return e.source===`native_discovered`&&wS(r)&&await this.markExternalHistoryHydrated(e.id,e.updatedAt),Ux(`sync-external.claude.error`,{projectId:t,sessionId:e.id,source:e.source,localEventCount:n.length,error:r instanceof Error?r.message:String(r)}),n}}if(e.provider!==`codex`)return n;let r=CS([e.nativeSessionId,e.id]);for(let i of r)try{let r=Date.now(),a=await my(i,!0),o=Date.now(),s=e.source===`gateway`&&n.length>0?kS({thread:a,provider:e.provider,sessionId:e.id,projectId:t,localEvents:n}):DS({thread:OS(a,n),provider:e.provider,sessionId:e.id,projectId:t}),c=Date.now(),l=await this.finalizeExternalRawHistorySync(e,n,s,FS(a.updatedAt));return Ux(`sync-external.codex`,{projectId:t,sessionId:e.id,source:e.source,threadId:i,localEventCount:n.length,historyEventCount:s.length,resultEventCount:l.length,readThreadDurationMs:o-r,buildHistoryDurationMs:c-o,finalizeDurationMs:Date.now()-c}),l}catch{}return n}async finalizeExternalRawHistorySync(e,t,n,r=e.updatedAt){let i=Date.now(),a=dS(e.provider,t,n),o=Date.now(),s=await this.maybePersistSyncedExternalRawEvents(e,a,!0);return await this.markExternalHistoryHydrated(e.id,r),Ux(`sync-external.finalize`,{sessionId:e.id,provider:e.provider,source:e.source,localEventCount:t.length,historyEventCount:n.length,mergedEventCount:a.length,persistedEventCount:s.length,hydratedExternalUpdatedAt:r,mergeDurationMs:o-i,persistDurationMs:Date.now()-o}),s}async markExternalHistoryHydrated(e,t){await this.options.historyStore.patchSession(e,{lastHydratedExternalUpdatedAt:t})}shouldAutoSyncGatewayCodexRawHistory(e,t){if(e.provider!==`codex`||e.providerMode!==`native`||e.source!==`gateway`||e.status===`running`)return!1;let n=Date.parse(e.updatedAt);if(!Number.isFinite(n))return!1;let r=e.lastHydratedExternalUpdatedAt?Date.parse(e.lastHydratedExternalUpdatedAt):NaN;if(Number.isFinite(r))return n>r+Kx;let i=t[t.length-1]?.ts,a=i?Date.parse(i):NaN;return Number.isFinite(a)?n>a+Kx:!1}async maybeSyncExternalRawHistoryForRead(e,t,n,r){let i=r?.forceSyncExternal===!0||this.shouldAutoSyncGatewayCodexRawHistory(e,n);if(Ux(`sync-external.decision`,{projectId:t,sessionId:e.id,provider:e.provider,source:e.source,providerMode:e.providerMode,localEventCount:n.length,forceSyncExternal:r?.forceSyncExternal===!0,shouldSyncExternal:i}),!i)return{session:e,rawEvents:n};let a=await this.options.historyStore.getSessionRawEvents(e.id,2**53-1),o=await this.syncExternalRawHistory(e,t,a);return{session:this.options.historyStore.getProjectSession(t,e.id)??e,rawEvents:o}}mustGetSession(e){let t=this.sessions.get(e);if(!t)throw Kg(e);return t}markSessionStreamReady(e){if(e.streamReady||(e.streamReady=!0,e.bufferedProviderEvents.length===0))return;let t=[...e.bufferedProviderEvents];e.bufferedProviderEvents.length=0;for(let n of t)this.handleProviderEvent(e,n)}async persistSessionSnapshot(e){await this.options.historyStore.upsertSession(this.toSessionSummary(e))}listAllSessionsWithRuntime(e=`all`){let t=new Map(this.options.historyStore.listSessions(`all`).map(e=>[e.id,e]));for(let e of this.sessions.values())(!t.get(e.id)||e.status===`running`)&&t.set(e.id,this.toSessionSummary(e));return[...t.values()].filter(t=>e===`all`||t.status===e).sort((e,t)=>{let n=e.updatedAt||e.createdAt;return(t.updatedAt||t.createdAt).localeCompare(n)})}listProjectSessionsWithRuntime(e,t=`all`){return this.listAllSessionsWithRuntime(t).filter(t=>t.projectId===e)}getRuntimeSessionSummary(e,t,n){let r=this.sessions.get(t);if(!(!r||r.projectId!==e)&&!(r.status!==`running`&&n))return this.toSessionSummary(r)}toSessionSummary(e){return{id:e.id,nativeSessionId:e.nativeSessionId,source:e.source,...e.source===`gateway`?{lastHydratedExternalUpdatedAt:e.updatedAt}:{},projectId:e.projectId,projectPath:e.projectPath,provider:e.provider,providerMode:e.providerMode,model:e.model,title:e.title,sessionTurnConfig:e.sessionTurnConfig,sessionTurnConfigUpdatedAt:e.sessionTurnConfigUpdatedAt,createdAt:e.createdAt,updatedAt:e.updatedAt,status:e.status,pendingApprovals:e.pendingToolApprovals.size,pendingUserInputs:e.pendingUserInputs.size,pendingActions:e.pendingToolApprovals.size+e.pendingUserInputs.size}}setSessionTitle(e,t){let n=jS(t);!n||n===e.title||(e.title=n,e.updatedAt=new Date().toISOString(),this.persistSessionSnapshot(e))}resolveCanonicalSessionId(e,t,n){return e===`codex`&&t.getNativeSessionId?.()||n}resolveNativeSessionId(e,t,n){return e!==`codex`&&e!==`claude`?n:t.getNativeSessionId?.()||n}maybePersistUpdatedNativeSessionId(e){let t=this.resolveNativeSessionId(e.provider,e.providerSession,e.nativeSessionId);!t||t===e.nativeSessionId||this.shouldPersistNativeSessionId(e,t)&&(e.nativeSessionId=t,e.updatedAt=new Date().toISOString(),this.persistSessionSnapshot(e))}shouldPersistNativeSessionId(e,t){return e.source===`native_discovered`?!1:e.nativeSessionId?e.nativeSessionId===e.id&&e.id.startsWith(`sess_`)?t!==e.nativeSessionId:!1:!0}};const sS=new Set([`thread.started`,`thread.title.updated`,`turn.started`,`turn.completed`,`turn.failed`,`item.started`,`item.updated`,`item.completed`]),cS=new Set([`thread.started`,`thread.title.updated`,`turn.started`,`turn.completed`,`turn.failed`,`item.started`,`item.updated`,`item.completed`]),lS=new Set([`claude.history.getSessionMessages`,`claude.history.jsonl`]);function uS(e,t,n){let r=new Map;for(let t of e)r.set(t.eventId,t);for(let e of t)r.set(e.eventId,e);return[...r.values()].sort((e,t)=>e.ts.localeCompare(t.ts)).slice(-Math.max(1,n))}function dS(e,t,n){let r=new Map,i=new Set;for(let n of t){r.set(n.eventId,n);for(let t of mS(e,n))i.add(t)}for(let t of n){if(r.has(t.eventId))continue;let n=mS(e,t);if(!(n.length>0&&n.every(e=>i.has(e)))){r.set(t.eventId,t);for(let e of n)i.add(e)}}return[...r.values()].sort((e,t)=>e.ts.localeCompare(t.ts))}function fS(e,t,n,r){let i=new Map,a=new Map;for(let t of e)if(i.set(t.eventId,t),n.has(t.type)){let e=pS(t);a.set(e,(a.get(e)??0)+1)}for(let e of t){if(!n.has(e.type))continue;let t=pS(e),r=a.get(t)??0;if(r>0){r===1?a.delete(t):a.set(t,r-1);continue}i.set(e.eventId,e)}return[...i.values()].sort((e,t)=>e.ts.localeCompare(t.ts)).slice(-Math.max(1,r))}function pS(e){let t=yS(e.payload.raw),n=yS(t.item),r=yS(t.turn),i=$(t.turn_id)??$(t.turnId)??$(r.id)??``,a=$(r.status)??$(t.status)??``,o=$(t.thread_id)??$(t.threadId)??``,s=$(n.type)??``,c=$(n.phase)??``,l=$(n.status)??``,u=$(n.command)??``,d=xS(n),f=bS(t.message)??``,p=bS(t.title)??``;return e.type.startsWith(`item.`)?[e.type,s,c,l,u,d||f].join(`|`):e.type.startsWith(`turn.`)?[e.type,i,a].join(`|`):e.type===`thread.title.updated`?[e.type,p].join(`|`):[e.type,o,i,s,p||f].join(`|`)}function mS(e,t){return e===`codex`?hS(t):e===`claude`?gS(t):[]}function hS(e){let t=yS(e.payload.raw),n=_S(e.type,t);if(n)return[n];if(e.type!==`native.raw`||$(t.source)!==`codex.history.thread_read`)return[];let r=yS(t.message),i=$(r.scope);if(i===`thread`){let e=yS(r.thread),t=$(e.id),n=[];t&&n.push(vS(`thread.started`,{thread_id:t,thread:e}));let i=MS(bS(e.preview)??bS(e.name)??``);return i&&n.push(vS(`thread.title.updated`,{title:i,thread_id:t})),n}if(i===`turn`){let e=yS(r.turn),t=$(e.status),n=[vS(`turn.started`,{turn:e})];return t===`completed`?n.push(vS(`turn.completed`,{status:t,turn:e})):(t===`failed`||t===`interrupted`)&&n.push(vS(`turn.failed`,{status:t,turn:e})),n}return i===`item`?[vS(`item.completed`,{turn_id:$(r.turn_id)??$(yS(r.item).turn_id),item:yS(r.item)})]:[]}function gS(e){let t=yS(e.payload.raw),n=_S(e.type,t);if(n)return[n];if(e.type!==`native.raw`)return[];let r=$(t.source);if(!r||!lS.has(r))return[];let i=yS(t.message),a=$(t.native_type)??$(i.type),o=yS(i.message);if(a===`user`){let e=SS(o),t=$(i.uuid);return!e||!t?[]:[vS(`item.completed`,{item:{id:t,type:`user_message`,text:e}})]}if(a===`assistant`){let e=SS(o),t=$(o.id)??$(i.uuid);return!e||!t?[]:[vS(`item.completed`,{item:{id:t,type:`agent_message`,text:e}})]}return[]}function _S(e,t){switch(e){case`thread.started`:case`thread.title.updated`:case`turn.started`:case`turn.completed`:case`turn.failed`:case`item.started`:case`item.updated`:case`item.completed`:return vS(e,t);default:return}}function vS(e,t){let n=yS(t.item),r=yS(t.turn),i=yS(t.thread),a=$(n.id)??``,o=$(t.turn_id)??$(t.turnId)??$(r.id)??$(n.turn_id)??``,s=$(r.status)??$(t.status)??``,c=$(t.thread_id)??$(t.threadId)??$(i.id)??``,l=$(n.type)??``,u=$(n.phase)??``,d=$(n.status)??``,f=$(n.command)??``,p=xS(n),m=bS(t.message)??``,h=bS(t.title)??``;return e.startsWith(`item.`)?[e,a,l,u,d,f,p||m].join(`|`):e.startsWith(`turn.`)?[e,o,s].join(`|`):e===`thread.title.updated`?[e,c,h].join(`|`):[e,c,o,a,l,h||m].join(`|`)}function yS(e){return typeof e==`object`&&e?e:{}}function $(e){return typeof e==`string`&&e.trim()||void 0}function bS(e){if(typeof e==`string`)return e.length>0?e:void 0}function xS(e){let t=bS(e.text);if(t)return t;let n=Array.isArray(e.content)?e.content:[];if(n.length>0){let e=[];for(let t of n){let n=bS(yS(t).text);n&&e.push(n)}if(e.length>0)return e.join(`
|
|
482
|
+
`)}let r=Array.isArray(e.summary)?e.summary:[];if(r.length>0){let e=r.map(e=>bS(e)).filter(e=>!!e);if(e.length>0)return e.join(`
|
|
483
|
+
`)}return``}function SS(e){let t=$(e.content);if(t)return t;let n=$(e.text)??$(e.prompt);if(n)return n;let r=Array.isArray(e.content)?e.content:[],i=[];for(let e of r){if(typeof e==`string`){let t=e.trim();t&&i.push(t);continue}let t=yS(e),n=$(t.type);if(n&&n!==`text`)continue;let r=$(t.text)??$(t.content);r&&i.push(r)}if(i.length!==0)return i.join(`
|
|
484
|
+
`)}function CS(e){let t=new Set;for(let n of e)n&&t.add(n);return[...t]}function wS(e){return String(e).includes(`returned no messages from getSessionMessages`)}function TS(e){return e.source===`native_discovered`?e.id:e.nativeSessionId}function ES(e){let t=[],n=e.thread.createdAt>0?e.thread.createdAt*1e3:Date.now(),r=0,i=()=>(r+=1,new Date(n+r).toISOString()),a=(n,a)=>{let o=`hist_${e.sessionId}_${r.toString().padStart(6,`0`)}_${n.replace(/\./g,`_`)}`;t.push({v:`1.0`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:o,ts:i(),type:n,payload:{raw:a}})};a(`thread.started`,{thread_id:e.thread.id,thread:{id:e.thread.id,preview:e.thread.preview,model_provider:e.thread.modelProvider,created_at:e.thread.createdAt,updated_at:e.thread.updatedAt,path:e.thread.path,cwd:e.thread.cwd,cli_version:e.thread.cliVersion,source:e.thread.source,git_info:e.thread.gitInfo,turns:[]}});let o=MS(e.thread.name??e.thread.preview);o&&a(`thread.title.updated`,{title:o,source:e.thread.name?`codex.thread_name`:`codex.thread_read_preview`,thread_id:e.thread.id});for(let t of e.thread.turns){let e={id:t.id,status:t.status,items:[],error:t.error};a(`turn.started`,{turn:e});for(let e of t.items)a(`item.completed`,{turn_id:t.id,item:e});if(t.status===`failed`||t.status===`interrupted`){a(`turn.failed`,{status:t.status,turn:e,error:t.error??{message:t.status===`interrupted`?`Turn interrupted`:`Turn failed`}});continue}t.status===`completed`&&a(`turn.completed`,{status:t.status,turn:e})}return t}function DS(e){let t=[],n=e.thread.createdAt>0?e.thread.createdAt*1e3:Date.now(),r=0,i=()=>(r+=1,new Date(n+r).toISOString()),a=n=>{let a=t.length+1,o=`raw_hist_codex_${e.sessionId}_${r.toString().padStart(6,`0`)}`;t.push({v:`1.0`,kind:`provider.raw`,rawSeq:a,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:o,ts:i(),type:`native.raw`,payload:{raw:{source:`codex.history.thread_read`,native_type:`thread.read.snapshot`,message:n,historyReplay:!0,replaySynthetic:!0}}})};a({scope:`thread`,thread:{id:e.thread.id,preview:e.thread.preview,model_provider:e.thread.modelProvider,created_at:e.thread.createdAt,updated_at:e.thread.updatedAt,path:e.thread.path,cwd:e.thread.cwd,cli_version:e.thread.cliVersion,source:e.thread.source,git_info:e.thread.gitInfo}});for(let t of e.thread.turns){a({scope:`turn`,thread_id:e.thread.id,turn:{id:t.id,status:t.status,error:t.error}});for(let n of t.items)a({scope:`item`,thread_id:e.thread.id,turn_id:t.id,item:n})}return t}function OS(e,t){if(t.length===0)return e;let n=new Set;for(let e of t){let t=yS(e.payload.raw);if(e.type===`turn.completed`||e.type===`turn.failed`){let e=$(t.turn_id)??$(t.turnId)??$(yS(t.turn).id)??$(yS(t.item).turn_id)??$(yS(t.item).turnId);e&&n.add(e);continue}if(e.type!==`native.raw`||$(t.source)!==`codex.history.thread_read`)continue;let r=yS(t.message);if($(r.scope)===`turn`){let e=yS(r.turn),t=$(e.id),i=$(e.status);t&&i&&AS(i)&&n.add(t)}}return n.size===0?e:{...e,turns:e.turns.filter(e=>!n.has(e.id))}}function kS(e){let t=new Set,n=new Set,r=new Map,i=new Set,a=0,o=1;for(let s of e.localEvents){let e=Date.parse(s.ts);Number.isFinite(e)&&(a=Math.max(a,e)),o=Math.max(o,s.rawSeq+1);let c=yS(s.payload.raw);if(s.type===`item.started`||s.type===`item.updated`||s.type===`item.completed`){let e=$(c.turn_id)??$(c.turnId)??$(yS(c.turn).id)??$(yS(c.item).turn_id)??$(yS(c.item).turnId);e&&i.add(e)}if(s.type===`turn.started`){let e=$(c.turn_id)??$(yS(c.turn).id);e&&t.add(e);continue}if(s.type===`item.completed`){let e=$(yS(c.item).id);e&&n.add(e);continue}if(s.type===`turn.completed`||s.type===`turn.failed`){let e=$(c.turn_id)??$(yS(c.turn).id);if(!e)continue;t.add(e);let n=$(c.status)??(s.type===`turn.completed`?`completed`:`failed`);r.set(e,n)}if(s.type!==`native.raw`||$(c.source)!==`codex.history.thread_read`)continue;let l=yS(c.message),u=$(l.scope);if(u===`turn`){let e=yS(l.turn),n=$(e.id);if(!n)continue;t.add(n);let i=$(e.status);i&&AS(i)&&r.set(n,i);continue}if(u===`item`){let e=$(l.turn_id)??$(yS(l.item).turn_id);e&&i.add(e);let t=$(yS(l.item).id);t&&n.add(t)}}let s=Math.max(a,e.thread.createdAt>0?e.thread.createdAt*1e3:Date.now()),c=0,l=()=>(c+=1,new Date(s+c).toISOString()),u=[],d=(t,n)=>{let r=l();u.push({v:`1.0`,kind:`provider.raw`,rawSeq:o,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`raw_sync_codex_${e.sessionId}_${o.toString().padStart(6,`0`)}`,ts:r,type:t,payload:{raw:{...n,historyReplay:!0,replaySynthetic:!0,source:`codex.history.thread_read.incremental`}}}),o+=1};for(let a of e.thread.turns){let e=t.has(a.id),o=i.has(a.id);if(e||d(`turn.started`,{type:`turn.started`,turn:{id:a.id,status:a.status,items:[],error:a.error}}),!o)for(let e of a.items){let t=$(e.id);t&&n.has(t)||d(`item.completed`,{type:`item.completed`,turn_id:a.id,item:e})}if(AS(a.status)&&r.get(a.id)!==a.status){if(a.status===`completed`){d(`turn.completed`,{type:`turn.completed`,status:a.status,turn:{id:a.id,status:a.status,items:[],error:a.error}});continue}d(`turn.failed`,{type:`turn.failed`,status:a.status,turn:{id:a.id,status:a.status,items:[],error:a.error},...a.error?{error:a.error}:{}})}}return u}function AS(e){return e===`completed`||e===`failed`||e===`interrupted`}function jS(e){let t=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,``).replace(/\s+/g,` `).trim();if(t)return t}function MS(e,t=60){let n=jS(e);if(!n)return;let r=Array.from(n);return r.length<=t?n:r.slice(0,t).join(``).trimEnd()}function NS(e){if(typeof e!=`string`)return;let t=jS(e);if(t)return t}function PS(e){let t=0;for(let n of Object.values(e))n.some(e=>e.trim().length>0)&&(t+=1);return t}function FS(e){return!Number.isFinite(e)||e<=0?new Date().toISOString():new Date(e*1e3).toISOString()}async function IS(e){if(!(await d.default.stat(e)).isDirectory())throw Error(`Project path is not a directory: ${e}`)}var LS=class{indexPath;eventsDir;sessions=new Map;rawEventsCacheBySession=new Map;compactedRawEventsCacheBySession=new Map;pendingRawMutationsBySession=new Map;ready;writeQueue=Promise.resolve();constructor(e){this.baseDir=e,this.indexPath=p.default.join(e,`session-index.json`),this.eventsDir=p.default.join(e,`session-events`),this.ready=this.loadFromDisk()}async init(){await this.ready}async flushRawCompactions(e){await this.ready}async shutdown(){await this.ready}async upsertSession(e){await this.ready;let t=this.sessions.get(e.id);this.sessions.set(e.id,{...t,...e}),await this.enqueueWrite(async()=>{await this.persistIndex()})}async patchSession(e,t){await this.ready;let n=this.sessions.get(e);return n?(this.sessions.set(e,{...n,...t}),await this.enqueueWrite(async()=>{await this.persistIndex()}),!0):!1}async setSessionStatus(e,t,n){await this.ready;let r=this.sessions.get(e);r&&(this.sessions.set(e,{...r,status:t,updatedAt:n,pendingApprovals:t===`running`?r.pendingApprovals:0,pendingUserInputs:t===`running`?r.pendingUserInputs:0,pendingActions:t===`running`?r.pendingActions:0}),await this.enqueueWrite(async()=>{await this.persistIndex()}))}async removeSession(e){if(await this.ready,!this.sessions.has(e))return;this.sessions.delete(e),this.rawEventsCacheBySession.delete(e),this.compactedRawEventsCacheBySession.delete(e);let t=p.default.join(this.eventsDir,`${e}.jsonl`),n=p.default.join(this.eventsDir,`${e}.raw.jsonl`);await this.enqueueWrite(async()=>{await Promise.all([this.persistIndex(),d.default.rm(t,{force:!0}),d.default.rm(n,{force:!0})])})}hasSession(e){return this.sessions.has(e)}getSession(e){return this.sessions.get(e)}getProjectSession(e,t){let n=this.sessions.get(t);if(!(!n||n.projectId!==e))return n}listSessions(e=`all`){return[...this.sessions.values()].filter(t=>e===`all`||t.status===e).sort((e,t)=>{let n=e.updatedAt||e.createdAt;return(t.updatedAt||t.createdAt).localeCompare(n)})}listProjectSessions(e,t=`all`){return this.listSessions(t).filter(t=>t.projectId===e)}async appendEvent(e){if(await this.ready,!this.sessions.has(e.sessionId))return;let t=p.default.join(this.eventsDir,`${e.sessionId}.jsonl`),n=`${JSON.stringify(e)}\n`;await this.enqueueWrite(async()=>{await d.default.appendFile(t,n,`utf8`)})}async appendRawEvent(e){await this.ready,this.sessions.has(e.sessionId)&&await this.enqueueRawSessionWrite(e.sessionId,async()=>{await this.appendRawEventLine(e),this.appendRawEventToCache(e)})}async mergeSessionRawEvents(e,t){if(await this.ready,!this.sessions.has(e))return[];let n=t.filter(t=>t.sessionId===e),r=[];return await this.enqueueRawSessionWrite(e,async()=>{r=KS(await this.readSessionRawEventsLocked(e),n);let t=p.default.join(this.eventsDir,`${e}.raw.jsonl`),i=r.map(e=>BS(e)).join(`
|
|
485
|
+
`);await d.default.writeFile(t,i?`${i}\n`:``,`utf8`),this.rawEventsCacheBySession.set(e,r),this.compactedRawEventsCacheBySession.set(e,HS(r))}),r}async getSessionRawEvents(e,t=300){return this.getSessionRawEventsCompacted(e,t)}async getSessionRawEventsCompacted(e,t=300){if(await this.ready,!this.sessions.has(e))return[];let n=Math.max(1,t),r=this.readSessionRawEventsCompactedFromCache(e);if(r!==void 0)return r.slice(-n);let i=[];return await this.enqueueWrite(async()=>{i=(await this.readSessionRawEventsCompactedLocked(e)).slice(-n)}),i}async getSessionRawEventsSinceSeq(e,t,n=2e3){if(await this.ready,!this.sessions.has(e))return[];let r=Math.max(1,n),i=this.readSessionRawEventsFromCache(e);if(i!==void 0)return i.filter(e=>e.rawSeq>t).slice(0,r);let a=[];return await this.enqueueWrite(async()=>{a=(await this.readSessionRawEventsLocked(e)).filter(e=>e.rawSeq>t).slice(0,r)}),a}async getSessionRawSeqRange(e){if(await this.ready,!this.sessions.has(e))return null;let t=this.readSessionRawEventsFromCache(e);if(t!==void 0)return VS(t);let n=null;return await this.enqueueWrite(async()=>{n=VS(await this.readSessionRawEventsLocked(e))}),n}async getSessionEvents(e,t=300){await this.ready;let n=p.default.join(this.eventsDir,`${e}.jsonl`);try{return(await d.default.readFile(n,`utf8`)).split(`
|
|
486
|
+
`).map(e=>e.trim()).filter(Boolean).map(e=>{try{return JSON.parse(e)}catch{return null}}).filter(e=>e!==null).slice(-Math.max(1,t))}catch(e){if(e.code===`ENOENT`)return[];throw e}}async loadFromDisk(){await d.default.mkdir(this.eventsDir,{recursive:!0});try{let e=await d.default.readFile(this.indexPath,`utf8`),t=JSON.parse(e);if(t.v!==1||!Array.isArray(t.sessions))return;for(let e of t.sessions)e?.id&&e?.provider&&e?.createdAt&&e?.updatedAt&&e?.status&&e?.projectId&&e?.projectPath&&this.sessions.set(e.id,{...e,status:`idle`,pendingApprovals:0,pendingUserInputs:0,pendingActions:0})}catch(e){if(e.code!==`ENOENT`)throw e}}async persistIndex(){await d.default.mkdir(this.baseDir,{recursive:!0});let e={v:1,sessions:[...this.sessions.values()].sort((e,t)=>{let n=e.updatedAt||e.createdAt;return(t.updatedAt||t.createdAt).localeCompare(n)})};await d.default.writeFile(this.indexPath,`${JSON.stringify(e,null,2)}\n`,`utf8`)}enqueueWrite(e){return this.writeQueue=this.writeQueue.then(e,e),this.writeQueue}async enqueueRawSessionWrite(e,t){this.incrementPendingRawMutation(e);try{let e;return await this.enqueueWrite(async()=>{e=await t()}),e}finally{this.decrementPendingRawMutation(e)}}async appendRawEventLine(e){let t=p.default.join(this.eventsDir,`${e.sessionId}.raw.jsonl`),n=`${BS(e)}\n`;await d.default.appendFile(t,n,`utf8`)}appendRawEventToCache(e){let t=this.rawEventsCacheBySession.get(e.sessionId),n=t?.[t.length-1];t&&t.push(e);let r=this.compactedRawEventsCacheBySession.get(e.sessionId);if(r){if(n&&GS(e,n)<0){this.compactedRawEventsCacheBySession.delete(e.sessionId);return}WS(r,e)}}async readSessionRawEventsCompactedLocked(e){let t=this.compactedRawEventsCacheBySession.get(e);if(t)return US(t);let n=HS(await this.readSessionRawEventsLocked(e));return this.compactedRawEventsCacheBySession.set(e,n),US(n)}async readSessionRawEventsLocked(e){let t=this.rawEventsCacheBySession.get(e);if(t)return t;let n=p.default.join(this.eventsDir,`${e}.raw.jsonl`),r;try{r=await d.default.readFile(n,`utf8`)}catch(t){if(t.code===`ENOENT`)return this.rawEventsCacheBySession.set(e,[]),[];throw t}let i=r.split(`
|
|
487
|
+
`).map(e=>e.trim()).filter(Boolean),a=[];for(let e of i)try{let t=JSON.parse(e);if(!RS(t)||t.kind!==`provider.raw`)continue;let n=zS(t.rawSeq);a.push({value:t,...n===void 0?{}:{rawSeq:n}})}catch{}if(a.length===0)return this.rawEventsCacheBySession.set(e,[]),[];let o=a.some(e=>e.rawSeq===void 0),s=a.map((e,t)=>({...e.value,rawSeq:e.rawSeq??t+1})),c=[];for(let e of s){let t=ua.safeParse(e);t.success&&c.push(t.data)}if(o){let e=c.map(e=>BS(e)).join(`
|
|
488
|
+
`),t=e?`${e}\n`:``;await d.default.writeFile(n,t,`utf8`)}return this.rawEventsCacheBySession.set(e,c),c}readSessionRawEventsFromCache(e){if(!this.hasPendingRawMutation(e))return this.rawEventsCacheBySession.get(e)}readSessionRawEventsCompactedFromCache(e){if(this.hasPendingRawMutation(e))return;let t=this.compactedRawEventsCacheBySession.get(e);if(t)return US(t);let n=this.rawEventsCacheBySession.get(e);if(!n)return;let r=HS(n);return this.compactedRawEventsCacheBySession.set(e,r),US(r)}incrementPendingRawMutation(e){this.pendingRawMutationsBySession.set(e,(this.pendingRawMutationsBySession.get(e)??0)+1)}decrementPendingRawMutation(e){let t=(this.pendingRawMutationsBySession.get(e)??0)-1;if(t>0){this.pendingRawMutationsBySession.set(e,t);return}this.pendingRawMutationsBySession.delete(e)}hasPendingRawMutation(e){return(this.pendingRawMutationsBySession.get(e)??0)>0}};function RS(e){return typeof e==`object`&&!!e}function zS(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function BS(e){let t=new WeakSet;return JSON.stringify(e,(e,n)=>{if(typeof n==`bigint`)return n.toString();if(typeof n==`function`)return`[Function ${n.name||`anonymous`}]`;if(typeof n==`object`&&n){if(t.has(n))return`[Circular]`;t.add(n)}return n})}function VS(e){if(e.length===0)return null;let t=e[0],n=e[e.length-1];return!t||!n?null:{min:t.rawSeq,max:n.rawSeq}}function HS(e){let t=Es(e),n=t.map(e=>e),r=new Map;for(let[e,t]of n.entries()){let n=Ds(t);n&&r.set(n.key,e)}return{slots:n,indexByKey:r,dense:t}}function US(e){return e.dense||=e.slots.filter(e=>e!==null),e.dense}function WS(e,t){let n=Ds(t);if(!n){e.slots.push(t),e.dense=null;return}let r=e.indexByKey.get(n.key);if(r===void 0){e.slots.push(t),e.indexByKey.set(n.key,e.slots.length-1),e.dense=null;return}let i=e.slots[r];if(!i){e.slots.push(t),e.indexByKey.set(n.key,e.slots.length-1),e.dense=null;return}let a=Os(i,t);if(!a){e.slots.push(t),e.indexByKey.set(n.key,e.slots.length-1),e.dense=null;return}e.slots[r]=null,e.slots.push(a),e.indexByKey.set(n.key,e.slots.length-1),e.dense=null}function GS(e,t){let n=e.ts.localeCompare(t.ts);return n===0?e.eventId.localeCompare(t.eventId):n}function KS(e,t){let n=new Map;for(let t of e)n.set(t.eventId,t);for(let e of t)n.set(e.eventId,e);return[...n.values()].sort((e,t)=>{let n=e.ts.localeCompare(t.ts);return n===0?e.eventId.localeCompare(t.eventId):n}).map((e,t)=>({...e,rawSeq:t+1}))}var qS=class{clients=new Map;clientIdsBySessionId=new Map;deliveryStateByClientSession=new Map;addClient(e,t){let n=`ws_${og(10)}`;return this.clients.set(n,{id:n,deviceId:e,socket:t,subscriptionsBySessionId:new Map}),n}removeClient(e){let t=this.clients.get(e);t&&(this.removeClientFromSessionIndexes(e,t.subscriptionsBySessionId.keys()),this.removeClientDeliveryState(e),this.clients.delete(e))}replaceSubscriptions(e,t,n=!0){let r=this.clients.get(e);if(!r)return[];n&&(this.removeClientFromSessionIndexes(e,r.subscriptionsBySessionId.keys()),this.removeClientSessionDeliveryState(e,r.subscriptionsBySessionId.keys()),r.subscriptionsBySessionId.clear());let i=new Map;for(let e of t)i.set(e.sessionId,e);for(let[t,n]of i){r.subscriptionsBySessionId.set(t,n);let i=this.clientIdsBySessionId.get(t)??new Set;i.add(e),this.clientIdsBySessionId.set(t,i),this.ensureClientSessionDeliveryState(e,t)}return[...r.subscriptionsBySessionId.values()]}getSubscriptions(e){let t=this.clients.get(e);return t?[...t.subscriptionsBySessionId.values()]:[]}routeProviderRaw(e){let t=this.clientIdsBySessionId.get(e.sessionId);if(!t||t.size===0)return;let n=JSON.stringify(e);for(let r of t){let t=this.deliveryStateByClientSession.get(this.clientSessionKey(r,e.sessionId));if(t?.paused){t.queued.push(e);continue}let i=this.clients.get(r);!i||i.socket.readyState!==i.socket.OPEN||i.socket.send(n)}}pauseSession(e,t){let n=this.ensureClientSessionDeliveryState(e,t);n.paused=!0}resumeSession(e,t){let n=this.clientSessionKey(e,t),r=this.deliveryStateByClientSession.get(n);if(!r||(r.paused=!1,r.queued.length===0))return;let i=this.clients.get(e);if(!i||i.socket.readyState!==i.socket.OPEN){r.queued=[];return}let a=[...r.queued].sort((e,t)=>e.rawSeq-t.rawSeq);r.queued=[];for(let e of a)i.socket.send(JSON.stringify(e))}sendStreamMessage(e,t){let n=this.clients.get(e);!n||n.socket.readyState!==n.socket.OPEN||n.socket.send(JSON.stringify(t))}sendSystemMessage(e,t){let n=this.clients.get(e);!n||n.socket.readyState!==n.socket.OPEN||n.socket.send(JSON.stringify(t))}broadcastSystemMessage(e){let t=JSON.stringify(e);for(let e of this.clients.values())e.socket.readyState===e.socket.OPEN&&e.socket.send(t)}count(){return this.clients.size}removeClientFromSessionIndexes(e,t){for(let n of t){let t=this.clientIdsBySessionId.get(n);t&&(t.delete(e),t.size===0&&this.clientIdsBySessionId.delete(n))}}clientSessionKey(e,t){return`${e}::${t}`}ensureClientSessionDeliveryState(e,t){let n=this.clientSessionKey(e,t),r=this.deliveryStateByClientSession.get(n);if(r)return r;let i={paused:!1,queued:[]};return this.deliveryStateByClientSession.set(n,i),i}removeClientSessionDeliveryState(e,t){for(let n of t)this.deliveryStateByClientSession.delete(this.clientSessionKey(e,n))}removeClientDeliveryState(e){let t=`${e}::`;for(let e of this.deliveryStateByClientSession.keys())e.startsWith(t)&&this.deliveryStateByClientSession.delete(e)}};async function JS(e,t={}){await ql(e.gatewayLogPath);let n=XS(e,t),r=YS(e,n.instance);await r.register(tg.default,{origin:!0}),await r.register(eg.default);let i=process.env.NODE_ENV!==`production`,a=4e3,o=`[unserializable payload]`,s=new $g(e);await s.init();let c=new a_(e.auditLogPath),l=new qS,u=new W_,d=new $_(e.projectStoreDir),f=new LS(e.sessionHistoryDir);await f.init();let m=new ex(p.default.join(e.sessionHistoryDir,`discovery-v1`));await m.init();let h=new Vb({store:m});await h.init();let g,_=null,v=await zs(e.authStoreDir),y=new oS({preferNativeProviders:e.enableNativeProviders,requireNativeCodex:e.requireNativeCodex,auditLogger:c,projectStore:d,historyStore:f,logger:r.log,runtimeLifecycle:{idleTtlMs:e.runtimeIdleTtlMs,sweepIntervalMs:e.runtimeSweepIntervalMs,maxSessions:e.runtimeMaxSessions,maxCodexSessions:e.runtimeMaxCodexSessions,maxClaudeSessions:e.runtimeMaxClaudeSessions},onEnvelope:e=>{l.routeProviderRaw(e)}});y.warmStartupProviderCapabilities().catch(e=>{r.log.warn({err:e},`startup provider capability warmup failed`)});let b=new pl({packageName:te.packageName,currentVersion:te.version,sessionHub:l,logger:r.log,consoleWrite:e=>{console.log(e)},getRunningSessionCount:async()=>(await y.listProjects()).reduce((e,t)=>e+(t.runningCount??0),0),requestPreparedUpdate:t.onUpdatePrepared});r.addHook(`onClose`,async()=>{r.log.info({hasRelayClient:!!_},`gateway shutdown starting`);try{_?.close(),x.close(),await b.shutdown(),await y.shutdown(),await f.shutdown(),r.log.info(`gateway shutdown completed`)}catch(e){throw r.log.error({err:e},`gateway shutdown failed`),e}finally{n.close()}}),i&&r.addHook(`onSend`,async(e,t,n)=>(r.log.info({method:e.method,url:e.url,statusCode:t.statusCode,responseBody:N(n)},`gateway response (dev)`),n)),r.get(`/health`,async()=>({ok:!0,service:`desktop-gateway`,now:new Date().toISOString(),wsClients:l.count(),machineName:Xc(),gatewayIdentity:v.identity})),r.get(`/api/pairing/descriptor`,async()=>Gc({gatewayId:e.gatewayId,machineName:Xc(),relayBaseUrl:e.relayEnabled?il({relayUrl:e.relayUrl,gatewayHost:e.host}):``,directBaseUrls:nl({protocol:e.httpsEnabled?`https`:`http`,host:e.host,port:e.httpsEnabled?e.httpsPort:e.port}),gatewayIdentity:v.identity})),r.post(`/api/pairing/start`,async(t,n)=>{if(!ee(t))return n.code(401).send({error:`Unauthorized`});try{let t=await s.createPairingCode(e.pairingCodeTtlSeconds);return await c.record({ts:new Date().toISOString(),action:`pairing.start`,detail:{expiresAt:t.expiresAt,source:`api`,ttlSeconds:e.pairingCodeTtlSeconds}}),t}catch(e){return r.log.error({err:e},`failed to generate pairing code via API`),n.code(500).send({error:`Failed to generate pairing code`,detail:String(e)})}}),r.post(`/api/pairing/claim`,async(e,t)=>{let n=ya.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{let e=de(n.data.deviceName),t=await s.claimPairingCode(n.data.code,e,n.data.deviceIdentity);return await c.record({ts:new Date().toISOString(),action:`pairing.claim`,deviceId:t.deviceId,detail:{deviceName:e}}),oC(v,t,n.data.code,n.data.deviceIdentity)}catch(e){return t.code(400).send({error:String(e)})}}),r.post(`/api/auth/refresh`,async(e,t)=>{let n=Sa.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{return await $S({authService:s,execute:()=>s.refreshAccessToken(n.data.refreshToken),logger:r.log,refreshToken:n.data.refreshToken,source:`direct_http`})}catch(e){return t.code(401).send({error:String(e)})}}),r.get(`/api/projects`,async(e,t)=>{if(L(e,t))return{projects:await y.listProjects()}}),r.get(`/api/gateway/update`,async(e,t)=>{if(L(e,t))try{return await b.getOrCheckInfo(`mobile`)}catch(e){return t.code(500).send({error:String(e)})}}),r.post(`/api/gateway/update/apply`,async(e,t)=>{if(!L(e,t))return;let n=e.body,r=Oa.safeParse(n?.requestedBy);try{let e=await b.applyUpdate(r.success?r.data:`mobile`);return Na.parse(e)}catch(e){let n=String(e),r=n.includes(`already up to date`)||n.includes(`does not support self-update`)||n.includes(`requires idle runtime`)?409:500;return t.code(r).send({error:n})}}),r.get(`/api/discovery/projects`,async(e,t)=>{if(L(e,t))try{return await h.getProjects()}catch(e){return t.code(500).send({error:String(e)})}}),r.post(`/api/discovery/projects/refresh`,async(e,t)=>{if(L(e,t))try{return await h.refreshProjects()}catch(e){return t.code(500).send({error:String(e)})}}),r.get(`/api/discovery/projects/sessions`,async(e,t)=>{if(!L(e,t))return;let n=e.query;if(typeof n.projectPath!=`string`||!n.projectPath.trim())return t.code(400).send({error:`projectPath is required and must be a non-empty string`});try{return await h.listProjectSessions(n.projectPath)}catch(e){let n=e instanceof Error?e.message:String(e);return Rg(e)&&e.code===`DISCOVERED_PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):uC(n)?t.code(400).send({error:n}):t.code(500).send({error:n})}}),r.get(`/api/workspace/directories`,async(e,t)=>{if(!L(e,t))return;let n=e.query,r=Number(n.limit??200),i=Number.isFinite(r)?Math.min(500,Math.max(1,r)):200;try{return await u.listDirectoriesUnrestricted(typeof n.path==`string`?n.path:void 0,i)}catch(e){return t.code(400).send({error:String(e)})}}),r.get(`/api/providers/:provider/capabilities`,async(e,t)=>{if(!L(e,t))return;let n=R(e,t);if(n)try{return{capabilities:await y.getProviderCapabilities(n.provider,n.projectId,n.agentVersion)}}catch(e){return Rg(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(400).send({error:String(e)})}}),r.get(`/api/agents/:provider/config`,async(e,t)=>{if(!L(e,t))return;let n=R(e,t);if(n)try{return await y.getAgentConfig(n.provider,{projectId:n.projectId,agentVersion:n.agentVersion})}catch(e){return Rg(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(400).send({error:String(e)})}}),r.post(`/api/projects`,async(e,t)=>{if(!L(e,t))return;let n=e.body;if(typeof n.path!=`string`||!n.path.trim())return t.code(400).send({error:`path is required and must be a non-empty string`});try{return{project:await y.createProject({path:n.path,title:typeof n.title==`string`?n.title:void 0})}}catch(e){return t.code(400).send({error:String(e)})}}),r.delete(`/api/projects/:projectId`,async(e,t)=>{if(!L(e,t))return;let n=e.params;try{return await y.deleteProject(n.projectId)?{removed:!0}:t.code(404).send({error:`Project not found`})}catch(e){return t.code(409).send({error:String(e)})}}),r.get(`/api/projects/:projectId/sessions`,async(e,t)=>{if(!L(e,t))return;let n=e.params,r=e.query,i=ie(r.status,t);if(!i)return;let a=ae(r.syncExternal);try{return{sessions:await y.listProjectSessions(n.projectId,i,{syncExternal:a})}}catch(e){return Rg(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(500).send({error:String(e)})}}),r.get(`/api/projects/:projectId/sessions/:sessionId`,async(e,t)=>{if(!L(e,t))return;let n=e.params,r=await y.getProjectSessionSummary(n.projectId,n.sessionId);return r?{session:r}:t.code(404).send({error:`Session not found`})}),r.get(`/api/projects/:projectId/sessions/:sessionId/events`,async(e,t)=>t.code(410).send({error:`Session events endpoint is deprecated. Use /api/projects/:projectId/sessions/:sessionId/raw-events`})),r.get(`/api/projects/:projectId/sessions/:sessionId/raw-events`,async(e,t)=>{if(!L(e,t))return;let n=e.params,r=e.query,i=(typeof r.limit==`string`?r.limit.trim().toLowerCase():``)===`all`?2**53-1:(()=>{let e=Number(r.limit??300);return Number.isFinite(e)?Math.min(2e3,Math.max(1,e)):300})(),a=ae(r.syncExternal);try{return{events:await y.getProjectSessionRawEvents(n.projectId,n.sessionId,i,{syncExternal:a})}}catch(e){return Rg(e)&&(e.code===`PROJECT_NOT_FOUND`||e.code===`PROJECT_SESSION_NOT_FOUND`)?t.code(e.status).send({error:String(e)}):t.code(500).send({error:String(e)})}}),r.get(`/api/projects/:projectId/fs/tree`,async(e,t)=>{if(!L(e,t))return;let n=e.params,r=e.query,i=await y.getProject(n.projectId);if(!i)return t.code(404).send({error:`Project not found`});try{return await u.listTree(i.path,r.path??`.`)}catch(e){return t.code(400).send({error:String(e)})}}),r.get(`/api/sessions`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/sessions`})),r.get(`/api/sessions/:sessionId`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/sessions/:sessionId`})),r.get(`/api/sessions/:sessionId/events`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/sessions/:sessionId/raw-events`})),r.get(`/api/fs/tree`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/fs/tree`})),r.get(`/api/devices`,async(e,t)=>ee(e)?{devices:s.listDevices()}:t.code(401).send({error:`Unauthorized`})),r.post(`/api/devices/:deviceId/revoke`,async(e,t)=>{if(!ee(e))return t.code(401).send({error:`Unauthorized`});let n=e.params;return await s.revokeDevice(n.deviceId)?(await c.record({ts:new Date().toISOString(),action:`device.revoke`,deviceId:n.deviceId}),{revoked:!0}):t.code(404).send({error:`Device not found`})}),r.get(`/ws`,{websocket:!0},(e,t)=>{let n=oe(t.headers.authorization)??se(t.url);if(!n){e.close(1008,`Missing access token`);return}let r;try{r=s.verifyAccessToken(n)}catch(t){e.close(1008,`Unauthorized: ${String(t)}`);return}let i=l.addClient(r.sub,e);e.on(`message`,async e=>{let t=e.toString(),n;try{let e=JSON.parse(t);e&&typeof e==`object`&&(n=e),await C(sa(e),r.sub,i)}catch(e){await w({deviceId:r.sub,clientId:i,rawCommand:t,parsedInput:n,error:e})}}),e.on(`close`,()=>{l.removeClient(i)})});let x=new px({gatewayId:e.gatewayId,relayTransportSecurityLevel:e.relayEnabled?`e2ee-relay`:`plaintext-relay`,gatewayIdentity:v.identity,gatewayIdentityPrivateKeyPem:v.privateKeyPem,sessionHub:l,handlePairingClaim:async e=>{let t=de(e.deviceName);return oC(v,await s.claimPairingCode(e.code,t,e.deviceIdentity),e.code,e.deviceIdentity)},handleRefresh:async t=>{let n=await $S({authService:s,execute:()=>s.refreshAccessToken(t.refreshToken),logger:r.log,refreshToken:t.refreshToken,requestedDeviceId:t.deviceId,source:`relay_http_forward`});return QS(t.deviceId,n.deviceId),{gatewayId:e.gatewayId,...n}},verifyDeviceIdentityBinding:async(e,t)=>s.verifyDeviceIdentityBinding(e,t),handleRpcRequest:async(e,t)=>iC(e,{authService:s,logger:r.log,sessionManager:y,projectDiscoveryService:h,fsService:u,updateService:b,relayDeviceId:t.deviceId}),sendFrame:e=>_?.send(e)??!1,dispatchCommand:async(e,t,n)=>{try{await C(e,t,n)}catch(r){await w({deviceId:t,clientId:n,rawCommand:JSON.stringify(e),parsedInput:e,error:r})}}}),S=async(e,t,n)=>{switch(e.type){case`session.start`:{let r=await y.startSession({...e.payload,deviceId:t});l.sendSystemMessage(n,{type:`command.ack`,commandType:e.type,commandId:e.commandId,payload:r});return}case`turn.input`:await y.sendInput(e.payload.sessionId,e.payload.text,t,{model:e.payload.model,sessionConfig:e.payload.sessionConfig,mode:e.payload.mode,config:e.payload.config});return;case`review.start`:throw Error(`review.start is not implemented yet.`);case`tool.approval.respond`:await y.respondToolPermission(e.payload.sessionId,e.payload.requestId,e.payload.decision,e.payload.reason,t);return;case`user.input.respond`:await y.respondUserInput(e.payload.sessionId,e.payload.requestId,e.payload.answers,t);return;case`session.interrupt`:await y.interruptSession(e.payload.sessionId,t);return;case`session.close`:throw Error(`session.close is deprecated. Use session.interrupt instead.`);case`session.stream.subscribe`:{let t=e.payload.sessions.map(e=>({sessionId:e.sessionId,projectId:e.projectId,cursor:e.cursor.kind===`raw_seq`?{kind:`raw_seq`,rawSeq:e.cursor.rawSeq}:{kind:`all`}}));await T(n,t,e.payload.replace),l.sendSystemMessage(n,{type:`command.ack`,commandType:e.type,commandId:e.commandId,payload:{replace:e.payload.replace,sessions:t.map(e=>e.sessionId)}});return}case`fs.read`:{let t=y.getSessionExecutionContext(e.payload.sessionId),n=await u.readFile(t.projectPath,e.payload.path);await y.emitExternalEvent({provider:t.provider,sessionId:e.payload.sessionId,projectId:t.projectId,type:`file.changed`,raw:{path:n.path,content:n.content}});return}case`fs.diff`:{let t=y.getSessionExecutionContext(e.payload.sessionId),n=await u.diffFile(t.projectPath,e.payload.path,e.payload.baseContent??``);await y.emitExternalEvent({provider:t.provider,sessionId:e.payload.sessionId,projectId:t.projectId,type:`file.diff.ready`,raw:{path:n.path,diff:n.diff,currentContent:n.currentContent}});return}default:{let t=e;throw Error(`Unhandled command: ${JSON.stringify(t)}`)}}},C=async(e,t,n)=>{await S(e,t,n)},w=async e=>{r.log.warn({deviceId:e.deviceId,rawCommand:e.rawCommand,err:e.error},`ws command failed`);let t=typeof e.parsedInput?.commandId==`string`?e.parsedInput.commandId:void 0,n=typeof e.parsedInput?.type==`string`?e.parsedInput.type:void 0;l.sendSystemMessage(e.clientId,{type:`command.error`,commandId:t,commandType:n,message:String(e.error)}),await y.emitExternalEvent({provider:`codex`,sessionId:`system`,type:`error.runtime`,raw:{message:String(e.error),source:`ws.command`}})},T=async(e,t,n)=>{let r=E(t),i=new Set(r.map(e=>e.sessionId));for(let t of i)l.pauseSession(e,t);l.replaceSubscriptions(e,r,n);try{for(let t of r)await D(e,t)}finally{for(let t of i)l.resumeSession(e,t)}},E=e=>{let t=new Map;for(let n of e)t.set(n.sessionId,n);return[...t.values()]},D=async(e,t)=>{let n=await O(t);if(t.cursor.kind===`all`){await k(e,n,`cursor_all`);return}let r=await y.getProjectSessionRawSeqRange(n.projectId,n.sessionId);if(!r){await k(e,n,`empty_history_snapshot`);return}let i=t.cursor.rawSeq;if(i<Math.max(0,r.min-1)||i>r.max){await k(e,n,`cursor_out_of_range_snapshot`);return}let a=await y.getProjectSessionRawEventsSinceSeq(n.projectId,n.sessionId,i,2**53-1),o=a[a.length-1]?.rawSeq??i;l.sendStreamMessage(e,j({provider:n.provider,sessionId:n.sessionId,projectId:n.projectId,decision:`delta`,reason:n.status===`running`?`cursor_resumed_delta`:`session_idle_delta`,fromRawSeq:i,toRawSeq:o}));for(let t of a)l.sendStreamMessage(e,t)},O=async e=>{let t=e.sessionId;if(!t)throw Error(`session.stream.subscribe requires sessionId`);let n=e.projectId?.trim()??``;if(n){let e=await y.getProjectSessionSummary(n,t);if(!e)throw Gg(n,t);return{sessionId:t,projectId:n,provider:e.provider,status:e.status}}let r=y.getSessionExecutionContext(t),i=await y.getProjectSessionSummary(r.projectId,t);return{sessionId:t,projectId:r.projectId,provider:i?.provider??r.provider,status:i?.status??`idle`}},k=async(e,t,n)=>{let r=`snap_${og(12)}`,i=await y.getProjectSessionRawEventsCompacted(t.projectId,t.sessionId,2**53-1),a=i[i.length-1]?.rawSeq;l.sendStreamMessage(e,j({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,decision:`snapshot`,reason:n,snapshotId:r,...a===void 0?{}:{toRawSeq:a}}));let o=A(i,100),s=o.length;for(let n=0;n<o.length;n+=1){let i=o[n]??[];l.sendStreamMessage(e,M({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,snapshotId:r,chunkIndex:n,totalChunks:s,events:i}))}},A=(e,t)=>{if(e.length===0)return[[]];let n=Math.max(1,Math.floor(t)),r=[];for(let t=0;t<e.length;t+=n)r.push(e.slice(t,t+n));return r},j=e=>({v:`1.0`,kind:`session.stream.sync`,type:`session.stream.sync`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`stream_sync_${og(12)}`,ts:new Date().toISOString(),payload:{raw:{decision:e.decision,reason:e.reason,snapshotId:e.snapshotId,fromRawSeq:e.fromRawSeq,toRawSeq:e.toRawSeq}}}),M=e=>({v:`1.0`,kind:`session.stream.snapshot.chunk`,type:`session.stream.snapshot.chunk`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`stream_snapshot_${e.snapshotId}_${e.chunkIndex}`,ts:new Date().toISOString(),payload:{raw:{snapshotId:e.snapshotId,chunkIndex:e.chunkIndex,totalChunks:e.totalChunks,events:e.events}}}),ee=t=>t.headers[`x-api-key`]===e.apiKey,N=e=>{if(e==null)return e;if(typeof e==`string`){let t=P(e);return t===void 0?ne(e,a):I(F(t))}if(Buffer.isBuffer(e)){let t=e.toString(`utf8`),n=P(t);return n===void 0?ne(t,a):I(F(n))}return typeof e==`object`?I(F(e)):String(e)},P=e=>{try{return JSON.parse(e)}catch{return}},ne=(e,t)=>e.length<=t?e:`${e.slice(0,t)}...<truncated>`,F=e=>{if(Array.isArray(e))return e.map(e=>F(e));if(e&&typeof e==`object`){let t=e,n={};for(let[e,r]of Object.entries(t)){let t=e.toLowerCase();t.includes(`token`)||t.includes(`secret`)||t.includes(`password`)||t.includes(`authorization`)?n[e]=`[REDACTED]`:n[e]=F(r)}return n}return e},I=e=>{let t=re(e);return t===o?t:t.length<=a?e:{truncated:!0,preview:ne(t,a)}},re=e=>{try{return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t)}catch{return o}},L=(e,t)=>{let n=oe(e.headers.authorization);if(!n)return t.code(401).send({error:`Missing bearer token`}),null;try{return s.verifyAccessToken(n)}catch(e){return t.code(401).send({error:String(e)}),null}},ie=(e,t)=>{let n=e??`all`;return[`running`,`idle`,`all`].includes(n)?n:(t.code(400).send({error:`Invalid status filter`}),null)},ae=e=>{let t=e?.trim().toLowerCase();return t===`true`||t===`1`},R=(e,t)=>{let n=e.params,r=e.query,i=ki.safeParse(n.provider);return i.success?{provider:i.data,projectId:typeof r.projectId==`string`?r.projectId:void 0,agentVersion:typeof r.agentVersion==`string`?r.agentVersion:void 0}:(t.code(400).send({error:`Invalid provider`}),null)},oe=e=>{if(!e)return null;let[t,n]=e.split(` `);return t?.toLowerCase()!==`bearer`||!n?null:n},se=e=>{try{return new URL(e,`http://localhost`).searchParams.get(`token`)}catch{return null}},ce=e.httpsEnabled?e.httpsPort:e.port,le=e.httpsEnabled?`https`:`http`,ue=Xc(),de=e=>e?.trim()||ue||`Gateway`;await r.listen({host:e.host,port:ce});let z=r.server.address(),fe=typeof z==`object`&&z?z.port:ce;if(r.log.info({host:e.host,port:fe,protocol:le,machineName:ue},ZS(le,e.host,fe)),e.relayEnabled&&(_=new xx({gatewayId:e.gatewayId,machineName:ue,relayUrl:e.relayUrl,relayGatewayAccessToken:e.relayGatewayAccessToken,resolveRelayGatewayAccessToken:e.relayGatewayAccessToken.trim()?void 0:()=>Ex({gatewayId:e.gatewayId,relayUrl:e.relayUrl,gatewayIdentity:v.identity,privateKeyPem:v.privateKeyPem}),gatewayIdentity:v.identity,directBaseUrls:nl({protocol:le,host:e.host,port:fe}),logger:r.log,onFrame:async e=>{await x.handleFrame(e)}}),_.start()),e.bootstrapPairingCodeOnStart)try{let t=await s.createPairingCode(e.pairingCodeTtlSeconds);g={code:t.code,expiresAt:t.expiresAt},await c.record({ts:new Date().toISOString(),action:`pairing.start`,detail:{expiresAt:t.expiresAt,source:`startup`,ttlSeconds:e.pairingCodeTtlSeconds}}),r.log.info({expiresAt:t.expiresAt},`startup pairing code generated`)}catch(e){r.log.error({err:e},`failed to generate startup pairing code`)}return await b.start(),{protocol:le,listenPort:fe,machineName:ue,gatewayIdentity:v.identity,close:()=>r.close(),getGatewayUpdateInfo:()=>b.getInfo(),requestGatewayUpdate:(e=`console`)=>b.applyUpdate(e),startupPairingCode:g}}function YS(e,t){let n=t;if(!e.httpsEnabled)return(0,ng.default)({disableRequestLogging:!0,loggerInstance:n});if(!e.tlsKeyPath||!e.tlsCertPath)throw Error(`TLS key/cert path is required when HTTPS is enabled.`);return(0,ng.default)({disableRequestLogging:!0,loggerInstance:n,https:{key:(0,u.readFileSync)(e.tlsKeyPath),cert:(0,u.readFileSync)(e.tlsCertPath),...e.tlsCaPath?{ca:(0,u.readFileSync)(e.tlsCaPath)}:{}}})}function XS(e,t){let n=process.env.NODE_ENV!==`production`,r=Ig.default.destination({dest:e.gatewayLogPath,mkdir:!0,sync:!1}),i=t.logToConsole?Ig.default.multistream([{stream:r},{stream:process.stdout}]):r;return{instance:(0,Ig.default)({level:n?`debug`:`info`},i),close:()=>{try{r.flushSync()}catch{}r.end()}}}function ZS(e,t,n){return`desktop-gateway listening on ${e}://${t}:${n}`}function QS(e,t){if(e&&e!==t)throw Ug()}async function $S(e){let t=eC(e.authService,e.refreshToken);e.logger?.info?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshToken:tC(t)},`auth refresh attempt`);try{let t=await e.execute(),n=eC(e.authService,e.refreshToken),r=eC(e.authService,t.refreshToken);return e.logger?.info?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshedDeviceId:t.deviceId,previousRefreshToken:tC(n),nextRefreshToken:tC(r)},`auth refresh succeeded`),t}catch(t){let n=eC(e.authService,e.refreshToken);throw e.logger?.warn?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshToken:tC(n),error:nC(t)},`auth refresh failed`),t}}function eC(e,t){return e.inspectRefreshToken?.(t)??{tokenRecordState:`missing`}}function tC(e){return{claimDeviceId:e.claimDeviceId??null,claimExpAt:e.claimExpAt??null,claimIssuedAt:e.claimIssuedAt??null,claimJtiSuffix:rC(e.claimJti),claimType:e.claimType??null,latestActiveTokenCreatedAt:e.latestActiveTokenCreatedAt??null,latestActiveTokenJtiSuffix:rC(e.latestActiveTokenJti),tokenRecordCreatedAt:e.tokenRecordCreatedAt??null,tokenRecordDeviceId:e.tokenRecordDeviceId??null,tokenRecordRevokedAt:e.tokenRecordRevokedAt??null,tokenRecordState:e.tokenRecordState}}function nC(e){return Rg(e)?{code:e.code,message:String(e),status:e.status}:e instanceof Error?{message:e.message,name:e.name}:{message:String(e)}}function rC(e){return e?e.slice(-8):null}async function iC(e,t){try{let n=To.parse(e);switch(n.method){case`auth.refresh`:{let e=await $S({authService:t.authService,execute:()=>t.authService.refreshAccessToken(n.params.refreshToken),logger:t.logger,refreshToken:n.params.refreshToken,requestedDeviceId:n.params.deviceId??t.relayDeviceId,source:`relay_rpc`});return QS(n.params.deviceId??t.relayDeviceId,e.deviceId),Eo.parse({method:n.method,result:e})}case`projects.list`:{let e=await t.sessionManager.listProjects();return Eo.parse({method:n.method,result:{projects:e}})}case`gateway.update.get`:{let e=await t.updateService.getOrCheckInfo(`mobile`);return Eo.parse({method:n.method,result:e})}case`gateway.update.apply`:{let e=await t.updateService.applyUpdate(n.params.requestedBy??`mobile`);return Eo.parse({method:n.method,result:e})}case`projects.discovery.get`:{let e=await t.projectDiscoveryService.getProjects();return Eo.parse({method:n.method,result:e})}case`projects.discovery.refresh`:{let e=await t.projectDiscoveryService.refreshProjects();return Eo.parse({method:n.method,result:e})}case`projects.create`:{let e=await t.sessionManager.createProject({path:n.params.path,title:n.params.title});return Eo.parse({method:n.method,result:{project:e}})}case`projects.delete`:if(!await t.sessionManager.deleteProject(n.params.projectId))throw cC(n.method,`NOT_FOUND`,404,`Project not found`);return Eo.parse({method:n.method,result:{removed:!0}});case`workspace.directories.list`:{let e=await t.fsService.listDirectoriesUnrestricted(n.params.path,n.params.limit??200);return Eo.parse({method:n.method,result:e})}case`sessions.list`:{let e=await t.sessionManager.listProjectSessions(n.params.projectId,n.params.status??`all`,{syncExternal:n.params.syncExternal});return Eo.parse({method:n.method,result:{sessions:e}})}case`sessions.discovery.list`:{let e=await t.projectDiscoveryService.listProjectSessions(n.params.projectPath);return Eo.parse({method:n.method,result:e})}case`sessions.get`:{let e=await t.sessionManager.getProjectSessionSummary(n.params.projectId,n.params.sessionId);if(!e)throw cC(n.method,`NOT_FOUND`,404,`Session ${n.params.sessionId} not found in project ${n.params.projectId}`);return Eo.parse({method:n.method,result:{session:e}})}case`sessions.rawEvents.list`:{let e=await t.sessionManager.getProjectSessionRawEvents(n.params.projectId,n.params.sessionId,n.params.limit===`all`?2**53-1:n.params.limit,{syncExternal:n.params.syncExternal});return Eo.parse({method:n.method,result:{events:e}})}case`providers.capabilities.get`:{let e=await t.sessionManager.getProviderCapabilities(n.params.provider,n.params.projectId??void 0,n.params.agentVersion??void 0);return Eo.parse({method:n.method,result:{capabilities:e}})}case`agents.config.get`:{let e=await t.sessionManager.getAgentConfig(n.params.provider,{projectId:n.params.projectId??void 0,agentVersion:n.params.agentVersion??void 0});return Eo.parse({method:n.method,result:e})}case`devices.list`:return Eo.parse({method:n.method,result:{devices:t.authService.listDevices()}});case`devices.revoke`:if(!await t.authService.revokeDevice(n.params.deviceId))throw cC(n.method,`NOT_FOUND`,404,`Device ${n.params.deviceId} not found`);return Eo.parse({method:n.method,result:{revoked:!0}});default:{let e=n;throw cC(void 0,`INTERNAL`,500,`Unhandled relay RPC method: ${JSON.stringify(e)}`)}}}catch(e){throw aC(e)}}function aC(e){if(Rg(e))switch(e.code){case`REFRESH_TOKEN_REVOKED`:case`DEVICE_REVOKED`:case`REFRESH_TOKEN_DEVICE_MISMATCH`:return cC(`UNAUTHORIZED`,e.status,String(e),e.details);case`PROJECT_NOT_FOUND`:case`DISCOVERED_PROJECT_NOT_FOUND`:case`PROJECT_SESSION_NOT_FOUND`:case`SESSION_NOT_FOUND`:return cC(`NOT_FOUND`,e.status,String(e),e.details);case`PROJECT_DELETE_CONFLICT`:return cC(`BAD_REQUEST`,e.status,String(e),e.details);default:return cC(e.status>=500?`INTERNAL`:`BAD_REQUEST`,e.status,String(e),e.details)}let t=Oo.safeParse(e);if(t.success)return t.data;let n=Do.safeParse(e);if(n.success)return cC(void 0,n.data.code,n.data.status,n.data.message,n.data.details);if(e&&typeof e==`object`&&`code`in e&&`status`in e&&`message`in e&&typeof e.code==`string`&&typeof e.status==`number`&&typeof e.message==`string`){let t=e;return cC(t.code,t.status,t.message,t.details)}let r=String(e);return e instanceof Error&&e.name===`ZodError`?cC(`BAD_REQUEST`,400,r):lC(e)?cC(`UNAUTHORIZED`,401,r):uC(r)?cC(`BAD_REQUEST`,400,r):cC(`INTERNAL`,500,r)}function oC(e,t,n,r){if(!r)return t;let i={gatewayId:t.gatewayId,deviceId:t.deviceId,mobilePublicKey:r.publicKey,pairingContext:{pairingCode:sC(n),signedAt:new Date().toISOString()}};return{...t,gatewayIdentity:e.identity,pairingConfirmation:Hs(e.identity,e.privateKeyPem,i)}}function sC(e){return e.replace(/\s+/gu,``).toUpperCase()}function cC(e,t,n,r,i){let a=typeof t==`string`,o=a?e:void 0,s=a?t:e,c=a?n:t,l=a?r:n,u=a?i:r;return Oo.parse({...o?{method:o}:{},code:s,status:c,message:l,...u===void 0?{}:{details:u}})}function lC(e){return Rg(e)&&(e.code===`REFRESH_TOKEN_REVOKED`||e.code===`DEVICE_REVOKED`||e.code===`REFRESH_TOKEN_DEVICE_MISMATCH`)||Qg(e)}function uC(e){let t=e.trim();return t===`Invalid provider`||t.startsWith(`Invalid provider:`)||t.startsWith(`Project path must be absolute:`)||t.startsWith(`Project path does not exist:`)||t.startsWith(`Project path is not a directory:`)||t.startsWith(`ZodError:`)}async function dC(e){let t=await Zs({configPath:e.configPath,ensureConfigFile:!0});tc(t.config);let n=await JS(t.config,{logToConsole:e.logToConsole,onUpdatePrepared:async e=>{pC({type:`worker.update.prepared`,payload:e})}});pC({type:`worker.ready`,payload:fC(n)});let r=null,i=e=>r||(r=Promise.resolve(n.close?.()).catch(e=>{console.error(`[gateway] worker shutdown failed: ${String(e)}`)}).finally(()=>{process.exit(e)}),r);process.on(`message`,e=>{let t=mC(e);if(t)switch(t.type){case`supervisor.request`:a(t);return;case`supervisor.shutdown`:i(0);return}}),process.on(`disconnect`,()=>{i(0)}),process.on(`SIGINT`,()=>{i(0)}),process.on(`SIGTERM`,()=>{i(0)}),process.on(`uncaughtException`,e=>{console.error(`[gateway] worker uncaught exception: ${String(e)}`),i(1)}),process.on(`unhandledRejection`,e=>{console.error(`[gateway] worker unhandled rejection: ${String(e)}`),i(1)});async function a(e){try{switch(e.method){case`gateway.update.apply`:{if(!n.requestGatewayUpdate)throw Error(`gateway update is unavailable`);let t=await n.requestGatewayUpdate(e.requestedBy);pC({type:`worker.response`,id:e.id,ok:!0,result:t});return}}}catch(t){pC({type:`worker.response`,id:e.id,ok:!1,error:String(t)})}}await new Promise(()=>{})}function fC(e){return{protocol:e.protocol,listenPort:e.listenPort,machineName:e.machineName,gatewayIdentity:e.gatewayIdentity,startupPairingCode:e.startupPairingCode}}function pC(e){process.send&&process.send(e)}function mC(e){if(!hC(e)||typeof e.type!=`string`)return null;switch(e.type){case`supervisor.shutdown`:return e.reason!==`signal`&&e.reason!==`update`?null:{type:`supervisor.shutdown`,reason:e.reason};case`supervisor.request`:return typeof e.id!=`string`||e.method!==`gateway.update.apply`||e.requestedBy!==`console`&&e.requestedBy!==`mobile`&&e.requestedBy!==`system`?null:{type:`supervisor.request`,id:e.id,method:`gateway.update.apply`,requestedBy:e.requestedBy};default:return null}}function hC(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}gC(process.argv.slice(2)).catch(e=>{console.error(String(e)),process.exit(1)});async function gC(e){let t=P(e);switch(t.command){case`help`:xC();return;case`version`:console.log(te.version);return;case`init`:await vC(t);return;case`doctor`:await yC(t);return;case`start`:await _C(t);return;case`__worker`:await bC(t);return;default:{let e=t.command;throw Error(`Unsupported command: ${e}`)}}}async function _C(e){let t=await Zs({configPath:e.configPath,ensureConfigFile:!0});tc(t.config);let n=await yc({configPath:t.configPath,configExists:t.configExists,config:t.config});try{await zl({args:e,loaded:t,doctorReport:n})}catch(e){throw Error(Jl(e,t.config))}bc(n)&&console.warn(`[doctor] startup continued despite bundled runtime check failures.`)}async function vC(e){let t=await Xs({configPath:e.configPath,overwrite:e.force});t.created?console.log(`[gateway] wrote config to ${t.configPath}`):(console.log(`[gateway] config already exists at ${t.configPath}`),console.log(`[gateway] rerun with --force to overwrite`));let n=await Zs({configPath:t.configPath,ensureConfigFile:!1}),r=await yc({configPath:n.configPath,configExists:n.configExists,config:n.config});console.log(xc(r))}async function yC(e){let t=await Zs({configPath:Ys(e.configPath),ensureConfigFile:!1,syncGatewayIdentityConfig:!1}),n=await yc({configPath:t.configPath,configExists:t.configExists,config:t.configExists?t.config:void 0});console.log(xc(n)),bc(n)&&(process.exitCode=1)}async function bC(e){try{await dC(e)}catch(t){let n=await Zs({configPath:e.configPath,ensureConfigFile:!0});throw Error(Jl(t,n.config))}}function xC(){console.log(`${te.cliName} ${te.version}`),console.log(``),console.log(`Usage:`),console.log(` ${te.cliName} [start] [--config <path>] [--log]`),console.log(` ${te.cliName} init [--config <path>] [--force]`),console.log(` ${te.cliName} doctor [--config <path>]`),console.log(` ${te.cliName} --version`)}exports.runCli=gC;
|